This function sets up exact match multiifo coincidence for injections
342786
def setup_multiifo_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files,
                                      stat_files, background_file, veto_file, veto_name,
                                      out_dir, pivot_ifo, fixed_ifo, tags=None):
    
    if tags is None:
        tags = []
    make_analysis_dir(out_dir)
    logging.info('Setting up coincidence for injections')

    if len(hdfbank) != 1:
        raise ValueError('Must use exactly 1 bank file for this coincidence '
                         'method, I got %i !' % len(hdfbank))
    hdfbank = hdfbank[0]

    # Wall time knob and memory knob
    factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags))

    ffiles = {}
    ifiles = {}
    for ifo, ffi in zip(*full_data_trig_files.categorize_by_attr('ifo')):
        ffiles[ifo] = ffi[0]
    for ifo, ifi in zip(*inj_trig_files.categorize_by_attr('ifo')):
        ifiles[ifo] = ifi[0]

    injinj_files = FileList()
    injfull_files = FileList()
    fullinj_files = FileList()
    # For the injfull and fullinj separation we take the pivot_ifo on one side,
    # and the rest that are attached to the fixed_ifo on the other side
    for ifo in ifiles:  # ifiles is keyed on ifo
        if ifo == pivot_ifo:
            injinj_files.append(ifiles[ifo])
            injfull_files.append(ifiles[ifo])
            fullinj_files.append(ffiles[ifo])
        else:
            injinj_files.append(ifiles[ifo])
            injfull_files.append(ffiles[ifo])
            fullinj_files.append(ifiles[ifo])

    combo = [(injinj_files, "injinj"),
             (injfull_files, "injfull"),
             (fullinj_files, "fullinj"),
            ]
    bg_files = {'injinj':[], 'injfull':[], 'fullinj':[]}

    for trig_files, ctag in combo:
        findcoinc_exe = PyCBCFindMultiifoCoincExecutable(workflow.cp,
                                                         'multiifo_coinc',
                                                         ifos=ifiles.keys(),
                                                         tags=tags + [ctag],
                                                         out_dir=out_dir)
        for i in range(factor):
            group_str = '%s/%s' % (i, factor)
            coinc_node = findcoinc_exe.create_node(trig_files, hdfbank,
                                                   stat_files,
                                                   veto_file, veto_name,
                                                   group_str,
                                                   pivot_ifo,
                                                   fixed_ifo,
                                                   tags=[veto_name, str(i)])

            bg_files[ctag] += coinc_node.output_files
            workflow.add_node(coinc_node)

    logging.info('...leaving coincidence for injections')

    return setup_multiifo_statmap_inj(workflow, ifiles.keys(), bg_files, background_file, out_dir, tags=tags + [veto_name])
1109620
def _match(self):
        """"""
        #disable optimized matching
        optimized_rows = None
        optimized_columns = None
        for match in self.__match_rows(optimized_rows):
            #match in rows
            yield match
        for match in self.__match_rows(optimized_columns,
                                       transpose=True):
            #match in columns and transpose coordinates
            yield match
173095
function supersede(target, source, force, deepStringMixin) {
    if (source) {
        eachProp(source, function (value, prop) {
            if (hasProp(target, prop)) {
                if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) {

                    if (!target[prop]) {
                        target[prop] = {};
                    }
                    supersede(target[prop], value, force, deepStringMixin);
                } else {
                    target[prop] = value;
                }
            }
        });
    }
    return target;
}
343825
def _random_inject(values, injects)
            used_indexes = {}
            count = injects.size > values.size ? values.size : injects.size
            (0...count).each do |i|
                inj = injects[i]
                times_inject = rand(values.size / injects.size / 10)
                times_inject = 1 if times_inject < 1
                times_inject.times do
                    rand_index = rand(values.size)
                    _loop do
                        break unless used_indexes.has_key? rand_index
                        rand_index = rand(values.size)
                    end
                    used_indexes[rand_index] = true
                    values[rand_index] = inj
                end
            end
        end
508391
def match(self, category, pattern):
        """"""

        return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)
1355873
function writeMatch(match, offset) {
    /** @type {Array.<number>} */
    var lz77Array = match.toLz77Array();
    /** @type {number} */
    var i;
    /** @type {number} */
    var il;

    for (i = 0, il = lz77Array.length; i < il; ++i) {
      lz77buf[pos++] = lz77Array[i];
    }
    freqsLitLen[lz77Array[0]]++;
    freqsDist[lz77Array[3]]++;
    skipLength = match.length + offset - 1;
    prevMatch = null;
  }
