Locates the location within the changelog where the injection should occur.
Also determines if the injection is a replacement or an addition.
506601
private function locateInjectionIndex(array $contents, string $type) : stdClass
    {
        $action = (object) [
            'index' => null,
            'type' => self::ACTION_NOT_FOUND,
        ];

        foreach ($contents as $index => $line) {
            if (! preg_match('/^### ' . $type . '/i', $line)) {
                continue;
            }

            $action->index = $index + 2;
            $action->type = preg_match('/^- Nothing/', $contents[$action->index])
                ? self::ACTION_REPLACE
                : self::ACTION_INJECT;
            break;
        }

        return $action;
    }
172694
def locate_run(output, target, no_newline):
    
    from .config import ConfigStore
    cfstore = ConfigStore()
    path = getattr(cfstore, "{0}_path".format(target))
    output.write(path)
    if not no_newline:
        output.write("\n")
1294092
function getLocation() {
    var trace = stackTrace.get();

    //trace.forEach(function(e){
    //    console.log('mytrace: ' + e.getFileName());
    //});

    //use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger
    //  However, component loggers put an extra level in, so search down until the location is not 'logger'
    //  There's code to search a long way down the stack, but in practice the next (3) will be hit and used
    //    since its name is not logger.
    var idx = 2;
    var modNm = 'logger';
    var rmodNm = null;
    var skip = ['logger', 'logger.js'];
    while ((_.includes(skip, modNm)) && trace.length > idx) {
        var fpath = trace[idx].getFileName();
        ++idx;
        if (fpath.slice(0, 'native'.length) === 'native') {
            continue; // skip native modules
        }
        modNm = null;
        var mod = null;
        try {
            mod = require(fpath);
        } catch (err) {
            // do nothing here, it's checked later
        }
        if (mod) { //__id is injected into services by the loader
            if (!mod.__id) {
                modNm = _.split(fpath, '/').pop();
                rmodNm = modNm;
            } else {
                modNm = mod.__id;
                if (modNm !== null) {
                    rmodNm = modNm;
                }
            }
        } else {
            modNm = _.split(fpath, '/').pop();
            rmodNm = modNm;
        }

    }
    return rmodNm;
}
457468
function() {
    let addon = this._findCoveredAddon();
    if (addon) {
      const addonDir = path.join(this.project.root, 'addon');
      const addonTestSupportDir = path.join(this.project.root, 'addon-test-support');
      return concat(
        this._getIncludesForDir(addonDir, addon.name),
        this._getIncludesForDir(addonTestSupportDir, `${addon.name}/test-support`)
      );
    }
  }
670728
function getOriginalPositionDetailsFor(
  lineNumber,
  columnNumber,
  moduleIds,
  context,
) {
  var moduleLineOffset = 0;
  var metadata = context.segments[moduleIds.segmentId];
  const {localId} = moduleIds;
  if (localId != null) {
    const {moduleOffsets} = metadata;
    if (!moduleOffsets) {
      throw new Error(
        'Module ID given for a source map that does not have ' +
          'an x_facebook_offsets field',
      );
    }
    if (moduleOffsets[localId] == null) {
      throw new Error('Unknown module ID: ' + localId);
    }
    moduleLineOffset = moduleOffsets[localId];
  }
  const original = metadata.consumer.originalPositionFor({
    line: Number(lineNumber) + moduleLineOffset,
    column: Number(columnNumber),
  });
  if (metadata.sourceFunctionsConsumer) {
    original.functionName =
      metadata.sourceFunctionsConsumer.functionNameFor(original) || null;
  } else {
    original.functionName = null;
  }
  return original;
}
653760
def find_insertion_line(self, code):
        """"""
        match = re.search(r'^(def|class)\s+', code)
        if match is not None:
            code = code[:match.start()]
        try:
            pymodule = libutils.get_string_module(self.project, code)
        except exceptions.ModuleSyntaxError:
            return 1
        testmodname = '__rope_testmodule_rope'
        importinfo = importutils.NormalImport(((testmodname, None),))
        module_imports = importutils.get_module_imports(self.project,
                                                        pymodule)
        module_imports.add_import(importinfo)
        code = module_imports.get_changed_source()
        offset = code.index(testmodname)
        lineno = code.count('\n', 0, offset) + 1
        return lineno
1146089
def at_line(self, line: FileLine) -> Iterator[InsertionPoint]:
        
        logger.debug("finding insertion points at line: %s", str(line))
        filename = line.filename  # type: str
        line_num = line.num  # type: int
        for ins in self.in_file(filename):
            if line_num == ins.location.line:
                logger.debug("found insertion point at line [%s]: %s",
                             str(line), ins)
                yield ins
