The purpose here is to create a more finely binned
        background CMD to sample from.
347799
def _setup_cmd(self,mode='cloud-in-cells'):
        
        # Only setup once...
        if hasattr(self,'bkg_lambda'): return

        logger.info("Setup color...")
        # In the limit theta->0: 2*pi*(1-cos(theta)) -> pi*theta**2
        # (Remember to convert from sr to deg^2) 
        #solid_angle_roi = sr2deg(2*np.pi*(1-np.cos(np.radians(self.roi_radius))))
        solid_angle_roi = self.roi.area_pixel*len(self.roi.pixels)

        # Large CMD bins cause problems when simulating
        config = Config(self.config) 
        config['color']['n_bins'] *= 5 #10
        config['mag']['n_bins']   *= 1 #2
        #config['mask']['minimum_solid_angle'] = 0
        roi = ugali.analysis.loglike.createROI(config,self.roi.lon,self.roi.lat)
        mask = ugali.analysis.loglike.createMask(config,roi)

        self.bkg_centers_color  = roi.centers_color
        self.bkg_centers_mag    = roi.centers_mag

        # Background CMD has units: [objs / deg^2 / mag^2]
        cmd_background = mask.backgroundCMD(self.catalog,mode)
        
        self.bkg_lambda=cmd_background*solid_angle_roi*roi.delta_color*roi.delta_mag
        np.sum(self.bkg_lambda)

        # Clean up 
        del config, roi, mask
1351213
function Header(cmd, size, checksum) {
  this.cmd = cmd;
  this.size = size;
  this.checksum = checksum;
}
473528
function globs(sourcePath, ignore, commands, done) {
  var expression = /\$g\[(.+?)\]/g;
  var result = [];
  each(commands, function(command, next) {
    var map = {};
    var match;
    var matches = [];
    while ((match = expression.exec(command))) matches.push(match);
    each(matches, function(patternMatch, next) {
      find(patternMatch[1], sourcePath, ignore, function(err, relativePaths) {
        if (err) return next(err);
        map[patternMatch[1]] = relativePaths;
        next();
      });
    }, function(err) {
      if (err) return next(err);
      result.push(command.replace(expression, function(match, matchKey) {
        return map[matchKey].join(' ');
      }));
      next();
    });
  }, function(err) {
    if (err) return done(err);
    done(undefined, result);
  });
}
513502
def main(dbfile, pidfile, mode):
    '''
    
    '''
    Inspector(dbfile, pidfile).reuse_snapshot().snapshot(mode)
439771
def exec_background(controller, cmd, *args):
    """"""
    controller.logger.info("Executing in the background: {0} {1}",
                           cmd, " ".join(args))

    try:
        subprocess.Popen([cmd] + list(args),
                         stdout=open(os.devnull, "wb"),
                         stderr=open(os.devnull, "wb"))
    except OSError as err:
        controller.logger.error("Failed to execute process: {0}", err)
121458
function commandSampleRateForCmdCyton (sampleRate) {
  return new Promise(function (resolve, reject) {
    switch (sampleRate) {
      case obciSampleRate16000:
        resolve(obciSampleRateCmdCyton16000);
        break;
      case obciSampleRate8000:
        resolve(obciSampleRateCmdCyton8000);
        break;
      case obciSampleRate4000:
        resolve(obciSampleRateCmdCyton4000);
        break;
      case obciSampleRate2000:
        resolve(obciSampleRateCmdCyton2000);
        break;
      case obciSampleRate1000:
        resolve(obciSampleRateCmdCyton1000);
        break;
      case obciSampleRate500:
        resolve(obciSampleRateCmdCyton500);
        break;
      case obciSampleRate250:
        resolve(obciSampleRateCmdCyton250);
        break;
      default:
        reject(Error('Invalid sample rate'));
        break;
    }
  });
}
885640
def _split_samples_by_qc(samples):
    
    to_process = []
    extras = []
    for data in [utils.to_single_data(x) for x in samples]:
        qcs = dd.get_algorithm_qc(data)
        # kraken doesn't need bam
        if qcs and (dd.get_align_bam(data) or dd.get_work_bam(data) or
                    tz.get_in(["config", "algorithm", "kraken"], data)):
            for qc in qcs:
                add = copy.deepcopy(data)
                add["config"]["algorithm"]["qc"] = [qc]
                to_process.append([add])
        else:
            extras.append([data])
    return to_process, extras
992323
function runCapturingProcess(options, config, outputFile, base64, onFinish) {
    const scriptFile = utils.filePath(SCRIPT_FILE),
          command = cliCommand(config).split(/[ ]+/),
          cmd = _.union(command, [scriptFile, base64, outputFile]),
          opts = {
              timeout: config.timeout
          };

    logger.debug(
        'Options for script: %s, base64: %s, command: %s',
        JSON.stringify(options), base64, JSON.stringify(cmd)
    );

    utils.execProcess(cmd, opts, (error) => {
        if (config.compress) {
            minimizeImage(outputFile, config.storage, () => onFinish(error));
        } else {
            onFinish(error);
        }
    });
}
1187507
def _prepare_sample_data(self, submission_type):
    
    # write images
    images = np.random.randint(0, 256,
                               size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
    for i in range(BATCH_SIZE):
      Image.fromarray(images[i, :, :, :]).save(
          os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i)))
    # write target class for targeted attacks
    if submission_type == 'targeted_attack':
      target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE])
      target_class_filename = os.path.join(self._sample_input_dir,
                                           'target_class.csv')
      with open(target_class_filename, 'w') as f:
        for i in range(BATCH_SIZE):
          f.write((IMAGE_NAME_PATTERN + ',{1}\n').format(i, target_classes[i]))