961923
private static Set<Interaction> getInter(Match match)
	{
		Set<Interaction> set = new HashSet<Interaction>();
		for (BioPAXElement ele : match.getVariables())
		{
			if (ele instanceof Interaction) 
			{
				set.add((Interaction) ele);
				addControlsRecursive((Interaction) ele, set);
			}
		}
		return set;
	}
188935
def match(tgt, opts=None):
    '''
    
    '''
    if not opts:
        opts = __opts__
    if not isinstance(tgt, six.string_types):
        return False

    return fnmatch.fnmatch(opts['id'], tgt)
375518
def _anonymous_match(self, struct1, struct2, fu, s1_supercell=True,
                         use_rms=False, break_on_match=False, single_match=False):
        
        if not isinstance(self._comparator, SpeciesComparator):
            raise ValueError('Anonymous fitting currently requires SpeciesComparator')

        # check that species lists are comparable
        sp1 = struct1.composition.elements
        sp2 = struct2.composition.elements
        if len(sp1) != len(sp2):
            return None

        ratio = fu if s1_supercell else 1/fu
        swapped = len(struct1) * ratio < len(struct2)

        s1_comp = struct1.composition
        s2_comp = struct2.composition
        matches = []
        for perm in itertools.permutations(sp2):
            sp_mapping = dict(zip(sp1, perm))

            # do quick check that compositions are compatible
            mapped_comp = Composition({sp_mapping[k]: v
                                       for k, v in s1_comp.items()})
            if (not self._subset) and (
                    self._comparator.get_hash(mapped_comp) !=
                    self._comparator.get_hash(s2_comp)):
                continue

            mapped_struct = struct1.copy()
            mapped_struct.replace_species(sp_mapping)
            if swapped:
                m = self._strict_match(struct2, mapped_struct, fu,
                                       (not s1_supercell), use_rms,
                                       break_on_match)
            else:
                m = self._strict_match(mapped_struct, struct2, fu, s1_supercell,
                                       use_rms, break_on_match)
            if m:
                matches.append((sp_mapping, m))
                if single_match:
                    break
        return matches