222345
protected void reloadChangesInfoAfterUC(ImportNodeData currentNodeInfo, String identifier)
      throws PathNotFoundException, IllegalPathException, RepositoryException
   {
      reloadChangesInfoAfterUC(getParent(), currentNodeInfo, identifier);
   }
225704
Changes findChanges(InvocationInfo invocationInfo) {
    /* Methods with one or fewer parameters cannot possibly have a swap */
    if (invocationInfo.formalParameters().size() <= 1) {
      return Changes.empty();
    }

    /* Sometimes we don't have enough actual parameters. This seems to happen sometimes with calls
     * to super and javac finds two parameters arg0 and arg1 and no arguments */
    if (invocationInfo.actualParameters().size() < invocationInfo.formalParameters().size()) {
      return Changes.empty();
    }

    ImmutableList<Parameter> formals =
        Parameter.createListFromVarSymbols(invocationInfo.formalParameters());
    ImmutableList<Parameter> actuals =
        Parameter.createListFromExpressionTrees(
            invocationInfo.actualParameters().subList(0, invocationInfo.formalParameters().size()));

    Costs costs = new Costs(formals, actuals);

    /* Set the distance between a pair to Inf if not assignable */
    costs
        .viablePairs()
        .filter(ParameterPair::isAlternativePairing)
        .filter(p -> !p.actual().isAssignableTo(p.formal(), invocationInfo.state()))
        .forEach(p -> costs.invalidatePair(p));

    /* If there are no formal parameters which are assignable to any alternative actual parameters
    then we can stop without trying to look for permutations */
    if (costs.viablePairs().noneMatch(ParameterPair::isAlternativePairing)) {
      return Changes.empty();
    }

    /* Set the lexical distance between pairs */
    costs.viablePairs().forEach(p -> costs.updatePair(p, distanceFunction().apply(p)));

    Changes changes = costs.computeAssignments();

    if (changes.isEmpty()) {
      return changes;
    }

    /* Only keep this change if all of the heuristics match */
    for (Heuristic heuristic : heuristics()) {
      if (!heuristic.isAcceptableChange(
          changes, invocationInfo.tree(), invocationInfo.symbol(), invocationInfo.state())) {
        return Changes.empty();
      }
    }
    return changes;
  }
1359169
def location(self):
        """"""
        location, _, revision = self.expression.partition('#')
        return location if location and revision else None
1060525
function findInsertLocation(matches, score) {
	const idx = binarySearch(matches, 0, matches.length, score);

	if(idx < 0) {
		// If the score was not found
		return - idx - 1;
	}

	/*
		* Something with the same score was found, make sure this item is
		* added after all previous items with the same score.
		*/
	for(let i=idx+1; i<matches.length; i++) {
		if(matches[i].score < score) return i;
	}

	return matches.length;
}
1059978
def fix_location_tag(dom):
    
    location = dom.match(
        "mods:mods",
        "mods:location",
    )

    # if no location tag found, there is nothing to be fixed
    if not location:
        return
    location = first(location)

    # fix only <mods:location> containing <mods:physicalLocation> tags
    if not location.find("mods:physicalLocation"):
        return

    url = location.find("mods:url", {"usage": "primary display"})

    # parse URL
    if url:
        url = first(url).getContent()
    else:
        urls = filter(
            lambda x: x.getContent(),
            location.find("mods:url")
        )

        if not urls:
            return

        url_tag = max(urls, key=lambda x: len(x.getContent()))
        url = url_tag.getContent()

    # replace the code with new tag
    replacer = dhtmlparser.parseString("""
  <mods:location>
    <mods:holdingSimple>
      <mods:copyInformation>
        <mods:electronicLocator>""" + url + """</mods:electronicLocator>
      </mods:copyInformation>
    </mods:holdingSimple>
  </mods:location>
    """)

    location.replaceWith(
        first(replacer.find("mods:location"))
    )

    dhtmlparser.makeDoubleLinked(dom)
1311636
public void addLocation(TaintLocation location, boolean isKnownTaintSource) {
        Objects.requireNonNull(location, "location is null");
        if (isKnownTaintSource) {
            taintLocations.add(location);
        } else {
            unknownLocations.add(location);
        }
    }
