Execute the anti_alias operation steps times on the given map
494881
def anti_alias(map_in, steps):
    

    height, width = map_in.shape

    map_part = (2.0/11.0)*map_in

    # notice how [-1/sqrt(3), -1/sqrt(3), -1/sqrt(3)] * [-1/sqrt(3), -1/sqrt(3), -1/sqrt(3)]^T
    # equals [[1/3, 1/3, 1/3], [1/3, 1/3, 1/3], [1/3, 1/3, 1/3]]
    # multiply that by (3/11) and we have the 2d kernel from the example above
    # therefore the kernel is seperable

    w = -1.0/numpy.sqrt(3.0)
    kernel = [w, w, w]

    def _anti_alias_step(original):

        # cf. comments above fo the factor
        # this also makes a copy which might actually be superfluous
        result = original * (3.0/11.0)

        # we need to handle boundary conditions by hand, unfortunately
        # there might be a better way but this works (circular boundary)
        # notice how we'll need to add 2 to width and height later 
        # because of this
        result = numpy.append(result, [result[0,:]], 0)
        result = numpy.append(result, numpy.transpose([result[:,0]]), 1)

        result = numpy.insert(result, [0], [result[-2,:]],0)
        result = numpy.insert(result, [0], numpy.transpose([result[:,-2]]), 1)

        # with a seperable kernel we can convolve the rows first ...
        for y in range(height+2):
            result[y,1:-1] = numpy.convolve(result[y,:], kernel, 'valid')

        # ... and then the columns
        for x in range(width+2):
            result[1:-1,x] = numpy.convolve(result[:,x], kernel, 'valid')

        # throw away invalid values at the boundary
        result = result[1:-1,1:-1]

        result += map_part

        return result

    current = map_in
    for i in range(steps):
        current = _anti_alias_step(current)
    return current
1315550
def map(self, func, iterable, chunksize=None):
        
        # The key magic is that we must call r.get() with a timeout, because a
        # Condition.wait() without a timeout swallows KeyboardInterrupts.
        r = self.map_async(func, iterable, chunksize)

        while True:
            try:
                return r.get(self.wait_timeout)
            except TimeoutError:
                pass
            except KeyboardInterrupt:
                self.terminate()
                self.join()
                raise
1305456
function cloneAliases(trail) {
  var copy = {};

  Object.keys(trail.__aliases__).forEach(function (extension) {
    copy[extension] = [].concat(trail.__aliases__[extension]);
  });

  return copy;
}
1127514
def run(self, call, num_alts):
        
        for key, value in call.data.items():
            self._check_count(call, key, value, num_alts)
