Ejemplo n.º 1
0
string Allele::tojson(void) {
    stringstream out;
    if (!genotypeAllele) {
        out << "{\"id\":\"" << readID << "\""
            << ",\"type\":\"" << typeStr() << "\""
            << ",\"length\":" << ((type == ALLELE_REFERENCE) ? 1 : length)
            << ",\"position\":" << position 
            << ",\"strand\":\"" << (strand == STRAND_FORWARD ? "+" : "-") << "\"";
        if (type == ALLELE_REFERENCE ) {
            out << ",\"base\":\"" << alternateSequence.at(referenceOffset()) << "\""
                //<< ",\"reference\":\"" << allele.referenceSequence.at(referenceOffset) << "\""
                << ",\"quality\":" << currentQuality();
        } else {
            out << ",\"base\":\"" << alternateSequence << "\""
                //<< ",\"reference\":\"" << allele.referenceSequence << "\""
                << ",\"quality\":" << quality;
        }
        out << "}";

    } else {
        out << "{\"type\":\"" << typeStr() << "\"";
        switch (type) {
            case ALLELE_REFERENCE:
                out << "}";
                break;
            default:
                out << "\",\"length\":" << length 
                    << ",\"alt\":\"" << alternateSequence << "\"}";
                break;
        }
    }
    return out.str();
}
Ejemplo n.º 2
0
std::shared_ptr< ExhaustiveLPOModelTrainer > makeExhaustiveTrainer( const ExhaustiveLPOModel & that, const std::vector< std::shared_ptr< ImageOverSegmentation > >& ios, const std::vector< T >& gt ) {
    std::string name = typeStr(that);

    std::vector< VectorXf > params = that.all_params_;
    const int N = ios.size(), M = params.size();
    std::vector<int> oid( gt.size()+1 );
    std::transform( gt.begin(), gt.end(), oid.data()+1, static_cast<int(*)(const T&)>(&no) );
    std::partial_sum( oid.begin(), oid.end(), oid.begin() );

    std::vector< float > avg_prop( params.size(), 0. );
    std::vector< std::vector< float > > iou( params.size(), std::vector< float >(oid.back(),0.f) );
    #pragma omp parallel for
    for( int i=0; i<N; i++ ) {
        std::vector<Proposals> s = that.generateProposals( *ios[i], params );
        for( int j=0; j<M; j++ ) {
            Proposals p = s[j];

            SegmentationOverlap o(p.s, gt[i]);
            const int no = o.nObjects();
            eassert( oid[i]+no == oid[i+1] );

            auto best_iou = VectorXf::Map(iou[j].data()+oid[i],no);
            int n = p.p.rows();
            for( int k=0; k<n; k++ )
                best_iou = best_iou.array().max( o.iou( p.p.row(k) ).array() );

            #pragma omp atomic
            avg_prop[j] += 1.0 * n / N;
        }
    }
    return std::make_shared<ExhaustiveLPOModelTrainerImplementation>( name, params, iou, avg_prop );
}
Ejemplo n.º 3
0
	//---------------------------------------------------------------------
	void SceneResource::processLight(const Util::XmlNode * lightNode, SceneNodePtr & parentSceneNode) const
	{
		Util::String typeStr(mXmlReader->getAttribute(lightNode, "type"));
		LightInfo lightInfo;
		
		Util::String str;
		if (boost::algorithm::equals("directional_light", typeStr))
		{
			lightInfo.Type = LT_DIRECTIONAL;

			str = mXmlReader->getAttribute(lightNode, "direction");
			XMStoreFloat3(&lightInfo.Direction, Util::StringToVector(str, 3));
		}
		else if (boost::algorithm::equals("point_light", typeStr))
		{
			lightInfo.Type = LT_POINT;

			str = mXmlReader->getAttribute(lightNode, "effect_distance");
			lightInfo.EffectDistance = boost::lexical_cast<Util::real>(str);
		}

		str = mXmlReader->getAttribute(lightNode, "color");
		XMStoreFloat3(&lightInfo.Color, Util::StringToVector(str, 3));

		Util::Wstring name = Util::StringToWstring(mXmlReader->getAttribute(lightNode, "name"));

		SceneObjectPtr light = EngineManager::getSingleton().getSceneManager()->createLight(name, lightInfo);

		parentSceneNode->attachSceneObject(light);
	}