1283295
def match(self,refimage, quiet_identity, **kwargs):
        
        ref_outxy = refimage.outxy
        refWCS = refimage.wcs
        refname = refimage.name
        ref_inxy = refimage.xy_catalog

        cat_src_type = kwargs['cat_src_type']
        del kwargs['cat_src_type']

        if not quiet_identity:
            print("Matching sources from \'{}\' with sources from "
                  "reference {} \'{}\'"
                  .format(self.name, cat_src_type, refname))
        #self.sortSkyCatalog() # apply any catalog sorting specified by the user
        self.transformToRef(refWCS)
        self.refWCS = refWCS
        # extract xyxymatch parameters from input parameters
        matchpars = kwargs.copy()
        self.match_pars = matchpars
        minobj = matchpars['minobj'] # needed for later
        del matchpars['minobj'] # not needed in xyxymatch

        self.goodmatch = True

        # Check to see whether or not it is being matched to itself
        if refname.strip() == self.name.strip():
            self.identityfit = True
            if not quiet_identity:
                log.info('NO fit performed for reference image: %s\n'%self.name)
        else:
            # convert tolerance from units of arcseconds to pixels, as needed
            radius = matchpars['searchrad']
            if matchpars['searchunits'] == 'arcseconds':
                radius /= refWCS.pscale

            # Determine xyoff (X,Y offset) and tolerance to be used with xyxymatch
            if matchpars['use2dhist']:
                xsh, ysh, maxval, flux, zpmat, qual = _estimate_2dhist_shift(
                    self.outxy,
                    ref_outxy,
                    searchrad=radius
                )
                xyoff = (xsh, ysh)

                if matchpars['see2dplot']:
                    zpstd = max(10, flux // 5) if qual else 10
                    title_str = ("Histogram of offsets: Peak has {:d} matches "
                                 "at ({:0.4g}, {:0.4g})"
                                 .format(maxval, xsh, ysh))
                    hist_name = None
                    if not self.interactive:
                        hist_name = 'hist2d_{0}.png'.format(self.rootname)

                    plot_pars = {
                        'data': zpmat,
                        'figure_id': self.figure_id,
                        'vmax': zpstd,
                        'xp': xsh,
                        'yp': ysh,
                        'searchrad': radius,
                        'title_str': title_str,
                        'plotname': hist_name,
                        'interactive': self.interactive
                    }

                    tweakutils.plot_zeropoint(plot_pars)

                if matchpars['see2dplot'] and ('residplot' in matchpars and
                                               'No' in matchpars['residplot']):
                    if self.interactive:
                        prompt = ("Press ENTER for next image, \n" +
                                  "     'n' to continue without updating header or \n" +
                                  "     'q' to quit immediately...\n")

                        if sys.version_info[0] >= 3:
                            a = input(prompt)
                        else:
                            a = raw_input(prompt)

                    else:
                        a = ' '

                    if 'n' in a.lower():
                        self.perform_update = False

                    if 'q' in a.lower():
                        self.quit_immediately = True

                if matchpars['see2dplot']:
                    self.figure_id += 1

            else:
                xoff = 0.
                yoff = 0.
                if not util.is_blank(matchpars['xoffset']):
                    xoff = matchpars['xoffset']
                if not util.is_blank(matchpars['yoffset']):
                    yoff = matchpars['yoffset']
                xyoff = (xoff, yoff)

            matches = xyxymatch(self.outxy, ref_outxy, origin=xyoff,
                                tolerance=matchpars['tolerance'],
                                separation=matchpars['separation'])

            if len(matches) > minobj:
                self.matches['image'] = np.column_stack([matches['input_x'][:,
                                np.newaxis],matches['input_y'][:,np.newaxis]])
                self.matches['ref'] = np.column_stack([matches['ref_x'][:,
                                np.newaxis],matches['ref_y'][:,np.newaxis]])
                self.matches['ref_idx'] = matches['ref_idx']
                self.matches['img_idx'] = self.all_radec[3][matches['input_idx']]
                self.matches['input_idx'] = matches['input_idx']
                self.matches['img_RA'] = self.all_radec[0][matches['input_idx']]
                self.matches['img_DEC'] = self.all_radec[1][matches['input_idx']]

                self.matches['ref_orig_xy'] = np.column_stack([
                                    np.array(ref_inxy[0])[matches['ref_idx']][:,np.newaxis],
                                    np.array(ref_inxy[1])[matches['ref_idx']][:,np.newaxis]])

                self.matches['img_orig_xy'] = np.column_stack([
                    np.array(self.xy_catalog[0])[matches['input_idx']][:,np.newaxis],
                    np.array(self.xy_catalog[1])[matches['input_idx']][:,np.newaxis]])
                self.matches['src_origin'] = ref_inxy[-1][matches['ref_idx']]
                print('Found %d matches for %s...'%(len(matches),self.name))

                if self.pars['writecat']:
                    matchfile = open(self.catalog_names['match'],mode='w+')
                    matchfile.write('#Reference: %s\n'%refname)
                    matchfile.write('#Input: %s\n'%self.name)
                    title = '#Ref_X        Ref_Y        '
                    title += 'Input_X    Input_Y        '
                    title += 'Ref_X0    Ref_Y0        '
                    title += 'Input_X0    Input_Y0        '
                    title += 'Ref_ID    Input_ID        '
                    title += 'Ref_Source\n'
                    fmtstr = '%0.6f    %0.6f        '*4
                    fmtstr += '%d    %d    %s\n'
                    matchfile.write(title)
                    for i in range(len(matches['input_x'])):
                        linestr = fmtstr%\
                            (matches['ref_x'][i],matches['ref_y'][i],\
                             matches['input_x'][i],matches['input_y'][i],
                            self.matches['ref_orig_xy'][:,0][i],
                            self.matches['ref_orig_xy'][:,1][i],
                            self.matches['img_orig_xy'][:,0][i],
                            self.matches['img_orig_xy'][:,1][i],
                            matches['ref_idx'][i],matches['input_idx'][i],
                            self.matches['src_origin'][i])
                        matchfile.write(linestr)
                    matchfile.close()
            else:
                warnstr = textutil.textbox('WARNING: \n'+
                    'Not enough matches (< %d) found for input image: %s'%(minobj,self.name))
                for line in warnstr.split('\n'):
                    log.warning(line)
                print(warnstr)
                self.goodmatch = False
538148
def indexMatch(L, func):
    ''
    for i, x in enumerate(L):
        if func(x):
            return i
1031223
function match(re) {
    var m = re.exec(css);
    if (!m) return;
    var str = m[0];
    updatePosition(str);
    css = css.slice(str.length);
    return m;
  }
735334
def match_in_kwargs(self, match_args, kwargs):
        """"""
        for match, default in match_args:
            names = get_match_names(match)
            if names:
                tempvar = self.get_temp_var()
                self.add_def(
                    tempvar + " = "
                    + "".join(
                        kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else "
                        for name in names
                    )
                    + default,
                )
                with self.down_a_level():
                    self.match(match, tempvar)
            else:
                raise CoconutDeferredSyntaxError("keyword-only pattern-matching function arguments must have names", self.loc)
240894
def name_match_funcdef_handle(self, original, loc, tokens):
        """"""
        if len(tokens) == 2:
            func, matches = tokens
            cond = None
        elif len(tokens) == 3:
            func, matches, cond = tokens
        else:
            raise CoconutInternalException("invalid match function definition tokens", tokens)
        matcher = Matcher(loc, match_check_var)

        req_args, def_args, star_arg, kwd_args, dubstar_arg = split_args_list(matches, loc)
        matcher.match_function(match_to_args_var, match_to_kwargs_var, req_args + def_args, star_arg, kwd_args, dubstar_arg)

        if cond is not None:
            matcher.add_guard(cond)

        before_docstring = (
            "def " + func
            + "(*" + match_to_args_var + ", **" + match_to_kwargs_var + "):\n"
            + openindent
        )
        after_docstring = (
            match_check_var + " = False\n"
            + matcher.out()
            # we only include match_to_args_var here because match_to_kwargs_var is modified during matching
            + self.pattern_error(original, loc, match_to_args_var, match_check_var) + closeindent
        )
        return before_docstring, after_docstring
51449
public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub)
    {
        assert (data != null);
        assert (func != null);
        assert (pub != null);
        Mtrie current = this;
        int idx = 0;

        while (true) {
            //  Signal the pipes attached to this node.
            if (current.pipes != null) {
                for (Pipe it : current.pipes) {
                    func.invoke(it, null, 0, pub);
                }
            }

            //  If we are at the end of the message, there's nothing more to match.
            if (size == 0) {
                break;
            }

            //  If there are no subnodes in the trie, return.
            if (current.count == 0) {
                break;
            }

            byte c = data.get(idx);
            //  If there's one subnode (optimisation).
            if (current.count == 1) {
                if (c != current.min) {
                    break;
                }
                current = current.next[0];
                idx++;
                size--;
                continue;
            }

            //  If there are multiple subnodes.
            if (c < current.min || c >= current.min + current.count) {
                break;
            }
            if (current.next[c - current.min] == null) {
                break;
            }
            current = current.next[c - current.min];
            idx++;
            size--;
        }
    }