677815
def run(self, arguments=None):
        
        # add arguments from filter classes before calling superclass run
        for f in self.filters:
            for fa in f.filterArgs:
                self.argparser.add_argument(fa[0], **fa[1])
        # now parse arguments and post-process
        LogFileTool.run(self, arguments)

        self.args = dict((k, self.args[k]
                          if k in ['logfile', 'markers', 'timezone']
                          else self._arrayToString(self.args[k]))
                         for k in self.args)
        # make sure logfile is always a list, even if 1 is provided
        # through sys.stdin
        if not isinstance(self.args['logfile'], list):
            self.args['logfile'] = [self.args['logfile']]

        # require at least 1 log file (either through stdin or as parameter)
        if len(self.args['logfile']) == 0:
            raise SystemExit('Error: Need at least 1 log file, either as '
                             'command line parameter or through stdin.')

        # handle timezone parameter
        if len(self.args['timezone']) == 1:
            self.args['timezone'] = (self.args['timezone'] *
                                     len(self.args['logfile']))
        elif len(self.args['timezone']) == len(self.args['logfile']):
            pass
        elif len(self.args['timezone']) == 0:
            self.args['timezone'] = [0] * len(self.args['logfile'])
        else:
            raise SystemExit('Error: Invalid number of timezone parameters. '
                             'Use either one parameter (for global '
                             'adjustment) or the number of log files '
                             '(for individual adjustments).')

        # create filter objects from classes and pass args
        self.filters = [f(self) for f in self.filters]

        # remove non-active filter objects
        self.filters = [f for f in self.filters if f.active]

        # call setup for each active filter
        for f in self.filters:
            f.setup()

        if self.args['shorten'] is not False:
            if self.args['shorten'] is None:
                self.args['shorten'] = 200

        if self.args['verbose']:
            print("command line arguments")
            for a in self.args:
                print("    %s: %s" % (a, self.args[a]))
            print("\nactive filters: " +
                  ", ".join([f.__class__.__name__ for f in self.filters]))
            print('\n====================')

        # handle markers parameter
        if len(self.args['markers']) == 1:
            marker = self.args['markers'][0]
            if marker == 'enum':
                self.args['markers'] = ['{%i}' % (i + 1)
                                        for i in range(len(self
                                                           .args['logfile']))]
            elif marker == 'alpha':
                self.args['markers'] = ['{%s}' % chr(97 + i)
                                        for i in range(len(self
                                                           .args['logfile']))]
            elif marker == 'none':
                self.args['markers'] = [None for _ in self.args['logfile']]
            elif marker == 'filename':
                self.args['markers'] = ['{%s}' % logfile.name
                                        for logfile in self.args['logfile']]
        elif len(self.args['markers']) == len(self.args['logfile']):
            pass
        else:
            raise SystemExit('Error: Number of markers not the same as '
                             'number of files.')

        # with --human, change to ctime format if not specified otherwise
        if self.args['timestamp_format'] == 'none' and self.args['human']:
            self.args['timestamp_format'] = 'ctime'

        # go through each line and ask each filter if it accepts
        if 'logfile' not in self.args or not self.args['logfile']:
            raise SystemExit('no logfile found.')

        for logevent in self.logfile_generator():
            if self.args['exclude']:
                # print line if any filter disagrees
                if any([not f.accept(logevent) for f in self.filters]):
                    self._outputLine(logevent, self.args['shorten'],
                                     self.args['human'])

            else:
                # only print line if all filters agree
                if all([f.accept(logevent) for f in self.filters]):
                    self._outputLine(logevent, self.args['shorten'],
                                     self.args['human'])

                # if at least one filter refuses to accept any
                # remaining lines, stop
                if any([f.skipRemaining() for f in self.filters]):
                    # if input is not stdin
                    if sys.stdin.isatty():
                        break
679672
def _every(times, step_size, index):
        
        current = index * step_size
        step = current // times * times
        reached = current >= step
        overshot = current >= step + step_size
        return current and reached and not overshot
955247
function absAliasPaths(alias) {
    return Object.keys(alias).reduce( (prev, key) => {
        prev[key] = alias[key].split(path.sep)
            .filter(item => !!item)
            .reduce((prev, item) => path.resolve(prev, item),  path.sep);
        return prev;
    }, {});
}
406002
function runGlob(args, opts, cb) {
  var dotIdx = args.indexOf('.');
  if (dotIdx !== -1) {
    args.splice(dotIdx, 1);
  }
  glob(args, opts, function(err, globbed) {
    if (Array.isArray(globbed) && dotIdx !== -1) globbed.push('.');
    cb(err, globbed);
  });
}
327888
def as_alias_handler(alias_list):
    """"""
    list_ = list()
    for alias in alias_list:
        if alias.asname:
            list_.append(alias.asname)
        else:
            list_.append(alias.name)
    return list_
114431
def run_spades(self, stop_at_first_success=False):
        ''''''
        n50 = {}
        kmer_to_dir = {}

        for k in self.spades_kmers:
            tmpdir = tempfile.mkdtemp(prefix=self.outdir + '.tmp.spades.' + str(k) + '.', dir=os.getcwd())
            kmer_to_dir[k] = tmpdir
            ok, errs = self.run_spades_once(k, tmpdir)
            if ok:
                contigs_fasta = os.path.join(tmpdir, 'contigs.fasta')
                contigs_fai = contigs_fasta + '.fai'
                common.syscall(self.samtools.exe() + ' faidx ' + contigs_fasta, verbose=self.verbose)
                stats = pyfastaq.tasks.stats_from_fai(contigs_fai)
                if stats['N50'] != 0:
                    n50[k] = stats['N50']

                    if stop_at_first_success:
                        break

        if len(n50) > 0:
            if self.verbose:
                print('[assemble]\tkmer\tN50')
                for k in sorted(n50):
                    print('[assemble]', k, n50[k], sep='\t')

            best_k = None

            for k in sorted(n50):
                if best_k is None or n50[k] >= n50[best_k]:
                    best_k = k

            assert best_k is not None

            for k, directory in kmer_to_dir.items():
                if k == best_k:
                    if self.verbose:
                        print('[assemble] using assembly with kmer', k)
                    os.rename(directory, self.outdir)
                else:
                    shutil.rmtree(directory)
        else:
            raise Error('Error running SPAdes. Output directories are:\n  ' + '\n  '.join(kmer_to_dir.values()) + '\nThe reason why should be in the spades.log file in each directory.')
