char *translateName(char *name, boolean toInt)
/* translates external name to internal name format or vice versa */
{
char *transName = NULL;
boolean prefixFound = FALSE;
int i;
        
for (i = 0; i < NUMPREFIXES && (!prefixFound); i++)
    {
    if (toInt)
        {
        if (startsWith(extNamePrefix[i], name))
            {
            transName = replaceChars(name, extNamePrefix[i], intNamePrefix[i]);
            prefixFound = TRUE;          
            }
        }
    else
        {
        if (startsWith(intNamePrefix[i], name))
            {
            transName = replaceChars(name, intNamePrefix[i], extNamePrefix[i]);
            prefixFound = TRUE;          
            }
        }
    }
if (prefixFound)
    return transName;
else
    return NULL;
}
Esempio n. 2
0
void removeElement(char *el, char ***array, unsigned *count)
/* Add a new element to a array of elements */
{
  char *arrayCurr, *arrayCurrDel, del[128];
  int sizeOne, size;
  char **cArray, **rArray=NULL, ***dArray;

  if (*count > 0)
    {
      size = *count;
      arrayCurr = sqlStringArrayToString(*array, *count);
      safef(del, ArraySize(del), "%s,", el);
      arrayCurrDel = replaceChars(arrayCurr, del, "");
      if (differentString(arrayCurr, arrayCurrDel))
	  size--;
      dArray = array;
      /* if (*dArray) 
	 freeMem(dArray); */
      sqlStringDynamicArray(arrayCurrDel, &cArray, &sizeOne);
      assert(sizeOne == size);
      *count = size;
      if (size > 0) 
	{
	  AllocArray(rArray, size);
	  CopyArray(cArray, rArray, size);
	  *array = rArray;
	}
      else
	*array = NULL;
    }
}
Esempio n. 3
0
static Color cgColorLikeHgGenome(struct track *tg, struct hvGfx *hvg)
/* Search the cart variables and use the colors corresponding to the hgGenome */
/* graph. */
{
Color ret;
struct hashEl *matchingCartSettings = NULL;
struct hashEl *el;
char cartGenomeWildStr[256];
char *graphCartVarName = NULL;
char *colorCartVarSetting = "black";
safef(cartGenomeWildStr, sizeof(cartGenomeWildStr), "hgGenome_graph_%s_*", database);
/* for ex. hgGenome_graph_hg18_1_1 */
matchingCartSettings = cartFindLike(cart, cartGenomeWildStr);
for (el = matchingCartSettings; el != NULL; el = el->next)
    {
    char *val = (char *)el->val;
    if (val && sameString(val, tg->track))
	{
	graphCartVarName = el->name;
	break;
	}
    }
if (graphCartVarName)
    {
    char *colorCartVarName = replaceChars(graphCartVarName, "_graph_", "_graphColor_");
    colorCartVarSetting = cartUsualString(cart, colorCartVarName, "black");
    freeMem(colorCartVarName);
    }
hashElFreeList(&matchingCartSettings);
ret = colorFromAscii(hvg, colorCartVarSetting);
return ret;
}
void setupTable(struct sqlConnection *conn) 
/* Set up the autoTest table for testing. Call dropTable() later
 to remove table. */
{
struct lineFile *lf = lineFileOpen("output/newTest.sql", TRUE);
char *update = NULL;
char *line = NULL;
struct dyString *ds = newDyString(256);
if(sqlTableExists(conn, testTableName))
    errAbort("dbLinkTest.c::setupTable() - Table %s.%s already exists. Can't create another.",
             sqlGetDatabase(conn), testTableName);
while(lineFileNextReal(lf, &line)) 
    {
    char *tmp = strstr(line, "not null");
    if(tmp != NULL)
	{
	*tmp = ',';
	tmp++;
	*tmp = '\0';
	}
    subChar(line, '\t', ' ');
    dyStringPrintf(ds, "%s", line);
    }
update = replaceChars(ds->string, "PRIMARY KEY", "UNIQUE");
sqlUpdate(conn, update);
freez(&update);
dyStringFree(&ds);
lineFileClose(&lf);
}
Esempio n. 5
0
u8 convertStringToPin( u8 *ucBuffer )
{
    // This function is constant string safe
    u8 i, ucPin;

    #ifdef __PYGMYNEBULA
        for( i = 0; i < PYGMYMAXPINS; i++ ){
            if( isStringSame( PYGMYNEBULAPINS[ i ].String, ucBuffer ) ){
                return( PYGMYNEBULAPINS[ i ].Value );
            } // if     
        } // for
    #endif // __PYGMYNEBULA
    // Pin isn't an alias, check for port letter and pin number
    if( replaceChars( ucBuffer, "pP", ' ' ) ){
        if( replaceChars( ucBuffer, "aA", ' ' ) ){
            ucPin = 0;
        } else if( replaceChars( ucBuffer, "bB", ' ' ) ){
            ucPin = 16;
        } else if( replaceChars( ucBuffer, "cC", ' ' ) ){
            ucPin = 32;
        } else if( replaceChars( ucBuffer, "dD", ' ' ) ){
            ucPin = 48;
        } else if( replaceChars( ucBuffer, "eE", ' ' ) ){
            ucPin = 64;
        } else if( replaceChars( ucBuffer, "fF", ' ' ) ){
            ucPin = 80;
        } else{
            return( 0xFF );
        } // else
        return( ucPin + convertStringToInt( ucBuffer ) );
    } // if

    return( 0xFF );
}
Esempio n. 6
0
void replaceTildeWithHome(char **pS)
/* if the path starts with ~ (tilde) char, replace with $HOME */
{
char *s = *pS;
if (s[0] == '~')
    {
    *pS = replaceChars(s, "~", getenv("HOME"));
    }
}
Esempio n. 7
0
void addVersion(boolean strict, char *database, char *dirName, char *raName,
                struct hash *uniqHash,
                struct hash *htmlHash,
                struct hgFindSpec **pSpecList)
