Searches the graph for a sub-graph that matches the given pattern
        and returns the first match it finds.
425509
def search(self, pattern):
        
        for node in self.nodes.values():
            match, following = pattern.match(self, node)
            if match:
                return match, following
        return [], None
318212
def findBest(self, pattern):
        
        findFailedRetry = True
        while findFailedRetry:
            best_match = None
            all_matches = self.findAll(pattern)
            for match in all_matches:
                if best_match is None or best_match.getScore() < match.getScore():
                    best_match = match
            self._lastMatch = best_match
            if best_match is not None:
                break
            path = pattern.path if isinstance(pattern, Pattern) else pattern
            findFailedRetry = self._raiseFindFailed("Could not find pattern '{}'".format(path))
            if findFailedRetry:
                time.sleep(self._repeatWaitTime)
        return best_match
530671
def _matcher(self, other):
        
        if isinstance(other, CGRContainer):
            return GraphMatcher(other, self, lambda x, y: y == x, lambda x, y: y == x)
        elif isinstance(other, QueryCGRContainer):
            return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
        raise TypeError('only cgr_query-cgr or cgr_query-cgr_query possible')
638458
def find_next_matching_line(self, match_func, count=1):
        
        result = None

        for index, line in enumerate(self.lines[self.cursor_position_row + 1:]):
            if match_func(line):
                result = 1 + index
                count -= 1

            if count == 0:
                break

        return result
1316751
private String matchPatternInBuffer(Pattern pattern) {
        matchValid = false;
        matcher.usePattern(pattern);
        matcher.region(position, buf.limit());
        if (matcher.lookingAt()) {
            if (matcher.hitEnd() && (!sourceClosed)) {
                // Get more input and try again
                needInput = true;
                return null;
            }
            position = matcher.end();
            return matcher.group();
        }

        if (sourceClosed)
            return null;

        // Read more to find pattern
        needInput = true;
        return null;
    }
330206
def __extract_pattern_nodes(graph):
    
    tp_nodes = graph.subjects(RDF.type, AGORA.TriplePattern)
    for tpn in tp_nodes:
        subject = list(graph.objects(tpn, AGORA.subject)).pop()
        predicate = list(graph.objects(tpn, AGORA.predicate)).pop()
        obj = list(graph.objects(tpn, AGORA.object)).pop()
        subject_str = list(graph.objects(subject, RDFS.label)).pop().toPython()
        predicate_str = graph.qname(predicate)
        if (obj, RDF.type, AGORA.Variable) in graph:
            object_str = list(graph.objects(obj, RDFS.label)).pop().toPython()
        else:
            object_str = list(graph.objects(obj, AGORA.value)).pop().toPython()
        __plan_patterns[tpn] = '{} {} {}'.format(subject_str, predicate_str, object_str)
655671
def FindFirst(params, ctxt, scope, stream, coord, interp):
    
    global FIND_MATCHES_ITER
    FIND_MATCHES_ITER = _find_helper(params, ctxt, scope, stream, coord, interp)

    try:
        first = six.next(FIND_MATCHES_ITER)
        return first.start() + FIND_MATCHES_START_OFFSET
    except StopIteration as e:
        return -1
538832
def _subsequent_step_to_match(match_step):
    """"""
    if not isinstance(match_step.root_block, (Traverse, Recurse)):
        raise AssertionError(u'Expected Traverse root block, received: '
                             u'{} {}'.format(match_step.root_block, match_step))

    is_recursing = isinstance(match_step.root_block, Recurse)

    match_step.root_block.validate()

    traversal_command = u'.%s(\'%s\')' % (match_step.root_block.direction,
                                          match_step.root_block.edge_name)

    parts = []
    if match_step.coerce_type_block:
        coerce_type_set = match_step.coerce_type_block.target_class
        if len(coerce_type_set) != 1:
            raise AssertionError(u'Found MATCH type coercion block with more than one target class:'
                                 u' {} {}'.format(coerce_type_set, match_step))
        coerce_type_target = list(coerce_type_set)[0]
        parts.append(u'class: %s' % (coerce_type_target,))

    if is_recursing:
        # In MATCH, "$depth < 1" means "include the source vertex and its immediate neighbors."
        # Yes, the "<" is intentional -- it's not supposed to be a "<=".
        parts.append(u'while: ($depth < %d)' % (match_step.root_block.depth,))

    if match_step.where_block:
        match_step.where_block.validate()
        parts.append(u'where: (%s)' % (match_step.where_block.predicate.to_match(),))

    if not is_recursing and match_step.root_block.optional:
        parts.append(u'optional: true')

    if match_step.as_block:
        match_step.as_block.validate()
        parts.append(u'as: %s' % (_get_vertex_location_name(match_step.as_block.location),))

    return u'%s {{ %s }}' % (traversal_command, u', '.join(parts))