Ejemplo n.º 4
0
void
zbar_receive_message (GstBus *bus, GstMessage *message, gpointer zbar)
{
  ZBarFilter *filter = (ZBarFilter *) zbar;

  if (GST_MESSAGE_SRC (message) == GST_OBJECT (filter->zbar) &&
      GST_MESSAGE_TYPE (message) == GST_MESSAGE_ELEMENT) {
    const GstStructure *st;
    guint64 ts;
    gchar *type, *symbol;

    st = gst_message_get_structure (message);

    if (g_strcmp0 (gst_structure_get_name (st), "barcode") != 0)
      return;

    if (!gst_structure_get (st, "timestamp", G_TYPE_UINT64, &ts,
                            "type", G_TYPE_STRING, &type, "symbol", G_TYPE_STRING, &symbol, NULL) )
      return;

    std::string symbolStr (symbol);
    std::string typeStr (type);

    g_free (type);
    g_free (symbol);

    filter->barcodeDetected (ts, typeStr, symbolStr);
  }
}
Ejemplo n.º 5
0
void BlitzMainWindow::slotModulate()
{
    QString filename(QFileDialog::getOpenFileName(this, tr("Select image to modulate")));
    if(filename.isEmpty())
        return;
    QImage modImg(filename);
    if(modImg.isNull()){
        QMessageBox::warning(this, tr("File Open Error"),
                             tr("Unable to open image."));
        return;
    }

    QStringList types;
    types << tr("Intensity") << tr("Saturation") << tr("Hue") << tr("Contrast");
    bool ok;
    QString typeStr(QInputDialog::getItem(this, tr("Select modulation type"),
                                          tr("Modulation type:"), types, 0,
                                          false, &ok));
    if(!ok)
        return;

    Blitz::ModulationType type;
    if(typeStr == tr("Intensity"))
        type = Blitz::Intensity;
    else if(typeStr == tr("Saturation"))
        type = Blitz::Saturation;
    else if(typeStr == tr("Hue"))
        type = Blitz::HueShift;
    else
        type = Blitz::Contrast;

    img = Blitz::modulate(img, modImg, false, type, 200, Blitz::All);
    lbl->setPixmap(QPixmap::fromImage(img));
    lbl->update();
}
Ejemplo n.º 6
0
void ZBarFilterImpl::busMessage (GstMessage *message)
{

  if (GST_MESSAGE_SRC (message) == GST_OBJECT (zbar) &&
      GST_MESSAGE_TYPE (message) == GST_MESSAGE_ELEMENT) {
    const GstStructure *st;
    guint64 ts;
    gchar *type, *symbol;

    st = gst_message_get_structure (message);

    if (g_strcmp0 (gst_structure_get_name (st), "barcode") != 0) {
      return;
    }

    if (!gst_structure_get (st, "timestamp", G_TYPE_UINT64, &ts,
                            "type", G_TYPE_STRING, &type, "symbol",
                            G_TYPE_STRING, &symbol, NULL) ) {
      return;
    }

    std::string symbolStr (symbol);
    std::string typeStr (type);

    g_free (type);
    g_free (symbol);

    barcodeDetected (ts, typeStr, symbolStr);
  }
}
Ejemplo n.º 7
0
pawsFrameDrawable::pawsFrameDrawable(csRef<iDocumentNode> node)
    : scfImplementationType (this)
{
    defaultTransparentColourBlue  = -1;
    defaultTransparentColourGreen = -1;
    defaultTransparentColourRed   = -1;

    defaultAlphaValue = 0;

    // Read off the image and file vars
    imageFileLocation = node->GetAttributeValue("file");
    resourceName = node->GetAttributeValue("resource");

    csString typeStr(node->GetAttributeValue("type"));
    type = FDT_FULL;
    if (typeStr == "horizontal")
        type = FDT_HORIZONTAL;
    else if (typeStr == "vertical")
        type = FDT_VERTICAL;

    csRef<iDocumentNodeIterator> iter = node->GetNodes();
    while ( iter->HasNext() )
    {
        csRef<iDocumentNode> childNode = iter->Next();

        // Read the default alpha value.
        if (strcmp(childNode->GetValue(), "alpha") == 0)
            defaultAlphaValue = childNode->GetAttributeValueAsInt("level");

        // Read the default transparent colour.
        else if (strcmp(childNode->GetValue(), "trans") == 0)
        {
            defaultTransparentColourRed   = childNode->GetAttributeValueAsInt("r");
            defaultTransparentColourGreen = childNode->GetAttributeValueAsInt("g");
            defaultTransparentColourBlue  = childNode->GetAttributeValueAsInt("b");
        }

        else if (strcmp(childNode->GetValue(), "top_left") == 0)
            LoadPiece(childNode, FDP_TOP_LEFT);
        else if (strcmp(childNode->GetValue(), "top") == 0)
            LoadPiece(childNode, FDP_TOP);
        else if (strcmp(childNode->GetValue(), "top_right") == 0)
            LoadPiece(childNode, FDP_TOP_RIGHT);
        else if (strcmp(childNode->GetValue(), "left") == 0)
            LoadPiece(childNode, FDP_LEFT);
        else if (strcmp(childNode->GetValue(), "middle") == 0)
            LoadPiece(childNode, FDP_MIDDLE);
        else if (strcmp(childNode->GetValue(), "right") == 0)
            LoadPiece(childNode, FDP_RIGHT);
        else if (strcmp(childNode->GetValue(), "bottom_left") == 0)
            LoadPiece(childNode, FDP_BOTTOM_LEFT);
        else if (strcmp(childNode->GetValue(), "bottom") == 0)
            LoadPiece(childNode, FDP_BOTTOM);
        else if (strcmp(childNode->GetValue(), "bottom_right") == 0)
            LoadPiece(childNode, FDP_BOTTOM_RIGHT);
    }

}
Ejemplo n.º 8
0
Archivo: pass3.c Proyecto: aeppert/pcp
static double
unwrap(double current, struct timeval *curtime, checkData *checkdata, int index)
{
    double	outval = current;
    int		wrapflag = 0;
    char	*str = NULL;

    if ((current - checkdata->instlist[index]->lastval) < 0.0 &&
        checkdata->instlist[index]->lasttime.tv_sec > 0) {
	switch (checkdata->desc.type) {
	    case PM_TYPE_32:
	    case PM_TYPE_U32:
		outval += (double)UINT_MAX+1;
		wrapflag = 1;
		break;
	    case PM_TYPE_64:
	    case PM_TYPE_U64:
		outval += (double)ULONGLONG_MAX+1;
		wrapflag = 1;
		break;
	    default:
		wrapflag = 0;
	}
    }

    if (wrapflag) {
	fprintf(stderr, "%s.%d:[", l_archname, l_ctxp->c_archctl->ac_vol);
	print_stamp(stderr, curtime);
	fprintf(stderr, "]: ");
	print_metric(stderr, checkdata->desc.pmid);
	if (pmNameInDom(checkdata->desc.indom, checkdata->instlist[index]->inst, &str) < 0)
	    fprintf(stderr, ": %s wrap", typeStr(checkdata->desc.type));
	else {
	    fprintf(stderr, "[%s]: %s wrap", str, typeStr(checkdata->desc.type));
	    free(str);
	}
	fprintf(stderr, "\n\tvalue %.0f at ", checkdata->instlist[index]->lastval);
	print_stamp(stderr, &checkdata->instlist[index]->lasttime);
	fprintf(stderr, "\n\tvalue %.0f at ", current);
	print_stamp(stderr, curtime);
	fputc('\n', stderr);
    }

    return outval;
}
Ejemplo n.º 9
0
bool parseArgs(const int argc, const char* const argv[], CLIOptions& options)
{
    std::list<std::string> optStr;
    for(int i = 1; i < argc; ++i)
        optStr.push_back(argv[i]);

    if (optStr.empty())
    {
        std::cerr << "No input specified" << std::endl;
        return false;
    }
    if(optStr.front() == "--help")
        return false;
    options.filePath = optStr.front();
    optStr.pop_front();

    bool moreOptions = true;
    while(!optStr.empty() && moreOptions)
    {
        std::string flag(optStr.front());
        if (flag == "--verbose" || flag == "-v") {
            optStr.pop_front();
        } else if(flag == "--display-type" || flag == "-t")
        {
            optStr.pop_front();
            if(optStr.empty())
                return false;

            std::string typeStr(optStr.front());
            optStr.pop_front();
            if(typeStr == "fileType")
                options.displayType = DisplayType::fileType;
            else if(typeStr == "subtree")
                options.displayType = DisplayType::subtree;
            else if(typeStr == "info")
                options.displayType = DisplayType::info;
            else if(typeStr == "value")
                options.displayType = DisplayType::value;
            else if(typeStr == "numberOfChildren")
                options.displayType = DisplayType::numberOfChildren;
            else if(typeStr == "size")
                options.displayType = DisplayType::size;
            else if(typeStr == "binary")
                options.displayType = DisplayType::binary;
            else
                return false;
        } else if(flag == "--max-depth" || flag == "-d")
        {
            optStr.pop_front();
            if(optStr.empty())
                return false;

            std::stringstream mdStream(optStr.front());
            mdStream >> options.maxDepth;
            optStr.pop_front();
        } else
        { moreOptions = false; }
Ejemplo n.º 10
0
jobject v8ToJava(JNIEnv* env, v8::Local<v8::Value> arg) {
  if(arg->IsNull() || arg->IsUndefined()) {
    return NULL;
  }

  if(arg->IsArray()) {
    v8::Local<v8::Array> array = v8::Array::Cast(*arg);
    uint32_t arraySize = array->Length();
    jclass objectClazz = env->FindClass("java/lang/Object");
    jobjectArray result = env->NewObjectArray(arraySize, objectClazz, NULL);
    for(uint32_t i=0; i<arraySize; i++) {
      jobject val = v8ToJava(env, array->Get(i));
      env->SetObjectArrayElement(result, i, val);
    }
    return result;
  }

  if(arg->IsString()) {
    v8::String::AsciiValue val(arg->ToString());
    return env->NewStringUTF(*val);
  }

  if(arg->IsInt32() || arg->IsUint32()) {
    jint val = arg->ToInt32()->Value();
    jclass clazz = env->FindClass("java/lang/Integer");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(I)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsNumber()) {
    jdouble val = arg->ToNumber()->Value();
    jclass clazz = env->FindClass("java/lang/Double");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(D)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsBoolean()) {
    jboolean val = arg->ToBoolean()->Value();
    jclass clazz = env->FindClass("java/lang/Boolean");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(Z)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsObject()) {
    v8::Local<v8::Object> obj = v8::Object::Cast(*arg);
    v8::String::AsciiValue constructorName(obj->GetConstructorName());
    if(strcmp(*constructorName, "JavaObject") == 0) {
      JavaObject* javaObject = node::ObjectWrap::Unwrap<JavaObject>(obj);
      return javaObject->getObject();
    }
  }

  // TODO: handle other arg types
  v8::String::AsciiValue typeStr(arg);
  printf("Unhandled type: %s\n", *typeStr);
  return NULL;
}
    string variantType(Variant & variant) {

        assert(variant.numAlts() > hasMissing(variant));

        if (variant.numAlts() > (1 + static_cast<uint>(hasMissing(variant)))) {

            return "Multi";
        } 

        auto cur_type = alleleAttributes(variant.alt(0), variant.ref());

        assert(cur_type.type != Type::Reference);
        assert(cur_type.type != Type::Missing);

        return cur_type.typeStr();
    }
Ejemplo n.º 12
0
void BlitzMainWindow::slotGrayscaleUnbalancedGradient()
{
    QStringList types;
    types << tr("Vertical") << tr("Horizontal") << tr("Diagonal") <<
        tr("Cross Diagonal") << tr("Pyramid") << tr("Rectangle") <<
        tr("Pipe Cross") << tr("Elliptic");
    bool ok;
    QString typeStr(QInputDialog::getItem(this, tr("Select gradient type"),
                                          tr("Gradient type:"), types, 0,
                                          false, &ok));
    if(!ok)
        return;
    img = Blitz::grayUnbalancedGradient(img.size(), 0xFF, 0x00,
                                        (Blitz::GradientType)types.indexOf(typeStr));
    lbl->setPixmap(QPixmap::fromImage(img));
    lbl->update();
}
Ejemplo n.º 13
0
int main(int argc, char* argv[]) {
    srand(time(NULL));

    setlocale(LC_ALL, "en_US.utf8");
    initscr();
    raw();
    noecho();
    start_color();
    init_pair(FAIL, COLOR_RED, COLOR_BLACK);

    WINDOW *typeWin = newwin(4, COLS, 0, 0);
    box(typeWin, 0, 0);
    refresh();
    typeStr(typeWin, genStr("data-russian", 50));

    endwin();
    return 0;
}
Ejemplo n.º 14
0
void StringBuilder::append(Value v, bool raw) {
    void *ptr = GET_PTR(v);
    if (IS_STRING(v)) {
        if (!raw) { append('\''); }
        append(GET_CSTR(v), len(v));
        if (!raw) { append('\''); }
    } else if (IS_NUM(v)) {
        append(GET_NUM(v));
        return;
    } else if (IS_ARRAY(v)) {
        Array *a = (Array *) ptr;
        int size = a->size();
        append('[');
        for (int i = 0; i < size; ++i) {
            append(i ? ", " : "");
            append(a->getI(i));
        }
        append(']');
    } else if (IS_MAP(v)) {
        Map *m = (Map *) ptr;
        int size = m->size();
        append('{');
        Value *keys = m->keyBuf();
        Value *vals = m->valBuf();
        for (int i = 0; i < size; ++i) {
            append(i ? ", " : "");
            append(keys[i]);
            append(':');
            append(vals[i]);
        }
        append('}');
    } else if (IS_NIL(v)) {
        append("nil");
    } else {
        append('<');
        append(typeStr(v));
        append('>');
        char tmp[32];
        snprintf(tmp, sizeof(tmp), "%p", ptr);
        append(tmp);
    }
}
Ejemplo n.º 15
0
////////////////////////////////////////////////////////////////////////////////
////
//// Payload classes
////
////////////////////////////////////////////////////////////////////////////////
vector<uint8_t> Payload::serialize(uint32_t magic_word) const
{
   //serialize payload
   auto payload_size = serialize_inner(nullptr);
   
   vector<uint8_t> msg;
   msg.resize(MESSAGE_HEADER_LEN + payload_size);
   if (payload_size > 0)
      serialize_inner(&msg[MESSAGE_HEADER_LEN]);

   //magic word
   uint8_t* ptr = &msg[0];
   uint32_t* magicword = (uint32_t*)(ptr + MAGIC_WORD_OFFSET);
   *magicword = magic_word;

   //message type
   auto&& type = typeStr();
   char* msgtype = (char*)(ptr + MESSAGE_TYPE_OFFSET);
   memset(msgtype, 0, MESSAGE_TYPE_LEN);
   memcpy(msgtype, type.c_str(), type.size());

   //length
   uint32_t msglen = payload_size;
   uint32_t* msglenptr = (uint32_t*)(ptr + PAYLOAD_LENGTH_OFFSET);
   *msglenptr = msglen;

   //checksum
   uint8_t* payloadptr = nullptr;
   if (payload_size > 0)
      payloadptr = &msg[MESSAGE_HEADER_LEN];
   BinaryDataRef bdr(payloadptr, payload_size);
   auto&& hash = BtcUtils::getHash256(bdr);
   uint32_t* checksum = (uint32_t*)hash.getPtr();
   uint32_t* checksumptr = (uint32_t*)(ptr + CHECKSUM_OFFSET);
   *checksumptr = *checksum;

   return msg;
}
Ejemplo n.º 16
0
void 
MediaDocument::UpdateTitleAndCharset(const nsACString& aTypeStr,
                                     const char* const* aFormatNames,
                                     int32_t aWidth, int32_t aHeight,
                                     const nsAString& aStatus)
{
  nsXPIDLString fileStr;
  GetFileName(fileStr);

  NS_ConvertASCIItoUTF16 typeStr(aTypeStr);
  nsXPIDLString title;

  if (mStringBundle) {
    // if we got a valid size (not all media have a size)
    if (aWidth != 0 && aHeight != 0) {
      nsAutoString widthStr;
      nsAutoString heightStr;
      widthStr.AppendInt(aWidth);
      heightStr.AppendInt(aHeight);
      // If we got a filename, display it
      if (!fileStr.IsEmpty()) {
        const char16_t *formatStrings[4]  = {fileStr.get(), typeStr.get(), 
          widthStr.get(), heightStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDimAndFile]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 4,
                                            getter_Copies(title));
      } 
      else {
        const char16_t *formatStrings[3]  = {typeStr.get(), widthStr.get(), 
          heightStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDim]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 3,
                                            getter_Copies(title));
      }
    } 
    else {
    // If we got a filename, display it
      if (!fileStr.IsEmpty()) {
        const char16_t *formatStrings[2] = {fileStr.get(), typeStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithFile]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2,
                                            getter_Copies(title));
      }
      else {
        const char16_t *formatStrings[1] = {typeStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithNoInfo]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 1,
                                            getter_Copies(title));
      }
    }
  } 

  // set it on the document
  if (aStatus.IsEmpty()) {
    SetTitle(title);
  }
  else {
    nsXPIDLString titleWithStatus;
    const nsPromiseFlatString& status = PromiseFlatString(aStatus);
    const char16_t *formatStrings[2] = {title.get(), status.get()};
    NS_NAMED_LITERAL_STRING(fmtName, "TitleWithStatus");
    mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2,
                                        getter_Copies(titleWithStatus));
    SetTitle(titleWithStatus);
  }
}
Ejemplo n.º 17
0
std::string petabricks::RIRExpr::debugStr() const { 
  return typeStr() + std::string(" ") + _str;
}
Ejemplo n.º 18
0
std::string petabricks::RIRNode::debugStr() const { 
  return typeStr(); 
}
Ejemplo n.º 19
0
void Event::trace()
{
    string sType = typeStr();
    AVG_TRACE(Logger::category::EVENTS,Logger::severity::INFO, sType); 
}
Ejemplo n.º 20
0
	static std::string get(const U & val){
		return typeStr(val);
	}
