Try predicting the effect of a variant on a particular transcript but
    suppress raised exceptions by converting them into `Failure` effect
    values.
974339
def predict_variant_effect_on_transcript_or_failure(variant, transcript):
    
    try:
        return predict_variant_effect_on_transcript(
            variant=variant,
            transcript=transcript)
    except (AssertionError, ValueError) as error:
        logger.warn(
            "Encountered error annotating %s for %s: %s",
            variant,
            transcript,
            error)
        return Failure(variant, transcript)
432595
def validate_mutations(vcffile, bams, reffa, chr_reffa, samples, output_format, outfile,
                       mpileup_parameters=mpileup_parser.MPILEUP_DEFAULT_PARAMS):
    """"""
    output_header = "sample chrom pos ref cov A C G T * - + " \
        "val_ref val_alt val_al_type val_al_count val_maf "\
        "most_common_indel most_common_indel_count most_common_indel_maf most_common_indel_type most_common_al " \
        "most_common_al_count most_common_al_maf most_common_count most_common_maf".split()

    # for backwards compatibility
    # if bam or samples is a string, convert to list instead
    if isinstance(samples, six.string_types):
        samples = [samples]
    if isinstance(bams, six.string_types):
        bams = [bams]

    if output_format == 'vcf':
        vcf_reader = vcf.Reader(open(vcffile))
        vcf_reader.samples = samples
        vcf_reader.formats['GT'] = vcf.parser._Format(id='GT', num=1, type='String', desc="Genotype")
        vcf_reader.formats['AD'] = vcf.parser._Format(id='AD', num='R', type='Integer', desc="Allelic depth")
        vcf_reader.formats['DP'] = vcf.parser._Format(id='DP', num=1, type='Integer', desc="Depth")
        vcf_writer = vcf.Writer(outfile, vcf_reader)
    else:
        vcf_reader = open(vcffile)


    if output_format == "sufam":
        outfile.write("\t".join(output_header))
        outfile.write("\n")
    for record in vcf_reader:
        if output_format != 'vcf':
            line = record
            if line.startswith("#CHROM"):
                header = line[1:].rstrip('\n').split("\t")
                # create spoof pyvcf record if vcf_reader is not used
                _Record = namedtuple('Record', header)
            if line.startswith("#"):
                continue
            if len(header) == 0:
                raise(Exception("No header found in vcf file #CHROM not found"))
            # zip all column values, except alt (needs to be list in pyvcf)
            record_args = dict(zip(header, line.rstrip('\n').split("\t")))
            record_args['ALT'] = [record_args['ALT']]
            record = _Record(**record_args)

        # determine type of mutation
        record_type = "snv"
        if len(record.ALT) > 1:
            warnings.warn("Multiple ALT in one record is not implemented - using first")
        if len(record.REF) > len(record.ALT[0]):
            record_type = "deletion"
        elif len(record.ALT[0]) > len(record.REF):
            record_type = "insertion"

        # no coverage results
        no_cov = pd.Series({
            "chrom": str(record.CHROM), "pos": str(record.POS),
            "ref": str(record.REF),
            "cov": 0, "A": 0, "C": 0, "G": 0, "T": 0,
            "val_ref": str(record.REF), "val_alt": str(record.ALT[0]),
            "val_al_type": record_type, "val_al_count": 0, "val_maf": 0})

        # collect mpileup baseparser results per bam
        bps = []
        for i, bam in enumerate(bams):
            sample = samples[i]
            no_cov['sample'] = sample
            bp_lines = mpileup_parser.run_and_parse(bam, str(record.CHROM), str(record.POS), str(record.POS), reffa,
                                                    chr_reffa, mpileup_parameters)
            bpdf = get_baseparser_extended_df(sample, bp_lines, str(record.REF), str(record.ALT[0]))
            if bpdf is None:
                bp = no_cov
            else:
                bp = bpdf.ix[0, :]
            bps += [bp]

        # output call
        if output_format == "vcf":
            _write_bp_vcf(outfile, bps, vcf_writer, record)
        else:
            # only one bam file supported for outputs other than vcf
            _write_bp(outfile, bps[0], output_header, output_format)
304644
def _outlier_rejection(self, params, model, signal, ii):
        
        # Z score across repetitions:
        z_score = (params - np.mean(params, 0))/np.std(params, 0)
        # Silence warnings: 
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            outlier_idx = np.where(np.abs(z_score)>3.0)[0]
            nan_idx = np.where(np.isnan(params))[0]
            outlier_idx = np.unique(np.hstack([nan_idx, outlier_idx]))
            ii[outlier_idx] = 0
            model[outlier_idx] = np.nan
            signal[outlier_idx] = np.nan
            params[outlier_idx] = np.nan

        return model, signal, params, ii
