nus-yam/ex-repair huggingface dataset:
Program: 131160
Project: 131160
Buggy source:
public static FgModel trainErma(FgModel model,FgExampleList data,Regularizer r,boolean sgd){
  BeliefPropagationPrm bpPrm=new BeliefPropagationPrm();
  bpPrm.schedule=BpScheduleType.TREE_LIKE;
  bpPrm.updateOrder=BpUpdateOrder.SEQUENTIAL;
  bpPrm.normalizeMessages=false;
  bpPrm.s=RealAlgebra.getInstance();
  CrfTrainerPrm prm=new CrfTrainerPrm();
  prm.infFactory=bpPrm;
  prm.bFactory=bpPrm;
  prm.dlFactory=new MeanSquaredErrorFactory();
  prm.trainer=Trainer.ERMA;
  if (sgd) {
    SGDPrm optPrm=new SGDPrm();
    optPrm.numPasses=10;
    optPrm.batchSize=2;
    optPrm.autoSelectLr=false;
    optPrm.sched.setEta0(0.2);
    prm.batchOptimizer=new SGD(optPrm);
    prm.optimizer=null;
  }
 else {
    prm.batchOptimizer=null;
    prm.optimizer=new MalletLBFGS(new MalletLBFGSPrm());
  }
  prm.regularizer=r;
  CrfTrainer trainer=new CrfTrainer(prm);
  trainer.train(model,data);
  return model;
}

Fixed version (ground truth):
public static FgModel trainErma(FgModel model,FgExampleList data,Regularizer r,boolean sgd){
  BeliefPropagationPrm bpPrm=new BeliefPropagationPrm();
  bpPrm.schedule=BpScheduleType.TREE_LIKE;
  bpPrm.updateOrder=BpUpdateOrder.SEQUENTIAL;
  bpPrm.normalizeMessages=false;
  bpPrm.s=RealAlgebra.getInstance();
  CrfTrainerPrm prm=new CrfTrainerPrm();
  prm.infFactory=bpPrm;
  prm.bFactory=bpPrm;
  prm.dlFactory=new L2DistanceFactory();
  prm.trainer=Trainer.ERMA;
  if (sgd) {
    SGDPrm optPrm=new SGDPrm();
    optPrm.numPasses=10;
    optPrm.batchSize=2;
    optPrm.autoSelectLr=false;
    optPrm.sched.setEta0(0.2);
    prm.batchOptimizer=new SGD(optPrm);
    prm.optimizer=null;
  }
 else {
    prm.batchOptimizer=null;
    prm.optimizer=new MalletLBFGS(new MalletLBFGSPrm());
  }
  prm.regularizer=r;
  CrfTrainer trainer=new CrfTrainer(prm);
  trainer.train(model,data);
  return model;
}
Program: 131161
Project: 131161
Buggy source:
private void testSimpleGradient(Algebra s){
  double[] params=new double[]{0.0,0.0,0.0,0.0};
  helpSimpleGradient(params,new ExpectedRecallFactory(),Trainer.ERMA,new double[]{-0.125,0.125,0.125,-0.125},s);
  helpSimpleGradient(params,new MeanSquaredErrorFactory(),Trainer.ERMA,new double[]{-0.25,0.25,0.25,-0.25},s);
  helpSimpleGradient(params,null,Trainer.CLL,new double[]{0.25,-0.25,-0.25,0.25},s);
  params=new double[]{1.0,2.0,3.0,4.0};
  helpSimpleGradient(params,new ExpectedRecallFactory(),Trainer.ERMA,new double[]{-0.0983,0.0983,0.0983,-0.0983},s);
  helpSimpleGradient(params,new MeanSquaredErrorFactory(),Trainer.ERMA,new double[]{-0.2875,0.2875,0.1058,-0.1058},s);
  helpSimpleGradient(params,null,Trainer.CLL,new double[]{0.3655,-0.3655,-0.1345,0.1345},s);
}

Fixed version (ground truth):
private void testSimpleGradient(Algebra s){
  double[] params=new double[]{0.0,0.0,0.0,0.0};
  helpSimpleGradient(params,new ExpectedRecallFactory(),Trainer.ERMA,new double[]{-0.125,0.125,0.125,-0.125},s);
  helpSimpleGradient(params,new L2DistanceFactory(),Trainer.ERMA,new double[]{-0.25,0.25,0.25,-0.25},s);
  helpSimpleGradient(params,null,Trainer.CLL,new double[]{0.25,-0.25,-0.25,0.25},s);
  params=new double[]{1.0,2.0,3.0,4.0};
  helpSimpleGradient(params,new ExpectedRecallFactory(),Trainer.ERMA,new double[]{-0.0983,0.0983,0.0983,-0.0983},s);
  helpSimpleGradient(params,new L2DistanceFactory(),Trainer.ERMA,new double[]{-0.2875,0.2875,0.1058,-0.1058},s);
  helpSimpleGradient(params,null,Trainer.CLL,new double[]{0.3655,-0.3655,-0.1345,0.1345},s);
}
Program: 131162
Project: 131162
Buggy source:
@Override public void init(UFgExample ex,FactorTemplateList fts){
  this.feats=new FeatureVector[ex.getFactorGraph().getNumFactors()];
  this.featExtractor.init(ex,fts);
}

Fixed version (ground truth):
@Deprecated public void init(FactorGraph fg){
  this.feats=new FeatureVector[fg.getNumFactors()];
}
Program: 131163
Project: 131163
Buggy source:
private void skipNonIncluded(){
  while (!included[iter.i][iter.j][iter.k]) {
    hasNext=iter.next();
  }
}

Fixed version (ground truth):
private void skipNonIncluded(){
  while (hasNext && !included[iter.i][iter.j][iter.k]) {
    hasNext=iter.next();
  }
}
Program: 131165
Project: 131165
Buggy source:
public void printModel(Writer writer) throws IOException {
  Iterator<String> iter=null;
  if (paramNames != null) {
    iter=paramNames.iterator();
  }
  for (int i=0; i < numParams; i++) {
    if (paramNames != null) {
      writer.write(iter.next());
    }
 else {
      writer.write(String.format("String_Node_Str",i));
    }
    writer.write("String_Node_Str");
    writer.write(String.format("String_Node_Str",params.get(i)));
    writer.write("String_Node_Str");
  }
  writer.flush();
}

Fixed version (ground truth):
public void printModel(Writer writer) throws IOException {
  Iterator<String> iter=null;
  if (paramNames != null) {
    iter=paramNames.iterator();
  }
  for (int i=0; i < numParams; i++) {
    if (paramNames != null && iter.hasNext()) {
      writer.write(iter.next());
    }
 else {
      writer.write(String.format("String_Node_Str",i));
    }
    writer.write("String_Node_Str");
    writer.write(String.format("String_Node_Str",params.get(i)));
    writer.write("String_Node_Str");
  }
  writer.flush();
}
Program: 131166
Project: 131166
Buggy source:
public static void init(File reportOut,boolean useLog4j){
  ReporterManager.useLog4j=useLog4j;
  if (wr != null) {
    throw new RuntimeException("String_Node_Str");
  }
  try {
    if (reportOut != null) {
      wr=new StreamReporter(new FileOutputStream(reportOut));
    }
  }
 catch (  FileNotFoundException e) {
    throw new RuntimeException(e);
  }
  initialized=true;
  for (  Class<?> clazz : reps.keySet()) {
    InitReporter rl=(InitReporter)reps.get(clazz);
    rl.set(getReporter(clazz));
  }
  reps=null;
}