/* Read in specs from raName and add them to list/database if new. */
{
    struct hgFindSpec *hfsList = NULL, *hfs = NULL;
    struct hgFindSpec *hfsNext = NULL;

    hfsList = hgFindSpecFromRa(database, raName, NULL);

    /* prune records of the incorrect release */
    hfsList = pruneRelease(hfsList);

    if (strict)
    {
        for (hfs = hfsList; hfs != NULL; hfs = hfsNext)
        {
            hfsNext = hfs->next;
            if (! hTableOrSplitExists(database, hfs->searchTable))
            {
                if (verboseLevel() > 1)
                    printf("%s missing\n", hfs->searchTable);
                slRemoveEl(&hfsList, hfs);
            }
            else if (hfs->xrefTable[0] != 0)
            {
                // Use sqlTableExists because xrefTable might be $db.$table,
                // not supported by hTableExists / hTableOrSplitExists
                // NOTE hfs->xrefTable can sometimes contain a comma-separated table list,
                // rather than just a single table.
                struct sqlConnection *conn = hAllocConn(database);
                char *tables = replaceChars(hfs->xrefTable, ",", " ");
                boolean exists = sqlTablesExist(conn, tables);
                hFreeConn(&conn);
                freeMem(tables);
                if (! exists)
                {
                    if (verboseLevel() > 1)
                        printf("%s (xref) missing\n", hfs->xrefTable);
                    slRemoveEl(&hfsList, hfs);
                }
            }
        }
    }

    for (hfs = hfsList; hfs != NULL; hfs = hfsNext)
    {
        hfsNext = hfs->next;
        if (! hashLookup(uniqHash, hfs->searchName))
        {
            hashAdd(uniqHash, hfs->searchName, hfs);
            slAddHead(pSpecList, hfs);
        }
    }
}
Esempio n. 8
0
u8 handler_ATSMSPROMPT( u8 *ucBuffer )
{
    u8 *ucParam;

    ucParam = getNextSubString( ucBuffer, NEWLINE );
    
    if( replaceChars( ucParam, ">", ' ' ) ){
        print( MODEM_COM, "\rATSMSPROMPT", ucParam );
        return( TRUE );
    } // if
    
    return( TRUE );
}
Esempio n. 9
0
static void handleCID(char **html, char *ctMain)
/* Handle CID replacements if needed */
{
if (optionExists("cid") && ctMain && sameWord(ctMain,"text/html"))
    {
    struct hashEl *el, *list = hashElListHash(cidHash);
    for(el=list;el;el=el->next)
	{
	char *cid=addSuffix("cid:",el->name);
	if (stringIn(cid,*html))
	    {
	    char *new = replaceChars(*html, cid, el->val);
	    freez(html);
	    *html = new;
	    }
	freez(&cid);
	// support for content-location
	if (stringIn(el->name,*html))
	    {
	    char *new = replaceChars(*html, el->name, el->val);
	    freez(html);
	    *html = new;
	    }
	}
Esempio n. 10
0
static struct slName *hgFindSpecNameList(char *db)
/* Return the hgFindSpec table name(s) to use (based on trackDb name). */
{
struct slName *trackDbList = hTrackDbList();
struct slName *specNameList = NULL;
struct slName *tdbName;
for (tdbName = trackDbList; tdbName != NULL; tdbName = tdbName->next)
    {
    char *subbed = replaceChars(tdbName->name, "trackDb", "hgFindSpec");
    if (hTableExists(db, subbed))
	slNameAddHead(&specNameList, subbed);
    freez(&subbed);
    }
if (!specNameList)
    specNameList = slNameNew("hgFindSpec");
else
    slReverse(&specNameList);
return specNameList;
}
void LoadCustomSettings(bool internal)
{
	std::string myString = replaceChars(RSP.romname);
	bool found = false;
	char buffer[256];
	char* line;
	FILE* fPtr;
	std::transform(myString.begin(), myString.end(), myString.begin(), ::toupper);
	if (internal) {
		line = strtok(customini, "\n");
	} else {
		const char *pathname = ConfigGetSharedDataFilepath("GLideN64.custom.ini");
		if (pathname == NULL || (fPtr = fopen(pathname, "rb")) == NULL)
			return;
	}
	while (true)
	{
		if (!internal) {
			if (fgets(buffer, 255, fPtr) == NULL)
				break;
			else
				line = buffer;
		}
		ini_line l = ini_parse_line(&line);
		switch (l.type)
		{
			case INI_SECTION:
			{
				if (myString == replaceChars(l.name))
					found = true;
				else
					found = false;
			}
			case INI_PROPERTY:
			{
				if (found) {
					if (!strcmp(l.name, "video\\cropMode"))
						config.video.cropMode = atoi(l.value);
					else if (!strcmp(l.name, "video\\cropWidth"))
						config.video.cropWidth = atoi(l.value);
					else if (!strcmp(l.name, "video\\cropHeight"))
						config.video.cropHeight = atoi(l.value);
					else if (!strcmp(l.name, "video\\multisampling"))
						config.video.multisampling = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\aspect"))
						config.frameBufferEmulation.aspect = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\nativeResFactor"))
						config.frameBufferEmulation.nativeResFactor = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\copyToRDRAM"))
						config.frameBufferEmulation.copyToRDRAM = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\copyFromRDRAM"))
						config.frameBufferEmulation.copyFromRDRAM = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\copyDepthToRDRAM"))
						config.frameBufferEmulation.copyDepthToRDRAM = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\copyAuxToRDRAM"))
						config.frameBufferEmulation.copyAuxToRDRAM = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\N64DepthCompare"))
						config.frameBufferEmulation.N64DepthCompare = atoi(l.value);
					else if (!strcmp(l.name, "frameBufferEmulation\\bufferSwapMode"))
						config.frameBufferEmulation.bufferSwapMode = atoi(l.value);
					else if (!strcmp(l.name, "texture\\bilinearMode"))
						config.texture.bilinearMode = atoi(l.value);
					else if (!strcmp(l.name, "texture\\maxAnisotropy"))
						config.texture.maxAnisotropy = atoi(l.value);
					else if (!strcmp(l.name, "generalEmulation\\enableNativeResTexrects"))
						config.generalEmulation.enableNativeResTexrects = atoi(l.value);
					else if (!strcmp(l.name, "generalEmulation\\correctTexrectCoords"))
						config.generalEmulation.correctTexrectCoords = atoi(l.value);
					else if (!strcmp(l.name, "generalEmulation\\enableLegacyBlending"))
						config.generalEmulation.enableLegacyBlending = atoi(l.value);
					else if (!strcmp(l.name, "generalEmulation\\enableFragmentDepthWrite"))
						config.generalEmulation.enableFragmentDepthWrite = atoi(l.value);
				}
			}
		}
		if (internal) {
			line = strtok(NULL, "\n");
			if (line == NULL)
				break;
		}
	}
}
void sortGenes(struct sqlConnection *conn)
/* Put up sort gene page. */
{
cartWebStart(cart, database, "Finding Candidate Genes for Gene Sorter");
if (!hgNearOk(database))
    errAbort("Sorry, gene sorter not available for this database.");

/* Get list of regions. */
struct genoGraph *gg = ggFirstVisible();
double threshold = getThreshold();
struct bed3 *bed, *bedList = regionsOverThreshold(gg);

/* Figure out what table and column are the sorter's main gene set. */
struct hash *genomeRa = hgReadRa(genome, database, "hgNearData", 
	"genome.ra", NULL);
char *geneTable = hashMustFindVal(genomeRa, "geneTable");
char *idColumn = hashMustFindVal(genomeRa, "idColumn");

/* if marker labels were present when the file was uploaded, they are saved here */
char cgmName[256];
safef(cgmName, sizeof(cgmName), "%s.cgm", gg->binFileName);
struct lineFile *m = lineFileMayOpen(cgmName, TRUE);
char *cgmRow[4];
cgmRow[0] = "";    /* dummy row */
cgmRow[1] = "";
cgmRow[2] = "0";
cgmRow[3] = "0";

FILE *g = NULL;
int markerCount = 0;
struct tempName snpTn;

if (m)
    {
    /* Create custom column output file. */
    trashDirFile(&snpTn, "hgg", "marker", ".mrk");  
    g = mustOpen(snpTn.forCgi, "w");
    fprintf(g, 
	"column name=\"%s Markers\" shortLabel=\"%s Markers over threshold\" longLabel=\"%s Markers in regions over threshold\" " 
	"visibility=on priority=99 "
        "\n"
        , gg->shortLabel
        , gg->shortLabel
        , gg->shortLabel
	);
    }

/*** Build up hash of all transcriptHash that are in region. */
struct hash *transcriptHash = hashNew(16);

/* This loop handles one chromosome at a time.  It depends on
 * the bedList being sorted by chromosome. */
for (bed = bedList; bed != NULL; )
    {

    /* Make binKeeper and stuff in all regions in this chromosome into it. */
    char *chrom = bed->chrom;
    int chromSize = hChromSize(database, chrom);
    struct binKeeper *bk = binKeeperNew(0, chromSize);
    while (bed != NULL && sameString(chrom, bed->chrom))
	{
	binKeeperAdd(bk, bed->chromStart, bed->chromEnd, bed);
	bed = bed->next;
	}

    struct binKeeper *bkGenes = NULL;
    if (m)
       bkGenes = binKeeperNew(0, chromSize);

    /* Query database to find out bounds of all genes on this chromosome
     * and if they overlap any of the regions then put them in the hash. */
    char query[512];
    safef(query, sizeof(query), 
    	"select name,txStart,txEnd from %s where chrom='%s'", geneTable, chrom);
    struct sqlResult *sr = sqlGetResult(conn, query);
    char **row;
    while ((row = sqlNextRow(sr)) != NULL)
        {
	char *name = row[0];
	int start = sqlUnsigned(row[1]);
	int end = sqlUnsigned(row[2]);
	if (binKeeperAnyOverlap(bk, start, end))
	    {
	    hashStore(transcriptHash, name);
	    if (m)
		binKeeperAdd(bkGenes, start, end, cloneString(name));
	    }
	}
    sqlFreeResult(&sr);

    if (m)
	{
	/* Read cgm file if it exists, looking at all markers on this chromosome
	 * and if they overlap any of the regions and genes then output them. */
	do 
	    {
	    // marker, chrom, chromStart, val
	    char *marker = cgmRow[0];
	    char *chr = cgmRow[1];
	    int start = sqlUnsigned(cgmRow[2]);
	    int end = start+1;
	    double val = sqlDouble(cgmRow[3]);
            int cmp = strcmp(chr,chrom);
            if (cmp > 0)
                break;
            if (cmp == 0)
		{
		if (val >= threshold)
		    {
		    struct binElement *el, *bkList = binKeeperFind(bkGenes, start, end);
		    for (el = bkList; el; el=el->next)
			{
			/* output to custom column trash file */
			fprintf(g, "%s %s\n", (char *)el->val, marker);
			}
		    if (bkList)
			{
			++markerCount;
			slFreeList(&bkList);
			}
		    }
		}
	    }
	while (lineFileRow(m, cgmRow));
	}

    /* Clean up for this chromosome. */
    binKeeperFree(&bk);

    if (m)
	{
	/* For speed, we do not free up the values (cloned the kg names earlier) */
	binKeeperFree(&bkGenes);  
	}

    }

/* Get list of all transcripts in regions. */
struct hashEl *el, *list = hashElListHash(transcriptHash);

/* Create file with all matching gene IDs. */
struct tempName keyTn;
trashDirFile(&keyTn, "hgg", "key", ".key");
FILE *f = mustOpen(keyTn.forCgi, "w");
for (el = list; el != NULL; el = el->next)
    fprintf(f, "%s\n", el->name);
carefulClose(&f);

/* Print out some info. */
hPrintf("Thresholding <i>%s</i> at %g. ", gg->shortLabel, threshold);
hPrintf("There are %d regions covering %lld bases.<BR>\n",
    slCount(bedList), bedTotalSize((struct bed*)bedList) );
hPrintf("Installed a Gene Sorter filter that selects only genes in these regions.<BR>\n");
if (m)
    {
    hPrintf("There are %d markers in the regions over threshold that overlap knownGenes.<BR>\n", markerCount);
    hPrintf("Installed a Gene Sorter custom column called \"%s Markers\" with these markers.<BR>\n", gg->shortLabel);
    }

/* close custom column output file */
if (m)
    {
    lineFileClose(&m);
    carefulClose(&g);
    }

/* Stuff cart variable with name of file. */
char keyCartName[256];
safef(keyCartName, sizeof(keyCartName), "%s%s.keyFile",
	advFilterPrefix, idColumn);
cartSetString(cart, keyCartName, keyTn.forCgi);

cartSetString(cart, customFileVarName, snpTn.forCgi);

char snpVisCartNameTemp[256];
char *snpVisCartName = NULL;
safef(snpVisCartNameTemp, sizeof(snpVisCartNameTemp), "%s%s Markers.vis",
	colConfigPrefix, gg->shortLabel);
snpVisCartName = replaceChars(snpVisCartNameTemp, " ", "_");
cartSetString(cart, snpVisCartName, "1");
freeMem(snpVisCartName);

hPrintf("<FORM ACTION=\"../cgi-bin/hgNear\" METHOD=GET>\n");
cartSaveSession(cart);
hPrintf("<CENTER>");
cgiMakeButton("submit", "go to gene sorter");
hPrintf("</CENTER>");
hPrintf("</FORM>");

cartWebEnd();
}
Esempio n. 13
0
char *menuBar(struct cart *cart, char *db)
// Return HTML for the menu bar (read from a configuration file);
// we fixup internal CGI's to add hgsid's and include the appropriate js and css files.
//
// Note this function is also called by hgTracks which extends the menu bar
//  with a View menu defined in hgTracks/menu.c
{
char *docRoot = hDocumentRoot();
char *menuStr, buf[4096], uiVars[128];
FILE *fd;
char *navBarFile = "inc/globalNavBar.inc";
struct stat statBuf;
char *scriptName = cgiScriptName();
if (cart)
    safef(uiVars, sizeof(uiVars), "%s=%s", cartSessionVarName(), cartSessionId(cart));
else
    uiVars[0] = 0;

if(docRoot == NULL)
    // tolerate missing docRoot (i.e. don't bother with menu when running from command line)
    return NULL;

jsIncludeFile("jquery.js", NULL);
jsIncludeFile("jquery.plugins.js", NULL);
webIncludeResourceFile("nice_menu.css");

// Read in menu bar html
safef(buf, sizeof(buf), "%s/%s", docRoot, navBarFile);
fd = mustOpen(buf, "r");
fstat(fileno(fd), &statBuf);
int len = statBuf.st_size;
menuStr = needMem(len + 1);
mustRead(fd, menuStr, statBuf.st_size);
menuStr[len] = 0;
carefulClose(&fd);

if (cart)
    {
    char *newMenuStr = menuBarAddUiVars(menuStr, "/cgi-bin/hg", uiVars);
    freez(&menuStr);
    menuStr = newMenuStr;
    }

if(scriptName)
    {
    // Provide hgTables options for some CGIs.
    char hgTablesOptions[1024] = "";
    char *track = (cart == NULL ? NULL :
                   (endsWith(scriptName, "hgGene") ?
                    cartOptionalString(cart, "hgg_type") :
                    cartOptionalString(cart, "g")));
    if (track && cart && db &&
        (endsWith(scriptName, "hgc") || endsWith(scriptName, "hgTrackUi") ||
         endsWith(scriptName, "hgGene")))
        {
        struct trackDb *tdb = hTrackDbForTrack(db, track);
        if (tdb)
	    {
	    struct trackDb *topLevel = trackDbTopLevelSelfOrParent(tdb); 
	    safef(hgTablesOptions, sizeof  hgTablesOptions, 
		    "../cgi-bin/hgTables?hgta_doMainPage=1&hgta_group=%s&hgta_track=%s&hgta_table=%s&", 
		    topLevel->grp, topLevel->track, tdb->table);
	    menuStr = replaceChars(menuStr, "../cgi-bin/hgTables?", hgTablesOptions);
	    trackDbFree(&tdb);
	    }
        }
    }

if(!loginSystemEnabled())
    stripRegEx(menuStr, "<\\!-- LOGIN_START -->.*<\\!-- LOGIN_END -->", REG_ICASE);

if(scriptName)
    {  // Provide optional official mirror servers menu items
    char *geoMenu = geoMirrorMenu();
    char *pattern = "<!-- OPTIONAL_MIRROR_MENU -->";
    char *newMenuStr = replaceChars(menuStr, pattern, geoMenu);
    freez(&menuStr);
    menuStr = newMenuStr;
    }


if(scriptName)
    {
    // Provide view menu for some CGIs.
    struct dyString *viewItems = dyStringCreate("");
    boolean hasViewMenu = TRUE;
    if (endsWith(scriptName, "hgGenome"))
        {
	safef(buf, sizeof(buf), "../cgi-bin/hgGenome?%s&hgGenome_doPsOutput=1", uiVars);
    	dyStringPrintf(viewItems, "<li><a href='%s' id='%s'>%s</a></li>\n", buf, "pdfLink", "PDF/PS");
        }
    else
	{
	hasViewMenu = FALSE;
	}
    if (hasViewMenu)
	{
	struct dyString *viewMenu = dyStringCreate("<li class='menuparent' id='view'><span>View</span>\n<ul style='display: none; visibility: hidden;'>\n");
	dyStringAppend(viewMenu, viewItems->string);
	dyStringAppend(viewMenu, "</ul>\n</li>\n");
    	menuStr = replaceChars(menuStr, "<!-- OPTIONAL_VIEW_MENU -->", viewMenu->string);
	dyStringFree(&viewMenu);
	}
    else if (!endsWith(scriptName, "hgTracks"))
	{
    	replaceChars(menuStr, "<!-- OPTIONAL_VIEW_MENU -->", "");
	}
    dyStringFree(&viewItems);
    }


if(scriptName)
    {
    // Provide context sensitive help links for some CGIs.
    char *link = NULL;
    char *label = NULL;
    if (endsWith(scriptName, "hgBlat"))
        {
        link = "../goldenPath/help/hgTracksHelp.html#BLATAlign";
        label = "Help on Blat";
        }
    else if (endsWith(scriptName, "hgHubConnect"))
        {
        link = "../goldenPath/help/hgTrackHubHelp.html";
        label = "Help on Track Hubs";
        }
    else if (endsWith(scriptName, "hgNear"))
        {
        link = "../goldenPath/help/hgNearHelp.html";
        label = "Help on Gene Sorter";
        }
    else if (endsWith(scriptName, "hgTables"))
        {
        link = "../goldenPath/help/hgTablesHelp.html";
        label = "Help on Table Browser";
        }
    else if (endsWith(scriptName, "hgGenome"))
        {
        link = "../goldenPath/help/hgGenomeHelp.html";
        label = "Help on Genome Graphs";
        }
    else if (endsWith(scriptName, "hgSession"))
        {
        link = "../goldenPath/help/hgSessionHelp.html";
        label = "Help on Sessions";
        }
    else if (endsWith(scriptName, "hgVisiGene"))
        {
        link = "../goldenPath/help/hgTracksHelp.html#VisiGeneHelp";
        label = "Help on VisiGene";
        }
    else if (endsWith(scriptName, "hgCustom"))
        {
        link = "../goldenPath/help/customTrack.html";
        label = "Help on Custom Tracks";
        }
    // Don't overwrite any previously set defaults
    if(!contextSpecificHelpLink && link)
        contextSpecificHelpLink = link;
    if(!contextSpecificHelpLabel && label)
        contextSpecificHelpLabel = label;
    }
if(contextSpecificHelpLink)
    {
    char buf[1024];
    safef(buf, sizeof(buf), "<li><a href='%s'>%s</a></li>", contextSpecificHelpLink, contextSpecificHelpLabel);
    menuStr = replaceChars(menuStr, "<!-- CONTEXT_SPECIFIC_HELP -->", buf);
    }
return menuStr;
}
static void gadPrint(struct section *section, 
	struct sqlConnection *conn, char *geneId)
/* Print out GAD section. */
{
int refPrinted = 0;
boolean showCompleteGadList;

char condStr[256];
char query[256];
struct sqlResult *sr;
char **row;
struct dyString *currentCgiUrl;
char *upperDisease;

char *url = 
cloneString("http://geneticassociationdb.nih.gov/cgi-bin/tableview.cgi?table=allview&cond=gene=");
char *itemName;

if (url != NULL && url[0] != 0)
    {
    safef(condStr, sizeof(condStr), 
    "k.kgId='%s' and k.geneSymbol = g.geneSymbol", geneId);
    itemName = sqlGetField(database, "kgXref k, gadAll g", "k.geneSymbol", condStr);
    showCompleteGadList = FALSE;
    if (cgiOptionalString("showAllRef") != NULL)
    	{
        if (sameWord(cgiOptionalString("showAllRef"), "Y") ||
	    sameWord(cgiOptionalString("showAllRef"), "y") )
	    {
	    showCompleteGadList = TRUE;
	    }
	}
    currentCgiUrl = cgiUrlString();
   
    printf("<B>Genetic Association Database: ");
    printf("<A HREF=\"%s'%s'\" target=_blank>", url, itemName);
    printf("%s</B></A>\n", itemName);

    printf("<BR><B>CDC HuGE Published Literature:  ");
    printf("<A HREF=\"%s%s%s\" target=_blank>", 
           "http://hugenavigator.net/HuGENavigator/searchSummary.do?firstQuery=",
           itemName, 
	   "&publitSearchType=now&whichContinue=firststart&check=n&dbType=publit&Mysubmit=go");
    printf("%s</B></A>\n", itemName);

    /* List diseases associated with the gene */
    safef(query, sizeof(query),
    "select distinct broadPhen from gadAll where geneSymbol='%s' and association = 'Y' order by broadPhen",
    itemName);
    sr = sqlMustGetResult(conn, query);
    row = sqlNextRow(sr);
    
    if (row != NULL) 
    	{
	upperDisease = replaceChars(row[0], "'", "''");
	touppers(upperDisease);
	printf("<BR><B>Positive Disease Associations:  </B>");
	printf("<A HREF=\"%s%s%s%s%s\" target=_blank>",
	"http://geneticassociationdb.nih.gov/cgi-bin/tableview.cgi?table=allview&cond=upper(DISEASE)%20like%20'%25",
	cgiEncode(upperDisease), "%25'%20AND%20upper(GENE)%20%20like%20'%25", itemName, "%25'");
	printf("%s</B></A>\n", row[0]);
        row = sqlNextRow(sr);
    	}
    while (row != NULL)
        {
	upperDisease = replaceChars(row[0], "'", "''");
	touppers(upperDisease);
	printf(", <A HREF=\"%s%s%s%s%s\" target=_blank>",
	"http://geneticassociationdb.nih.gov/cgi-bin/tableview.cgi?table=allview&cond=upper(DISEASE)%20like%20'%25",
	cgiEncode(upperDisease), "%25'%20AND%20upper(GENE)%20%20like%20'%25", itemName, "%25'");
	printf("%s</B></A>\n", row[0]);
        row = sqlNextRow(sr);
	}
    sqlFreeResult(&sr);

    refPrinted = 0;
    safef(query, sizeof(query), 
       "select broadPhen,reference,title,journal, pubMed, conclusion from gadAll where geneSymbol='%s' and association = 'Y' order by broadPhen",
       itemName);
    sr = sqlMustGetResult(conn, query);
    row = sqlNextRow(sr);
    
    if (row != NULL) printf("<BR><B>Related Studies: </B><OL>");
    while (row != NULL)
        {
        printf("<LI><B>%s </B>", row[0]);

	printf("<br>%s, %s, %s.\n", row[1], row[2], row[3]);
	if (!sameWord(row[4], ""))
	    {
	    printf(" [PubMed ");
	    printf("<A HREF=\"%s%s%s'\" target=_blank>",
	    "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&cmd=Retrieve&dopt=Abstract&list_uids=",
	    row[4],"&query_hl=1&itool=genome.ucsc.edu");
	    printf("%s</B></A>]\n", row[4]);
	    }
	printf("<br><i>%s</i>\n", row[5]);
	
	printf("</LI>\n");
        refPrinted++;
        if ((!showCompleteGadList) && (refPrinted >= 3)) break;
	row = sqlNextRow(sr);
    	}
    sqlFreeResult(&sr);
    printf("</OL>");
    
    if ((!showCompleteGadList) && (row != NULL))
    	{
        printf("<B>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; more ...  </B>");
        printf(
	      "<A HREF=\"%s?showAllRef=Y&%s&#35;gad\">click here to view the complete list</A> ", 
	      "hgGene", currentCgiUrl->string);
    	}
    }
}
Esempio n. 15
0
char *menuBar(struct cart *cart)
// Return HTML for the menu bar (read from a configuration file);
// we fixup internal CGI's to add hgsid's and include the appropriate js and css files.
{
char *docRoot = hDocumentRoot();
char *menuStr, buf[4096], uiVars[128];
FILE *fd;
int len, offset, err;
char *navBarFile = "inc/globalNavBar.inc";
struct stat statBuf;
regex_t re;
regmatch_t match[2];
char *scriptName = cgiScriptName();
if (cart)
    safef(uiVars, sizeof(uiVars), "%s=%u", cartSessionVarName(), cartSessionId(cart));
else
    uiVars[0] = 0;

if(docRoot == NULL)
    // tolerate missing docRoot (i.e. don't bother with menu when running from command line)
    return NULL;

jsIncludeFile("jquery.js", NULL);
jsIncludeFile("jquery.plugins.js", NULL);
webIncludeResourceFile("nice_menu.css");

// Read in menu bar html
safef(buf, sizeof(buf), "%s/%s", docRoot, navBarFile);
fd = mustOpen(buf, "r");
fstat(fileno(fd), &statBuf);
len = statBuf.st_size;
menuStr = needMem(len + 1);
mustRead(fd, menuStr, statBuf.st_size);
menuStr[len] = 0;
carefulClose(&fd);

if (cart)
    {
    // fixup internal CGIs to have hgsid
    safef(buf, sizeof(buf), "/cgi-bin/hg[A-Za-z]+(%c%c?)", '\\', '?');
    err = regcomp(&re, buf, REG_EXTENDED);
    if(err)
	errAbort("regcomp failed; err: %d", err);
    struct dyString *dy = newDyString(0);
    for(offset = 0; offset < len && !regexec(&re, menuStr + offset, ArraySize(match), match, 0); offset += match[0].rm_eo)
	{
	dyStringAppendN(dy, menuStr + offset, match[0].rm_eo);
	if(match[1].rm_so == match[1].rm_eo)
	    dyStringAppend(dy, "?");
	dyStringAppend(dy, uiVars);
	if(match[1].rm_so != match[1].rm_eo)
	    dyStringAppend(dy, "&");
	}
    if(offset < len)
	dyStringAppend(dy, menuStr + offset);
    freez(&menuStr);
    menuStr = dyStringCannibalize(&dy);
    }
if(!loginSystemEnabled())
    stripRegEx(menuStr, "<\\!-- LOGIN_START -->.*<\\!-- LOGIN_END -->", REG_ICASE);

if(scriptName)
    {  // Provide optional official mirror servers menu items
    char *geoMenu = geoMirrorMenu();
    char *pattern = "<!-- OPTIONAL_MIRROR_MENU -->";
    char *newMenuStr = replaceChars(menuStr, pattern, geoMenu);
    freez(&menuStr);
    menuStr = newMenuStr;
    }


if(scriptName)
    {
    // Provide view menu for some CGIs.
    struct dyString *viewItems = dyStringCreate("");
    boolean hasViewMenu = TRUE;
    if (endsWith(scriptName, "hgGenome"))
        {
	safef(buf, sizeof(buf), "../cgi-bin/hgGenome?%s&hgGenome_doPsOutput=1", uiVars);
    	dyStringPrintf(viewItems, "<li><a href='%s' id='%s'>%s</a></li>\n", buf, "pdfLink", "PDF/PS");
        }
    else
	{
	hasViewMenu = FALSE;
	}
    if (hasViewMenu)
	{
	struct dyString *viewMenu = dyStringCreate("<li class='menuparent' id='view'><span>View</span>\n<ul style='display: none; visibility: hidden;'>\n");
	dyStringAppend(viewMenu, viewItems->string);
	dyStringAppend(viewMenu, "</ul>\n</li>\n");
    	menuStr = replaceChars(menuStr, "<!-- OPTIONAL_VIEW_MENU -->", viewMenu->string);
	dyStringFree(&viewMenu);
	}
    dyStringFree(&viewItems);
    }


if(scriptName)
    {
    // Provide context sensitive help links for some CGIs.
    char *link = NULL;
    char *label = NULL;
    if (endsWith(scriptName, "hgBlat"))
        {
        link = "../goldenPath/help/hgTracksHelp.html#BLATAlign";
        label = "Help on Blat";
        }
    else if (endsWith(scriptName, "hgHubConnect"))
        {
        link = "../goldenPath/help/hgTrackHubHelp.html";
        label = "Help on Track Hubs";
        }
    else if (endsWith(scriptName, "hgNear"))
        {
        link = "../goldenPath/help/hgNearHelp.html";
        label = "Help on Gene Sorter";
        }
    else if (endsWith(scriptName, "hgTables"))
        {
        link = "../goldenPath/help/hgTablesHelp.html";
        label = "Help on Table Browser";
        }
    else if (endsWith(scriptName, "hgGenome"))
        {
        link = "../goldenPath/help/hgGenomeHelp.html";
        label = "Help on Genome Graphs";
        }
    else if (endsWith(scriptName, "hgSession"))
        {
        link = "../goldenPath/help/hgSessionHelp.html";
        label = "Help on Sessions";
        }
    else if (endsWith(scriptName, "hgVisiGene"))
        {
        link = "../goldenPath/help/hgTracksHelp.html#VisiGeneHelp";
        label = "Help on VisiGene";
        }
    else if (endsWith(scriptName, "hgCustom"))
        {
        link = "../goldenPath/help/customTrack.html";
        label = "Help on Custom Tracks";
        }
    // Don't overwrite any previously set defaults
    if(!contextSpecificHelpLink && link)
        contextSpecificHelpLink = link;
    if(!contextSpecificHelpLabel && label)
        contextSpecificHelpLabel = label;
    }
if(contextSpecificHelpLink)
    {
    char buf[1024];
    safef(buf, sizeof(buf), "<li><a href='%s'>%s</a></li>", contextSpecificHelpLink, contextSpecificHelpLabel);
    menuStr = replaceChars(menuStr, "<!-- CONTEXT_SPECIFIC_HELP -->", buf);
    }
return menuStr;
}
void doUserFiles(char *u, struct commit *commits)
/* process one user's files-view (or all if u is NULL) */
{

// http://hgwdev.cse.ucsc.edu/cvs-reports/branch/user/galt/index-by-file.html
// if u is NULL
// http://hgwdev.cse.ucsc.edu/cvs-reports/branch/file/index.html
char userPath[1024];
if (u)
    safef(userPath, sizeof(userPath), "%s/%s/%s/%s/index-by-file.html", outDir, outPrefix, "user", u);
else
    safef(userPath, sizeof(userPath), "%s/%s/%s/index.html", outDir, outPrefix, "file");

FILE *h = mustOpen(userPath, "w");
if (u)
    {
    fprintf(h, "<html>\n<head>\n<title>File Changes for %s</title>\n</head>\n</body>\n", u);
    fprintf(h, "<h1>File Changes for %s</h1>\n", u);
    fprintf(h, "switch to <A href=\"index.html\">commits view</A>, <A href=\"../index.html\">user index</A>");
    }
else
    {
    fprintf(h, "<html>\n<head>\n<title>All File Changes</title>\n</head>\n</body>\n");
    fprintf(h, "<h1>All File Changes</h1>\n");
    }

fprintf(h, "<h3>%s to %s (%s to %s) %s</h3>\n", startTag, endTag, startDate, endDate, title);

fprintf(h, "<ul>\n");


int totalLinesChanged = 0;
int totalFileCount = 0;

char *cDiff = NULL, *cHtml = NULL, *fDiff = NULL, *fHtml = NULL;
char *relativePath = NULL;

struct commit *c = NULL;
struct files *f = NULL;

struct comFile *comFiles = NULL, *cf = NULL;

// pre-filter for u if u is not NULL  
for(c = commits; c; c = c->next)
    {
    if (!u || (u && sameString(c->author, u)))
	{
	for(f = c->files; f; f = f->next)
	    {
	    AllocVar(cf);
	    cf->f = f;
	    cf->commit = c;
	    slAddHead(&comFiles, cf);
	    }
	}
    }
// sort by file path, and then by commitNumber
//  so that newest commit is on the bottom.
slSort(&comFiles, slComFileCmp);

char *lastPath = "";
char *closure = "";

for(cf = comFiles; cf; cf = cf->next)
    {
    c = cf->commit;
    f = cf->f;
 
    if (!sameString(f->path, lastPath))
	{
	fprintf(h, "%s", closure);
	lastPath = f->path;
	fprintf(h, "<li>%s\n", f->path);
    	closure = "</li>\n";
	}


    char path[1024];

    // context unified
    if (u)
	safef(path, sizeof(path), "%s/%s%s", "context", f->path, c->commitId);
    else
	safef(path, sizeof(path), "../user/%s/%s/%s%s", c->author, "context", f->path, c->commitId);
    relativePath = cloneString(path);
    safef(path, sizeof(path), "%s.html", relativePath);
    cHtml = cloneString(path);
    safef(path, sizeof(path), "%s.diff", relativePath);
    cDiff = cloneString(path);



    // full text (up to 10,000 lines)
    freeMem(relativePath);
    if (u)
	safef(path, sizeof(path), "%s/%s%s", "full", f->path, c->commitId);
    else
	safef(path, sizeof(path), "../user/%s/%s/%s%s", c->author, "context", f->path, c->commitId);
    relativePath = cloneString(path);
    safef(path, sizeof(path), "%s.html", relativePath);
    fHtml = cloneString(path);
    safef(path, sizeof(path), "%s.diff", relativePath);
    fDiff = cloneString(path);

    // make file view links
    fprintf(h, "<ul><li>");
    fprintf(h, " lines changed %d, "
	"context: <A href=\"%s\">html</A>, <A href=\"%s\">text</A>, "
	"full: <A href=\"%s\">html</A>, <A href=\"%s\">text</A><br>\n"
	, f->linesChanged
	, cHtml, cDiff, fHtml, fDiff);

    //fprintf(h, "  %s\n", c->commitId);
    //fprintf(h, "  %s\n", c->date);
    char *cc = htmlEncode(c->comment);
    char *ccc = replaceChars(cc, "\n", "<br>\n");
    fprintf(h, "    %s\n", ccc);
    freeMem(cc);
    freeMem(ccc);
    fprintf(h, "</li></ul>\n");

    freeMem(relativePath);
    freeMem(cDiff);
    freeMem(cHtml);
    freeMem(fDiff);
    freeMem(fHtml);

    totalLinesChanged += f->linesChanged;
    ++totalFileCount;

    fprintf(h, "\n");
    }
fprintf(h, "%s", closure);
fprintf(h, "</ul>\n");
if (u)
    {
    fprintf(h, "switch to <A href=\"index.html\">commits view</A>, <A href=\"../index.html\">user index</A>");
    }
else
    {
    fprintf(h, "<ul>\n");
    fprintf(h, "<li> lines changed: %d</li>\n", totalLinesChanged);
    fprintf(h, "<li> files changed: %d</li>\n", totalFileCount);
    fprintf(h, "</ul>\n");
    }
fprintf(h, "</body>\n</html>\n");
fclose(h);
}
void doUserCommits(char *u, struct commit *commits, int *saveUlc, int *saveUfc)
/* process one user, commit-view */
{


char userPath[1024];
safef(userPath, sizeof(userPath), "%s/%s/%s/%s/index.html", outDir, outPrefix, "user", u);

FILE *h = mustOpen(userPath, "w");
fprintf(h, "<html>\n<head>\n<title>Commits for %s</title>\n</head>\n</body>\n", u);
fprintf(h, "<h1>Commits for %s</h1>\n", u);

fprintf(h, "switch to <A href=\"index-by-file.html\">files view</A>, <A href=\"../index.html\">user index</A>\n");
fprintf(h, "<h3>%s to %s (%s to %s) %s</h3>\n", startTag, endTag, startDate, endDate, title);

fprintf(h, "<ul>\n");


int userLinesChanged = 0;
int userFileCount = 0;

char *cDiff = NULL, *cHtml = NULL, *fDiff = NULL, *fHtml = NULL;
char *relativePath = NULL;
char *commonPath = NULL;

struct commit *c = NULL;
struct files *f = NULL;
for(c = commits; c; c = c->next)
    {
    if (sameString(c->author, u))
	{
	//fprintf(h, "%s\n", c->commitId);
	//fprintf(h, "%s\n", c->date);

	char *cc = htmlEncode(c->comment);
	char *ccc = replaceChars(cc, "\n", "<br>\n");
	fprintf(h, "<li>%s\n", ccc);
	freeMem(cc);
	freeMem(ccc);

	makeDiffAndSplit(c, u, FALSE);
	makeDiffAndSplit(c, u, TRUE);
	for(f = c->files; f; f = f->next)
	    {
	    char path[1024];

            // context unified
	    safef(path, sizeof(path), "%s/%s%s", "context", f->path, c->commitId);
	    relativePath = cloneString(path);

	    safef(path, sizeof(path), "%s/%s/%s/%s/%s", outDir, outPrefix, "user", u, relativePath);
	    commonPath = cloneString(path);

	    safef(path, sizeof(path), "%s.html", commonPath);
	    cHtml = cloneString(path);

	    safef(path, sizeof(path), "%s.diff", commonPath);
	    cDiff = cloneString(path);

	    // make context html page
	    f->linesChanged = makeHtml(cDiff, cHtml, f->path, c->commitId);

	    userLinesChanged += f->linesChanged;
	    ++userFileCount;

	    freeMem(cDiff);
	    freeMem(cHtml);
	    safef(path, sizeof(path), "%s.html", relativePath);
	    cHtml = cloneString(path);
	    safef(path, sizeof(path), "%s.diff", relativePath);
	    cDiff = cloneString(path);



            // full text (up to 10,000 lines)
	    freeMem(relativePath);
	    safef(path, sizeof(path), "%s/%s%s", "full", f->path, c->commitId);
	    relativePath = cloneString(path);

	    safef(path, sizeof(path), "%s/%s/%s/%s/%s", outDir, outPrefix, "user", u, relativePath);
	    freeMem(commonPath);
	    commonPath = cloneString(path);

	    safef(path, sizeof(path), "%s.html", commonPath);
	    fHtml = cloneString(path);

	    safef(path, sizeof(path), "%s.diff", commonPath);
	    fDiff = cloneString(path);


	    //git show --unified=10000 11a20b6cd113d75d84549eb642b7f2ac7a2594fe src/utils/qa/weeklybld/buildEnv.csh

	    // make full html page
	    makeHtml(fDiff, fHtml, f->path, c->commitId);

	    freeMem(fDiff);
	    freeMem(fHtml);
	    safef(path, sizeof(path), "%s.html", relativePath);
	    fHtml = cloneString(path);
	    safef(path, sizeof(path), "%s.diff", relativePath);
	    fDiff = cloneString(path);

	    // make file diff links
	    fprintf(h, "<ul><li> %s - lines changed %d, "
		"context: <A href=\"%s\">html</A>, <A href=\"%s\">text</A>, "
		"full: <A href=\"%s\">html</A>, <A href=\"%s\">text</A></li></ul>\n"
		, f->path, f->linesChanged
		, cHtml, cDiff, fHtml, fDiff);

	    freeMem(relativePath);
	    freeMem(commonPath);
	    freeMem(cDiff);
	    freeMem(cHtml);
	    freeMem(fDiff);
	    freeMem(fHtml);

	    }
	fprintf(h, "</li>\n");
	}
    }
fprintf(h, "</ul>\n");
fprintf(h, "switch to <A href=\"index-by-file.html\">files view</A>, <A href=\"../index.html\">user index</A>\n");
fprintf(h, "</body>\n</html>\n");
fclose(h);
*saveUlc = userLinesChanged;
*saveUfc = userFileCount;
}
Esempio n. 18
0
void hgTrackDb(char *org, char *database, char *trackDbName, char *sqlFile, char *hgRoot,
               boolean strict)
/* hgTrackDb - Create trackDb table from text files. */
{
struct trackDb *td;
char tab[PATH_LEN];
safef(tab, sizeof(tab), "%s.tab", trackDbName);

struct trackDb *tdbList = buildTrackDb(org, database, hgRoot, strict);
tdbList = flatten(tdbList);
slSort(&tdbList, trackDbCmp);
verbose(1, "Loaded %d track descriptions total\n", slCount(tdbList));

/* Write to tab-separated file; hold off on html, since it must be encoded */
    {
    verbose(2, "Starting write of tabs to %s\n", tab);
    FILE *f = mustOpen(tab, "w");
    for (td = tdbList; td != NULL; td = td->next)
        {
        hVarSubstTrackDb(td, database);
        char *hold = td->html;
        td->html = "";
	subChar(td->type, '\t', ' ');	/* Tabs confuse things. */
	subChar(td->shortLabel, '\t', ' ');	/* Tabs confuse things. */
	subChar(td->longLabel, '\t', ' ');	/* Tabs confuse things. */
	trackDbTabOut(td, f);
        td->html = hold;
        }
    carefulClose(&f);
    verbose(2, "Wrote tab representation to %s\n", tab);
    }

/* Update database */
    {
    char *create, *end;
    char query[256];
    struct sqlConnection *conn = sqlConnect(database);

    /* Load in table definition. */
    readInGulp(sqlFile, &create, NULL);
    create = trimSpaces(create);
    create = substituteTrackName(create, trackDbName);
    end = create + strlen(create)-1;
    if (*end == ';') *end = 0;
    sqlRemakeTable(conn, trackDbName, create);

    /* Load in regular fields. */
    sqlSafef(query, sizeof(query), "load data local infile '%s' into table %s", tab, trackDbName);
    verbose(2, "sending mysql \"%s\"\n", query);
    sqlUpdate(conn, query);
    verbose(2, "done tab file load");

    /* Load in html and settings fields. */
    for (td = tdbList; td != NULL; td = td->next)
	{
        if (isEmpty(td->html))
	    {
	    if (strict && !trackDbLocalSetting(td, "parent") && !trackDbLocalSetting(td, "superTrack") &&
	        !sameString(td->track,"cytoBandIdeo"))
		{
		fprintf(stderr, "Warning: html missing for %s %s %s '%s'\n",org, database, td->track, td->shortLabel);
		}
	    }
	else
	    {
	    updateBigTextField(conn,  trackDbName, "tableName", td->track, "html", td->html);
	    }
	if (td->settingsHash != NULL)
	    {
	    char *settings = settingsFromHash(td->settingsHash);
	    updateBigTextField(conn, trackDbName, "tableName", td->track,
	        "settings", settings);
	    if (showSettings)
		{
		verbose(1, "%s: type='%s';", td->track, td->type);
		if (isNotEmpty(settings))
		    {
		    char *oneLine = replaceChars(settings, "\n", "; ");
		    eraseTrailingSpaces(oneLine);
		    verbose(1, " %s", oneLine);
		    freeMem(oneLine);
		    }
		verbose(1, "\n");
		}
	    freeMem(settings);
	    }
	}

    sqlDisconnect(&conn);
    verbose(1, "Loaded database %s\n", database);
    }
}
Esempio n. 19
0
void cleanTicketNumbers(LPFIELDSRESULTS lpFieldsResults) {
	 char *resultsStr = lpFieldsResults->result;
	 int numGr, i, k;
	 int iStart, iStop;
	 char strT[10];
	 int ret;
	 int numLines = 0;

	 int thGroups = 5;
	 int numChars;
	 int beginCut = 0;
	 resultTmp[0] = 0;
	 cand2Tmp[0] = 0;
// test every line
//printf("\n\n");
//printf(resultsStr);
//printf("\n\n");
// get number of lines
	 i = 0;
	 while(1){
		if(getLine(resultsStr, i, &iStart, &iStop) < 0) break;
		numLines++;
		i++;
	 }
// test last lines
// printf("--- numLines= %d\n",numLines);

	 k = numLines-1;
	 while(k>0){
		 if(getLine(resultsStr, k, &iStart, &iStop) < 0) break;
		 if(testLineConf(lpFieldsResults, iStart, iStop) < 0)
			 numLines--;
		 else
			 break;
		 k--;
	 }

	 i = 0;
	 k = 0;
	 while(i < numLines){
		if(getLine(resultsStr, i, &iStart, &iStop) < 0) break;
           testLeftSideForLine(resultsStr, &iStart, iStop);
//printLine(resultsStr, iStart, iStop);

	    numGr = getNumberOfGroups(resultsStr, iStart, iStop);
	    beginCut = 0;
// printf("--- line i= %d; numGr= %d, iStart= %d, iStop= %d\n",i, numGr, iStart, iStop);
        numChars = getNumChars(resultsStr, iStart, iStop);
//printf("--- line i= %d; numGr= %d, numChars= %d\n",i, numGr, numChars);
        if(numGr == thGroups){
        	beginCut = testBeginCut(lpFieldsResults, iStart, iStop);
            if(beginCut > 0)
            	numGr++;
        }

//   printLine(resultsStr, iStart, iStop);

//   printf("--- line i= %d; numGr= %d, numChars= %d\n",i, numGr, numChars);
	    if(numGr > thGroups && strlen(resultsStr) > 15 && numChars < 20){
	       copyLine(lpFieldsResults, iStart, iStop);
//  printLine(resultsStr, iStart, iStop);

//    printfQuad();
//  printf("--- line i= %d; %s\n",i, result);
	       if(beginCut > 0){


//  printf("--- line i= %d; beginCut= %d\n",i, beginCut);

               strT[0] = 'A'+k;
               strT[1] = 32;
               strT[2] = 0;
               replaceChars(0, -1, strT);
	       }else{
              getFirstCharFromNumLine(&iStart, &iStop);

//  printfQuad();
//   printf("--- getFirstCharFromNumLine i= %d; iStart= %d, iStop= %d\n",i, iStart, iStop);

              if(numGr < 8 && iStart == 0 && iStop == 0 && result[1] != 32) {
                 strT[0] = 'A'+k;
                 strT[1] = 32;
                 strT[2] = 0;
                 replaceChars(0, -1, strT);
             }else{
//  	   printf("--- numGr= %d; iStart= %d, iStop= %d, result[1]= %d\n",numGr, iStart, iStop, result[1]);
                 strT[0] = 'A'+k;
                 strT[1] = 0;
                replaceChars(iStart, iStop, strT);
             }
	       }
           iStop = -1;
           ret = getFirstQPFromNumLine(&iStart, &iStop);
           if(ret >= 0) {
               replaceChars(iStart, iStop, "QP");
           }
           if( ret > 0 || numGr >6) {
              if(getSecondQPFromNumLine(&iStart, &iStop) >=0){
                 replaceChars(iStart, iStop, "QP");
              }
           }
	       addLineToTmp();
	       k++;
//printTmp();
	    }
	    i++;
	 }
	 copyResultsBack(lpFieldsResults);
}
static void loadDatabase(char *database, char *track, int bedSize, struct bedStub *bedList)
/* Load database from bedList. */
{
struct sqlConnection *conn;
struct dyString *dy = newDyString(1024);
char *tab = (char *)NULL;
int loadOptions = (optionExists("onServer") ? SQL_TAB_FILE_ON_SERVER : 0);

if ( ! noLoad )
    conn = sqlConnect(database);

if ((char *)NULL != tmpDir)
    tab = cloneString(rTempName(tmpDir,"loadBed",".tab"));
else
    tab = cloneString("bed.tab");

if (bedDetail && sqlTable == NULL) 
    errAbort("bedDetail format requires sqlTable option");
if (bedDetail && !strictTab) 
    errAbort("bedDetail format must be tab separated");
if (bedDetail && !noBin) 
    noBin = TRUE;

/* First make table definition. */
if (sqlTable != NULL && !oldTable)
    {
    /* Read from file. */
    char *sql, *s;
    readInGulp(sqlTable, &sql, NULL);
    /* Chop off end-of-statement semicolon if need be. */
    s = strchr(sql, ';');
    if (s != NULL) *s = 0;
    
    if ( !noLoad )
        {
        if (renameSqlTable)
            {
            char *pos = stringIn("CREATE TABLE ", sql);
            if (pos == NULL)
                errAbort("Can't find CREATE TABLE in %s\n", sqlTable);
            char *oldSql = cloneString(sql);
            nextWord(&pos); nextWord(&pos);
            char *tableName = nextWord(&pos);
            sql = replaceChars(oldSql, tableName, track);
            }
        verbose(1, "Creating table definition for %s\n", track);
        sqlRemakeTable(conn, track, sql);
        if (!noBin) 
	    addBinToEmptyTable(conn, track);
	adjustSqlTableColumns(conn, track, bedSize);
	}
    
    freez(&sql);
    }
else if (!oldTable)
    {
    int minLength;

    if (noLoad)
	minLength=6;
    else if (maxChromNameLength)
	minLength = maxChromNameLength;
    else
	minLength = hGetMinIndexLength(database);
    verbose(2, "INDEX chrom length: %d\n", minLength);

    /* Create definition statement. */
    verbose(1, "Creating table definition for %s\n", track);
    dyStringPrintf(dy, "CREATE TABLE %s (\n", track);
    if (!noBin)
       dyStringAppend(dy, "  bin smallint unsigned not null,\n");
    dyStringAppend(dy, "  chrom varchar(255) not null,\n");
    dyStringAppend(dy, "  chromStart int unsigned not null,\n");
    dyStringAppend(dy, "  chromEnd int unsigned not null,\n");
    if (bedSize >= 4)
       maybeBedGraph(4, dy, "  name varchar(255) not null,\n");
    if (bedSize >= 5)
	{
	if (allowNegativeScores)
	    maybeBedGraph(5, dy, "  score int not null,\n");
	else
	    maybeBedGraph(5, dy, "  score int unsigned not null,\n");
	}
    if (bedSize >= 6)
       maybeBedGraph(6, dy, "  strand char(1) not null,\n");
    if (bedSize >= 7)
       maybeBedGraph(7, dy, "  thickStart int unsigned not null,\n");
    if (bedSize >= 8)
       maybeBedGraph(8, dy, "  thickEnd int unsigned not null,\n");
    /*	As of 2004-11-22 the reserved field is used as itemRgb in code */
    if (bedSize >= 9)
       maybeBedGraph(9, dy, "  reserved int unsigned  not null,\n");
    if (bedSize >= 10)
       maybeBedGraph(10, dy, "  blockCount int unsigned not null,\n");
    if (bedSize >= 11)
       maybeBedGraph(11, dy, "  blockSizes longblob not null,\n");
    if (bedSize >= 12)
       maybeBedGraph(12, dy, "  chromStarts longblob not null,\n");
    if (bedSize >= 13)
       maybeBedGraph(13, dy, "  expCount int unsigned not null,\n");
    if (bedSize >= 14)
       maybeBedGraph(14, dy, "  expIds longblob not null,\n");
    if (bedSize >= 15)
       maybeBedGraph(15, dy, "  expScores longblob not null,\n");
    dyStringAppend(dy, "#Indices\n");
    if (nameIx && (bedSize >= 4) && (0 == bedGraph))
       dyStringAppend(dy, "  INDEX(name(16)),\n");
    if (noBin)
	{
	dyStringPrintf(dy, "  INDEX(chrom(%d),chromStart)\n", minLength);
	}
    else
	{
        dyStringPrintf(dy, "  INDEX(chrom(%d),bin)\n", minLength);
	}
    dyStringAppend(dy, ")\n");
    if (noLoad)
	verbose(2,"%s", dy->string);
    else
	sqlRemakeTable(conn, track, dy->string);
    }

verbose(1, "Saving %s\n", tab);
writeBedTab(tab, bedList, bedSize);

if ( ! noLoad )
    {
    verbose(1, "Loading %s\n", database);
    if (customTrackLoader)
	sqlLoadTabFile(conn, tab, track, loadOptions|SQL_TAB_FILE_WARN_ON_WARN);
    else
	sqlLoadTabFile(conn, tab, track, loadOptions);

    if (! noHistory)
	{
	char comment[256];
	/* add a comment to the history table and finish up connection */
	safef(comment, sizeof(comment),
	    "Add %d element(s) from bed list to %s table",
		slCount(bedList), track);
	hgHistoryComment(conn, comment);
	}
    if(fillInScoreColumn != NULL)
        {
        char query[500];
        char buf[500];
        struct sqlResult *sr;
        safef(query, sizeof(query), "select sum(score) from %s", track);
        if(sqlQuickQuery(conn, query, buf, sizeof(buf)))
            {
            unsigned sum = sqlUnsigned(buf);
            if (!sum)
                {
                safef(query, sizeof(query), "select min(%s), max(%s) from %s", fillInScoreColumn, fillInScoreColumn, track);
                if ((sr = sqlGetResult(conn, query)) != NULL)
                    {
                    char **row = sqlNextRow(sr);
                    if(row != NULL)
                        {
                        float min = sqlFloat(row[0]);
                        float max = sqlFloat(row[1]);
			if ( !(max == -1 && min == -1)) // if score is -1 then ignore, as if it werent present
			    {
			    if (max == min || sameString(row[0],row[1])) // this will lead to 'inf' score value in SQL update causing an error
				errAbort("Could not set score in table %s max(%s)=min(%s)=%s\n", track, fillInScoreColumn, fillInScoreColumn, row[0]);
                            sqlFreeResult(&sr);

			    // Calculate a, b s/t f(x) = ax + b maps min-max => minScore-1000
			    float a = (1000-minScore) / (max - min);
			    float b = 1000 - ((1000-minScore) * max) / (max - min);

			    safef(query, sizeof(query), "update %s set score = round((%f * %s) + %f)",  track, a, fillInScoreColumn, b);
			    int changed = sqlUpdateRows(conn, query, NULL);
			    verbose(2, "update query: %s; changed: %d\n", query, changed);
			    }
			else
			    {
                            sqlFreeResult(&sr);
			    verbose(2, "score not updated; all values for column %s are -1\n", fillInScoreColumn);
			    }
			}
                    }
                }
            }

        }
    sqlDisconnect(&conn);
    /*	if temp dir specified, unlink file to make it disappear */
    if ((char *)NULL != tmpDir)
	unlink(tab);
    }
else
    verbose(1, "No load option selected, see file: %s\n", tab);

}	/*	static void loadDatabase()	*/
Esempio n. 21
0
void galleryDisplay(struct galleryEntry *galList)
/* Print a table containing the gallery data from galList */
{
struct galleryEntry *thisSession = galList;

/* Hide the orderable columns and disable ordering on the visible columns
 * https://datatables.net/reference/option/columnDefs for more info.
 * Then set up the ordering drop-down menu */
printf ("<script type=\"text/javascript\">");
printf("$(document).ready(function () {\n"
    "    $('#sessionTable').DataTable({\"columnDefs\": [{\"visible\":false, \"targets\":[2,3]},\n"
    "                                                   {\"orderable\":false, \"targets\":[0,1]}\n"
    "                                                  ],\n"
    "                                       \"dom\":\"lftip\",\n"
    "                                       \"stateSave\":true,\n"
    "                                       \"stateSaveCallback\": %s,\n"
    "                                       \"stateLoadCallback\": %s,\n"
    "                                });\n"
    /* Recover previous sorting choice from the cart settings, if available */
    "    var startOrder = $('#sessionTable').DataTable().order();\n"
    "    if (startOrder[0][0] == 3) {\n"
    "        if (startOrder[0][1] == \"asc\") {\n"
    "            $('#sortMethod').val(\"useAsc\");\n"
    "        } else {\n"
    "            $('#sortMethod').val(\"useDesc\");\n"
    "        }\n"
    "    } else {\n"
    "        if (startOrder[0][0] == 2) {\n"
    "            if (startOrder[0][1] == \"asc\") {\n"
    "                $('#sortMethod').val(\"dateAsc\");\n"
    "            } else {\n"
    "                $('#sortMethod').val(\"dateDesc\");\n"
    "            }\n"
    "        } else {\n"
    "            $('#sessionTable').DataTable().order([3,'desc']).draw();\n"
    "            $('#sortMethod').val(\"useDesc\");\n"
    "        }\n"
    "    }\n"
    "});\n",
    jsDataTableStateSave(hgPublicSessionsPrefix), jsDataTableStateLoad(hgPublicSessionsPrefix, cart));
printf ("function changeSort() {\n"
    "    var newSort = document.getElementById('sortMethod').value;\n"
    "    var theTable = $('#sessionTable').DataTable();\n"
    "    if (newSort == \"useDesc\") {theTable.order([3,'desc']).draw(); }\n"
    "    if (newSort == \"useAsc\") {theTable.order([3,'asc']).draw(); }\n"
    "    if (newSort == \"dateDesc\") {theTable.order([2,'desc']).draw(); }\n"
    "    if (newSort == \"dateAsc\") {theTable.order([2,'asc']).draw(); }\n"
    "}\n");
printf("</script>\n");

printf ("<p>\n");
printf ("<b>Sort by:</b> <select id=\"sortMethod\" onchange=\"changeSort()\">\n");
printf ("\t\t<option value=\"useDesc\">Popularity (descending)</option>\n");
printf ("\t\t<option value=\"useAsc\">Popularity (ascending)</option>\n");
printf ("\t\t<option value=\"dateDesc\">Creation (newest first)</option>\n");
printf ("\t\t<option value=\"dateAsc\">Creation (oldest first)</option>\n");
printf ("</select></p>\n");
printf ("<table id=\"sessionTable\" class=\"sessionTable stripe hover row-border compact\" width=\"100%%\">\n"
    "    <thead>"
    "        <tr>"
    "            <th>Screenshot</th>\n"
    "            <th>Session Properties</th>\n"
    "            <th>Creation Date</th>\n"
    "            <th>Use Count</th>\n"
    "        </tr>\n"
    "    </thead>\n");

printf ("<tbody>\n");

while (thisSession != NULL)
    {
    char *settingString = NULL;
    printf ("\t<tr>\n");
    if (isNotEmpty(thisSession->imgUri))
        {
        printf ("\t\t<td><a href=\"../cgi-bin/hgTracks?%s\">",
            dyStringContents(thisSession->sessionUrl));
        printf ("<img src=\"%s\" class=\"sessionThumbnail\"></a></td>\n", thisSession->imgUri);
        }
    else
        {
        printf ("\t\t<td><center><nobr>Screenshot not available</nobr><br>\n");
        printf ("\t\t<a href=\"../cgi-bin/hgTracks?%s\">Click Here</a> to view</center></td>\n",
            dyStringContents(thisSession->sessionUrl));
        }

    struct hash *settingsHash = raFromString(thisSession->settings);
    settingString = (char*) hashFindVal(settingsHash, "description");
    if (settingString == NULL)
        settingString = "";
    else
        {
        settingString = replaceChars(settingString, "\\\\", "\\__ESC__");
        settingString = replaceChars(settingString, "\\r", "\r");
        settingString = replaceChars(settingString, "\\n", "\n");
        settingString = replaceChars(settingString, "\\__ESC__", "\\");
        }
    printf ("\t\t<td><b>Description:</b> %s<br>\n", settingString);
    printf ("\t\t<b>Author:</b> %s<br>\n", thisSession->userName);
    printf ("\t\t<b>Session Name:</b> %s<br>\n", thisSession->sessionName);
    printf ("\t\t<b>Genome Assembly:</b> %s<br>\n", thisSession->db);
    printf ("\t\t<b>Creation Date:</b> %s<br>\n", thisSession->firstUse);
    printf ("\t\t<b>Views:</b> %ld\n", thisSession->useCount);
    printf ("\t\t</td>\n");
    struct tm creationDate;
    strptime(thisSession->firstUse, "%Y-%m-%d", &creationDate);
    /* Hidden columns */
    printf ("\t\t<td>%ld</td>\n", mktime(&creationDate));
    printf ("\t\t<td>%ld</td>\n", thisSession->useCount);
    printf ("\t</tr>\n");
    thisSession = thisSession->next;
    }

printf ("</tbody>\n");
printf ("</table>\n");
}