663859
function bin(argv) {
  // setup config
  var config = require('../config/config.js')

  program
  .option('-d, --database <database>', 'Database')
  .parse(argv)

  var defaultDatabase = 'media'

  config.database = program.database || config.database || defaultDatabase
  var url = process.argv[2] || 'https://www.reddit.com/r/perfectloops/top/?sort=top&t=all&count=25&after=t3_4j0v4f'


  qpm_media.getRandomUnseenFragment(null, config).then(function(ret){
    console.table(ret.ret[0])
    ret.conn.close()
  }).catch(function (err) {
    console.error(err)
  })


}
1214940
def generate_samples(self):
        """"""
        filenames = glob_all(self.args.random_data_folder, '*.wav')
        shuffle(filenames)
        while True:
            for fn in filenames:
                for x, y in self.vectors_from_fn(fn):
                    yield x, y
1023486
def _prepare_sample(data, run_folder):
    
    want = set(["description", "files", "genome_build", "name", "analysis", "upload", "algorithm"])
    out = {}
    for k, v in data.items():
        if k in want:
            out[k] = _relative_paths(v, run_folder)
    if "algorithm" not in out:
        analysis, algorithm = _select_default_algorithm(out.get("analysis"))
        out["algorithm"] = algorithm
        out["analysis"] = analysis
    description = "%s-%s" % (out["name"], clean_name(out["description"]))
    out["name"] = [out["name"], description]
    out["description"] = description
    return out
1340853
def trim_sample(data):
    
    data = utils.to_single_data(data)
    trim_reads = dd.get_trim_reads(data)
    # this block is to maintain legacy configuration files
    if not trim_reads:
        logger.info("Skipping trimming of %s." % dd.get_sample_name(data))
    else:
        if "skewer" in dd.get_tools_on(data) or trim_reads == "skewer":
            trim_adapters = skewer.trim_adapters
        else:
            trim_adapters = trim.trim_adapters
        out_files = trim_adapters(data)
        data["files"] = out_files
    return [[data]]
655340
def _generate_ffmpeg_cmd(
        self,
        cmd: List[str],
        input_source: Optional[str],
        output: Optional[str],
        extra_cmd: Optional[str] = None,
    ) -> None:
        """"""
        self._argv = [self._ffmpeg]

        # start command init
        if input_source is not None:
            self._put_input(input_source)
        self._argv.extend(cmd)

        # exists a extra cmd from customer
        if extra_cmd is not None:
            self._argv.extend(shlex.split(extra_cmd))

        self._merge_filters()
        self._put_output(output)
223220
def sample(config, samples):
  """"""
  url = get_api_path('sample.json')
  multiple_files = []
  images = [s['image'] for s in samples]
  labels = [s['label'] for s in samples]
  for image in images:
    multiple_files.append(('images', (image, open(image, 'rb'), 'image/png')))
  headers=get_headers(no_content_type=True)
  headers["config"]= json.dumps(config, cls=HCEncoder)
  headers["labels"]= json.dumps(labels)
  print("With headers", headers)

  try:
      r = requests.post(url, files=multiple_files, headers=headers, timeout=30)
      return r.text
  except requests.exceptions.RequestException:
      e = sys.exc_info()[0]
      print("Error while calling hyperchamber - ", e)
      return None
651403
def _prepare_smoove_bams(full_bams, sr_bams, disc_bams, items, tx_work_dir):
    
    input_dir = utils.safe_makedir(tx_work_dir)
    out = []
    for full, sr, disc, data in zip(full_bams, sr_bams, disc_bams, items):
        if sr and disc:
            new_full = os.path.join(input_dir, "%s.bam" % dd.get_sample_name(data))
            new_sr = os.path.join(input_dir, "%s.split.bam" % dd.get_sample_name(data))
            new_disc = os.path.join(input_dir, "%s.disc.bam" % dd.get_sample_name(data))
            utils.symlink_plus(full, new_full)
            utils.symlink_plus(sr, new_sr)
            utils.symlink_plus(disc, new_disc)
            out.append(new_full)
        else:
            out.append(full)
    return out
1338839
def cnvkit_background(background_cnns, out_file, items, target_bed=None, antitarget_bed=None):
    
    if not utils.file_exists(out_file):
        with file_transaction(items[0], out_file) as tx_out_file:
            cmd = [_get_cmd(), "reference", "-f", dd.get_ref_file(items[0]), "-o", tx_out_file]
            gender = _get_batch_gender(items)
            if gender:
                cmd += ["--sample-sex", gender]
            if len(background_cnns) == 0:
                assert target_bed and antitarget_bed, "Missing CNNs and target BEDs for flat background"
                cmd += ["-t", target_bed, "-a", antitarget_bed]
            else:
                cmd += background_cnns
            do.run(_prep_cmd(cmd, tx_out_file), "CNVkit background")
    return out_file