Ejemplo n.º 21
0
	/// Determine if this M_PDU matches expected parameters.
	/// @param expectedSize The intended size of the unit.
	/// @throw WrongSize If getUnitLength() is different than expectedSize.
	void throwIfInvalid(const size_t expectedSize) {
		if ( expectedSize != getUnitLength() )
			throw WrongSize(WrongSize::msg(typeStr(), expectedSize, getUnitLength()));
	}
void 
nsMediaDocument::UpdateTitleAndCharset(const nsACString& aTypeStr,
                                       const char* const* aFormatNames,
                                       PRInt32 aWidth, PRInt32 aHeight,
                                       const nsAString& aStatus)
{
  nsXPIDLString fileStr;
  if (mDocumentURI) {
    nsCAutoString fileName;
    nsCOMPtr<nsIURL> url = do_QueryInterface(mDocumentURI);
    if (url)
      url->GetFileName(fileName);

    nsCAutoString docCharset;

    // Now that the charset is set in |StartDocumentLoad| to the charset of
    // the document viewer instead of a bogus value ("ISO-8859-1" set in
    // |nsDocument|'s ctor), the priority is given to the current charset. 
    // This is necessary to deal with a media document being opened in a new 
    // window or a new tab, in which case |originCharset| of |nsIURI| is not 
    // reliable.
    if (mCharacterSetSource != kCharsetUninitialized) {  
      docCharset = mCharacterSet;
    }
    else {  
      // resort to |originCharset|
      mDocumentURI->GetOriginCharset(docCharset);
      SetDocumentCharacterSet(docCharset);
    }
    if (!fileName.IsEmpty()) {
      nsresult rv;
      nsCOMPtr<nsITextToSubURI> textToSubURI = 
        do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
      if (NS_SUCCEEDED(rv))
        // UnEscapeURIForUI always succeeds
        textToSubURI->UnEscapeURIForUI(docCharset, fileName, fileStr);
      else 
        CopyUTF8toUTF16(fileName, fileStr);
    }
  }


  NS_ConvertASCIItoUTF16 typeStr(aTypeStr);
  nsXPIDLString title;

  if (mStringBundle) {
    // if we got a valid size (not all media have a size)
    if (aWidth != 0 && aHeight != 0) {
      nsAutoString widthStr;
      nsAutoString heightStr;
      widthStr.AppendInt(aWidth);
      heightStr.AppendInt(aHeight);
      // If we got a filename, display it
      if (!fileStr.IsEmpty()) {
        const PRUnichar *formatStrings[4]  = {fileStr.get(), typeStr.get(), 
          widthStr.get(), heightStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDimAndFile]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 4,
                                            getter_Copies(title));
      } 
      else {
        const PRUnichar *formatStrings[3]  = {typeStr.get(), widthStr.get(), 
          heightStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithDim]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 3,
                                            getter_Copies(title));
      }
    } 
    else {
    // If we got a filename, display it
      if (!fileStr.IsEmpty()) {
        const PRUnichar *formatStrings[2] = {fileStr.get(), typeStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithFile]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2,
                                            getter_Copies(title));
      }
      else {
        const PRUnichar *formatStrings[1] = {typeStr.get()};
        NS_ConvertASCIItoUTF16 fmtName(aFormatNames[eWithNoInfo]);
        mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 1,
                                            getter_Copies(title));
      }
    }
  } 

  // set it on the document
  if (aStatus.IsEmpty()) {
    SetTitle(title);
  }
  else {
    nsXPIDLString titleWithStatus;
    const nsPromiseFlatString& status = PromiseFlatString(aStatus);
    const PRUnichar *formatStrings[2] = {title.get(), status.get()};
    NS_NAMED_LITERAL_STRING(fmtName, "TitleWithStatus");
    mStringBundle->FormatStringFromName(fmtName.get(), formatStrings, 2,
                                        getter_Copies(titleWithStatus));
    SetTitle(titleWithStatus);
  }
}
Ejemplo n.º 23
0
void
MediaDocument::UpdateTitleAndCharset(const nsACString& aTypeStr,
                                     nsIChannel* aChannel,
                                     const char* const* aFormatNames,
                                     int32_t aWidth, int32_t aHeight,
                                     const nsAString& aStatus)
{
  nsAutoString fileStr;
  GetFileName(fileStr, aChannel);

  NS_ConvertASCIItoUTF16 typeStr(aTypeStr);
  nsAutoString title;

  if (mStringBundle) {
    // if we got a valid size (not all media have a size)
    if (aWidth != 0 && aHeight != 0) {
      nsAutoString widthStr;
      nsAutoString heightStr;
      widthStr.AppendInt(aWidth);
      heightStr.AppendInt(aHeight);
      // If we got a filename, display it
      if (!fileStr.IsEmpty()) {
        const char16_t *formatStrings[4]  = {fileStr.get(), typeStr.get(),
          widthStr.get(), heightStr.get()};
        mStringBundle->FormatStringFromName(aFormatNames[eWithDimAndFile],
                                            formatStrings, 4, title);
      }
      else {
        const char16_t *formatStrings[3]  = {typeStr.get(), widthStr.get(),
          heightStr.get()};
        mStringBundle->FormatStringFromName(aFormatNames[eWithDim],
                                            formatStrings, 3, title);
      }
    }
    else {
    // If we got a filename, display it
      if (!fileStr.IsEmpty()) {
        const char16_t *formatStrings[2] = {fileStr.get(), typeStr.get()};
        mStringBundle->FormatStringFromName(aFormatNames[eWithFile],
                                            formatStrings, 2, title);
      }
      else {
        const char16_t *formatStrings[1] = {typeStr.get()};
        mStringBundle->FormatStringFromName(aFormatNames[eWithNoInfo],
                                            formatStrings, 1, title);
      }
    }
  }

  // set it on the document
  if (aStatus.IsEmpty()) {
    IgnoredErrorResult ignored;
    SetTitle(title, ignored);
  }
  else {
    nsAutoString titleWithStatus;
    const nsPromiseFlatString& status = PromiseFlatString(aStatus);
    const char16_t *formatStrings[2] = {title.get(), status.get()};
    mStringBundle->FormatStringFromName("TitleWithStatus", formatStrings,
                                        2, titleWithStatus);
    IgnoredErrorResult ignored;
    SetTitle(titleWithStatus, ignored);
  }
}
Ejemplo n.º 24
0
	void getSummary(const string & vcf_filename, const string & output_prefix, const float min_called_probability, const string & parents_trio_regular_expression, const vector<string> & excluded_sample_ids) {

		cout << "[" << Utils::getLocalTime() << "] Running BayesTyperUtils (" << BTU_VERSION << ") getSummary ...\n" << endl;

		GenotypedVcfFileReader vcf_reader(vcf_filename, true);

        for (auto &sample_id: excluded_sample_ids) {

        	vcf_reader.metaData().rmSample(sample_id);
        }

        cout << "[" << Utils::getLocalTime() << "] Excluded " << excluded_sample_ids.size() << " sample(s)" << endl;

		uint num_parent_samples = 0;
		regex parent_sample_id_regex(parents_trio_regular_expression);

    	for (auto &sample_id: vcf_reader.metaData().sampleIds()) {

        	if (regex_match(sample_id, parent_sample_id_regex)) {

        		num_parent_samples++;
        	}
        }

		cout << "[" << Utils::getLocalTime() << "] Calculating population statistics on " << num_parent_samples << " parent sample(s)\n" << endl;

		Variant * cur_var;

		uint num_variants = 0;
		uint num_alleles = 0;

		uint num_genotypes = 0;

		unordered_map<string, uint> variant_summary_stats;
		unordered_map<string, uint> allele_summary_stats;
		unordered_map<string, uint> mac_summary_stats;
		unordered_map<string, uint> de_novo_summary_stats;
	 
		while (vcf_reader.getNextVariant(&cur_var)) {

			num_variants++;
			num_alleles += cur_var->numAlls();

			assert(cur_var->filters().size() == 1);

			string chrom_type = vcf_reader.metaData().getContig(cur_var->chrom()).typeStr();

			uint num_filtered_samples = 0;
			uint num_filtered_parent_samples = 0;

			uint num_called_samples = 0;
			uint num_called_parent_samples = 0;

			for (auto &sample_id: vcf_reader.metaData().sampleIds()) {

    			num_genotypes++;
    			Sample & cur_sample = cur_var->getSample(sample_id);

				assert(cur_sample.ploidy() != Sample::Ploidy::Polyploid);
				assert(cur_sample.callStatus() != Sample::CallStatus::Partial);

    			if (!(cur_sample.isInformative())) {

    				if (cur_sample.callStatus() == Sample::CallStatus::Missing) {

    					num_filtered_samples++;

    					if (regex_match(sample_id, parent_sample_id_regex)) {

    						num_filtered_parent_samples++;
    					}

    				} else {

    					assert(chrom_type != "Autosomal");
						assert(cur_sample.ploidy() == Sample::Ploidy::Zeroploid);		
    				}

    			} else {

    				assert(cur_sample.callStatus() == Sample::CallStatus::Complete);

    				auto genotype_gpp = Auxiliaries::getGenotypePosterior(cur_sample);
            		assert(genotype_gpp == Auxiliaries::getMaxGenotypePosterior(cur_sample));

    				assert(genotype_gpp.second);

					if (genotype_gpp.first >= min_called_probability) {

    					num_called_samples++;

    					if (regex_match(sample_id, parent_sample_id_regex)) {

    						num_called_parent_samples++;
    					}	
					}
    			}
			}

			assert(num_filtered_samples <= vcf_reader.metaData().sampleIds().size());
			assert(num_filtered_parent_samples <= num_parent_samples);

			auto allele_call_prob = Stats::calcAlleleCallProbAndQualFromAllelePosteriors(cur_var);

			for (uint i = 0; i < cur_var->numAlls(); i++) {

            	assert(!cur_var->allele(i).info().setValue<float>("ACP", allele_call_prob.first.at(i)));
		
				JoiningString allele_summary_stats_str('\t');
				allele_summary_stats_str.join(chrom_type);
				allele_summary_stats_str.join(cur_var->filters().front());
				allele_summary_stats_str.join(Utils::boolToString(Auxiliaries::isAlleleAnnotated(cur_var->allele(i))));
				allele_summary_stats_str.join(getAlleleStringAttribute(cur_var->allele(i), "ACO"));
				allele_summary_stats_str.join(Utils::boolToString(Auxiliaries::isAlleleCalled(cur_var->allele(i), min_called_probability)));

				auto allele_attributes = Auxiliaries::alleleAttributes(cur_var->allele(i), cur_var->ref());
				auto at_value = cur_var->allele(i).info().getValue<string>("AT");
				
				if (at_value.second) {

					assert(allele_attributes.typeStr() == at_value.first);

				} else {

					assert(allele_attributes.type == Auxiliaries::Type::Reference);						
				}

				allele_summary_stats_str.join(allele_attributes.typeStr());
				allele_summary_stats_str.join(to_string(allele_attributes.length));
				allele_summary_stats_str.join(to_string(allele_attributes.num_ambiguous));
				allele_summary_stats_str.join(to_string(allele_attributes.sv_length));
				allele_summary_stats_str.join(getAlleleStringAttribute(cur_var->allele(i), "RMA"));

				auto allele_summary_stats_emplace = allele_summary_stats.emplace(allele_summary_stats_str.str(), 0);
				allele_summary_stats_emplace.first->second++;
			}

			JoiningString variant_summary_stats_str('\t');

			variant_summary_stats_str.join(chrom_type);
			variant_summary_stats_str.join(cur_var->filters().front());
			variant_summary_stats_str.join(Utils::boolToString(Auxiliaries::hasAmbiguous(*cur_var)));				
			variant_summary_stats_str.join(Utils::boolToString(Auxiliaries::hasAnnotatedAlternativeAllele(*cur_var)));				
			variant_summary_stats_str.join(Auxiliaries::variantType(*cur_var));
			variant_summary_stats_str.join(to_string(cur_var->numAlls()));
			variant_summary_stats_str.join(to_string(Auxiliaries::getCalledAlleleIdxsSorted(*cur_var, min_called_probability).size()));
			variant_summary_stats_str.join(to_string(num_filtered_samples));
			variant_summary_stats_str.join(to_string(num_called_samples));

			auto variant_summary_stats_emplace = variant_summary_stats.emplace(variant_summary_stats_str.str(), 0);
			variant_summary_stats_emplace.first->second++;

			if ((cur_var->numAlls() == 2) and (num_filtered_parent_samples == 0)) {

				assert(!(cur_var->allele(1).isMissing()));

				JoiningString mac_summary_stats_str('\t');

				mac_summary_stats_str.join(chrom_type);
				mac_summary_stats_str.join(cur_var->filters().front());
				mac_summary_stats_str.join(Utils::boolToString(Auxiliaries::hasAnnotatedAlternativeAllele(*cur_var)));				
				mac_summary_stats_str.join(getAlleleStringAttribute(cur_var->allele(1), "ACO"));
				mac_summary_stats_str.join(getAlleleStringAttribute(cur_var->allele(1), "RMA"));

				auto allele_attributes = Auxiliaries::alleleAttributes(cur_var->allele(1), cur_var->ref());
				auto at_value = cur_var->allele(1).info().getValue<string>("AT");
				
				assert(at_value.second);
				assert(allele_attributes.typeStr() == at_value.first);

				mac_summary_stats_str.join(allele_attributes.typeStr());
				mac_summary_stats_str.join(to_string(allele_attributes.length));
				mac_summary_stats_str.join(to_string(allele_attributes.num_ambiguous));
				mac_summary_stats_str.join(to_string(allele_attributes.sv_length));
				mac_summary_stats_str.join(to_string(num_called_parent_samples));

				auto allele_stats = Stats::calcAlleleStats(cur_var, parent_sample_id_regex);				
				assert(allele_stats.second);
				
				assert(allele_stats.first.allele_count_sum > 0);
				assert(allele_stats.first.allele_counts.size() == 2);

				if (allele_stats.first.allele_counts.front() <= allele_stats.first.allele_counts.back()) {

					mac_summary_stats_str.join(to_string(allele_stats.first.allele_counts.front()));
					mac_summary_stats_str.join(Utils::boolToString(false));
				
				} else {

					mac_summary_stats_str.join(to_string(allele_stats.first.allele_counts.back()));	
					mac_summary_stats_str.join(Utils::boolToString(true));
				}

				auto mac_summary_stats_emplace = mac_summary_stats.emplace(mac_summary_stats_str.str(), 0);
				mac_summary_stats_emplace.first->second++;
			}

			if (cur_var->info().hasValue("DNE")) {

    			assert(chrom_type == "Autosomal");

				auto dne_att_split = Utils::splitString(cur_var->info().getValue<string>("DNE").first, ',');
				assert(!(dne_att_split.empty()));

				for (auto &dne: dne_att_split) {

					auto dne_value_split = Utils::splitString(dne, ':');
					assert(dne_value_split.size() == 5);

					JoiningString de_novo_summary_stats_str('\t');
					de_novo_summary_stats_str.join(dne_value_split.front());

					assert(stoi(dne_value_split.at(2)) > 0);
					assert(stoi(dne_value_split.at(2)) != stoi(dne_value_split.at(1)));

					auto allele_attributes = Auxiliaries::alleleAttributes(cur_var->allele(stoi(dne_value_split.at(2))), cur_var->allele(stoi(dne_value_split.at(1))));
					assert(allele_attributes.typeStr() == dne_value_split.at(3));
					assert(allele_attributes.num_ambiguous == 0);

					de_novo_summary_stats_str.join(allele_attributes.typeStr());
					de_novo_summary_stats_str.join(to_string(allele_attributes.length));
					de_novo_summary_stats_str.join(to_string(allele_attributes.sv_length));

					de_novo_summary_stats_str.join(to_string(cur_var->numAlls()));
					de_novo_summary_stats_str.join(to_string(Auxiliaries::getNonZeroProbAlleleIdxsSorted(*cur_var).size()));

					if (stoi(dne_value_split.at(1)) == 0) {

						de_novo_summary_stats_str.join(getAlleleStringAttribute(cur_var->allele(stoi(dne_value_split.at(2))), "RMA"));

					} else {

						de_novo_summary_stats_str.join(getAlleleStringAttribute(cur_var->allele(0), "RMA"));
					}

					auto de_novo_summary_stats_emplace = de_novo_summary_stats.emplace(de_novo_summary_stats_str.str(), 0);
					de_novo_summary_stats_emplace.first->second++;
				}
			}

			delete cur_var;

			if ((num_variants % 100000) == 0) {

				std::cout << "[" << Utils::getLocalTime() << "] Parsed " << num_variants << " variants" << endl;
			}
		}

		JoiningString variant_summary_stats_header('\t');
		variant_summary_stats_header.join(variant_misc_attributes);

		writeSummaryStats(variant_summary_stats, output_prefix + "_variant.txt", variant_summary_stats_header.str());

		JoiningString mac_summary_stats_header('\t');
		mac_summary_stats_header.join(mac_misc_attributes);

		writeSummaryStats(mac_summary_stats, output_prefix + "_mac.txt", mac_summary_stats_header.str());

		JoiningString allele_summary_stats_header('\t');
		allele_summary_stats_header.join(allele_misc_attributes);

		writeSummaryStats(allele_summary_stats, output_prefix + "_allele.txt", allele_summary_stats_header.str());

		JoiningString de_novo_summary_stats_header('\t');
		de_novo_summary_stats_header.join(de_novo_misc_attributes);

		writeSummaryStats(de_novo_summary_stats, output_prefix + "_de_novo.txt", de_novo_summary_stats_header.str());


		cout << "\n[" << Utils::getLocalTime() << "] Parsed " << num_variants << " variants and " << num_alleles << " alleles (including reference and missing)\n" << endl;

		cout << "[" << Utils::getLocalTime() << "] Wrote summary statistics for a total of " << num_variants << " variant, " << num_alleles << " alleles and " << num_genotypes << " genotypes" << endl;
		cout << endl;
	}
	void generateRelease(const string & vcf_filename, const string & output_prefix, const float min_called_probability) {

		cout << "[" << Utils::getLocalTime() << "] Running BayesTyperUtils (" << BTU_VERSION << ") generateRelease ...\n" << endl;

		GenotypedVcfFileReader vcf_reader(vcf_filename, true);

		assert(vcf_reader.metaData().miscMeta().erase("CommandLine"));

		assert(vcf_reader.metaData().infoDescriptors().erase("AE"));
		assert(vcf_reader.metaData().infoDescriptors().erase("ANC"));
		assert(vcf_reader.metaData().infoDescriptors().erase("HCR"));
		assert(vcf_reader.metaData().infoDescriptors().erase("HRS"));
		assert(vcf_reader.metaData().infoDescriptors().erase("VCGI"));
		assert(vcf_reader.metaData().infoDescriptors().erase("VCGS"));
		assert(vcf_reader.metaData().infoDescriptors().erase("VCI"));
		assert(vcf_reader.metaData().infoDescriptors().erase("VCS"));
		assert(vcf_reader.metaData().infoDescriptors().erase("VT"));

		auto complete_meta_data = vcf_reader.metaData();

		assert(complete_meta_data.infoDescriptors().emplace("AT", Attribute::DetailedDescriptor("AT", Attribute::Number::A, Attribute::Type::String, "Allele type")).second);

		string lvq_label("LVQ");
		assert(complete_meta_data.filterDescriptors().emplace(lvq_label, Attribute::Descriptor(lvq_label, "All alternative alleles excluding missing have low allele call probability (ACP < " + to_string(min_called_probability) + ")")).second);

		string nc_label("NC");
		assert(complete_meta_data.filterDescriptors().emplace(nc_label, Attribute::Descriptor(nc_label, "All alternative alleles excluding missing are not called (ACP == 0)")).second);

		VcfMetaData called_file_meta_data = complete_meta_data;
		called_file_meta_data.filterDescriptors().clear();
		called_file_meta_data.clearSamples();

		assert(called_file_meta_data.infoDescriptors().erase("ACP"));				
		assert(called_file_meta_data.infoDescriptors().erase("ACO"));				
		
		called_file_meta_data.infoDescriptors().erase("AsmVar_ASQR");
		called_file_meta_data.infoDescriptors().erase("DNE");
		called_file_meta_data.infoDescriptors().erase("RMA");

		VcfMetaData de_novo_file_meta_data = complete_meta_data;
		de_novo_file_meta_data.filterDescriptors().clear();

		VcfFileWriter vcf_writer_complete(output_prefix + "_complete.vcf", complete_meta_data, true);
		VcfFileWriter vcf_writer_called(output_prefix + "_called_alleles.vcf", called_file_meta_data, true);
		VcfFileWriter vcf_writer_de_novo(output_prefix + "_de_novo.vcf", de_novo_file_meta_data, true);

		Variant * cur_var;

		uint num_variants = 0;
		uint num_alleles = 0;

		uint num_low_prob_variants = 0;
		uint num_filt_variants = 0;

		uint num_missing_alleles = 0;
		uint num_not_called_variants = 0;
		uint num_low_prob_alleles = 0;

		uint num_de_novo_events = 0;
		uint num_de_novo_multiple_events = 0;

		assert(min_called_probability > 0);
		assert(min_called_probability <= 1);

		while (vcf_reader.getNextVariant(&cur_var)) {

			num_variants++;
			num_alleles += cur_var->numAlls();

			assert(cur_var->filters().size() == 1);

			// Label alleles
			vector<uint> alt_rm_idxs;
			alt_rm_idxs.reserve(cur_var->numAlts());

			float alt_acp_max = 0;

			for (uint allele_idx = 0; allele_idx < cur_var->numAlls(); allele_idx++) {

				assert(cur_var->info().hasValue("AN"));

				auto acp_value = cur_var->allele(allele_idx).info().getValue<float>("ACP");
				assert(acp_value.second);

				if (allele_idx > 0) {

					assert(cur_var->allele(allele_idx).info().hasValue("AC"));
					assert(cur_var->allele(allele_idx).info().hasValue("AF"));
					assert(cur_var->allele(allele_idx).info().hasValue("ACO"));
					assert(cur_var->allele(allele_idx).info().hasValue("AAI"));

					auto at = Auxiliaries::alleleAttributes(cur_var->allele(allele_idx), cur_var->ref());
					auto rma_value = cur_var->allele(allele_idx).info().getValue<string>("RMA");

					if (rma_value.second) {

						assert((rma_value.first == ".") or (at.type == Auxiliaries::Type::Insertion) or (at.type == Auxiliaries::Type::Deletion));
					}

					assert(cur_var->allele(allele_idx).info().setValue("AT", at.typeStr()));

					if (cur_var->allele(allele_idx).isMissing()) {

						alt_rm_idxs.push_back(allele_idx - 1);
						num_missing_alleles++;

						continue;
					}

					alt_acp_max = max(alt_acp_max, acp_value.first);
					
					if (acp_value.first < min_called_probability) {

						alt_rm_idxs.push_back(allele_idx - 1);
						num_low_prob_alleles++;
					}
				}
			}

			if (cur_var->filters().front() == "PASS") {

				auto var_qual = cur_var->qual();
				assert(var_qual.second);

				auto var_call_prob = 1 - pow(10, -1 * var_qual.first/10);
				assert((var_call_prob == alt_acp_max) or (abs(var_call_prob - alt_acp_max) < pow(10, -3)));

				if (floatCompare(alt_acp_max, 0)) {

					assert(alt_rm_idxs.size() == cur_var->numAlts());

					cur_var->setFilters({nc_label});
					num_not_called_variants++;
			
				} else if (alt_acp_max < min_called_probability) {

					assert(alt_rm_idxs.size() == cur_var->numAlts());

					cur_var->setFilters({lvq_label});
					num_low_prob_variants++;

				} else {

					assert(alt_rm_idxs.size() < cur_var->numAlts());
				}

			} else {

				num_filt_variants++;
			}

			vcf_writer_complete.write(cur_var);

			auto dne_att = cur_var->info().getValue<string>("DNE");

			if (dne_att.second) {

				assert(cur_var->filters().front() == "PASS");

				if (dne_att.first.find(",") == string::npos) {

					num_de_novo_events++;

				} else {

					num_de_novo_multiple_events++;
				}

				vcf_writer_de_novo.write(cur_var);
			}

			if (cur_var->filters().front() == "PASS") {

				assert(alt_rm_idxs.size() < cur_var->numAlts());

				int alt_rm_ac = 0;

				for (auto & alt_rm_idx: alt_rm_idxs) {

					auto ac_value = cur_var->alt(alt_rm_idx).info().getValue<int>("AC");
					assert(ac_value.second);

					alt_rm_ac += ac_value.first;
				}

				cur_var->clearSamples();
				cur_var->removeAlts(alt_rm_idxs);
	            
	            auto an_value = cur_var->info().getValue<int>("AN");
	            assert(an_value.second);
	            assert(an_value.first >= alt_rm_ac);

	            if (alt_rm_ac > 0) {

		            assert(!cur_var->info().setValue<int>("AN", an_value.first - alt_rm_ac));
					assert(cur_var->numAlts() > 0);

					for (uint alt_idx = 0; alt_idx < cur_var->numAlts(); alt_idx++) {

		                if (an_value.first == alt_rm_ac) {

			                assert(!cur_var->alt(alt_idx).info().setValue<float>("AF", 0));

		                } else {

		                	auto ac_value = cur_var->alt(alt_idx).info().getValue<int>("AC");
		                	assert(ac_value.second);
			                
			                assert(!cur_var->alt(alt_idx).info().setValue<float>("AF", ac_value.first / static_cast<float>(an_value.first - alt_rm_ac)));
		                }
		            }
	        	}

				vcf_writer_called.write(cur_var);
			}

			delete cur_var;

			if ((num_variants % 100000) == 0) {

				std::cout << "[" << Utils::getLocalTime() << "] Parsed " << num_variants << " variants" << endl;
			}
		}

		cout << "\n[" << Utils::getLocalTime() << "] Parsed " << num_variants << " variants and " << num_alleles << " alleles (including reference and missing)\n" << endl;
		cout << "\t\t - " << num_filt_variants << " variant(s) were already labelled as filtered (UV or ISD)" << endl;
		cout << "\t\t - " << num_not_called_variants << " variant(s) were labelled as not called (NC)" << endl;
		cout << "\t\t - " << num_low_prob_variants << " variant(s) were labelled as low variant quality (LVQ)\n" << endl;
		cout << "\t\t - " << num_missing_alleles << " missing alleles(s)" << endl;
		cout << "\t\t - " << num_low_prob_alleles << " alleles(s) had probability below threshold\n" << endl;
		cout << "\t\t - " << num_de_novo_events << " de novo events" << endl;
		cout << "\t\t - " << num_de_novo_multiple_events << " multi de novo events" << endl;
		cout << endl;
	}