704896
private Node tryReplaceIf(Node n) {

    Node next = null;
    for (Node child = n.getFirstChild();
         child != null; child = next){
      next = child.getNext();
      if (child.isIf()){
        Node cond = child.getFirstChild();
        Node thenBranch = cond.getNext();
        Node elseBranch = thenBranch.getNext();
        Node nextNode = child.getNext();

        if (nextNode != null && elseBranch == null
            && isReturnBlock(thenBranch)
            && nextNode.isIf()) {
          Node nextCond = nextNode.getFirstChild();
          Node nextThen = nextCond.getNext();
          Node nextElse = nextThen.getNext();
          if (thenBranch.isEquivalentToTyped(nextThen)) {
            // Transform
            //   if (x) return 1; if (y) return 1;
            // to
            //   if (x||y) return 1;
            child.detach();
            child.detachChildren();
            Node newCond = new Node(Token.OR, cond);
            nextNode.replaceChild(nextCond, newCond);
            newCond.addChildToBack(nextCond);
            reportChangeToEnclosingScope(newCond);
          } else if (nextElse != null
              && thenBranch.isEquivalentToTyped(nextElse)) {
            // Transform
            //   if (x) return 1; if (y) foo() else return 1;
            // to
            //   if (!x&&y) foo() else return 1;
            child.detach();
            child.detachChildren();
            Node newCond = new Node(Token.AND,
                IR.not(cond).srcref(cond));
            nextNode.replaceChild(nextCond, newCond);
            newCond.addChildToBack(nextCond);
            reportChangeToEnclosingScope(newCond);
          }
        } else if (nextNode != null && elseBranch == null
            && isReturnBlock(thenBranch) && isReturnExpression(nextNode)) {
          Node thenExpr = null;
          // if(x)return; return 1 -> return x?void 0:1
          if (isReturnExpressBlock(thenBranch)) {
            thenExpr = getBlockReturnExpression(thenBranch);
            thenExpr.detach();
          } else {
            thenExpr = NodeUtil.newUndefinedNode(child);
          }

          Node elseExpr = nextNode.getFirstChild();

          cond.detach();
          elseExpr.detach();

          Node returnNode = IR.returnNode(
                                IR.hook(cond, thenExpr, elseExpr)
                                    .srcref(child));
          n.replaceChild(child, returnNode);
          n.removeChild(nextNode);
          reportChangeToEnclosingScope(n);
          // everything else in the block is dead code.
          break;
        } else if (elseBranch != null && statementMustExitParent(thenBranch)) {
          child.removeChild(elseBranch);
          n.addChildAfter(elseBranch, child);
          reportChangeToEnclosingScope(n);
        }
      }
    }
    return n;
  }
686693
def __add_location(self, type, *args):
        

        if type == "directory":
            location = umbra.ui.common.store_last_browsed_path((QFileDialog.getExistingDirectory(self,
                                                                                                 "Add Directory:",
                                                                                                 RuntimeGlobals.last_browsed_path)))
        elif type == "file":
            location = umbra.ui.common.store_last_browsed_path((QFileDialog.getOpenFileName(self,
                                                                                            "Add File:",
                                                                                            RuntimeGlobals.last_browsed_path,
                                                                                            "All Files (*)")))
        elif type == "editors":
            location = self.__targets_format.format(self.__default_target)
        elif type == "include_filter":
            location = self.__filters_in_format.format(self.__default_filter_in)
        elif type == "exclude_filter":
            location = self.__filters_out_format.format(self.__default_filter_out)

        location and self.Where_lineEdit.setText(", ".join(filter(bool, (foundations.strings.to_string(
            self.Where_lineEdit.text()), location))))
1371220
function multiUpdateInLocation(queryReplacements, location) {
  location = getLocation(location);

  // if a query is there, use it, otherwise parse the search string
  const currQuery = location.query || parseQueryString(location.search);

  const newQuery = {
    ...currQuery,
    ...queryReplacements,
  };

  // remove if it is nully or an empty string when encoded
  Object.keys(queryReplacements).forEach(queryParam => {
    const encodedValue = queryReplacements[queryParam];
    if (encodedValue == null || encodedValue === '') {
      delete newQuery[queryParam];
    }
  });

  const newLocation = mergeLocationQueryOrSearch(location, newQuery);

  // remove the key from the location
  delete newLocation.key;

  return newLocation;
}
406063
private boolean findBinding(Injector injector, Class<?> type) {
        boolean found = false;
        for (Key<?> key : injector.getBindings().keySet()) {
            if (key.getTypeLiteral().getRawType().equals(type)) {
                found = true;
                break;
            }
        }
        if (!found && injector.getParent() != null) {
            return findBinding(injector.getParent(), type);
        }

        return found;
    }