1133762
def go_to_error(self, text):
        """"""
        match = get_error_match(to_text_string(text))
        if match:
            fname, lnb = match.groups()
            if ("<ipython-input-" in fname and
                    self.run_cell_filename is not None):
                fname = self.run_cell_filename
            self.edit_goto.emit(osp.abspath(fname), int(lnb), '')
68603
def collapse_substrings(variant_sequences):
    
    if len(variant_sequences) <= 1:
        # if we don't have at least two VariantSequences then just
        # return your input
        return variant_sequences

    # dictionary mapping VariantSequence objects to lists of reads
    # they absorb from substring VariantSequences
    extra_reads_from_substrings = defaultdict(set)
    result_list = []
    # sort by longest to shortest total length
    for short_variant_sequence in sorted(
            variant_sequences,
            key=lambda seq: -len(seq)):
        found_superstring = False
        for long_variant_sequence in result_list:
            found_superstring = long_variant_sequence.contains(short_variant_sequence)
            if found_superstring:
                extra_reads_from_substrings[long_variant_sequence].update(
                    short_variant_sequence.reads)
        if not found_superstring:
            result_list.append(short_variant_sequence)
    # add to each VariantSequence the reads it absorbed from dropped substrings
    # and then return
    return [
        variant_sequence.add_reads(
            extra_reads_from_substrings[variant_sequence])
        for variant_sequence in result_list
    ]
291658
def raise_infinitive_error(sentence_str):
    """"""
    sent_doc = textacy.Doc(sentence_str, lang='en_core_web_lg')
    inf_pattern = r'<PART|ADP><VERB>' # To aux/auxpass* csubj
    infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern)
    for inf in infinitives:
        if inf[0].text.lower() != 'to':
            continue
        if inf[-1].tag_ != 'VB':
            raise Exception('InfinitivePhraseError')
1176896
def apply_to_transcript_if_exists(effect, fn, default):
    
    return apply_to_field_if_exists(
        effect=effect,
        field_name="transcript",
        fn=fn,
        default=default)
212818
def _raise_fail(self, response, expected):
        
        try:
            if self.logger:
                self.logger.error("Status code "
                                  "{} != {}. \n\n "
                                  "Payload: {}".format(response.status_code,
                                                       expected,
                                                       response.content))
            raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
        except TestStepFail:
            raise
        except:  # pylint: disable=bare-except
            if self.logger:
                self.logger.error("Status code "
                                  "{} != {}. \n\n "
                                  "Payload: {}".format(response.status_code,
                                                       expected,
                                                       "Unable to parse payload"))
            raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
1140357
def __evaluation_error(self, result, condition, throw):
        """"""
        self.log.error("Result does not match condition, dropping item. "
                       "Result %s; Condition: %s; Throw: %s",
                       result, condition, throw)
        return False
158120
def p_error_raise(p):
    
    q = make_number(1, lineno=p.lineno(2))
    r = make_binary(p.lineno(1), 'MINUS',
                    make_typecast(TYPE.ubyte, p[2], p.lineno(1)), q,
                    lambda x, y: x - y)
    p[0] = make_sentence('ERROR', r)
1148
def precise_matcher(text_log_error):
    """"""
    failure_line = text_log_error.metadata.failure_line
    logger.debug("Looking for test match in failure %d", failure_line.id)

    if failure_line.action != "test_result" or failure_line.message is None:
        return

    f = {
        'text_log_error___metadata__failure_line__action': 'test_result',
        'text_log_error___metadata__failure_line__test': failure_line.test,
        'text_log_error___metadata__failure_line__subtest': failure_line.subtest,
        'text_log_error___metadata__failure_line__status': failure_line.status,
        'text_log_error___metadata__failure_line__expected': failure_line.expected,
        'text_log_error___metadata__failure_line__message': failure_line.message
    }
    qwargs = (
        Q(text_log_error___metadata__best_classification=None)
        & (Q(text_log_error___metadata__best_is_verified=True)
           | Q(text_log_error__step__job=text_log_error.step.job))
    )
    qs = (TextLogErrorMatch.objects.filter(**f)
                                   .exclude(qwargs)
                                   .order_by('-score', '-classified_failure'))

    if not qs:
        return

    # chunk through the QuerySet because it could potentially be very large
    # time bound each call to the scoring function to avoid job timeouts
    # returns an iterable of (score, classified_failure_id) tuples
    chunks = chunked_qs_reverse(qs, chunk_size=20000)
    return chain.from_iterable(time_boxed(score_matches, chunks, time_budget=500))
1268163
def strerror(errno):
    """"""
    from pypy.module._codecs.locale import str_decode_locale_surrogateescape
    return str_decode_locale_surrogateescape(os.strerror(errno))