Ejemplo n.º 26
0
jobject v8ToJava(JNIEnv* env, v8::Local<v8::Value> arg) {
  if(arg.IsEmpty() || arg->IsNull() || arg->IsUndefined()) {
    return NULL;
  }

  if(arg->IsArray()) {
    v8::Local<v8::Array> array = v8::Array::Cast(*arg);
    uint32_t arraySize = array->Length();
    jclass objectClazz = env->FindClass("java/lang/Object");
    jobjectArray result = env->NewObjectArray(arraySize, objectClazz, NULL);
    for(uint32_t i=0; i<arraySize; i++) {
      jobject val = v8ToJava(env, array->Get(i));
      env->SetObjectArrayElement(result, i, val);
    }
    return result;
  }

  if(arg->IsString()) {
    v8::String::Utf8Value val(arg->ToString());
    return env->NewStringUTF(*val);
  }

  if(arg->IsInt32() || arg->IsUint32()) {
    jint val = arg->ToInt32()->Value();
    jclass clazz = env->FindClass("java/lang/Integer");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(I)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsNumber()) {
    jdouble val = arg->ToNumber()->Value();
    jclass clazz = env->FindClass("java/lang/Double");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(D)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsBoolean()) {
    jboolean val = arg->ToBoolean()->Value();
    jclass clazz = env->FindClass("java/lang/Boolean");
    jmethodID constructor = env->GetMethodID(clazz, "<init>", "(Z)V");
    return env->NewObject(clazz, constructor, val);
  }

  if(arg->IsObject()) {
    v8::Local<v8::Object> obj = v8::Object::Cast(*arg);

    v8::Local<v8::Value> isJavaObject = obj->GetHiddenValue(v8::String::New(V8_HIDDEN_MARKER_JAVA_OBJECT));
    if(!isJavaObject.IsEmpty() && isJavaObject->IsBoolean()) {
      return v8ToJava_javaObject(env, obj);
    }

    v8::Local<v8::Value> isJavaLong = obj->GetHiddenValue(v8::String::New(V8_HIDDEN_MARKER_JAVA_LONG));
    if(!isJavaLong.IsEmpty() && isJavaLong->IsBoolean()) {
      return v8ToJava_javaLong(env, obj);
    }
  }

  // TODO: handle other arg types
  v8::String::AsciiValue typeStr(arg);
  printf("v8ToJava: Unhandled type: %s\n", *typeStr);
  return NULL;
}
Ejemplo n.º 27
0
string Event::typeStr() const
{
    return typeStr(m_Type);
}
Ejemplo n.º 28
0
void Event::trace()
{
    string sType = typeStr();
    AVG_TRACE(Logger::EVENTS, sType); 
}
Ejemplo n.º 29
0
bool ctConfigToolDoc::DoOpen(wxSimpleHtmlTag* tag, ctConfigItem* parent)
{
    ctConfigItem* newItem = NULL;
    if (tag->NameIs(wxT("setting")))
    {
        wxSimpleHtmlAttribute* attr = tag->FindAttribute(wxT("type"));
        if (attr)
        {
            ctConfigType type = ctTypeUnknown;
            wxString typeStr(attr->GetValue());
            if (typeStr == wxT("group"))
                type = ctTypeGroup;
            else if (typeStr == wxT("option-group") || typeStr == wxT("check-group"))
                type = ctTypeCheckGroup;
            else if (typeStr == wxT("radio-group"))
                type = ctTypeRadioGroup;
            else if (typeStr == wxT("bool-check"))
                type = ctTypeBoolCheck;
            else if (typeStr == wxT("bool-radio"))
                type = ctTypeBoolRadio;
            else if (typeStr == wxT("string"))
                type = ctTypeString;
            else if (typeStr == wxT("integer"))
                type = ctTypeInteger;
            else
            {
                wxLogError(wxT("Unknown type %s"), (const wxChar*) typeStr);
            }
            if (type != ctTypeUnknown)
            {
                newItem = new ctConfigItem(parent, type, wxT(""));
                newItem->InitProperties();
                if (!parent)
                    SetTopItem(newItem);
            }
        }
    }
    wxSimpleHtmlTag* childTag = tag->GetChildren();

    while (childTag)
    {
        if (childTag->GetType() == wxSimpleHtmlTag_Open)
        {
            if (childTag->GetName() == wxT("setting"))
            {
                DoOpen(childTag, newItem);
            }
            else if (childTag->GetName() == wxT("name"))
            {
                if (newItem)
                {
                    wxString name(childTag->GetNext()->GetTagText());
                    newItem->SetName(name);
                }
            }
            else if (childTag->GetName() == wxT("active"))
            {
                if (newItem)
                    newItem->SetActive(GetHtmlBoolValue(childTag->GetNext()->GetTagText()));
            }
            else if (childTag->GetName() == wxT("enabled"))
            {
                if (newItem)
                    newItem->Enable(GetHtmlBoolValue(childTag->GetNext()->GetTagText()));
            }
            else
            {
                if (newItem)
                {
                    ctProperty* prop = newItem->GetProperties().FindProperty(childTag->GetName());
                    if (!prop)
                    {
                        // A custom property, else an obsolete
                        // property that we should ignore.
                        wxString isCustom;
                        if (childTag->GetAttributeValue(isCustom, wxT("custom")) &&
                            isCustom == wxT("true"))
                        {
                            prop = new ctProperty;

                            wxString name(childTag->GetName());
                            wxString type(wxT("string"));
                            wxString choices;
                            wxString editorType(wxT("string"));
                            wxString description(wxT(""));
                            childTag->GetAttributeValue(type, wxT("type"));
                            childTag->GetAttributeValue(type, wxT("editor-type"));
                            childTag->GetAttributeValue(type, wxT("choices"));
                            childTag->GetAttributeValue(description, wxT("description"));

                            if (type == wxT("bool"))
                                prop->GetVariant() = wxVariant(false, name);
                            else if (type == wxT("double"))
                                prop->GetVariant() = wxVariant((double) 0.0, name);
                            else if (type == wxT("long"))
                                prop->GetVariant() = wxVariant((long) 0, name);
                            else
                                prop->GetVariant() = wxVariant(wxT(""), name);
                            prop->SetDescription(description);
                            prop->SetCustom(true);
                            prop->SetEditorType(editorType);
                            if (!choices.IsEmpty())
                            {
                                wxArrayString arr;
                                ctConfigItem::StringToArray(choices, arr);
                                prop->SetChoices(arr);
                            }
                            newItem->GetProperties().AddProperty(prop);
                        }
                    }
                    if (prop)
                    {
                        if (prop->GetVariant().GetType() == wxT("string"))
                            prop->GetVariant() = childTag->GetNext()->GetTagText();
                        else if (prop->GetVariant().GetType() == wxT("long"))
                            prop->GetVariant() = (long) GetHtmlIntegerValue(childTag->GetNext()->GetTagText());
                        else if (prop->GetVariant().GetType() == wxT("bool"))
                            prop->GetVariant() = GetHtmlBoolValue(childTag->GetNext()->GetTagText());
                        else if (prop->GetVariant().GetType() == wxT("double"))
                            prop->GetVariant() = (double) GetHtmlDoubleValue(childTag->GetNext()->GetTagText());
                    }
                }
            }
        }
        childTag = childTag->GetNext();
    }
    return true;
}
Ejemplo n.º 30
0
nsresult
RDFContentSinkImpl::OpenObject(const PRUnichar* aName, 
                               const PRUnichar** aAttributes)
{
    // an "object" non-terminal is either a "description", a "typed
    // node", or a "container", so this change the content sink's
    // state appropriately.
    nsCOMPtr<nsIAtom> localName;
    const nsDependentSubstring& nameSpaceURI =
        SplitExpatName(aName, getter_AddRefs(localName));

    // Figure out the URI of this object, and create an RDF node for it.
    nsCOMPtr<nsIRDFResource> source;
    GetIdAboutAttribute(aAttributes, getter_AddRefs(source));

    // If there is no `ID' or `about', then there's not much we can do.
    if (! source)
        return NS_ERROR_FAILURE;

    // Push the element onto the context stack
    PushContext(source, mState, mParseMode);

    // Now figure out what kind of state transition we need to
    // make. We'll either be going into a mode where we parse a
    // description or a container.
    PRBool isaTypedNode = PR_TRUE;

    if (nameSpaceURI.EqualsLiteral(RDF_NAMESPACE_URI)) {
        isaTypedNode = PR_FALSE;

        if (localName == kDescriptionAtom) {
            // it's a description
            mState = eRDFContentSinkState_InDescriptionElement;
        }
        else if (localName == kBagAtom) {
            // it's a bag container
            InitContainer(kRDF_Bag, source);
            mState = eRDFContentSinkState_InContainerElement;
        }
        else if (localName == kSeqAtom) {
            // it's a seq container
            InitContainer(kRDF_Seq, source);
            mState = eRDFContentSinkState_InContainerElement;
        }
        else if (localName == kAltAtom) {
            // it's an alt container
            InitContainer(kRDF_Alt, source);
            mState = eRDFContentSinkState_InContainerElement;
        }
        else {
            // heh, that's not *in* the RDF namespace: just treat it
            // like a typed node
            isaTypedNode = PR_TRUE;
        }
    }

    if (isaTypedNode) {
        const char* attrName;
        localName->GetUTF8String(&attrName);

        NS_ConvertUTF16toUTF8 typeStr(nameSpaceURI);
        typeStr.Append(attrName);

        nsCOMPtr<nsIRDFResource> type;
        nsresult rv = gRDFService->GetResource(typeStr, getter_AddRefs(type));
        if (NS_FAILED(rv)) return rv;

        rv = mDataSource->Assert(source, kRDF_type, type, PR_TRUE);
        if (NS_FAILED(rv)) return rv;

        mState = eRDFContentSinkState_InDescriptionElement;
    }

    AddProperties(aAttributes, source);
    return NS_OK;
}