Fixed version (ground truth):
public static void init(File reportOut,boolean useLogger){
  if (initialized) {
    log.warn("String_Node_Str");
  }
  ReporterManager.useLogger=useLogger;
  if (wr != null) {
    throw new RuntimeException("String_Node_Str");
  }
  try {
    if (reportOut != null) {
      wr=new StreamReporter(new FileOutputStream(reportOut));
    }
  }
 catch (  FileNotFoundException e) {
    throw new RuntimeException(e);
  }
  initialized=true;
  if (reps != null) {
    for (    Class<?> clazz : reps.keySet()) {
      InitReporter rep=(InitReporter)reps.get(clazz);
      rep.set(getReporter(clazz));
    }
    reps=null;
  }
}
Program: 131167
Project: 131167
Buggy source:
public static Reporter getReporter(Class<?> clazz){
  Reporter r;
  if (!initialized) {
    r=new InitReporter();
    reps.put(clazz,r);
  }
 else   if (useLog4j && wr != null) {
    r=new ReporterList(new Log4jReporter(clazz),wr);
  }
 else   if (useLog4j && wr == null) {
    r=new Log4jReporter(clazz);
  }
 else   if (!useLog4j && wr != null) {
    r=wr;
  }
 else {
    r=new ReporterList();
  }
  return r;
}

Fixed version (ground truth):
public static Reporter getReporter(Class<?> clazz){
  Reporter r;
  if (!initialized) {
    r=new InitReporter();
    reps.put(clazz,r);
  }
 else   if (useLogger && wr != null) {
    r=new ReporterList(new Log4jReporter(clazz),wr);
  }
 else   if (useLogger && wr == null) {
    r=new Log4jReporter(clazz);
  }
 else   if (!useLogger && wr != null) {
    r=wr;
  }
 else {
    r=new ReporterList();
  }
  return r;
}
Program: 131168
Project: 131168
Buggy source:
/** 
 * Gets a topological sort for the graph, where the depth-first search is cutoff by an input set.
 * @param inputs The input set which is excluded from the graph.
 * @param root The root of the graph.
 * @param deps Functional description of the graph's dependencies.
 * @return The topological sort.
 */
public static <T>List<T> toposort(final Set<T> inputSet,T root,final Deps<T> deps){
  checkIsValidLeafSet(inputSet,root,deps);
  Deps<T> cutoffDeps=getCutoffDeps(inputSet,deps);
  return Toposort.toposort(root,cutoffDeps);
}

Fixed version (ground truth):
/** 
 * Gets a topological sort for the graph, where the depth-first search is cutoff by an input set.
 * @param inputSet The input set which is excluded from the graph.
 * @param root The root of the graph.
 * @param deps Functional description of the graph's dependencies.
 * @param isFullCut Whether the input set is a full cut of the graph.
 * @return The topological sort.
 */
public static <T>List<T> toposort(final Set<T> inputSet,T root,final Deps<T> deps,boolean isFullCut){
  checkAreDescendentsOf(inputSet,root,deps);
  if (isFullCut) {
    checkIsFullCut(inputSet,root,deps);
  }
  Deps<T> cutoffDeps=getCutoffDeps(inputSet,deps);
  return Toposort.toposort(root,cutoffDeps);
}
Program: 131169
Project: 131169
Buggy source:
public EmpiricalRisk(FactorGraph fg,VarConfig goldConfig,Module<MVecFgModel> mid,BeliefsModuleFactory bFactory,DlFactory dlFactory,int curIter,int maxIter){
  super();
  this.mid=mid;
  try (TimerAdder t0=new TimerAdder(tot)){
    try (TimerAdder t=new TimerAdder(initTimer)){
      effm=new FactorsModule(mid,fg,bFactory.getAlgebra());
      inf=bFactory.getBeliefsModule(effm,fg);
      dl=dlFactory.getDl(goldConfig,effm,inf,curIter,maxIter);
      shallowCopy(new TopoOrder<Tensor>(QLists.getList(mid),dl,"String_Node_Str"));
    }
   }
 }

Fixed version (ground truth):
public EmpiricalRisk(FactorGraph fg,VarConfig goldConfig,Module<MVecFgModel> mid,BeliefsModuleFactory bFactory,DlFactory dlFactory,int curIter,int maxIter){
  super();
  this.mid=mid;
  try (TimerAdder t0=new TimerAdder(tot)){
    try (TimerAdder t=new TimerAdder(initTimer)){
      effm=new FactorsModule(mid,fg,bFactory.getAlgebra());
      inf=bFactory.getBeliefsModule(effm,fg);
      dl=dlFactory.getDl(goldConfig,effm,inf,curIter,maxIter);
      shallowCopy(new TopoOrder<Tensor>(QLists.getList(mid),dl,"String_Node_Str",false));
    }
   }
 }
Program: 131170
Project: 131170
Buggy source:
@Test public void testTopoSortWithInputs2(){
  List<String> valid=Arrays.asList(new String[]{"String_Node_Str"});
  Deps<String> deps=new DiamondGraph();
  List<String> sort=Toposort.toposort(QLists.getList("String_Node_Str"),"String_Node_Str",deps);
  System.out.println(sort);
  assertTrue(valid.contains(sort.toString()));
}

Fixed version (ground truth):
@Test public void testTopoSortWithInputs2(){
  List<String> valid=Arrays.asList(new String[]{"String_Node_Str"});
  Deps<String> deps=new DiamondGraph();
  List<String> sort=Toposort.toposort(QLists.getList("String_Node_Str"),"String_Node_Str",deps,true);
  System.out.println(sort);
  assertTrue(valid.contains(sort.toString()));
}
Program: 131171
Project: 131171
Buggy source:
@Test public void testTopoSortWithInputs(){
  Prng.seed(1l);
  List<String> valid=Arrays.asList(new String[]{"String_Node_Str","String_Node_Str","String_Node_Str","String_Node_Str","String_Node_Str"});
  for (  int i : QLists.getList(0,1,2)) {
    Deps<String> deps=new ShuffledSimpleGraph(i * 3);
    List<String> sort=Toposort.toposort(QLists.getList("String_Node_Str","String_Node_Str","String_Node_Str"),"String_Node_Str",deps);
    if (valid.contains(sort.toString())) {
      System.out.println("String_Node_Str" + i);
    }
    System.out.println(sort);
    assertTrue(valid.contains(sort.toString()));
  }
}

Fixed version (ground truth):
@Test public void testTopoSortWithInputs(){
  Prng.seed(1l);
  List<String> valid=Arrays.asList(new String[]{"String_Node_Str","String_Node_Str","String_Node_Str","String_Node_Str","String_Node_Str"});
  for (  int i : QLists.getList(0,1,2)) {
    Deps<String> deps=new ShuffledSimpleGraph(i * 3);
    List<String> sort=Toposort.toposort(QLists.getList("String_Node_Str","String_Node_Str","String_Node_Str"),"String_Node_Str",deps,true);
    if (valid.contains(sort.toString())) {
      System.out.println("String_Node_Str" + i);
    }
    System.out.println(sort);
    assertTrue(valid.contains(sort.toString()));
  }
}
Program: 131172
Project: 131172
Buggy source:
@Test public void testTopoSortWithBadInputs(){
  SimpleGraph deps=new SimpleGraph();
  try {
    Toposort.toposort(QLists.getList("String_Node_Str","String_Node_Str"),"String_Node_Str",deps);
    fail();
  }
 catch (  IllegalStateException e) {
  }
  try {
    Toposort.toposort(QLists.getList("String_Node_Str","String_Node_Str","String_Node_Str"),"String_Node_Str",deps);
    fail();
  }
 catch (  IllegalStateException e) {
  }
}