849051
def findLastCharIndexMatching(text, func):
    
    for i in range(len(text) - 1, -1, -1):
      if func(text[i]):
        return i
543975
private static Object matchOrReplace(Context cx, Scriptable scope,
                                         Scriptable thisObj, Object[] args,
                                         RegExpImpl reImpl,
                                         GlobData data, NativeRegExp re)
    {
        String str = data.str;
        data.global = (re.getFlags() & NativeRegExp.JSREG_GLOB) != 0;
        int[] indexp = { 0 };
        Object result = null;
        if (data.mode == RA_SEARCH) {
            result = re.executeRegExp(cx, scope, reImpl,
                                      str, indexp, NativeRegExp.TEST);
            if (result != null && result.equals(Boolean.TRUE))
                result = Integer.valueOf(reImpl.leftContext.length);
            else
                result = Integer.valueOf(-1);
        } else if (data.global) {
            re.lastIndex = 0d;
            for (int count = 0; indexp[0] <= str.length(); count++) {
                result = re.executeRegExp(cx, scope, reImpl,
                                          str, indexp, NativeRegExp.TEST);
                if (result == null || !result.equals(Boolean.TRUE))
                    break;
                if (data.mode == RA_MATCH) {
                    match_glob(data, cx, scope, count, reImpl);
                } else {
                    if (data.mode != RA_REPLACE) Kit.codeBug();
                    SubString lastMatch = reImpl.lastMatch;
                    int leftIndex = data.leftIndex;
                    int leftlen = lastMatch.index - leftIndex;
                    data.leftIndex = lastMatch.index + lastMatch.length;
                    replace_glob(data, cx, scope, reImpl, leftIndex, leftlen);
                }
                if (reImpl.lastMatch.length == 0) {
                    if (indexp[0] == str.length())
                        break;
                    indexp[0]++;
                }
            }
        } else {
            result = re.executeRegExp(cx, scope, reImpl, str, indexp,
                                      ((data.mode == RA_REPLACE)
                                       ? NativeRegExp.TEST
                                       : NativeRegExp.MATCH));
        }

        return result;
    }