void loadConf(char **src , const char* fileName) { char buf[BUF_SIZE] = ""; unsigned int read_size = 0; FILE *file = NULL; if(fopen_s(&file , fileName , "r")) { printf("找不到%s\n" , fileName); return; } while(1) { //每次少读一个字符,最后一个字符给'\0' read_size = fread(buf , 1 , BUF_SIZE - 1 , file); buf[read_size] = '\0'; if( BUF_SIZE - 1 > read_size ) { appendStr(src , buf); break; } appendStr(src , buf ); } fclose(file); }
void ActiveContours::runSDF() { dout << endl << "--------Running SDF ("<< width << "," << height << ")" << endl; bool norm = false; try { // Create the program from source if (!usingOGL) { //If we are not using the OpenGL texture, then we write it from the array. err = queue->enqueueWriteImage(img_in, CL_FALSE, origin, region, 0, 0, (void*) arr_img_in, 0, &evImgInWrt); } queue->finish(); //Writes the mask as the original value for err = queue->enqueueWriteBuffer(buf_mask, CL_FALSE, 0, sizeof (float) *width*height, (void*) arr_buf_mask, 0, &evImgSegWrt); // err = queue->enqueueWriteImage(img_mask, CL_FALSE, origin, region, 0, 0, (void*) arr_img_phi, 0, &evImgSegWrt); char* sdfPath = (char*) "images/SDF/CurrentRun/"; //Path to save SDF images if (WRITE) {//Writes the original mask string fileName = appendStr(sdfPath, (char*) "MASK.png"); ImageManager::writeGrayScaleImage((char*) fileName.c_str(), arr_buf_mask, FIF_PNG, width, height, norm); if (PRINT_IMG_VAL) { cout << "Mask: " << endl; ImageManager::printImage(width, height, arr_buf_mask, 1); } cout << "--------------------Computing the SDF..." << endl; } vecWriteImage.push_back(evImgSegWrt); SignedDistFunc sdfObj; // It reads from img_mask the mask, and writes into img_phi the output evSDF = sdfObj.runSDFBuf(&clMan, SDFmethod, buf_mask, buf_sdf, max_warp_size, width, height, evImgSegWrt, sdfPath); vecEvSDF.push_back(evSDF); if (WRITE) {// Saves the SDF result as an image cout << "Saving SDF result..." << endl; string fileName = appendStr(sdfPath, (char*) "SDFResult.png"); //Reads from buf_sdf (GPU) and writes to arr_img_out (Host) res = queue->enqueueReadBuffer(buf_sdf, CL_TRUE, 0, sizeof (float) *width*height, (void*) arr_img_out, &vecEvSDF, 0); // Prints image into png file ImageManager::writeGrayScaleImage((char*) fileName.c_str(), arr_img_out, FIF_PNG, width, height,norm); if (PRINT_IMG_VAL) { ImageManager::printImage(width, height, arr_img_out, 1); } } queue->finish(); //Be sure we finish dout << "Out of ActiveContours initialization ......." << endl; } catch (cl::Error ex) { clMan.printError(ex); return; } }
char * appendPinStatus(char *buffer, io_pin_e pin) { char *ptr = appendStr(buffer, getPinShortName(pin)); int state = getOutputPinValue(pin); // todo: should we handle INITIAL_PIN_STATE? if (state) { return appendStr(ptr, ":Y "); } else { return appendStr(ptr, ":n "); } }
static char * prepareCltIatTpsLine(char *buffer) { char *ptr = buffer; *ptr++ = 'C'; ptr = ftoa(ptr, getCoolantTemperature(), 10.0f); ptr = appendStr(ptr, " C"); ptr = ftoa(ptr, getIntakeAirTemperature(), 10.0f); ptr = appendStr(ptr, " TP"); ptr = itoa10(ptr, (int) getTPS()); return ptr; }
static void set_defaults(ImageInfo *ii) { // default filename char *basename = get_basename(ii->filename); char *def = appendStr(basename, "_aoi"); if (strncmp_case(def, "LED-", 4) == 0 || strncmp_case(def, "IMG-", 4) == 0 || strncmp_case(def, "TRL-", 4) == 0 || strncmp_case(def, "VOL-", 4) == 0) { char *tmp = STRDUP(def+4); free(def); def = tmp; } free(basename); put_string_to_entry("filename_entry", def); free(def); // default directory char *dir = get_dirname(ii->filename); if (dir && strlen(dir) > 0) put_string_to_entry("dir_entry", dir); else put_string_to_entry("dir_entry", ""); FREE(dir); // default data to save (Pixel Values) set_combo_box_item("data_combobox", 0); }
static char * prepareCltIatTpsLine(Engine *engine, char *buffer) { char *ptr = buffer; *ptr++ = 'C'; ptr = appendStr(ptr, " TP"); ptr = itoa10(ptr, (int) getTPS(PASS_ENGINE_PARAMETER_F)); return ptr; }
static char * prepareVBattMapLine(engine_configuration_s *engineConfiguration, char *buffer) { char *ptr = buffer; *ptr++ = 'V'; ptr = ftoa(ptr, getVBatt(PASS_ENGINE_PARAMETER_F), 10.0f); ptr = appendStr(ptr, " M"); ptr = ftoa(ptr, getRawMap(), 10.0f); return ptr; }
static char * prepareVBattMapLine(char *buffer) { char *ptr = buffer; *ptr++ = 'V'; ptr = ftoa(ptr, getVBatt(), 10.0f); ptr = appendStr(ptr, " M"); ptr = ftoa(ptr, getRawMap(), 10.0f); return ptr; }
void joinList(SLIST *strList, struct String *dest) { strList->cur = strList->head; while(strList->cur != NULL) { appendStr(dest, strList->cur->str); appendChar(dest, ' '); strList->cur = strList->cur->next; } strList->cur = NULL; }
void AccessLog::log( const char * pVHostName, int len, HttpConnection* pConn ) { if ( pVHostName ) { m_buf.append( '[' ); appendStr( pVHostName, len ); m_buf.append( ']' ); m_buf.append( ' ' ); } log( pConn ); }
static char * prepareInfoLine(char *buffer) { char *ptr = buffer; ptr = appendStr(ptr, algorithmStr[engineConfiguration->algorithm]); ptr = appendStr(ptr, " "); ptr = appendStr(ptr, ignitionModeStr[engineConfiguration->ignitionMode]); ptr = appendStr(ptr, " "); ptr = appendStr(ptr, injectionModeStr[engineConfiguration->injectionMode]); ptr = appendStr(ptr, " "); ptr = appendStr(ptr, idleModeStr[engineConfiguration->idleMode]); ptr = appendStr(ptr, " "); return ptr; }
static char * prepareInfoLine(engine_configuration_s *engineConfiguration, char *buffer) { char *ptr = buffer; ptr = appendStr(ptr, " "); ptr = appendStr(ptr, ignitionModeStr[engineConfiguration->ignitionMode]); ptr = appendStr(ptr, " "); ptr = appendStr(ptr, injectionModeStr[engineConfiguration->injectionMode]); ptr = appendStr(ptr, " "); ptr = appendStr(ptr, idleModeStr[engineConfiguration->idleMode]); ptr = appendStr(ptr, " "); return ptr; }
int getVirtualSlot(struct p11Slot_t *slot, int index, struct p11Slot_t **vslot) { struct p11Slot_t *newslot; char postfix[3]; FUNC_CALLED(); if ((index < 0) || (index > sizeof(slot->virtualSlots) / sizeof(*slot->virtualSlots))) FUNC_FAILS(CKR_ARGUMENTS_BAD, "Index must not exceed size of virtual slot list"); if (slot->primarySlot) FUNC_FAILS(CKR_ARGUMENTS_BAD, "Slot is a virtual slot"); if (slot->virtualSlots[index]) { *vslot = slot->virtualSlots[index]; FUNC_RETURNS(CKR_OK); } newslot = (struct p11Slot_t *) calloc(1, sizeof(struct p11Slot_t)); if (newslot == NULL) FUNC_FAILS(CKR_HOST_MEMORY, "Out of memory"); *newslot = *slot; newslot->token = NULL; newslot->next = NULL; newslot->primarySlot = slot; /* If we already have a pre-allocated slot id, then assign the next id value */ if (slot->id != 0) newslot->id = slot->id + index + 1; slot->virtualSlots[index] = newslot; postfix[0] = '.'; postfix[1] = '2' + index; postfix[2] = 0; appendStr(newslot->info.slotDescription, sizeof(slot->info.slotDescription), postfix); addSlot(&context->slotPool, newslot); *vslot = newslot; FUNC_RETURNS(CKR_OK); }
/** * Runs the SDF from the initialized mask. */ void ActiveContours::runSDF() { buf_size = width*height*depth;//Local variable of the buffer size try { queue->finish();//We need to finish everything that it was queued before //Writes the mask stored in 'arr_buf_mask' into the cl::Buffer 'buf_mask' err = queue->enqueueWriteBuffer(buf_mask, CL_FALSE, 0, sizeof (unsigned char)*buf_size, (void*) arr_buf_mask, 0, &evImgSegWrt); char* sdfPath = (char*) "images/SDF/"; //Path to save SDF images if (WRITE) {//Writes the original mask //if (false) {//Writes the original mask dout << "******** Writing original mask .... " << endl; string folder = appendStr(sdfPath, (char*) "OriginalMask/"); ImageManager::write3DImageSDF( (char*) folder.c_str(), arr_buf_mask, width, height, depth); } SignedDistFunc sdfObj; dev_max_work_items = 512; dout << "Max warpsize for SDF: " << dev_max_work_items << endl; // It reads from buf_mask the mask, and writes into buf_phi the output evSDF_newPhi = sdfObj.run3DSDFBuf(&clMan, buf_mask, buf_phi, dev_max_work_items, width, height, depth, evImgSegWrt, sdfPath); if (WRITE) {// Saves the SDF result as an image cout << "--------------------Displaying some values of the SDF..." << endl; vecEvPrevPrinting.clear(); vecEvPrevPrinting.push_back(evSDF_newPhi); //printBuffer(buf_phi, 10, vecEvPrevPrinting); printBuffer(buf_phi, width*height*2, 0, width, height, vecEvPrevPrinting); } if (WRITE) {// Saves the SDF result as an image dout << "Saving SDF result..." << endl; string folder = appendStr(sdfPath, (char*) "SDFOutput/"); vecEvPrevPrinting.push_back(evSDF_newPhi); //Reads from buf_phi (GPU) and writes to arr_img_out (Host) res = queue->enqueueReadBuffer(buf_phi, CL_TRUE, 0, sizeof (float) *buf_size, (void*) arr_img_out, &vecEvPrevPrinting, 0); // Prints image into png file ImageManager::write3DImage((char*) folder.c_str(), arr_img_out, width, height, depth, 0); } vecEvPrevCurvature.push_back(evSDF_newPhi); // Copying result to GL 3d Texture err = queue->enqueueAcquireGLObjects(&cl_textures, NULL, &evAcOGL); queue->finish(); dout << "Initializing origin and region with " << width << "," << height << "," << depth << endl; origin.push_back(0); origin.push_back(0); origin.push_back(0); region.push_back(width); region.push_back(height); region.push_back(depth); queue->enqueueCopyBufferToImage(buf_phi, img_phi_gl, (size_t)0, origin, region, &vecEvPrevCurvature, &evAcOGL); err = queue->enqueueReleaseGLObjects(&cl_textures, NULL, 0); dout << "Out of ActiveContours initialization SDF computed!......." << endl; } catch (cl::Error ex) { clMan.printError(ex); return; } }
int extraction(char *host, char *path, SLIST *wordList, SLIST *urlList) { int conn; char buff[(BUFFSIZE + 1)] = {0}; int len; struct String *htmlString = createStr(); //Contains raw html pulled from web page struct String *cleanString = createStr(); //Contains the truncated html code struct String *baseURL = createStr(); //Contains the url in the <base href = ""> /* contact the web server */ conn = socketClient(host, HTTPPORT); if (conn < 0) { exit(1); } /* send an HTTP/1.1 request to the webserver */ sprintf(buff, "GET %s HTTP/1.1\r\nHost: %s\r\n", path, host); strcat(buff, "User-Agent: self-module\r\n"); strcat(buff, "Accept: text/html,application/xhtml+xml\r\n"); strcat(buff, "Accept-Language: en-us,en;q=0.5\r\n"); // strcat(buff, "Accept-Encoding: gzip,defalte\r\n"); strcat(buff, "Accept-Charset: ISO-8859-1,utf-8;q=0.7\r\n"); strcat(buff, "Keep-Alive: 115\r\n"); strcat(buff, "Connection: keep-alive\r\n"); strcat(buff, "\r\n"); len = strlen(buff); (void) send(conn, buff, len, 0); /* convert all data received into chunks, append it to htmlString */ while((len = recv(conn, buff, BUFFSIZE, 0)) > 0) { appendLit(htmlString, buff); memset(buff, 0, BUFFSIZE); } //Parsing base url if (-1 == parseBaseURL(baseURL, htmlString)) { printf("Could not locate base url.\n"); return -1; } //Parsing url links //printf("Building url link list.\n"); buildLinkList(urlList, htmlString, baseURL); //Add the url that the crawler parsed the html from urlList->key = createStr(); appendStr(urlList->key, baseURL); //creating word list appendStr(cleanString, htmlString); //cleaning html string by replacing all non-alphanumeric characters with spaces. truncateStr(cleanString); charSplit(wordList, cleanString, ' '); wordList->key = createStr(); appendStr(wordList->key, baseURL); //cleaning word list based on existing stop words //printf("Started removing stop words.\n"); rmStopWords(wordList); //free up memory //printf("Extraction: destroying htmlString, cleanString, & baseURL.\n"); destroyStr(htmlString); destroyStr(cleanString); destroyStr(baseURL); return 0; }
//PrettyPrinting type names PCCOR_SIGNATURE PrettyPrintType( PCCOR_SIGNATURE typePtr, // type to convert, CQuickBytes *out, // where to put the pretty printed string IMDInternalImport *pIMDI, // ptr to IMDInternal class with ComSig DWORD formatFlags /*= formatILDasm*/) { mdToken tk; const char* str; int typ; CQuickBytes tmp; CQuickBytes Appendix; BOOL Reiterate; int n; do { Reiterate = FALSE; switch(typ = *typePtr++) { case ELEMENT_TYPE_VOID : str = "void"; goto APPEND; case ELEMENT_TYPE_BOOLEAN : str = "bool"; goto APPEND; case ELEMENT_TYPE_CHAR : str = "char"; goto APPEND; case ELEMENT_TYPE_I1 : str = "int8"; goto APPEND; case ELEMENT_TYPE_U1 : str = "uint8"; goto APPEND; case ELEMENT_TYPE_I2 : str = "int16"; goto APPEND; case ELEMENT_TYPE_U2 : str = "uint16"; goto APPEND; case ELEMENT_TYPE_I4 : str = "int32"; goto APPEND; case ELEMENT_TYPE_U4 : str = "uint32"; goto APPEND; case ELEMENT_TYPE_I8 : str = "int64"; goto APPEND; case ELEMENT_TYPE_U8 : str = "uint64"; goto APPEND; case ELEMENT_TYPE_R4 : str = "float32"; goto APPEND; case ELEMENT_TYPE_R8 : str = "float64"; goto APPEND; case ELEMENT_TYPE_U : str = "native uint"; goto APPEND; case ELEMENT_TYPE_I : str = "native int"; goto APPEND; case ELEMENT_TYPE_OBJECT : str = "object"; goto APPEND; case ELEMENT_TYPE_STRING : str = "string"; goto APPEND; case ELEMENT_TYPE_TYPEDBYREF : str = "typedref"; goto APPEND; APPEND: appendStr(out, (char*)str); break; case ELEMENT_TYPE_VALUETYPE : if ((formatFlags & FormatKwInNames) != 0) str = "valuetype "; else str = ""; goto DO_CLASS; case ELEMENT_TYPE_CLASS : if ((formatFlags & FormatKwInNames) != 0) str = "class "; else str = ""; goto DO_CLASS; DO_CLASS: appendStr(out, (char*)str); typePtr += CorSigUncompressToken(typePtr, &tk); if(IsNilToken(tk)) { appendStr(out, "[ERROR! NIL TOKEN]"); } else PrettyPrintClass(out, tk, pIMDI, formatFlags); break; case ELEMENT_TYPE_SZARRAY : insertStr(&Appendix,"[]"); Reiterate = TRUE; break; case ELEMENT_TYPE_ARRAY : { typePtr = PrettyPrintType(typePtr, out, pIMDI, formatFlags); unsigned rank = CorSigUncompressData(typePtr); // <TODO> what is the syntax for the rank 0 case? </TODO> if (rank == 0) { appendStr(out, "[BAD: RANK == 0!]"); } else { _ASSERTE(rank != 0); #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:22009) // "Suppress PREfast warnings about integer overflow" // PREFAST warns about using _alloca in a loop. However when we're in this switch case we do NOT // set Reiterate to true, so we only execute through the loop once! #pragma warning(disable:6263) // "Suppress PREfast warnings about stack overflow due to _alloca in a loop." #endif int* lowerBounds = (int*) _alloca(sizeof(int)*2*rank); int* sizes = &lowerBounds[rank]; memset(lowerBounds, 0, sizeof(int)*2*rank); unsigned numSizes = CorSigUncompressData(typePtr); _ASSERTE(numSizes <= rank); unsigned i; for(i =0; i < numSizes; i++) sizes[i] = CorSigUncompressData(typePtr); unsigned numLowBounds = CorSigUncompressData(typePtr); _ASSERTE(numLowBounds <= rank); for(i = 0; i < numLowBounds; i++) typePtr+=CorSigUncompressSignedInt(typePtr,&lowerBounds[i]); appendChar(out, '['); if (rank == 1 && numSizes == 0 && numLowBounds == 0) appendStr(out, "..."); else { for(i = 0; i < rank; i++) { //if (sizes[i] != 0 || lowerBounds[i] != 0) { if (lowerBounds[i] == 0 && i < numSizes) appendStrNum(out, sizes[i]); else { if(i < numLowBounds) { appendStrNum(out, lowerBounds[i]); appendStr(out, "..."); if (/*sizes[i] != 0 && */i < numSizes) appendStrNum(out, lowerBounds[i] + sizes[i] - 1); } } } if (i < rank-1) appendChar(out, ','); } } appendChar(out, ']'); #ifdef _PREFAST_ #pragma warning(pop) #endif } } break; case ELEMENT_TYPE_VAR : appendChar(out, '!'); n = CorSigUncompressData(typePtr); appendStrNum(out, n); break; case ELEMENT_TYPE_MVAR : appendChar(out, '!'); appendChar(out, '!'); n = CorSigUncompressData(typePtr); appendStrNum(out, n); break; case ELEMENT_TYPE_FNPTR : appendStr(out, "method "); appendStr(out, "METHOD"); // was: typePtr = PrettyPrintSignature(typePtr, 0x7FFF, "*", out, pIMDI, NULL); break; case ELEMENT_TYPE_GENERICINST : { typePtr = PrettyPrintType(typePtr, out, pIMDI, formatFlags); if ((formatFlags & FormatSignature) == 0) break; if ((formatFlags & FormatAngleBrackets) != 0) appendStr(out, "<"); else appendStr(out,"["); unsigned numArgs = CorSigUncompressData(typePtr); bool needComma = false; while(numArgs--) { if (needComma) appendChar(out, ','); typePtr = PrettyPrintType(typePtr, out, pIMDI, formatFlags); needComma = true; } if ((formatFlags & FormatAngleBrackets) != 0) appendStr(out, ">"); else appendStr(out,"]"); break; } case ELEMENT_TYPE_PINNED : str = " pinned"; goto MODIFIER; case ELEMENT_TYPE_PTR : str = "*"; goto MODIFIER; case ELEMENT_TYPE_BYREF : str = "&"; goto MODIFIER; MODIFIER: insertStr(&Appendix, str); Reiterate = TRUE; break; default: case ELEMENT_TYPE_SENTINEL : case ELEMENT_TYPE_END : //_ASSERTE(!"Unknown Type"); if(typ) { char sz[64]; sprintf_s(sz,COUNTOF(sz),"/* UNKNOWN TYPE (0x%X)*/",typ); appendStr(out, sz); } break; } // end switch } while(Reiterate); if (Appendix.Size() > 0) appendStr(out,asString(&Appendix)); return(typePtr); }
const char* PrettyPrintClass( CQuickBytes *out, // where to put the pretty printed string mdToken tk, // The class token to look up IMDInternalImport *pIMDI, // ptr to IMDInternalImport class with ComSig DWORD formatFlags /*= formatILDasm*/) { if(tk == mdTokenNil) // Zero resolution scope for "somewhere here" TypeRefs { appendStr(out,"[*]"); return(asString(out)); } if (!pIMDI->IsValidToken(tk)) { char str[1024]; sprintf_s(str,COUNTOF(str)," [ERROR: INVALID TOKEN 0x%8.8X] ",tk); appendStr(out, str); return(asString(out)); } switch (TypeFromToken(tk)) { case mdtTypeRef: case mdtTypeDef: { const char *nameSpace = 0; const char *name = 0; mdToken tkEncloser = mdTokenNil; if (TypeFromToken(tk) == mdtTypeRef) { if ((formatFlags & FormatAssembly) && FAILED(pIMDI->GetResolutionScopeOfTypeRef(tk, &tkEncloser)) || FAILED(pIMDI->GetNameOfTypeRef(tk, &nameSpace, &name))) { char str[1024]; sprintf_s(str, COUNTOF(str), " [ERROR: Invalid TypeRef record 0x%8.8X] ", tk); appendStr(out, str); return asString(out); } } else { if (((formatFlags & FormatNamespace) == 0) || FAILED(pIMDI->GetNestedClassProps(tk,&tkEncloser))) { tkEncloser = mdTypeDefNil; } if (FAILED(pIMDI->GetNameOfTypeDef(tk, &name, &nameSpace))) { char str[1024]; sprintf_s(str, COUNTOF(str), " [ERROR: Invalid TypeDef record 0x%8.8X] ", tk); appendStr(out, str); return asString(out); } } MAKE_NAME_IF_NONE(name,tk); if((tkEncloser == mdTokenNil) || RidFromToken(tkEncloser)) { if (TypeFromToken(tkEncloser) == mdtTypeRef || TypeFromToken(tkEncloser) == mdtTypeDef) { PrettyPrintClass(out,tkEncloser,pIMDI, formatFlags); if (formatFlags & FormatSlashSep) appendChar(out, '/'); else appendChar(out, '+'); //nameSpace = ""; //don't print namespaces for nested classes! } else if (formatFlags & FormatAssembly) { PrettyPrintClass(out,tkEncloser,pIMDI, formatFlags); } } if(TypeFromToken(tk)==mdtTypeDef) { unsigned L = (unsigned)strlen(name)+1; char* szFN = NULL; if(((formatFlags & FormatNamespace) != 0) && nameSpace && *nameSpace) { const char* sz = nameSpace; L+= (unsigned)strlen(sz)+1; szFN = new char[L]; sprintf_s(szFN,L,"%s.",sz); } else { szFN = new char[L]; *szFN = 0; } strcat_s(szFN,L, name); appendStr(out, szFN); if (szFN) delete[] (szFN); } else { if (((formatFlags & FormatNamespace) != 0) && nameSpace && *nameSpace) { appendStr(out, nameSpace); appendChar(out, '.'); } appendStr(out, name); } } break; case mdtAssemblyRef: { LPCSTR szName = NULL; pIMDI->GetAssemblyRefProps(tk,NULL,NULL,&szName,NULL,NULL,NULL,NULL); if(szName && *szName) { appendChar(out, '['); appendStr(out, szName); appendChar(out, ']'); } } break; case mdtAssembly: { LPCSTR szName = NULL; pIMDI->GetAssemblyProps(tk,NULL,NULL,NULL,&szName,NULL,NULL); if(szName && *szName) { appendChar(out, '['); appendStr(out, szName); appendChar(out, ']'); } } break; case mdtModuleRef: { LPCSTR szName = NULL; pIMDI->GetModuleRefProps(tk,&szName); if(szName && *szName) { appendChar(out, '['); appendStr(out, ".module "); appendStr(out, szName); appendChar(out, ']'); } } break; case mdtTypeSpec: { ULONG cSig; PCCOR_SIGNATURE sig; if (FAILED(pIMDI->GetSigFromToken(tk, &cSig, &sig))) { char str[128]; sprintf_s(str, COUNTOF(str), " [ERROR: Invalid token 0x%8.8X] ", tk); appendStr(out, str); } else { PrettyPrintType(sig, out, pIMDI, formatFlags); } } break; case mdtModule: break; default: { char str[128]; sprintf_s(str,COUNTOF(str)," [ERROR: INVALID TOKEN TYPE 0x%8.8X] ",tk); appendStr(out, str); } } return(asString(out)); }
static void appendStrNum(CQuickBytes *out, int num) { char buff[16]; sprintf_s(buff, COUNTOF(buff), "%d", num); appendStr(out, buff); }
char * tftp_get(IPAddr server, char * file, void(*receiver)(Octet *, Uint32)) { UDP *sendBuf = (UDP *)enet_alloc(); UDPPort local = udp_allocPort(NULL); sendBuf->ip.dest = hton(server); sendBuf->udp.dest = htons(tftpPort); sendBuf->udp.srce = htons(local); TFTPHeader * sendHeader = (TFTPHeader *)&(sendBuf->data[0]); sendHeader->op = htons(tftpOpRRQ); Uint32 pos = tftpPosName; appendStr(sendBuf, &pos, file); appendStr(sendBuf, &pos, "octet"); Uint32 blockNum; for (blockNum = 1; ; blockNum++) { Uint32 recvLen; IP * recvBuf; TFTPHeader * recvHeader; Octet * recvData; Uint32 dataLen; int tries; for (tries = 0; ; tries++) { if (tries >= retryLimit) { udp_freePort(local); enet_free((Enet *)sendBuf); return "Timeout"; } udp_send(sendBuf, pos); recvLen = udp_recv(&recvBuf, local, timeout); if (recvBuf) { recvHeader = (TFTPHeader *)udp_payload(recvBuf); recvData = udp_payload(recvBuf) + tftpPosData; dataLen = recvLen - tftpPosData; if (ntohs(recvHeader->op) == tftpOpData) { if (ntohs(recvHeader->block) == blockNum) break; } else if (ntohs(recvHeader->op) == tftpOpError) { recvData[dataLen-1] = 0; // in case server omitted it udp_freePort(local); enet_free((Enet *)sendBuf); int slen = strlen((char *)recvData); char *s = malloc(slen+1); strncpy(s, (char *)recvData, slen+1); udp_recvDone(recvBuf); return s; } else { udp_freePort(local); enet_free((Enet *)sendBuf); udp_recvDone(recvBuf); return "Unknown opcode from server"; } // ignore other stuff - excess retransmissions udp_recvDone(recvBuf); } } // The only way to get here is by receiving the expected data block receiver(recvData, dataLen); UDPHeader *recvUDPHeader = (UDPHeader *)ip_payload(recvBuf); sendBuf->udp.dest = recvUDPHeader->srce; sendHeader->op = htons(tftpOpAck); sendHeader->block = recvHeader->block; pos = tftpPosData; udp_recvDone(recvBuf); if (dataLen < 512) break; } udp_send(sendBuf, pos); // final ACK, sent without retransmissions udp_freePort(local); enet_free((Enet *)sendBuf); return NULL; }
QString convertTimeDate(const QString &mac_format, const QDateTime &datetime) { QDate date = datetime.date(); QTime time = datetime.time(); QString str; if (mac_format.contains('%')) { const QChar *chars = mac_format.constData(); bool is_percent = false; int length = 0; bool error = false; while ((*chars).unicode() && !error) { if (is_percent) { is_percent = false; switch ((*chars).unicode()) { case L'%': str += *chars; break; case L'a': appendStr(str, QDate::shortDayName(date.dayOfWeek()), length); break; case L'A': appendStr(str, QDate::longDayName(date.dayOfWeek()), length); break; case L'b': appendStr(str, QDate::shortMonthName(date.day()), length); break; case L'B': appendStr(str, QDate::longMonthName(date.day()), length); break; case L'c': appendStr(str, QLocale::system().toString(datetime), length); break; case L'd': appendInt(str, date.day(), length > 0 ? length : 2); break; case L'e': appendInt(str, date.day(), length); break; case L'F': appendInt(str, time.msec(), length > 0 ? length : 3); break; case L'H': appendInt(str, time.hour(), length > 0 ? length : 2); break; case L'I': appendInt(str, time.hour() % 12, length > 0 ? length : 2); break; case L'j': appendInt(str, date.dayOfYear(), length > 0 ? length : 3); break; case L'm': appendInt(str, date.month(), length > 0 ? length : 2); break; case L'M': appendInt(str, time.minute(), length > 0 ? length : 2); break; case L'p': appendStr(str, time.hour() < 12 ? "AM" : "PM", length); break; case L'S': appendInt(str, time.second(), length > 0 ? length : 2); break; case L'w': appendInt(str, date.dayOfWeek(), length); break; case L'x': appendStr(str, QLocale::system().toString(date), length); break; case L'X': appendStr(str, QLocale::system().toString(time), length); break; case L'y': appendInt(str, date.year() % 100, length > 0 ? length : 2); break; case L'Y': appendInt(str, date.year(), length > 0 ? length : 4); break; case L'Z': // It should be localized, isn't it?.. appendStr(str, SystemInfo::instance()->timezone(), length); break; case L'z': { int offset = SystemInfo::instance()->timezoneOffset(); appendInt(str, (offset/60)*100 + offset%60, length > 0 ? length : 4); break; } default: if ((*chars).isDigit()) { is_percent = true; length *= 10; length += (*chars).digitValue(); } else error = true; } } else if (*chars == '%') { length = 0; is_percent = true; } else str += *chars; chars++; } if (!error) return str; str.clear(); } WeekDate week_date(date); QChar last; QChar cur; int length = 0; bool quote = false; const QChar *chars = mac_format.constData(); forever { cur = *chars; if (cur == '\'') { if (*(chars+1) == '\'') { chars++; str += cur; } else { if (!quote) finishStr(str, week_date, date, time, last, length); quote = !quote; } length = 0; } else if (quote) str += cur; else { if (cur == last) length++; else { finishStr(str, week_date, date, time, last, length); length = 1; } } if (!chars->unicode()) break; last = cur; chars++; } return str; }
void AccessLog::log( HttpConnection* pConn ) { int n; HttpReq* pReq = pConn->getReq(); HttpResp* pResp = pConn->getResp(); const char * pUser = pReq->getAuthUser(); long contentWritten = pResp->getBodySent(); const ClientInfo * pInfo = pConn->getClientInfo(); const char * pAddr = pInfo->getHostName(); pResp->needLogAccess( 0 ); if ( m_iPipedLog ) { if ( !m_pManager ) return; m_pAppender = m_pManager->getAppender(); if ( !m_pAppender ) return; } if ( m_pCustomFormat ) return customLog( pConn ); if (( pAddr )&&( *pAddr )) { n = pInfo->getHostNameLen(); } else { pAddr = pInfo->getAddrString(); n = pInfo->getAddrStrLen(); } m_buf.appendNoCheck( pAddr, n ); if ( ! *pUser ) { m_buf.appendNoCheck( " - - ", 5 ); } else { n = safe_snprintf( m_buf.end(), 70, " - \"%s\" ", pUser ); m_buf.used( n ); } DateTime::getLogTime( pConn->getReqTime(), m_buf.end() ); m_buf.used( 30 ); n = pReq->getOrgReqLineLen(); char * pOrgReqLine = (char *)pReq->getOrgReqLine(); if ( pReq->getVersion() == HTTP_1_0 ) *(pOrgReqLine + n - 1) = '0'; if (( n > 4096 )||( m_buf.available() < 100 + n )) { flush(); m_pAppender->append( pOrgReqLine, n ); } else m_buf.appendNoCheck(pOrgReqLine, n ); m_buf.append( '"' ); m_buf.appendNoCheck( HttpStatusCode::getCodeString( pReq->getStatusCode() ), 5 ); if ( contentWritten == 0 ) { m_buf.append( '-' ); } else { n = safe_snprintf( m_buf.end(), 20, "%ld", contentWritten ); m_buf.used( n ); } if ( getAccessLogHeader() & LOG_REFERER ) { m_buf.append( ' ' ); appendStr( pReq->getHeader( HttpHeader::H_REFERER ), pReq->getHeaderLen( HttpHeader::H_REFERER )); } if ( getAccessLogHeader() & LOG_USERAGENT ) { m_buf.append( ' ' ); appendStr( pReq->getHeader( HttpHeader::H_USERAGENT), pReq->getHeaderLen( HttpHeader::H_USERAGENT) ); } if ( getAccessLogHeader() & LOG_VHOST ) { m_buf.append( ' ' ); appendStr( pReq->getHeader( HttpHeader::H_HOST ), pReq->getHeaderLen( HttpHeader::H_HOST ) ); } m_buf.append( '\n' ); if (( m_buf.available() < MAX_LOG_LINE_LEN ) ||!asyncAccessLog() ) { flush(); } }
// Input: // meta_parameters *meta_sar-- SAR geometry to subset the DEM // const char *demImg -- DEM data filename // const char *demMeta -- DEM metadata filename // int pad -- number of lines to add at the top/bottom/left/right // double tolerance -- how accurate the approximation mapping needs to be, // in units of pixels // const char *output_name -- output filename (basename) // int test_mode -- adds checks for the accuracy of the mapping, and // does some unit testing // Output: // no output parameters, the output is the output_name files (.img and .meta) // Return Value: // return TRUE on success, FALSE on fail // int make_gr_dem_ext(meta_parameters *meta_sar, const char *demImg, const char *demMeta, int pad, double tolerance, const char *output_name, int test_mode) { if (test_mode) test_interp(); asfPrintStatus("Reading DEM...\n"); meta_parameters *meta_dem = meta_read(demMeta); float *demData = NULL; FloatImage *fi_dem = NULL; int dnl = meta_dem->general->line_count; int dns = meta_dem->general->sample_count; if (0) demData = read_dem(meta_dem, demImg); else fi_dem = float_image_new_from_metadata(meta_dem, demImg); if (demData) asfPrintStatus("Old method: reading entire DEM.\n"); if (fi_dem) asfPrintStatus("New method: float image\n"); if (demData && fi_dem) asfPrintError("Impossible.\n"); char *outImg = appendExt(output_name, ".img"); char *output_name_tmp, *outImgTmp; // do not do DEM smoothing if the DEM pixel size is better or close to the // SAR image's pixel size. int do_averaging = TRUE; if (meta_dem->general->y_pixel_size - 10 < meta_sar->general->y_pixel_size) do_averaging = FALSE; asfPrintStatus("Averaging: %s (DEM %f, SAR: %f)\n", do_averaging ? "YES" : "NO", meta_dem->general->y_pixel_size, meta_sar->general->y_pixel_size); if (do_averaging) { output_name_tmp = appendStr(output_name, "_unsmoothed"); outImgTmp = appendExt(output_name_tmp, ".img"); } else { output_name_tmp = STRDUP(output_name); outImgTmp = STRDUP(outImg); } // add the padding if requested meta_parameters *meta_out = meta_copy(meta_sar); meta_out->general->line_count += pad*2; meta_out->general->sample_count += pad*2; meta_out->general->start_line -= pad; meta_out->general->start_sample -= pad; // fixing up the output metadata. Note that we must keep the SAR section // intact since that specifies our geometry which is the whole point of // this exercise. strcpy(meta_out->general->basename, meta_dem->general->basename); strcpy(meta_out->general->sensor, MAGIC_UNSET_STRING); strcpy(meta_out->general->processor, MAGIC_UNSET_STRING); strcpy(meta_out->general->mode, MAGIC_UNSET_STRING); strcpy(meta_out->general->sensor_name, MAGIC_UNSET_STRING); meta_out->general->image_data_type = DEM; meta_out->general->radiometry = MAGIC_UNSET_INT; strcpy(meta_out->general->acquisition_date, meta_dem->general->acquisition_date); meta_out->general->orbit = MAGIC_UNSET_INT; meta_out->general->orbit_direction = MAGIC_UNSET_CHAR; meta_out->general->frame = MAGIC_UNSET_INT; meta_out->general->band_count = 1; strcpy(meta_out->general->bands, "DEM"); int nl = meta_out->general->line_count; int ns = meta_out->general->sample_count; // finding the right grid size int size = find_grid_size(meta_sar, meta_dem, 512, .1*tolerance); asfPrintStatus("Creating ground range image...\n"); float *buf = MALLOC(sizeof(float)*ns*size); FILE *fpOut = FOPEN(outImgTmp, "wb"); // these are for tracking the quality of the bilinear interp // not used if test_mode is false int num_out_of_tol = 0; int num_checked = 0; int num_bad = 0; double max_err = 0; double avg_err = 0; int ii, jj; for (ii=0; ii<nl; ii += size) { int line_lo = ii; int line_hi = ii + size; for (jj=0; jj<ns; jj += size) { double lines[4], samps[4]; int samp_lo = jj; int samp_hi = jj + size; get_interp_params(meta_sar, meta_dem, line_lo, line_hi, samp_lo, samp_hi, lines, samps); int iii, jjj; for (iii=0; iii<size; ++iii) { for (jjj=0; jjj<size && jj+jjj<ns; ++jjj) { int index = iii*ns + jj + jjj; assert(index < ns*size); double line_out, samp_out; xy_interp(ii+iii, jj+jjj, line_lo, line_hi, samp_lo, samp_hi, lines, samps, &line_out, &samp_out); // random checking of the quality of our interpolations if (test_mode && iii%11==0 && jjj%13==0) { double real_line, real_samp; sar_to_dem(meta_sar, meta_dem, ii+iii, jj+jjj, &real_line, &real_samp); double err = hypot(real_line - line_out, real_samp - samp_out); avg_err += err; if (err > max_err) max_err = err; if (err > tolerance) { asfPrintStatus("Out of tolerance at %d,%d: (%f,%f) vs (%f,%f) -> %f\n", ii+iii, jj+jjj, line_out, samp_out, real_line, real_samp, err); ++num_out_of_tol; } if (err > .5) { asfPrintStatus("Error is larger than 1 pixel!\n"); ++num_bad; } ++num_checked; } if (demData) buf[index] = interp_demData(demData, dnl, dns, line_out, samp_out); else if (fi_dem) buf[index] = interp_dem(fi_dem, line_out, samp_out); else asfPrintError("Oops.\n"); } } } put_float_lines(fpOut, meta_out, ii, size, buf); asfPrintStatus("Completed %.1f%% \r", 100.*ii/(double)nl); } asfPrintStatus("Completed 100%% \n"); if (test_mode) { asfPrintStatus("Tolerance was %f\n", tolerance); asfPrintStatus("%d/%d checked pixels had error exceeding tolerance. (%.1f%%)\n", num_out_of_tol, num_checked, 100.*num_out_of_tol/(double)num_checked); asfPrintStatus("%d/%d checked pixels had error larger than half a pixel. (%.1f%%)\n", num_bad, num_checked, 100.*num_bad/(double)num_checked); asfPrintStatus("Maximum error: %f pixels\n", max_err); avg_err /= (double)num_checked; asfPrintStatus("Average error: %f pixels\n", avg_err); } FCLOSE(fpOut); meta_write(meta_out, outImgTmp); meta_free(meta_out); meta_free(meta_dem); FREE(buf); FREE(demData); if (fi_dem) float_image_free(fi_dem); // now apply 3x3 filter if (do_averaging) { asfPrintStatus("Smoothing with 3x3 kernel ...\n"); smooth(outImgTmp, outImg, 3, EDGE_TRUNCATE); } FREE(outImg); FREE(outImgTmp); FREE(output_name_tmp); return FALSE; }
void SSDBProtocolRequest::appendInt64(int64_t val) { char str[30]; snprintf(str, sizeof(str), "%lld", val); appendStr(str); }
void main(void) { char s[256] = "C "; appendStr(s); printf("%s\n", s); }