836483
def check_next_match(self, match, new_relations, subject_graph, one_match):
        """"""
        # only returns true for ecaxtly one set of new_relations from all the
        # ones that are symmetrically equivalent
        if not (self.criteria_sets is None or one_match):
            for check in self.duplicate_checks:
                vertex_a = new_relations.get(check[0])
                vertex_b = new_relations.get(check[1])
                if vertex_a is None and vertex_b is None:
                    continue # if this pair is completely absent in the new
                    # relations, it is either completely in the match or it
                    # is to be matched. So it is either already checked for
                    # symmetry duplicates, or it will be check in future.
                if vertex_a is None:
                    # maybe vertex_a is in the match and vertex_b is the only
                    # one in the new relations. try to get vertex_a from the
                    # match.
                    vertex_a = match.forward.get(check[0])
                    if vertex_a is None:
                        # ok, vertex_a is to be found, don't care about it right
                        # now. it will be checked in future calls.
                        continue
                elif vertex_b is None:
                    # maybe vertex_b is in the match and vertex_a is the only
                    # one in the new relations. try to get vertex_b from the
                    # match.
                    vertex_b = match.forward.get(check[1])
                    if vertex_b is None:
                        # ok, vertex_b is to be found, don't care about it right
                        # now. it will be checked in future calls.
                        continue
                if vertex_a > vertex_b:
                    # Why does this work? The answer is not so easy to explain,
                    # and certainly not easy to find. if vertex_a > vertex_b, it
                    # means that there is a symmetry operation that leads to
                    # an equivalent match where vertex_b < vertex_a. The latter
                    # match is preferred for as much pairs (vertex_a, vertex_b)
                    # as possible without rejecting all possible matches. The
                    # real difficulty is to construct a proper list of
                    # (vertex_a, vertex_b) pairs that will reject all but one
                    # matches. I conjecture that this list contains all the
                    # first two vertices from each normalized symmetry cycle of
                    # the pattern graph. We need a math guy to do the proof. -- Toon
                    return False
            return True
        return True
124420
def find_global(self, pattern):
		
		pos_s = self.reader.search(pattern)
		if len(pos_s) == 0:
			return -1
		
		return pos_s[0]
1184001
def underscore_search(input, list, first_match=false)
      meth = first_match ? :find : :select
      return (first_match ? input : [input]) if list.include?(input)
      input = input.to_s
      if input.include?("_")
        underscore_regex = input.split('_').map {|e|
          Regexp.escape(e) }.join("([^_]+)?_")
        list.send(meth) {|e| e.to_s =~ /^#{underscore_regex}/ }
      else
        escaped_input = Regexp.escape(input)
        list.send(meth) {|e| e.to_s =~ /^#{escaped_input}/ }
      end
    end
576040
public static List<Match> search(Match m, Pattern pattern)
	{
		assert pattern.getStartingClass().isAssignableFrom(m.get(0).getModelInterface());

		return searchRecursive(m, pattern.getConstraints(), 0);
	}
807058
public static RegexpMatcher getMatcher( String pattern, boolean multiline ) {
      if( isJDK13() ){
         return new Perl5RegexpMatcher( pattern, true );
      }else{
         return new JdkRegexpMatcher( pattern, true );
      }
   }
696151
def _next_pattern(self):
        """"""
        current_state = self.state_stack[-1]
        position = self._position
        for pattern in self.patterns:
            if current_state not in pattern.states:
                continue

            m = pattern.regex.match(self.source, position)
            if not m:
                continue

            position = m.end()
            token = None

            if pattern.next_state:
                self.state_stack.append(pattern.next_state)

            if pattern.action:
                callback = getattr(self, pattern.action, None)
                if callback is None:
                    raise RuntimeError(
                        "No method defined for pattern action %s!" %
                        pattern.action)

                if "token" in m.groups():
                    value = m.group("token")
                else:
                    value = m.group(0)
                token = callback(string=value, match=m,
                                 pattern=pattern)

            self._position = position

            return token

        self._error("Don't know how to match next. Did you forget quotes?",
                    start=self._position, end=self._position + 1)
661112
def matcher(graph1, graph2, confidence=0.5, output_file="matching_results.csv", class_or_prop="classes", verbose=False):
	

	printDebug("----------\nNow matching...")

	f = open(output_file, 'wt')
	counter = 0

	try:
		writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
		writer.writerow( ('name 1', 'name 2', 'uri 1', 'uri 2') )

		# a) match classes

		if class_or_prop == "classes":

			for x in graph1.all_classes:
				l1 = unicode(x.bestLabel(qname_allowed=True))

				for y in graph2.all_classes:
					l2 = unicode(y.bestLabel(qname_allowed=True))

					if similar(l1, l2) > confidence:
						counter += 1
						row = [l1, l2, x.uri, y.uri]
						writer.writerow([s.encode('utf8') if type(s) is unicode else s for s in row])
						if verbose:
							print("%s ==~== %s" % (l1, l2))


		# b) match properties

		elif class_or_prop == "properties":

			for x in graph1.all_properties:
				l1 = unicode(x.bestLabel(qname_allowed=True))

				for y in graph2.all_properties:
					l2 = unicode(y.bestLabel(qname_allowed=True))

					if similar(l1, l2) > confidence:
						counter += 1
						row = [l1, l2, x.uri, y.uri]
						writer.writerow([s.encode('utf8') if type(s) is unicode else s for s in row])
						if verbose:
							print("%s ==~== %s" % (l1, l2))

	finally:
		f.close()

	printDebug("%d candidates found." % counter)
1339156
function Matcher (patternFn, successFn, next) {
    this.patternFn = patternFn;
    this.successFn = successFn;
    this.next = next;
  }
499217
def search(self, pattern, count=None):
        
        return self._scan(match=pattern, count=count)