181707
def do_unalias(self, arg):
        
        args = arg.split()
        if len(args) == 0: return
        if args[0] in self.aliases:
            del self.aliases[args[0]]
921261
def run_commands(commands,  # type: List[Union[str, List[str], Dict[str, Union[str, List[str]]]]]
                 directory,  # type: str
                 env=None  # type: Optional[Dict[str, Union[str, int]]]
                ):  # noqa
    # type: (...) -> None
    """"""
    if env is None:
        env = os.environ.copy()
    for step in commands:
        if isinstance(step, (list, six.string_types)):
            execution_dir = directory
            raw_command = step
        elif step.get('command'):  # dictionary
            execution_dir = os.path.join(directory,
                                         step.get('cwd')) if step.get('cwd') else directory  # noqa pylint: disable=line-too-long
            raw_command = step['command']
        else:
            raise AttributeError("Invalid command step: %s" % step)
        command_list = raw_command.split(' ') if isinstance(raw_command, six.string_types) else raw_command  # noqa pylint: disable=line-too-long
        if platform.system().lower() == 'windows':
            command_list = fix_windows_command_list(command_list)

        with change_dir(execution_dir):
            check_call(command_list, env=env)
1128782
def skip(mapping):
    
    found = set()
    for m in mapping:
        matched_atoms = set(m.values())
        if found.intersection(matched_atoms):
            continue
        found.update(matched_atoms)
        yield m
1010331
function processAliases(aliases) {
	const result = {
		long: {},
		short: {}
	};

	if (!aliases) {
		return result;
	}

	if (!Array.isArray(aliases)) {
		if (typeof aliases === 'object') {
			if (aliases.long && typeof aliases.long === 'object') {
				Object.assign(result.long, aliases.long);
			}
			if (aliases.short && typeof aliases.short === 'object') {
				Object.assign(result.short, aliases.short);
			}
			return result;
		}

		aliases = [ aliases ];
	}

	for (const alias of aliases) {
		if (!alias || typeof alias !== 'string') {
			throw E.INVALID_ALIAS('Expected aliases to be a string or an array of strings',
				{ name: 'aliases', scope: 'Option.constructor', value: alias });
		}

		for (const a of alias.split(/[ ,|]+/)) {
			const m = a.match(aliasRegExp);
			if (!m) {
				throw E.INVALID_ALIAS(`Invalid alias format "${alias}"`, { name: 'aliases', scope: 'Option.constructor', value: alias });
			}

			if (m[2]) {
				result.short[m[2]] = !m[1];
			} else if (m[3]) {
				result.long[m[3]] = !m[1];
			}
		}
	}

	return result;
}
1364832
def run_steps(node: Node, pipeline: RenderingPipeline, **args):
    """"""
    for step in pipeline.steps:
        result = step(node, pipeline=pipeline, **args)
        if isinstance(result, dict):
            args = {**args, **result}
1160831
private void CalculateMap(IntRange inRange, IntRange outRange, int[] map) {
        double k = 0, b = 0;

        if (inRange.getMax() != inRange.getMin()) {
            k = (double) (outRange.getMax() - outRange.getMin()) / (double) (inRange.getMax() - inRange.getMin());
            b = (double) (outRange.getMin()) - k * inRange.getMin();
        }

        for (int i = 0; i < 256; i++) {
            int v = (int) i;

            if (v >= inRange.getMax())
                v = outRange.getMax();
            else if (v <= inRange.getMin())
                v = outRange.getMin();
            else
                v = (int) (k * v + b);

            map[i] = v;
        }
    }
871919
def run(self):
    """"""
    while not self._abort:
      hashes = self._GetHashes(self._hash_queue, self.hashes_per_batch)
      if hashes:
        time_before_analysis = time.time()
        hash_analyses = self.Analyze(hashes)
        current_time = time.time()
        self.seconds_spent_analyzing += current_time - time_before_analysis
        self.analyses_performed += 1
        for hash_analysis in hash_analyses:
          self._hash_analysis_queue.put(hash_analysis)
          self._hash_queue.task_done()
        time.sleep(self.wait_after_analysis)
      else:
        # Wait for some more hashes to be added to the queue.
        time.sleep(self.EMPTY_QUEUE_WAIT_TIME)