Fixed version (ground truth):
@Test public void testTopoSortWithBadInputs(){
  SimpleGraph deps=new SimpleGraph();
  try {
    Toposort.toposort(QLists.getList("String_Node_Str","String_Node_Str"),"String_Node_Str",deps,true);
    fail();
  }
 catch (  IllegalStateException e) {
  }
  try {
    Toposort.toposort(QLists.getList("String_Node_Str","String_Node_Str","String_Node_Str"),"String_Node_Str",deps,true);
    fail();
  }
 catch (  IllegalStateException e) {
  }
}
Program: 131173
Project: 131173
Buggy source:
public static void assertEqualMarginals(FactorGraph fg,FgInferencer bf,FgInferencer bp,double tolerance){
  for (  Var var : fg.getVars()) {
{
      VarTensor bfm=bf.getMarginals(var);
      VarTensor bpm=bp.getMarginals(var);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
{
      VarTensor bfm=bf.getLogMarginals(var);
      VarTensor bpm=bp.getLogMarginals(var);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
  }
  for (  Factor f : fg.getFactors()) {
{
      VarTensor bfm=bf.getMarginals(f);
      VarTensor bpm=bp.getMarginals(f);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
{
      VarTensor bfm=bf.getLogMarginals(f);
      VarTensor bpm=bp.getLogMarginals(f);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
  }
  assertEquals(bf.getPartition(),bp.getPartition(),tolerance);
  assertEquals(bf.getLogPartition(),bp.getLogPartition(),tolerance);
}

Fixed version (ground truth):
public static void assertEqualMarginals(FactorGraph fg,FgInferencer bf,FgInferencer bp,double tolerance,boolean compareGlobalFactors){
  for (  Var var : fg.getVars()) {
{
      VarTensor bfm=bf.getMarginals(var);
      VarTensor bpm=bp.getMarginals(var);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
{
      VarTensor bfm=bf.getLogMarginals(var);
      VarTensor bpm=bp.getLogMarginals(var);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
  }
  for (  Factor f : fg.getFactors()) {
    if (!compareGlobalFactors && f instanceof GlobalFactor) {
      continue;
    }
{
      VarTensor bfm=bf.getMarginals(f);
      VarTensor bpm=bp.getMarginals(f);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
{
      VarTensor bfm=bf.getLogMarginals(f);
      VarTensor bpm=bp.getLogMarginals(f);
      if (!bfm.equals(bpm,tolerance)) {
        assertEquals(bfm,bpm);
      }
    }
  }
  assertEquals(bf.getPartition(),bp.getPartition(),tolerance);
  assertEquals(bf.getLogPartition(),bp.getLogPartition(),tolerance);
}
Program: 131174
Project: 131174
Buggy source:
protected void addEdgeToOrder(int e,BipartiteGraph<Var,Factor> bg,boolean[] markedGF){
  if (!bg.isT1T2(e) && bg.t2E(e) instanceof GlobalFactor) {
    if (!markedGF[bg.parentE(e)]) {
      order.add(bg.t2E(e));
      markedGF[bg.parentE(e)]=true;
      log.warn("String_Node_Str");
    }
  }
 else {
    order.add(e);
  }
}

Fixed version (ground truth):
protected void addEdgeToOrder(int e,BipartiteGraph<Var,Factor> bg,boolean[] markedGF,boolean warnGF){
  if (!bg.isT1T2(e) && bg.t2E(e) instanceof GlobalFactor) {
    if (!markedGF[bg.parentE(e)]) {
      order.add(bg.t2E(e));
      markedGF[bg.parentE(e)]=true;
      if (warnGF) {
        log.warn("String_Node_Str");
      }
    }
  }
 else {
    order.add(e);
  }
}
Program: 131175
Project: 131175
Buggy source:
public RandomMpSchedule(FactorGraph fg){
  BipartiteGraph<Var,Factor> bg=fg.getBipgraph();
  order=new ArrayList<Object>();
  for (int v=0; v < fg.getNumVars(); v++) {
    for (int nb=0; nb < bg.numNbsT1(v); nb++) {
      order.add(bg.edgeT1(v,nb));
    }
  }
  for (int f=0; f < fg.getNumFactors(); f++) {
    if (bg.t2E(f) instanceof GlobalFactor) {
      order.add(bg.t2E(f));
    }
 else {
      for (int nb=0; nb < bg.numNbsT2(f); nb++) {
        order.add(bg.edgeT2(f,nb));
      }
    }
  }
}

Fixed version (ground truth):
public RandomMpSchedule(FactorGraph fg){
  BipartiteGraph<Var,Factor> bg=fg.getBipgraph();
  order=new ArrayList<Object>();
  for (int v=0; v < fg.getNumVars(); v++) {
    for (int nb=0; nb < bg.numNbsT1(v); nb++) {
      order.add(bg.edgeT1(v,nb));
    }
  }
  for (int f=0; f < fg.getNumFactors(); f++) {
    if (bg.getT2s().get(f) instanceof GlobalFactor) {
      order.add(bg.getT2s().get(f));
    }
 else {
      for (int nb=0; nb < bg.numNbsT2(f); nb++) {
        order.add(bg.edgeT2(f,nb));
      }
    }
  }
}
Program: 131176
Project: 131176
Buggy source:
@Override public Tensor forward(){
  fmLatPred=new FactorsModule(mid,fgLatPred,s);
  fmLatPred.forward();
  fgLat=CrfObjective.getFgLat(fgLatPred,goldConfig);
  fmLat=new FactorsModule(mid,fgLat,s);
  fmLat.forward();
  infLatPred=infFactory.getInferencer(fgLatPred);
  infLatPred.run();
  infLat=infFactory.getInferencer(fgLat);
  infLat.run();
  double ll=CrfObjective.getValue(fgLat,infLat,fgLatPred,infLatPred,-1,goldConfig,weight);
  y=Scalar.getInstance(s,ll);
  return y;
}

Fixed version (ground truth):
@Override public Tensor forward(){
  fmLatPred=new FactorsModule(mid,fgLatPred,facS);
  fmLatPred.forward();
  fgLat=CrfObjective.getFgLat(fgLatPred,goldConfig);
  fmLat=new FactorsModule(mid,fgLat,facS);
  fmLat.forward();
  infLatPred=infFactory.getInferencer(fgLatPred);
  infLatPred.run();
  infLat=infFactory.getInferencer(fgLat);
  infLat.run();
  double ll=CrfObjective.getValue(fgLat,infLat,fgLatPred,infLatPred,-1,goldConfig,weight);
  y=Scalar.getInstance(s,ll);
  return y;
}
Program: 131177
Project: 131177
Buggy source:
@Override public Module<Tensor> getInstance(FgModelIdentity mid,FactorGraph fg,VarConfig goldConfig,double weight,int curIter,int maxIter){
  if (weight != 1.0) {
    throw new IllegalArgumentException("String_Node_Str");
  }
  if (true || hasLatentVars(fg)) {
    return new MarginalLogLikelihood(mid,fg,infFactory,goldConfig);
  }
 else {
    return new LogLikelihood(mid,fg,infFactory,goldConfig);
  }
}

Fixed version (ground truth):
@Override public Module<Tensor> getInstance(FgModelIdentity mid,FactorGraph fg,VarConfig goldConfig,double weight,int curIter,int maxIter){
  if (weight != 1.0) {
    throw new IllegalArgumentException("String_Node_Str");
  }
  if (hasLatentVars(fg)) {
    return new MarginalLogLikelihood(mid,fg,infFactory,goldConfig);
  }
 else {
    return new LogLikelihood(mid,fg,infFactory,goldConfig);
  }
}
Program: 131178
Project: 131178
Buggy source:
@Override public void addExpectedPartials(IFgModel counts,VarTensor factorMarginal,double multiplier){
  int numConfigs=factorMarginal.getVars().calcNumConfigs();
  for (int c=0; c < numConfigs; c++) {
    double prob=factorMarginal.getValue(c);
    FeatureVector fv=getFeatures(c);
    counts.addAfterScaling(fv,multiplier * prob);
  }
}

Fixed version (ground truth):
@Override public void addExpectedPartials(IFgModel counts,VarTensor factorMarginal,double multiplier){
  log.trace("String_Node_Str",factorMarginal);
  int numConfigs=factorMarginal.getVars().calcNumConfigs();
  for (int c=0; c < numConfigs; c++) {
    double prob=factorMarginal.getValue(c);
    FeatureVector fv=getFeatures(c);
    counts.addAfterScaling(fv,multiplier * prob);
  }
}
Program: 131179
Project: 131179
Buggy source:
@Override public Tensor forward(){
  fmLatPred=new FactorsModule(mid,fgLatPred,facS);
  fmLatPred.forward();
  fgLat=CrfObjective.getFgLat(fgLatPred,goldConfig);
  fmLat=new FactorsModule(mid,fgLat,facS);
  fmLat.forward();
  infLatPred=infFactory.getInferencer(fgLatPred);
  infLatPred.run();
  infLat=infFactory.getInferencer(fgLat);
  infLat.run();
  double ll=CrfObjective.getValue(fgLat,infLat,fgLatPred,infLatPred,-1,goldConfig,weight);
  y=Scalar.getInstance(s,ll);
  return y;
}

Fixed version (ground truth):
@Override public Tensor forward(){
  fmLatPred=new FactorsModule(mid,fgLatPred,s);
  fmLatPred.forward();
  fgLat=CrfObjective.getFgLat(fgLatPred,goldConfig);
  fmLat=new FactorsModule(mid,fgLat,s);
  fmLat.forward();
  infLatPred=infFactory.getInferencer(fgLatPred);
  infLatPred.run();
  infLat=infFactory.getInferencer(fgLat);
  infLat.run();
  double numerator=s.fromLogProb(infLat.getLogPartition());
  double denominator=s.fromLogProb(infLatPred.getLogPartition());
  double ll=s.divide(numerator,denominator);
  log.trace(String.format("String_Node_Str",ll,numerator,denominator));
  if (ll > MAX_LOG_LIKELIHOOD) {
    log.warn("String_Node_Str" + ll);
  }
  return y=Scalar.getInstance(s,ll);
}
Program: 131180
Project: 131180
Buggy source:
public MarginalLikelihood(Module<MVecFgModel> mid,FactorGraph fg,FgInferencerFactory infFactory,VarConfig goldConfig,double weight){
  super(LogSemiring.getInstance());
  this.mid=mid;
  this.fgLatPred=fg;
  this.infFactory=infFactory;
  this.goldConfig=goldConfig;
  this.weight=weight;
}

Fixed version (ground truth):
public MarginalLikelihood(Module<MVecFgModel> mid,FactorGraph fg,FgInferencerFactory infFactory,VarConfig goldConfig){
  super(LogSignAlgebra.getInstance());
  this.mid=mid;
  this.fgLatPred=fg;
  this.infFactory=infFactory;
  this.goldConfig=goldConfig;
}
Program: 131181
Project: 131181
Buggy source:
@Test public void testErmaGradientLinearChainWithLoops(){
  FgAndVars fgv=FactorGraphTest.getLinearChainFgWithVars();
  FactorGraph fg=fgv.fg;
  ExplicitFactor loop0=new ExplicitFactor(new VarSet(fgv.t0,fgv.t2));
  ExplicitFactor loop1=new ExplicitFactor(new VarSet(fgv.w0,fgv.w2));
  ExplicitFactor loop2=new ExplicitFactor(new VarSet(fgv.t0,fgv.t1,fgv.t2));
  ExplicitFactor loop3=new ExplicitFactor(new VarSet(fgv.w0,fgv.w1,fgv.w2));
  fg.addFactor(loop0);
  fg.addFactor(loop1);
  fg.addFactor(loop2);
  fg.addFactor(loop3);
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(fgv.w0,0);
  goldConfig.put(fgv.w1,1);
  goldConfig.put(fgv.w2,0);
  goldConfig.put(fgv.t1,1);
  goldConfig.put(fgv.t2,1);
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.updateOrder=BpUpdateOrder.SEQUENTIAL;
  prm.schedule=BpScheduleType.TREE_LIKE;
  prm.maxIterations=2;
  prm.s=s;
  prm.normalizeMessages=true;
  testGradientByFiniteDifferences(fg,goldConfig,prm);
}

Fixed version (ground truth):
@Test public void testErmaGradientLinearChainWithLoops(){
  FgAndVars fgv=FactorGraphsForTests.getLinearChainFgWithVars();
  FactorGraph fg=fgv.fg;
  ExplicitFactor loop0=new ExplicitFactor(new VarSet(fgv.t0,fgv.t2));
  ExplicitFactor loop1=new ExplicitFactor(new VarSet(fgv.w0,fgv.w2));
  ExplicitFactor loop2=new ExplicitFactor(new VarSet(fgv.t0,fgv.t1,fgv.t2));
  ExplicitFactor loop3=new ExplicitFactor(new VarSet(fgv.w0,fgv.w1,fgv.w2));
  fg.addFactor(loop0);
  fg.addFactor(loop1);
  fg.addFactor(loop2);
  fg.addFactor(loop3);
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(fgv.w0,0);
  goldConfig.put(fgv.w1,1);
  goldConfig.put(fgv.w2,0);
  goldConfig.put(fgv.t1,1);
  goldConfig.put(fgv.t2,1);
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.updateOrder=BpUpdateOrder.SEQUENTIAL;
  prm.schedule=BpScheduleType.TREE_LIKE;
  prm.maxIterations=2;
  prm.s=s;
  prm.normalizeMessages=true;
  testGradientByFiniteDifferences(fg,goldConfig,prm);
}
Program: 131182
Project: 131182
Buggy source:
@Test public void testErmaGradientWithGlobalExplicitFactor(){
  FgAndVars fgv=FactorGraphTest.getLinearChainFgWithVars();
  FactorGraph fg=fgv.fg;
  ExplicitFactor loop0=new GlobalExplicitFactor(new VarSet(fgv.t0,fgv.t1,fgv.t2));
  loop0.setValue(0,2);
  loop0.setValue(1,3);
  loop0.setValue(2,5);
  loop0.setValue(3,7);
  loop0.setValue(4,11);
  loop0.setValue(5,15);
  loop0.setValue(6,19);
  loop0.setValue(7,23);
  fg.addFactor(loop0);
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(fgv.w0,0);
  goldConfig.put(fgv.w1,1);
  goldConfig.put(fgv.w2,0);
  goldConfig.put(fgv.t1,1);
  goldConfig.put(fgv.t2,1);
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.updateOrder=BpUpdateOrder.PARALLEL;
  prm.maxIterations=10;
  prm.s=s;
  prm.normalizeMessages=true;
  testGradientByFiniteDifferences(fg,goldConfig,prm);
}

Fixed version (ground truth):
@Test public void testErmaGradientWithGlobalExplicitFactor(){
  FgAndVars fgv=FactorGraphsForTests.getLinearChainFgWithVars();
  FactorGraph fg=fgv.fg;
  ExplicitFactor loop0=new GlobalExplicitFactor(new VarSet(fgv.t0,fgv.t1,fgv.t2));
  loop0.setValue(0,2);
  loop0.setValue(1,3);
  loop0.setValue(2,5);
  loop0.setValue(3,7);
  loop0.setValue(4,11);
  loop0.setValue(5,15);
  loop0.setValue(6,19);
  loop0.setValue(7,23);
  fg.addFactor(loop0);
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(fgv.w0,0);
  goldConfig.put(fgv.w1,1);
  goldConfig.put(fgv.w2,0);
  goldConfig.put(fgv.t1,1);
  goldConfig.put(fgv.t2,1);
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.updateOrder=BpUpdateOrder.PARALLEL;
  prm.maxIterations=10;
  prm.s=s;
  prm.normalizeMessages=true;
  testGradientByFiniteDifferences(fg,goldConfig,prm);
}
Program: 131183
Project: 131183
Buggy source:
@Test public void testErmaGradientLinearChain(){
  FgAndVars fgv=FactorGraphTest.getLinearChainFgWithVars();
  FactorGraph fg=fgv.fg;
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(fgv.w0,0);
  goldConfig.put(fgv.w1,1);
  goldConfig.put(fgv.w2,0);
  goldConfig.put(fgv.t1,1);
  goldConfig.put(fgv.t2,1);
  testGradientByFiniteDifferences(fg,goldConfig);
}

Fixed version (ground truth):
@Test public void testErmaGradientLinearChain(){
  FgAndVars fgv=FactorGraphsForTests.getLinearChainFgWithVars();
  FactorGraph fg=fgv.fg;
  VarConfig goldConfig=new VarConfig();
  goldConfig.put(fgv.w0,0);
  goldConfig.put(fgv.w1,1);
  goldConfig.put(fgv.w2,0);
  goldConfig.put(fgv.t1,1);
  goldConfig.put(fgv.t2,1);
  testGradientByFiniteDifferences(fg,goldConfig);
}
Program: 131184
Project: 131184
Buggy source:
private void testOneVarHelper(Algebra s){
  FactorGraph fg=new FactorGraph();
  Var t0=new Var(VarType.PREDICTED,2,"String_Node_Str",null);
  ExplicitFactor emit0=new ExplicitFactor(new VarSet(t0));
  emit0.setValue(0,1.1);
  emit0.setValue(1,1.9);
  fg.addFactor(emit0);
  for (  Factor f : fg.getFactors()) {
    ((VarTensor)f).convertRealToLog();
  }
  BruteForceInferencer bf=new BruteForceInferencer(fg,s);
  bf.run();
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.maxIterations=10;
  prm.s=s;
  ErmaBp bp=new ErmaBp(fg,prm);
  bp.run();
  assertEqualMarginals(fg,bf,bp);
}

Fixed version (ground truth):
private void testOneVarHelper(Algebra s){
  FactorGraph fg=FactorGraphsForTests.getOneVarFg();
  BruteForceInferencer bf=new BruteForceInferencer(fg,s);
  bf.run();
  ErmaBpPrm prm=new ErmaBpPrm();
  prm.maxIterations=10;
  prm.s=s;
  ErmaBp bp=new ErmaBp(fg,prm);
  bp.run();
  assertEqualMarginals(fg,bf,bp);
}
Program: 131185
Project: 131185
Buggy source:
@Before public void setUp(){
  FgAndVars fgv=FactorGraphTest.getLinearChainFgWithVars();
  VarTensor[] xsa=new VarTensor[3];
  xsa[0]=new VarTensor(fgv.emit0);
  xsa[1]=new VarTensor(fgv.emit1);
  xsa[2]=new VarTensor(fgv.tran0);
  MVecArray<VarTensor> xs=new MVecArray<>(xsa);
  for (int a=0; a < xs.dim(); a++) {
    xs.get(a).exp();
  }
  modIn=new Identity<MVecArray<VarTensor>>(xs);
}

Fixed version (ground truth):
@Before public void setUp(){
  FgAndVars fgv=FactorGraphsForTests.getLinearChainFgWithVars();
  VarTensor[] xsa=new VarTensor[3];
  xsa[0]=new VarTensor(fgv.emit0);
  xsa[1]=new VarTensor(fgv.emit1);
  xsa[2]=new VarTensor(fgv.tran0);
  MVecArray<VarTensor> xs=new MVecArray<>(xsa);
  for (int a=0; a < xs.dim(); a++) {
    xs.get(a).exp();
  }
  modIn=new Identity<MVecArray<VarTensor>>(xs);
}
Program: 131186
Project: 131186
Buggy source:
public void testUpdatingOfTemplates(){
  FactorGraph fg=FactorGraphTest.getLinearChainGraph();
  VarConfig vc=new VarConfig();
  for (  Var v : fg.getVars()) {
    vc.put(v,0);
  }
  FactorTemplateList fts=new FactorTemplateList();
  LFgExample ex=new LabeledFgExample(fg,vc,new SimpleVCObsFeatureExtractor(fts),fts);
  FgExampleMemoryStore data=new FgExampleMemoryStore();
  data.add(ex);
  System.out.println(fts);
  assertEquals(2,fts.size());
  assertEquals(2,fts.getNumObsFeats());
}

Fixed version (ground truth):
public void testUpdatingOfTemplates(){
  FactorGraph fg=FactorGraphsForTests.getLinearChainGraph();
  VarConfig vc=new VarConfig();
  for (  Var v : fg.getVars()) {
    vc.put(v,0);
  }
  FactorTemplateList fts=new FactorTemplateList();
  LFgExample ex=new LabeledFgExample(fg,vc,new SimpleVCObsFeatureExtractor(fts),fts);
  FgExampleMemoryStore data=new FgExampleMemoryStore();
  data.add(ex);
  System.out.println(fts);
  assertEquals(2,fts.size());
  assertEquals(2,fts.getNumObsFeats());
}
Program: 131187
Project: 131187
Buggy source:
public static FactorGraph getLinearChainGraph(){
  FactorGraph fg=FactorGraphTest.getLinearChainGraph();
  return fg;
}

Fixed version (ground truth):
public static FactorGraph getLinearChainGraph(){
  FactorGraph fg=FactorGraphsForTests.getLinearChainGraph();
  return fg;
}
Program: 131189
Project: 131189
Buggy source:
@Test public void testNumParams(){
  FactorTemplateList fts=getFtl();
  ObsFeatureConjoiner ofc=new ObsFeatureConjoiner(new ObsFeatureConjoinerPrm(),fts);
  ofc.init(null);
  assertEquals((3 * 2) * 2 + 2 * 1,ofc.getNumParams());
}

Fixed version (ground truth):
@Test public void testNumParams(){
  FactorTemplateList fts=getFtl();
  ObsFeatureConjoinerPrm prm=new ObsFeatureConjoinerPrm();
  prm.featCountCutoff=-1;
  prm.includeUnsupportedFeatures=true;
  ObsFeatureConjoiner ofc=new ObsFeatureConjoiner(prm,fts);
  ofc.init(null);
  assertEquals((3 * 2) * 2 + 2 * 1,ofc.getNumParams());
}
Program: 131191
Project: 131191
Buggy source:
/** 
 * Computes the expected feature counts for a factor graph, and adds them to the gradient after scaling them.
 * @param ex 
 * @param inferencer The inferencer for a clamped factor graph, which has already been run.
 * @param multiplier The value which the expected features will be multiplied by.
 * @param gradient The OUTPUT gradient vector to which the scaled expected features will be added.
 * @param factorId The id of the factor.
 * @param featCache The feature cache for the clamped factor graph, on which the inferencer was run.
 */
private void addExpectedFeatureCounts(FactorGraph fg,LFgExample ex,FgInferencer inferencer,double multiplier,IFgModel gradient){
  for (int factorId=0; factorId < fg.getNumFactors(); factorId++) {
    Factor f=fg.getFactor(factorId);
    if (f instanceof GlobalFactor) {
      ((GlobalFactor)f).addExpectedFeatureCounts(gradient,multiplier,inferencer,factorId);
    }
 else {
      VarTensor marg=inferencer.getMarginalsForFactorId(factorId);
      f.addExpectedFeatureCounts(gradient,marg,multiplier);
    }
  }
}

Fixed version (ground truth):
/** 
 * Computes the expected feature counts for a factor graph, and adds them to the gradient after scaling them.
 * @param fg The factor graph.
 * @param inferencer The inferencer for a clamped factor graph, which has already been run.
 * @param multiplier The value which the expected features will be multiplied by.
 * @param gradient The OUTPUT gradient vector to which the scaled expected features will be added.
 */
private static void addExpectedFeatureCounts(FactorGraph fg,FgInferencer inferencer,double multiplier,IFgModel gradient){
  for (int factorId=0; factorId < fg.getNumFactors(); factorId++) {
    Factor f=fg.getFactor(factorId);
    if (f instanceof GlobalFactor) {
      ((GlobalFactor)f).addExpectedFeatureCounts(gradient,multiplier,inferencer,factorId);
    }
 else {
      VarTensor marg=inferencer.getMarginalsForFactorId(factorId);
      f.addExpectedFeatureCounts(gradient,marg,multiplier);
    }
  }
}
Program: 131192
Project: 131192
Buggy source:
public void accumWithException(FgModel model,int i,Accumulator ac){
  Timer t0=new Timer();
  t0.start();
  LFgExample ex=data.get(i);
  Timer t=new Timer();
  t.reset();
  t.start();
  FactorGraph fgLat=ex.getFgLat();
  FactorGraph fgLatPred=ex.getFgLatPred();
  fgLat.updateFromModel(model);
  fgLatPred.updateFromModel(model);
  t.stop();
  updTimer.add(t);
  t.reset();
  t.start();
  FgInferencer infLat=infFactory.getInferencer(fgLat);
  FgInferencer infLatPred=infFactory.getInferencer(fgLatPred);
  t.stop();
  infTimer.add(t);
  t.reset();
  t.start();
  infLat.run();
  infLatPred.run();
  t.stop();
  infTimer.add(t);
  if (ac.accumValue) {
    t.reset();
    t.start();
    if (useMseForValue) {
      ac.value+=-getMseLoss(ex,infLatPred);
    }
 else {
      ac.value+=getValue(ex,fgLat,infLat,fgLatPred,infLatPred,i);
    }
    t.stop();
    valTimer.add(t);
  }
  if (ac.accumGradient) {
    t.reset();
    t.start();
    addGradient(ex,ac.getGradient(),fgLat,infLat,fgLatPred,infLatPred);
    t.stop();
    gradTimer.add(t);
  }
  if (ac.accumWeight) {
    ac.weight+=ex.getWeight();
  }
  if (ac.accumLoss) {
  }
  t0.stop();
  tot.add(t0);
}

Fixed version (ground truth):
public void accumWithException(FgModel model,int i,Accumulator ac){
  Timer t0=new Timer();
  t0.start();
  LFgExample ex=data.get(i);
  Timer t=new Timer();
  t.reset();
  t.start();
  FactorGraph fgLat=ex.getFgLat();
  FactorGraph fgLatPred=ex.getFgLatPred();
  fgLat.updateFromModel(model);
  fgLatPred.updateFromModel(model);
  t.stop();
  updTimer.add(t);
  t.reset();
  t.start();
  FgInferencer infLat=infFactory.getInferencer(fgLat);
  FgInferencer infLatPred=infFactory.getInferencer(fgLatPred);
  t.stop();
  infTimer.add(t);
  t.reset();
  t.start();
  infLat.run();
  infLatPred.run();
  t.stop();
  infTimer.add(t);
  if (ac.accumValue) {
    t.reset();
    t.start();
    if (useMseForValue) {
      ac.value+=-getMseLoss(infLatPred,ex.getGoldConfig(),ex.getWeight());
    }
 else {
      ac.value+=getValue(fgLat,infLat,fgLatPred,infLatPred,i,ex.getGoldConfig(),ex.getWeight());
    }
    t.stop();
    valTimer.add(t);
  }
  if (ac.accumGradient) {
    t.reset();
    t.start();
    addGradient(fgLat,infLat,fgLatPred,infLatPred,ex.getWeight(),ac.getGradient());
    t.stop();
    gradTimer.add(t);
  }
  if (ac.accumWeight) {
    ac.weight+=ex.getWeight();
  }
  if (ac.accumLoss) {
  }
  t0.stop();
  tot.add(t0);
}
Program: 131193
Project: 131193
Buggy source:
/** 
 * Adds the gradient of the marginal conditional log-likelihood for a particular example to the gradient vector.
 * @param gradient The gradient vector to which this example's contributionis added.
 * @param fgLat The factor graph with the predicted and observed variables clamped. 
 * @param infLat The inferencer for fgLat.
 * @param fgLatPred The factor graph with the observed variables clamped. 
 * @param infLatPred The inferencer for fgLatPred.
 * @param i The data example.
 */
public void addGradient(LFgExample ex,IFgModel gradient,FactorGraph fgLat,FgInferencer infLat,FactorGraph fgLatPred,FgInferencer infLatPred){
  addExpectedFeatureCounts(fgLat,ex,infLat,1.0 * ex.getWeight(),gradient);
  addExpectedFeatureCounts(fgLatPred,ex,infLatPred,-1.0 * ex.getWeight(),gradient);
}

Fixed version (ground truth):
/** 
 * Adds the gradient of the marginal conditional log-likelihood for a particular example to the gradient vector.
 * @param fgLat The factor graph with the predicted and observed variables clamped. 
 * @param infLat The inferencer for fgLat.
 * @param fgLatPred The factor graph with the observed variables clamped. 
 * @param infLatPred The inferencer for fgLatPred.
 * @param weight The weight of the training example.
 * @param gradient The OUTPUT gradient vector to which this example's contributionis added.
 */
private static void addGradient(FactorGraph fgLat,FgInferencer infLat,FactorGraph fgLatPred,FgInferencer infLatPred,double weight,IFgModel gradient){
  addExpectedFeatureCounts(fgLat,infLat,1.0 * weight,gradient);
  addExpectedFeatureCounts(fgLatPred,infLatPred,-1.0 * weight,gradient);
}
Program: 131194
Project: 131194
Buggy source:
/** 
 * Gets the "expected" feature counts. 
 */
public FeatureVector getExpectedFeatureCounts(FgModel model,double[] params){
  model.updateModelFromDoubles(params);
  FgModel feats=model.getDenseCopy();
  feats.zero();
  for (int i=0; i < data.size(); i++) {
    LFgExample ex=data.get(i);
    FactorGraph fgLatPred=ex.getFgLatPred();
    fgLatPred.updateFromModel(model);
    FgInferencer infLatPred=infFactory.getInferencer(fgLatPred);
    infLatPred.run();
    addExpectedFeatureCounts(fgLatPred,ex,infLatPred,1.0 * ex.getWeight(),feats);
  }
  double[] f=new double[model.getNumParams()];
  feats.updateDoublesFromModel(f);
  return new FeatureVector(f);
}

Fixed version (ground truth):
/** 
 * Gets the "expected" feature counts. 
 */
public FeatureVector getExpectedFeatureCounts(FgModel model,double[] params){
  model.updateModelFromDoubles(params);
  FgModel feats=model.getDenseCopy();
  feats.zero();
  for (int i=0; i < data.size(); i++) {
    LFgExample ex=data.get(i);
    FactorGraph fgLatPred=ex.getFgLatPred();
    fgLatPred.updateFromModel(model);
    FgInferencer infLatPred=infFactory.getInferencer(fgLatPred);
    infLatPred.run();
    addExpectedFeatureCounts(fgLatPred,infLatPred,1.0 * ex.getWeight(),feats);
  }
  double[] f=new double[model.getNumParams()];
  feats.updateDoublesFromModel(f);
  return new FeatureVector(f);
}
Program: 131195
Project: 131195
Buggy source:
private double getMseLoss(LFgExample ex,FgInferencer infLatPred){
  MseMarginalEvaluator mse=new MseMarginalEvaluator();
  return mse.evaluate(ex.getGoldConfig(),infLatPred);
}

Fixed version (ground truth):
/** 
 * Gets the mean-squared error of the i'th example for the given model parameters.
 * @param infLatPred The inferencer for fgLatPred.
 * @param goldConfig The assignment to the predicted variables.
 * @param weight The weight of this training example.
 * @return The weighted MSE.
 */
private static double getMseLoss(FgInferencer infLatPred,VarConfig goldConfig,double weight){
  MseMarginalEvaluator mse=new MseMarginalEvaluator();
  return mse.evaluate(goldConfig,infLatPred) * weight;
}
Program: 131196
Project: 131196
Buggy source:
/** 
 * Gets the "observed" feature counts. 
 */
public FeatureVector getObservedFeatureCounts(FgModel model,double[] params){
  model.updateModelFromDoubles(params);
  FgModel feats=model.getDenseCopy();
  feats.zero();
  for (int i=0; i < data.size(); i++) {
    LFgExample ex=data.get(i);
    FactorGraph fgLat=ex.getFgLat();
    fgLat.updateFromModel(model);
    FgInferencer infLat=infFactory.getInferencer(fgLat);
    infLat.run();
    addExpectedFeatureCounts(fgLat,ex,infLat,1.0 * ex.getWeight(),feats);
  }
  double[] f=new double[model.getNumParams()];
  feats.updateDoublesFromModel(f);
  return new FeatureVector(f);
}

Fixed version (ground truth):
/** 
 * Gets the "observed" feature counts. 
 */
public FeatureVector getObservedFeatureCounts(FgModel model,double[] params){
  model.updateModelFromDoubles(params);
  FgModel feats=model.getDenseCopy();
  feats.zero();
  for (int i=0; i < data.size(); i++) {
    LFgExample ex=data.get(i);
    FactorGraph fgLat=ex.getFgLat();
    fgLat.updateFromModel(model);
    FgInferencer infLat=infFactory.getInferencer(fgLat);
    infLat.run();
    addExpectedFeatureCounts(fgLat,infLat,1.0 * ex.getWeight(),feats);
  }
  double[] f=new double[model.getNumParams()];
  feats.updateDoublesFromModel(f);
  return new FeatureVector(f);
}
Program: 131197
Project: 131197
Buggy source:
/** 
 * Increments the current state of \a forVars (prefix) and returns linear index of the current state of indexVars. 
 */
public int next(){
  int curIndex=_index;
  if (_index >= 0) {
    int i=0;
    while (i < _state.length) {
      _index+=_sum[i];
      if (++_state[i] < _ranges[i])       break;
      _index-=_sum[i] * _ranges[i];
      _state[i]=0;
      i++;
    }
    if (i == _state.length)     _index=-1;
  }
  return curIndex;
}

Fixed version (ground truth):
/** 
 * Increments the current state of \a forVars (prefix) and returns linear index of the current state of indexVars. 
 */
public int next(){
  int curIndex=_index;
  if (_index >= 0) {
    int i=_state.length - 1;
    while (i >= 0) {
      _index+=_sum[i];
      if (++_state[i] < _ranges[i])       break;
      _index-=_sum[i] * _ranges[i];
      _state[i]=0;
      i--;
    }
    if (i == -1)     _index=-1;
  }
  return curIndex;
}
Program: 131198
Project: 131198
Buggy source:
/** 
 * Construct IndexFor object from \a indexVars and \a forVars. 
 */
public IndexFor(final VarSet indexVars,final VarSet forVars){
  long sum=1;
  _state=new int[forVars.size()];
  _ranges=new int[forVars.size()];
  _sum=new long[forVars.size()];
  int cur=0;
  Iterator<Var> jIter=forVars.iterator();
  Iterator<Var> iIter=indexVars.iterator();
  Var j=jIter.hasNext() ? jIter.next() : null;
  for (Var i=iIter.hasNext() ? iIter.next() : null; i != null; i=iIter.hasNext() ? iIter.next() : null) {
    for (; j != null && j.compareTo(i) <= 0; j=jIter.hasNext() ? jIter.next() : null) {
      _ranges[cur]=j.getNumStates();
      _sum[cur]=(i.equals(j)) ? sum : 0;
      cur++;
    }
    sum*=i.getNumStates();
  }
  for (; j != null; j=jIter.hasNext() ? jIter.next() : null) {
    _ranges[cur]=j.getNumStates();
    _sum[cur]=0l;
    cur++;
  }
  _index=0;
  assert(cur == _state.length);
}

Fixed version (ground truth):
/** 
 * Construct IndexFor object from \a indexVars and \a forVars. 
 */
public IndexFor(final VarSet indexVars,final VarSet forVars){
  long sum=1;
  _state=new int[forVars.size()];
  _ranges=new int[forVars.size()];
  _sum=new long[forVars.size()];
  for (int ii=0; ii < indexVars.size(); ii++) {
    Var i=indexVars.get(ii);
    sum*=i.getNumStates();
  }
  int cur=0;
  int jj=0;
  for (int ii=0; ii < indexVars.size(); ii++) {
    Var i=indexVars.get(ii);
    sum/=i.getNumStates();
    for (; jj < forVars.size() && forVars.get(jj).compareTo(i) <= 0; jj++) {
      Var j=forVars.get(jj);
      _ranges[cur]=j.getNumStates();
      _sum[cur]=(i.equals(j)) ? sum : 0;
      cur++;
    }
  }
  for (; jj < forVars.size(); jj++) {
    Var j=forVars.get(jj);
    _ranges[cur]=j.getNumStates();
    _sum[cur]=0l;
    cur++;
  }
  _index=0;
  assert(cur == _state.length);
}
Program: 131199
Project: 131199
Buggy source:
/** 
 * Gets the index of the configuration of the variables where all those in config  have the specified value, and all other variables in vars have the zero state.
 * @param vars The variable set over which to iterate.
 * @param config An assignment to a subset of vars.
 * @return The configuration index.
 */
public static int getConfigIndex(VarSet vars,VarConfig config){
  int configIndex=0;
  int numStatesProd=1;
  for (  Var var : vars) {
    int state=config.getState(var,0);
    configIndex+=state * numStatesProd;
    numStatesProd*=var.getNumStates();
  }
  return configIndex;
}

Fixed version (ground truth):
/** 
 * Gets the index of the configuration of the variables where all those in config  have the specified value, and all other variables in vars have the zero state.
 * @param vars The variable set over which to iterate.
 * @param config An assignment to a subset of vars.
 * @return The configuration index.
 */
public static int getConfigIndex(VarSet vars,VarConfig config){
  int configIndex=0;
  int numStatesProd=1;
  for (int v=vars.size() - 1; v >= 0; v--) {
    Var var=vars.get(v);
    int state=config.getState(var,0);
    configIndex+=state * numStatesProd;
    numStatesProd*=var.getNumStates();
  }
  return configIndex;
}
Program: 131200
Project: 131200
Buggy source:
/** 
 * Gets the index of this configuration for the given variable set. This is used to provide a unique index for each setting of the the variables in a VarSet.
 */
public int getConfigIndexOfSubset(VarSet vars){
  int configIndex=0;
  int numStatesProd=1;
  for (  Var var : vars) {
    int state=config.get(var);
    configIndex+=state * numStatesProd;
    numStatesProd*=var.getNumStates();
    if (numStatesProd <= 0) {
      throw new IllegalStateException("String_Node_Str" + numStatesProd);
    }
  }
  return configIndex;
}

Fixed version (ground truth):
/** 
 * Gets the index of this configuration for the given variable set. This is used to provide a unique index for each setting of the the variables in a VarSet.
 */
public int getConfigIndexOfSubset(VarSet vars){
  int configIndex=0;
  int numStatesProd=1;
  for (int v=vars.size() - 1; v >= 0; v--) {
    Var var=vars.get(v);
    int state=config.get(var);
    configIndex+=state * numStatesProd;
    numStatesProd*=var.getNumStates();
    if (numStatesProd <= 0) {
      throw new IllegalStateException("String_Node_Str" + numStatesProd);
    }
  }
  return configIndex;
}
Program: 131201
Project: 131201
Buggy source:
/** 
 * Returns a string representation of the VarTensor, which (optionally) excludes zero-valued rows. 
 */
public String toString(boolean sparse){
  StringBuilder sb=new StringBuilder();
  sb.append("String_Node_Str");
  for (  Var var : vars) {
    String name=var.getName();
    name=name.substring(Math.max(0,name.length() - 5));
    sb.append(String.format("String_Node_Str",name));
  }
  sb.append(String.format("String_Node_Str","String_Node_Str"));
  for (int c=0; c < vars.calcNumConfigs(); c++) {
    if (!sparse || values[c] != 0.0) {
      int[] states=vars.getVarConfigAsArray(c);
      for (      int state : states) {
        sb.append(String.format("String_Node_Str",state));
      }
      sb.append(String.format("String_Node_Str",values[c]));
    }
  }
  sb.append("String_Node_Str");
  return sb.toString();
}

Fixed version (ground truth):
/** 
 * Returns a string representation of the VarTensor, which (optionally) excludes zero-valued rows. 
 */
public String toString(boolean sparse){
  StringBuilder sb=new StringBuilder();
  sb.append("String_Node_Str");
  for (  Var var : vars) {
    String name=var.getName();
    name=name.substring(Math.max(0,name.length() - 5));
    sb.append(String.format("String_Node_Str",name));
  }
  sb.append(String.format("String_Node_Str","String_Node_Str"));
  for (int c=0; c < vars.calcNumConfigs(); c++) {
    if (!sparse || values[c] != 0.0) {
      int[] states=vars.getVarConfigAsArray(c);
      for (int i=0; i < states.length; i++) {
        int state=states[i];
        Var v=vars.get(i);
        if (v.getStateNames() != null) {
          sb.append(String.format("String_Node_Str",v.getStateNames().get(state)));
        }
 else {
          sb.append(String.format("String_Node_Str",state));
        }
      }
      sb.append(String.format("String_Node_Str",values[c]));
    }
  }
  sb.append("String_Node_Str");
  return sb.toString();
}
Program: 131202
Project: 131202
Buggy source:
@Test public void testGlobalExplicitFactor() throws IOException {
  FactorGraph fg=getThreeConnectedComponentsFactorGraph();
  VarSet allVars=new VarSet(fg.getVars().toArray(new Var[0]));
  ExplicitFactor gf=new GlobalExplicitFactor(allVars);
  gf.setValue(0,2);
  gf.setValue(1,3);
  gf.setValue(2,5);
  gf.setValue(3,7);
  gf.setValue(4,11);
  gf.setValue(5,15);
  gf.setValue(6,19);
  gf.setValue(7,23);
  gf.convertRealToLog();
  fg.addFactor(gf);
  Algebra s=LogSemiring.LOG_SEMIRING;
  BruteForceInferencer bf=new BruteForceInferencer(fg,s);
  bf.run();
  ErmaBp bp=runDefaultBpForAcyclic(s,fg);
  System.out.println(bp.isConverged());
  assertEqualMarginals(fg,bf,bp);
}

Fixed version (ground truth):
@Test public void testGlobalExplicitFactor() throws IOException {
  FactorGraph fg=getThreeConnectedComponentsFactorGraph();
  VarSet allVars=new VarSet(fg.getVars().toArray(new Var[0]));
  ExplicitFactor gf=new GlobalExplicitFactor(allVars);
  gf.setValue(0,2);
  gf.setValue(1,3);
  gf.setValue(2,5);
  gf.setValue(3,7);
  gf.setValue(4,11);
  gf.setValue(5,15);
  gf.setValue(6,19);
  gf.setValue(7,23);
  gf.convertRealToLog();
  fg.addFactor(gf);
  Algebra s=LogSemiring.LOG_SEMIRING;
  BruteForceInferencer bf=new BruteForceInferencer(fg,s);
  bf.run();
  ErmaBp bp=runDefaultBpForAcyclic(s,fg);
  System.out.println(bp.isConverged());
  assertEqualMarginals(fg,bf,bp,1e-12);
}