390776
def error_value_processor(value, error):
    
    if isinstance(error, (str, unicode)):
        try:
            if "%" in error:
                error_float = float(error.replace("%", ""))
                error_abs = (value/100) * error_float
                return error_abs
            elif error == "":
                error = 0.0
            else:
                error = float(error)
        except:
            pass

    return error
341551
private int handleMultipleFailures(ErrorInfo error) {
    MultipleFailureException multiFailure = (MultipleFailureException) error.getException();
    int runStatus = OK;
    for (Throwable failure : multiFailure.getFailures())
      runStatus = error(new ErrorInfo(error.getMethod(), failure));
    return runStatus;
  }

  private boolean isFailedEqualityComparison(Throwable exception) {
    if (!(exception instanceof ConditionNotSatisfiedError)) return false;

    ConditionNotSatisfiedError conditionNotSatisfiedError = (ConditionNotSatisfiedError) exception;
    Condition condition = conditionNotSatisfiedError.getCondition();
    ExpressionInfo expr = condition.getExpression();
    return expr != null && expr.isEqualityComparison() && // it is equality
        conditionNotSatisfiedError.getCause() == null;    // and it is not failed because of exception
  }

  // enables IDE support (diff dialog)
  private Throwable convertToComparisonFailure(Throwable exception) {
    assert isFailedEqualityComparison(exception);

    ConditionNotSatisfiedError conditionNotSatisfiedError = (ConditionNotSatisfiedError) exception;
    Condition condition = conditionNotSatisfiedError.getCondition();
    ExpressionInfo expr = condition.getExpression();

    String actual = renderValue(expr.getChildren().get(0).getValue());
    String expected = renderValue(expr.getChildren().get(1).getValue());
    ComparisonFailure failure = new SpockComparisonFailure(condition, expected, actual);
    failure.setStackTrace(exception.getStackTrace());

    if (conditionNotSatisfiedError.getCause()!=null){
      failure.initCause(conditionNotSatisfiedError.getCause());
    }

    return failure;
  }

  private String renderValue(Object value) {
    try {
      return diffedObjectRenderer.render(value);
    } catch (Throwable t) {
      return "Failed to render value due to:\n\n" + TextUtil.printStackTrace(t);
    }
  }

  private int statusFor(ErrorInfo error) {
    switch (error.getMethod().getKind()) {
      case DATA_PROCESSOR:
      case INITIALIZER:
      case ITERATION_EXECUTION:
      case SETUP:
      case CLEANUP:
      case FEATURE:
        return END_ITERATION;
      case FEATURE_EXECUTION:
      case DATA_PROVIDER:
        return END_FEATURE;
      case SHARED_INITIALIZER:
      case SETUP_SPEC:
      case CLEANUP_SPEC:
      case SPEC_EXECUTION:
        return END_SPEC;
      default:
        throw new InternalSpockError("unknown method kind");
    }
  }

  @Override
  public void afterIteration(IterationInfo iteration) {
    masterListener.afterIteration(iteration);
    if (currentFeature.isReportIterations())
      notifier.fireTestFinished(iteration.getDescription());

    currentIteration = null;
  }

  @Override
  public void afterFeature(FeatureInfo feature) {
    if (feature.isParameterized()) {
      if (iterationCount == 0 && !errorSinceLastReset)
        notifier.fireTestFailure(new Failure(feature.getDescription(),
            new SpockExecutionException("Data provider has no data")));
    }

    masterListener.afterFeature(feature);
    if (!feature.isReportIterations())
      notifier.fireTestFinished(feature.getDescription());

    currentFeature = null;
  }

  @Override
  public void afterSpec(SpecInfo spec) {
    masterListener.afterSpec(spec);
  }

  @Override
  public void specSkipped(SpecInfo spec) {
    masterListener.specSkipped(spec);
    notifier.fireTestIgnored(spec.getDescription());
  }

  @Override
  public void featureSkipped(FeatureInfo feature) {
    masterListener.featureSkipped(feature);
    notifier.fireTestIgnored(feature.getDescription());
  }

  private Description getCurrentDescription() {
    if (currentIteration != null && currentFeature.isReportIterations())
      return currentIteration.getDescription();
    if (currentFeature != null)
      return currentFeature.getDescription();
    return spec.getDescription();
  }
}
619768
def ExceptionHook(exctype, value, tb):
    '''
    

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
819324
def _check_prob_and_prob_vector(predictions):
    
    from .._deps import numpy

    ptype = predictions.dtype
    import array
    if ptype not in [float, numpy.ndarray, array.array, int]:
        err_msg  = "Input `predictions` must be of numeric type (for binary "
        err_msg += "classification) or array (of probability vectors) for "
        err_msg += "multiclass classification."
        raise TypeError(err_msg)
1263469
def maybe_raise(cls, error_type, ignores=None):
        
        ignores = set(ignores or [])
        ignores.add(ErrorType.Ok)
        if error_type not in ignores:
            raise LibError(error_type)