JNIEXPORT void JNICALL Java_com_netbirdtech_libcurl_Curl_curlEasyCleanupNative (JNIEnv * env, jobject obj, jlong handle) { if (handle != 0) { Holder* holder = (Holder*) handle; curl_easy_cleanup(holder->getCurl()); delete holder; holder = 0; } }
void TeleopPeriodic() { bool button = joystick->GetRawButton(1); if(button && !pButton){ holder->PushBall(); } pButton=button; holder->TeleopPeriodic(); }
void JsonSerializer::serialize(Holder h) { if (!h.isValid()) return; auto desc = h.descriptor(); switch (desc->getKind()) { case TypeDescriptor::kPrimitive: { auto primDesc = static_cast< const PrimitiveTypeDescriptor * >(desc); os << '"' << primDesc->getString(h) << '"'; } break; case TypeDescriptor::kClass: { auto classDesc = static_cast< const ClassDescriptor * >(desc); ModelClass * obj = classDesc->get(h); serialize(obj); } break; case TypeDescriptor::kList: { ++level; os << '['; auto vecDesc = static_cast< const ListTypeDescriptor * >(desc); const auto values = vecDesc->getValue(h); for (size_t i = 0; i < values.size(); i++) { os << std::endl << indent(); serialize(values[i]); if (i + 1 < values.size()) os << ','; } --level; os << std::endl << indent(); os << ']'; } break; default: os << "\"Unsupported type\""; break; } }
int SaveGameIterator::CreateSaveGame(Holder<SaveGame> save, const char *slotname) { if (!slotname) { return -1; } if (int cansave = CanSave()) return cansave; GameControl *gc = core->GetGameControl(); int index; if (save) { index = save->GetSaveID(); DeleteSaveGame(save); save.release(); } else { //leave space for autosaves //probably the hardcoded slot names should be read by this object //in that case 7 == size of hardcoded slot names array (savegame.2da) index = 7; for (size_t i = 0; i < save_slots.size(); ++i) { Holder<SaveGame> save = save_slots[i]; if (save->GetSaveID() >= index) { index = save->GetSaveID() + 1; } } } char Path[_MAX_PATH]; if (!CreateSavePath(Path, index, slotname)) { displaymsg->DisplayConstantString(STR_CANTSAVE, DMC_BG2XPGREEN); if (gc) { gc->SetDisplayText(STR_CANTSAVE, 30); } return -1; } if (!DoSaveGame(Path)) { displaymsg->DisplayConstantString(STR_CANTSAVE, DMC_BG2XPGREEN); if (gc) { gc->SetDisplayText(STR_CANTSAVE, 30); } return -1; } // Save succesful displaymsg->DisplayConstantString(STR_SAVESUCCEED, DMC_BG2XPGREEN); if (gc) { gc->SetDisplayText(STR_SAVESUCCEED, 30); } return 0; }
Holder StatusManager::status(const QString& name) { Holder res (statusRef(name)); // Devuelve siempre una copìa if (res.is_valid()) { res = Holder(res.clone()); } return res; }
void StatusManager::setStatus(const QString& name, Holder holder) { Holder older(status(name)); if (holder.is_valid() && older.is_valid()) { using namespace ::gsim::core::utils; Holder newer(older.clone()); // Hace una copia 'reflectiva' ya que holder puede no ser // del mismo tipo que el tipo del estado. reflective_copy(holder, newer); // Region protegida reducida al mÃnimo if (applyStatus(name, older, newer)) { unique_lock lock(m_data->messageMutex); m_data->status[name] = newer; // Ha de estar dentro de la región protegida para la // notificación en orden emit statusChanged(name, newer); emit statusChanged(name, older, newer); } } }
int SaveGameIterator::CreateSaveGame(int index, bool mqs) { AutoTable tab("savegame"); const char *slotname = NULL; if (tab) { slotname = tab->QueryField(index); } if (mqs) { assert(index==1); PruneQuickSave(slotname); } //if index is not an existing savegame, we create a unique slotname for (size_t i = 0; i < save_slots.size(); ++i) { Holder<SaveGame> save = save_slots[i]; if (save->GetSaveID() == index) { DeleteSaveGame(save); break; } } char Path[_MAX_PATH]; CreateSavePath(Path, index, slotname); if (!DoSaveGame(Path)) { return -1; } // Save succesful / Quick-save succesful if (index == 1) { displaymsg->DisplayConstantString(STR_QSAVESUCCEED, 0xbcefbc); if (core->GetGameControl()) { core->GetGameControl()->SetDisplayText(STR_QSAVESUCCEED, 30); } } else { displaymsg->DisplayConstantString(STR_SAVESUCCEED, 0xbcefbc); if (core->GetGameControl()) { core->GetGameControl()->SetDisplayText(STR_SAVESUCCEED, 30); } } return 0; }
void TeleopPeriodic() { bool button = joystick->GetRawButton(2); switch(state){ case WAIT_FOR_BUTTON: if(button && !pButton){ holder->PushBall(); pButton = true; state = CHECK_BALL; } break; case CHECK_BALL: if(holder->CheckPushed()){ state = WAIT_FOR_BUTTON; pButton = false; } break; } holder->TeleopPeriodic(); }
int main() { Holder h; Holder::Pointer hp, hp2; int i; h.initialize(); hp.initialize(&h); hp2.initialize(&h); for(i = 0; i < sz; i++) { hp.set(i); hp.next(); } hp.top(); hp2.end(); for(i = 0; i < sz; i++) { cout << "hp = " << hp.read() << ", hp2 = " << hp2.read() << endl; hp.next(); hp2.previous(); } } ///:~
// virtual void GWag::trainInner(GMatrix& features, GMatrix& labels) { GNeuralNet* pTemp = NULL; Holder<GNeuralNet> hTemp; size_t weights = 0; double* pWeightBuf = NULL; double* pWeightBuf2 = NULL; ArrayHolder<double> hWeightBuf; for(size_t i = 0; i < m_models; i++) { m_pNN->train(features, labels); if(pTemp) { // Average m_pNN with pTemp if(!m_noAlign) m_pNN->align(*pTemp); pTemp->weights(pWeightBuf); m_pNN->weights(pWeightBuf2); GVec::multiply(pWeightBuf, double(i) / (i + 1), weights); GVec::addScaled(pWeightBuf, 1.0 / (i + 1), pWeightBuf2, weights); pTemp->setWeights(pWeightBuf); } else { // Copy the m_pNN GDom doc; GDomNode* pNode = m_pNN->serialize(&doc); GLearnerLoader ll(m_rand); pTemp = new GNeuralNet(pNode, ll); hTemp.reset(pTemp); weights = pTemp->countWeights(); pWeightBuf = new double[2 * weights]; hWeightBuf.reset(pWeightBuf); pWeightBuf2 = pWeightBuf + weights; } } pTemp->weights(pWeightBuf); m_pNN->setWeights(pWeightBuf); }
JNIEXPORT jint JNICALL Java_com_netbirdtech_libcurl_Curl_curlEasySetoptObjectPointArrayNative (JNIEnv *env, jobject obj, jlong handle, jint opt, jobjectArray values) { Holder* holder = (Holder*) handle; CURL * curl = holder->getCurl(); const char *str; struct curl_slist *slist = 0; int nargs = env->GetArrayLength(values); for (int i = 0; i < nargs; i++) { jstring value = (jstring) env->GetObjectArrayElement(values, i); str = env->GetStringUTFChars(value, 0); if (str == 0) { return 0; } //LOGV("append slist"); slist = curl_slist_append(slist, str); env->ReleaseStringUTFChars(value, str); } holder->addCurlSlist(slist); //LOGD("set slist option=%d, size=%d", opt, nargs); return curl_easy_setopt(curl, (CURLoption) opt, slist); }
void GeoSearch::addExactPoints(const GeoPoint& pt, Holder& points, int& before, int& after, bool force){ before = 0; after = 0; if(pt.isExact()){ if(force) points.insert(pt); return; } vector<BSONObj> locs; getPointsFor(pt.key(), pt.obj(), locs, _uniqueDocs); GeoPoint nearestPt(pt, -1, true); for(vector<BSONObj>::iterator i = locs.begin(); i != locs.end(); i++){ Point loc(*i); double d; if(! exactDocCheck(loc, d)) continue; if(_uniqueDocs && (nearestPt.distance() < 0 || d < nearestPt.distance())){ nearestPt._distance = d; nearestPt._pt = *i; continue; } else if(! _uniqueDocs){ GeoPoint exactPt(pt, d, true); exactPt._pt = *i; points.insert(exactPt); exactPt < pt ? before++ : after++; } } if(_uniqueDocs && nearestPt.distance() >= 0){ points.insert(nearestPt); if(nearestPt < pt) before++; else after++; } }
void MessageProcessorManager::processMessage( Connection_ptr con, Message_ptr msg) { // Obtiene el contenido y el descriptor del mensaje Holder holder = msg->holder(); TypeDescriptor_ptr messageDescriptor = holder.get_type_descriptor(); // creates the key map_t::iterator it = m_processors.find( std::make_pair(con.get(), messageDescriptor)); if (it != m_processors.end() && !it->second.empty()) { // Iterates over its associated processors processors_t::const_iterator pit = it->second.begin(); for (; pit != it->second.end(); ++pit) { const MessageProcessor_ptr processor = *pit; const ReflectivePath_t& path = processor->path(); // Results TypeDescriptor_ptr descriptor = NULL; Holder value; bool res = followPath(messageDescriptor, holder, path, // Results descriptor, value); if (res) processor->process(msg, value); } } }
Renderer::Ptr CreateRenderer(const Holder& holder, Parameters::Accessor::Ptr params, Sound::Receiver::Ptr target) { if (const Sound::FadeGainer::Ptr fade = CreateFadeGainer(params, target)) { if (FadeoutFilter::Ptr fadeout = CreateFadeOutFilter(params, holder.GetModuleInformation(), fade)) { const Devices::AYM::Chip::Ptr chip = CreateChip(params, fadeout); const Renderer::Ptr result = holder.CreateRenderer(params, chip); fadeout->SetTrackState(result->GetTrackState()); return result; } else { //only fade in const Devices::AYM::Chip::Ptr chip = CreateChip(params, fade); return holder.CreateRenderer(params, chip); } } else { const Devices::AYM::Chip::Ptr chip = CreateChip(params, target); return holder.CreateRenderer(params, chip); } }
void aggregateRows(GArgReader& args) { size_t r = args.pop_uint(); vector<string> files; GFile::fileList(files); GMatrix* pResults = NULL; Holder<GMatrix> hResults; for(vector<string>::iterator it = files.begin(); it != files.end(); it++) { PathData pd; GFile::parsePath(it->c_str(), &pd); if(strcmp(it->c_str() + pd.extStart, ".arff") != 0) continue; GMatrix* pData = loadData(it->c_str()); Holder<GMatrix> hData(pData); if(!pResults) { pResults = new GMatrix(pData->relation()); hResults.reset(pResults); } pResults->takeRow(pData->releaseRow(r)); } pResults->print(cout); }
//immediately fire for testing void AutonomousInit() { holder->AutonomousInit(); holder->PushBall(); }
void IniSpawn::InitSpawn(const ieResRef DefaultArea) { const char *s; Holder<DataFileMgr> inifile = GetIniFile(DefaultArea); if (!inifile) { strnuprcpy(NamelessSpawnArea, DefaultArea, 8); return; } s = inifile->GetKeyAsString("nameless","destare",DefaultArea); strnuprcpy(NamelessSpawnArea, s, 8); s = inifile->GetKeyAsString("nameless","point","[0.0]"); int x,y; if (sscanf(s,"[%d.%d]", &x, &y)!=2) { x=0; y=0; } NamelessSpawnPoint.x=x; NamelessSpawnPoint.y=y; s = inifile->GetKeyAsString("nameless", "partyarea", DefaultArea); strnuprcpy(PartySpawnArea, s, 8); s = inifile->GetKeyAsString("nameless", "partypoint", "[0.0]"); if (sscanf(s,"[%d.%d]", &x, &y) != 2) { x = NamelessSpawnPoint.x; y = NamelessSpawnPoint.y; } PartySpawnPoint.x = x; PartySpawnPoint.y = y; //35 - already standing //36 - getting up NamelessState = inifile->GetKeyAsInt("nameless","state",36); namelessvarcount = inifile->GetKeysCount("namelessvar"); if (namelessvarcount) { NamelessVar = new VariableSpec[namelessvarcount]; for (y=0;y<namelessvarcount;y++) { const char* Key = inifile->GetKeyNameByIndex("namelessvar",y); strnlwrcpy(NamelessVar[y].Name, Key, 32); NamelessVar[y].Value = inifile->GetKeyAsInt("namelessvar",Key,0); } } localscount = inifile->GetKeysCount("locals"); if (localscount) { Locals = new VariableSpec[localscount]; for (y=0;y<localscount;y++) { const char* Key = inifile->GetKeyNameByIndex("locals",y); strnlwrcpy(Locals[y].Name, Key, 32); Locals[y].Value = inifile->GetKeyAsInt("locals",Key,0); } } s = inifile->GetKeyAsString("spawn_main","enter",NULL); if (s) { ReadSpawnEntry(inifile.get(), s, enterspawn); } s = inifile->GetKeyAsString("spawn_main","exit",NULL); if (s) { ReadSpawnEntry(inifile.get(), s, exitspawn); } s = inifile->GetKeyAsString("spawn_main","events",NULL); if (s) { eventcount = CountElements(s,','); eventspawns = new SpawnEntry[eventcount]; ieVariable *events = new ieVariable[eventcount]; GetElements(s, events, eventcount); int ec = eventcount; while(ec--) { ReadSpawnEntry(inifile.get(), events[ec], eventspawns[ec]); } delete[] events; } //maybe not correct InitialSpawn(); }
T& operator*() { Object* o = v[i]; Holder* h = static_cast<Holder*>(o); return h->value(); }
JNIEXPORT jint JNICALL Java_com_netbirdtech_libcurl_Curl_curlEasyPerformNavite (JNIEnv *env, jobject obj, jlong handle) { Holder* holder = (Holder*) handle; CURL * curl = holder->getCurl(); return (int) curl_easy_perform(curl); }
JNIEXPORT jint JNICALL Java_com_netbirdtech_libcurl_Curl_curlEasySetoptLongNative (JNIEnv *env, jobject obj, jlong handle, jint opt, jlong value) { Holder* holder = (Holder*) handle; return (int) curl_easy_setopt(holder->getCurl(), (CURLoption) opt, (long) value); }
void readFile(const char * filename = "stlinnerevo.root") { TFile *f = TFile::Open(filename,"READ"); std::cout << "Reading a Track.\n"; Track *tr = 0; f->GetObject("val",tr); if (tr) Print(*tr); else std::cout << "Value not read\n"; std::cout << "Reading a vector<int> into a vector<float>.\n"; vector<float> *vecint = 0; f->GetObject("vecint",vecint); if (vecint) Print(*vecint); else std::cout << "vector of float/int not read\n"; std::cout << "Reading a vector<Values> into a vector<Track>.\n"; vector<Track> *vec = 0; f->GetObject("vec",vec); if (vec) Print(*vec); else std::cout << "vector not read\n"; std::cout << "Reading a map<string,int> into a map<string,long>.\n"; map<string,long> *dict = 0; f->GetObject("dict",dict); if (dict) Print(*dict); else std::cout << "map not read\n"; if (1) { std::cout << "Reading a Holder object.\n"; Holder *h = 0; f->GetObject("holder",h); if(h) h->Print(); delete h; h = 0; } if (1) { TTree *t; f->GetObject("T",t); Holder *h = 0; std::vector<Track> *vecbr = 0; vector<float> *vecintbr = 0; t->SetBranchAddress("vec",&vecbr); // t->GetBranch("vec")->GetEntry(0); // Print(*vecbr); // return; t->SetBranchAddress("vecint",&vecintbr); t->SetBranchAddress("vec",&vecbr); t->SetBranchAddress("holder",&h); for(Long64_t e = 0; e < 2 ; ++e) { t->GetEntry(e); std::cout << "Reading from TTree entry #" << e << ".\n"; std::cout << "Reading a vector<int> into a vector<float>.\n"; if (vecintbr) Print(*vecintbr); std::cout << "Reading a vector<Values> into a vector<Track>.\n"; if (vecbr) Print(*vecbr); std::cout << "Reading a Holder object.\n"; if (h) h->Print(); } delete h; } delete f; }
void selfOrganizingMap(GArgReader& args){ // Load the file GMatrix* pData = loadData(args.pop_string()); Holder<GMatrix> hData(pData); // Parse arguments std::vector<double> netDims; unsigned numNodes = 1; while(args.next_is_uint()){ unsigned dim = args.pop_uint(); netDims.push_back(dim); numNodes *= dim; } if(netDims.size() < 1){ throw Ex("No dimensions specified for self organizing map. ", "A map must be at least 1 dimensional."); } Holder<SOM::ReporterChain> reporters(new SOM::ReporterChain); Holder<SOM::TrainingAlgorithm> alg(NULL); Holder<GDistanceMetric> weightDist(new GRowDistance); Holder<GDistanceMetric> nodeDist(new GRowDistance); Holder<SOM::NodeLocationInitialization> topology(new SOM::GridTopology); Holder<SOM::NodeWeightInitialization> weightInit (new SOM::NodeWeightInitializationTrainingSetSample(NULL)); Holder<SOM::NeighborhoodWindowFunction> windowFunc(new SOM::GaussianWindowFunction()); //Loading and saving string loadFrom = ""; string saveTo = ""; //Parameters for different training algorithms string algoName = "batch"; double startWidth = -1;//Start width - set later if still negative double endWidth = -1;//End width - set later if still negative double startRate = -1;//Start learning rate double endRate = -1;//End learning rate unsigned numIter = 100;//Total iterations unsigned numConverge = 1;//#steps for batch to converge while(args.next_is_flag()){ if(args.if_pop("-tofile")){ saveTo = args.pop_string(); }else if(args.if_pop("-fromfile")){ loadFrom = args.pop_string(); }else if(args.if_pop("-seed")){ GRand::global().setSeed(args.pop_uint()); }else if(args.if_pop("-neighborhood")){ string name = args.pop_string(); if(name == "gaussian"){ windowFunc.reset(new SOM::GaussianWindowFunction()); }else if(name == "uniform"){ windowFunc.reset(new SOM::UniformWindowFunction()); }else{ throw Ex("Only gaussian and uniform are acceptible ", "neighborhood types"); } }else if(args.if_pop("-printMeshEvery")){ using namespace SOM; unsigned interval = args.pop_uint(); string baseFilename = args.pop_string(); unsigned xDim = args.pop_uint(); unsigned yDim = args.pop_uint(); bool showTrain = false; if(args.if_pop("showTrain") || args.if_pop("showtrain")){ showTrain = true; } smart_ptr<Reporter> weightReporter (new SVG2DWeightReporter(baseFilename, xDim, yDim, showTrain)); Holder<IterationIntervalReporter> intervalReporter (new IterationIntervalReporter(weightReporter, interval)); reporters->add(intervalReporter.release()); }else if(args.if_pop("-batchTrain")){ algoName = "batch"; startWidth = args.pop_double(); endWidth = args.pop_double(); numIter = args.pop_uint(); numConverge = args.pop_uint(); }else if(args.if_pop("-stdTrain")){ algoName = "standard"; startWidth = args.pop_double(); endWidth = args.pop_double(); startRate = args.pop_double(); endRate = args.pop_double(); numIter = args.pop_uint(); }else{ throw Ex("Invalid option: ", args.peek()); } } //Create the training algorithm Holder<SOM::TrainingAlgorithm> algo; if(algoName == "batch"){ double netRadius = *std::max_element(netDims.begin(), netDims.end()); if(startWidth < 0){ startWidth = 2*netRadius; } if(endWidth < 0){ endWidth = 1; } algo.reset( new SOM::BatchTraining (startWidth, endWidth, numIter, numConverge, weightInit.release(), windowFunc.release(), reporters.release())); }else if(algoName == "standard"){ algo.reset( new SOM::TraditionalTraining (startWidth, endWidth, startRate, endRate, numIter, weightInit.release(), windowFunc.release(), reporters.release())); }else{ throw Ex("Unknown type of training algorithm: \"", algoName, "\""); } //Create the network & transform the data Holder<GSelfOrganizingMap> som; Holder<GMatrix> out; if(loadFrom == ""){ //Create map from arguments given som.reset(new GSelfOrganizingMap (netDims, numNodes, topology.release(), algo.release(), weightDist.release(), nodeDist.release())); //Train the network and transform the data in place out.reset(som->doit(*pData)); }else{ //Create map from file GDom source; source.loadJson(loadFrom.c_str()); som.reset(new GSelfOrganizingMap(source.root())); //Transform using the loaded network out.reset(som->transformBatch(*pData)); } //Save the trained network if(saveTo != ""){ GDom serialized; GDomNode* root = som->serialize(&serialized); serialized.setRoot(root); serialized.saveJson(saveTo.c_str()); } //Print the result out->print(cout); }
//immediately fire for testing void AutonomousInit() { holder->AutonomousInit(); }
void Font::Print(Region cliprgn, Region rgn, const unsigned char* string, Palette* hicolor, ieByte Alignment, bool anchor, Font* initials, Sprite2D* cursor, unsigned int curpos, bool NoColor) const { int capital = (initials) ? 1 : 0; unsigned int psx = IE_FONT_PADDING; Palette* pal = hicolor; if (!pal) { pal = palette; } if (initials==this) { initials = NULL; } Holder<Palette> blitPalette = pal; ieWord* tmp = NULL; size_t len = GetDoubleByteString(string, tmp); while (len > 0 && (tmp[len - 1] == '\n' || tmp[len - 1] == '\r')) { // ignore trailing newlines tmp[len - 1] = 0; len--; } SetupString( tmp, rgn.w, NoColor, initials, capital ); int ystep; if (Alignment & IE_FONT_SINGLE_LINE) { ystep = CalcStringHeight(tmp, len, NoColor); if (!ystep) ystep = maxHeight; } else { ystep = maxHeight; } int x = psx, y = ystep; Video* video = core->GetVideoDriver(); if (Alignment & IE_FONT_ALIGN_CENTER) { size_t w = CalcStringWidth( tmp, NoColor ); x = ( rgn.w - w ) / 2; } else if (Alignment & IE_FONT_ALIGN_RIGHT) { size_t w = CalcStringWidth( tmp, NoColor ); x = ( rgn.w - w ) - IE_FONT_PADDING; } if (Alignment & IE_FONT_ALIGN_MIDDLE) { int h = 0; for (size_t i = 0; i <= len; i++) { if (tmp[i] == 0) h++; } h = h * ystep; y += ( rgn.h - h ) / 2; } else if (Alignment & IE_FONT_ALIGN_BOTTOM) { int h = 0; for (size_t i = 0; i <= len; i++) { if (tmp[i] == 0) h++; } h = h * ystep; y += ( rgn.h - h ) - IE_FONT_PADDING; } else if (Alignment & IE_FONT_ALIGN_TOP) { y += IE_FONT_PADDING; } ieWord currChar = '\0'; const Sprite2D* currGlyph = NULL; for (size_t i = 0; i < len; i++) { if (( tmp[i] ) == '[' && !NoColor) { i++; char tag[256]; tag[0]=0; for (size_t k = 0; k < 256 && i<len; k++) { if (tmp[i] == ']') { tag[k] = 0; break; } tag[k] = tmp[i++]; } if (strnicmp( tag, "capital=",8)==0) { sscanf( tag, "capital=%d", &capital); continue; } if (strnicmp( tag, "color=", 6 ) == 0) { unsigned int r,g,b; if (sscanf( tag, "color=%02X%02X%02X", &r, &g, &b ) != 3) continue; const Color c = {(unsigned char)r, (unsigned char)g, (unsigned char)b, 0}; Palette* newPal = core->CreatePalette( c, palette->back ); blitPalette = newPal; gamedata->FreePalette( newPal ); continue; } if (stricmp( tag, "/color" ) == 0) { blitPalette = pal; continue; } if (stricmp( "p", tag ) == 0) { psx = x; continue; } if (stricmp( "/p", tag ) == 0) { psx = IE_FONT_PADDING; continue; } continue; } if (tmp[i] == 0) { y += ystep; x = psx; size_t w = CalcStringWidth( &tmp[i + 1], NoColor ); if (Alignment & IE_FONT_ALIGN_CENTER) { x = ( rgn.w - w ) / 2; } else if (Alignment & IE_FONT_ALIGN_RIGHT) { x = ( rgn.w - w ); } continue; } currChar = tmp[i]; currGlyph = GetCharSprite(currChar); if (initials && capital) { x = initials->PrintInitial( x, y, rgn, currChar ); continue; } if (i > 0) { // kerning x -= GetKerningOffset(tmp[i-1], currChar); } video->BlitSprite(currGlyph, x + rgn.x, y + rgn.y, anchor, &cliprgn, blitPalette.get()); if (cursor && ( curpos == i )) video->BlitSprite( cursor, x + rgn.x, y + rgn.y, anchor, &cliprgn ); x += currGlyph->Width; } if (cursor && ( curpos == len )) { video->BlitSprite( cursor, x + rgn.x, y + rgn.y, anchor, &cliprgn ); } blitPalette = NULL; free( tmp ); }
JNIEXPORT jint JNICALL Java_com_netbirdtech_libcurl_Curl_setFormdataNative (JNIEnv* env, jobject obj, jlong handle, jobjectArray multi_array) { Holder* holder = (Holder*) handle; if (holder == NULL) { return 0; } CURL* curl = holder->getCurl(); struct curl_httppost* post = holder->getPost();; struct curl_httppost* last = NULL; // clear all if (post != NULL) { //LOGD("clear previous form."); curl_formfree(post); post = NULL; } if (multi_array != NULL) { CURLFORMcode code; int len = env->GetArrayLength(multi_array); //LOGD("set name/parts size=%d", len); for (int i = 0; i < len; i++) { //LOGV("."); jobject part = env->GetObjectArrayElement(multi_array, i); jstring name = (jstring) env->CallObjectMethod(part, MID_MultiPart_get_name); jstring filename = (jstring) env->CallObjectMethod(part, MID_MultiPart_get_filename); jstring content_type = (jstring) env->CallObjectMethod(part, MID_MultiPart_get_content_type); jbyteArray content = (jbyteArray) env->CallObjectMethod(part, MID_MultiPart_get_content); jbyte* bytes = env->GetByteArrayElements(content, 0); int content_length = env->GetArrayLength(content); holder->addByteArrayGlobalRefs(env->NewGlobalRef(content), (const char*)bytes); // release after perform const char* name_str = env->GetStringUTFChars(name, 0); // content_type and filename may be null if (content_type == NULL && filename == NULL) { code = curl_formadd(&post, &last, CURLFORM_COPYNAME, name_str, CURLFORM_BUFFER, "file.dat", CURLFORM_BUFFERPTR, bytes, CURLFORM_BUFFERLENGTH, content_length, CURLFORM_END); } else if (content_type == NULL) { const char* filename_str = env->GetStringUTFChars(filename, 0); code = curl_formadd(&post, &last, CURLFORM_COPYNAME, name_str, CURLFORM_BUFFER, filename_str, CURLFORM_BUFFERPTR, bytes, CURLFORM_BUFFERLENGTH, content_length, CURLFORM_END); env->ReleaseStringUTFChars(filename, filename_str); } else if (filename == NULL) { const char* content_type_str = env->GetStringUTFChars(content_type, 0); code = curl_formadd(&post, &last, CURLFORM_COPYNAME, name_str, CURLFORM_BUFFER, "file.dat", CURLFORM_CONTENTTYPE, content_type_str, CURLFORM_BUFFERPTR, bytes, CURLFORM_BUFFERLENGTH, content_length, CURLFORM_END); env->ReleaseStringUTFChars(content_type, content_type_str); } else { const char* filename_str = env->GetStringUTFChars(filename, 0); const char* content_type_str = env->GetStringUTFChars(content_type, 0); code = curl_formadd(&post, &last, CURLFORM_COPYNAME, name_str, CURLFORM_BUFFER, filename_str, CURLFORM_CONTENTTYPE, content_type_str, CURLFORM_BUFFERPTR, bytes, CURLFORM_BUFFERLENGTH, content_length, CURLFORM_END); env->ReleaseStringUTFChars(filename, filename_str); env->ReleaseStringUTFChars(content_type, content_type_str); } env->ReleaseStringUTFChars(name, name_str); } if (code != CURL_FORMADD_OK) { ////LOGW("curl_formadd error %d", code); curl_formfree(post); // TODO return fromadd error or setopt error? return (int) code; } } if (post != NULL) { //LOGV("set_opt CURLOPT_HTTPPOST"); holder->setPost(post); return curl_easy_setopt(curl, CURLOPT_HTTPPOST, post); } return 0; }
void Font::PrintFromLine(int startrow, Region rgn, const unsigned char* string, Palette* hicolor, ieByte Alignment, Font* initials, Sprite2D* cursor, unsigned int curpos, bool NoColor) const { bool enablecap=false; int capital = 0; int initials_rows = 0; int last_initial_row = 0; int initials_x = 0; int initials_row = 0; ieWord currCap = 0; ieWord* tmp = NULL; size_t len = GetDoubleByteString(string, tmp); ieWord num_empty_rows = 0; if (initials && initials != this) { capital=1; enablecap=true; initials_rows = 1 + ((initials->maxHeight - 1) / maxHeight); // ceiling currCap = string[0]; if ((startrow > 0 && initials_rows > 0) || (len > 0 && isspace(currCap))) { // we need to look back to get the cap while(isspace(currCap) && num_empty_rows < len){//we cant cap whiteSpace so keep looking currCap = string[++num_empty_rows]; // WARNING: this assumes all preceeding whiteSpace is an empty line } last_initial_row = startrow - 1; // always the row before current since this cannot be the first row initials_rows = initials_rows - (startrow + 1) + num_empty_rows; // startrow + 1 because start row is 0 based, but initials_rows is 1 based } } unsigned int psx = IE_FONT_PADDING; Palette *pal = hicolor; if (!pal) { pal = palette; } Holder<Palette> blitPalette = pal; SetupString( tmp, rgn.w, NoColor, initials, enablecap ); if (startrow) enablecap=false; int ystep; if (Alignment & IE_FONT_SINGLE_LINE) { ystep = CalcStringHeight(tmp, len, NoColor); if (!ystep) ystep = maxHeight; } else { ystep = maxHeight; } int x = psx, y = ystep; size_t w = CalcStringWidth( tmp, NoColor ); if (Alignment & IE_FONT_ALIGN_CENTER) { x = ( rgn.w - w) / 2; } else if (Alignment & IE_FONT_ALIGN_RIGHT) { x = ( rgn.w - w ) - IE_FONT_PADDING; } if (Alignment & IE_FONT_ALIGN_MIDDLE) { int h = 0; for (size_t i = 0; i <= len; i++) { if (( tmp[i] == 0 ) || ( tmp[i] == '\n' )) h++; } h = h * ystep; y += ( rgn.h - h ) / 2; } else if (Alignment & IE_FONT_ALIGN_BOTTOM) { int h = 0; for (size_t i = 0; i <= len; i++) { if (( tmp[i] == 0 ) || ( tmp[i] == '\n' )) h++; } h = h * ystep; y += ( rgn.h - h ) - IE_FONT_PADDING; } else if (Alignment & IE_FONT_ALIGN_TOP) { y += IE_FONT_PADDING; } Video* video = core->GetVideoDriver(); const Sprite2D* currGlyph; ieWord currChar = '\0'; int row = 0; for (size_t i = 0; i < len; i++) { if (( tmp[i] ) == '[' && !NoColor) { i++; char tag[256]; tag[0]=0; for (size_t k = 0; k < 256 && i<len; k++) { if (tmp[i] == ']') { tag[k] = 0; break; } tag[k] = tmp[i++]; } if (strnicmp( tag, "capital=",8)==0) { sscanf( tag, "capital=%d", &capital); if (capital && (row>=startrow) ) { enablecap=true; } continue; } if (strnicmp( tag, "color=", 6 ) == 0) { unsigned int r,g,b; if (sscanf( tag, "color=%02X%02X%02X", &r, &g, &b ) != 3) continue; const Color c = {(unsigned char)r, (unsigned char)g, (unsigned char)b, 0}; Palette* newPal = core->CreatePalette( c, palette->back ); blitPalette = newPal; gamedata->FreePalette( newPal ); continue; } if (stricmp( tag, "/color" ) == 0) { blitPalette = pal; continue; } if (stricmp( "p", tag ) == 0) { psx = x; continue; } if (stricmp( "/p", tag ) == 0) { psx = IE_FONT_PADDING; } continue; } if (row < startrow) { if (tmp[i] == 0) { row++; } continue; } if (( tmp[i] == 0 ) || ( tmp[i] == '\n' )) { y += ystep; x = psx; size_t w = CalcStringWidth( &tmp[i + 1], NoColor ); if (initials_rows > 0) { initials_rows--; x += initials_x; w += initials_x; } if (Alignment & IE_FONT_ALIGN_CENTER) { x = ( rgn.w - w ) / 2; } else if (Alignment & IE_FONT_ALIGN_RIGHT) { x = ( rgn.w - w ); } continue; } currChar = tmp[i]; if (initials && capital && enablecap) { currCap = currChar; x = initials->PrintInitial( x, y, rgn, currChar ); initials_x = x; //how many more lines to be indented (one was already indented) initials_rows = (initials->maxHeight - 1) / maxHeight; initials_rows += num_empty_rows; initials_row = row; last_initial_row = initials_row; enablecap = false; continue; } else if (initials && currCap && row > last_initial_row && (row - num_empty_rows - initials_row) <= ((initials->maxHeight-1)/maxHeight)){ // means this row doesnt have a cap, but a preceeding one did and its overlapping this row int initY = y; if (!num_empty_rows || row > num_empty_rows) {// num_empty_rows is for scrolling text areas initY = (y - (maxHeight * (row - initials_row - num_empty_rows))); } x = initials->PrintInitial( x, initY, rgn, currCap ); initials_x = x; last_initial_row++; if (num_empty_rows && row <= num_empty_rows) continue; else x += psx; } if (i > 0) { // kerning x -= GetKerningOffset(tmp[i-1], currChar); } currGlyph = GetCharSprite(currChar); video->BlitSprite(currGlyph, x + rgn.x, y + rgn.y, true, &rgn, blitPalette.get()); if (cursor && ( i == curpos )) { video->BlitSprite( cursor, x + rgn.x, y + rgn.y, true, &rgn ); } x += currGlyph->Width; } if (cursor && ( curpos == len )) { video->BlitSprite( cursor, x + rgn.x, y + rgn.y, true, &rgn ); } blitPalette = NULL; free( tmp ); }
// TODO: Refactor this back into holder class, allow to run periodically when we are seeing // a lot of pts void GeoSearch::expandEndPoints(bool finish) { processExtraPoints(); // All points in array *could* be in maxDistance // Step 1 : Trim points to max size TODO: This check will do little for now, but is // skeleton for future work in incremental $near // searches if(_max > 0){ int numToErase = _points.size() - _max; if(numToErase > 0){ Holder tested; // Work backward through all points we're not sure belong in the set Holder::iterator maybePointIt = _points.end(); maybePointIt--; double approxMin = maybePointIt->distance() - 2 * _distError; // Insert all int erased = 0; while(_points.size() > 0 && (maybePointIt->distance() >= approxMin || erased < numToErase)){ Holder::iterator current = maybePointIt; if (current != _points.begin()) --maybePointIt; addExactPoints(*current, tested, true); _points.erase(current); erased++; if(tested.size()) approxMin = tested.begin()->distance() - 2 * _distError; } int numToAddBack = erased - numToErase; verify(numToAddBack >= 0); Holder::iterator testedIt = tested.begin(); for(int i = 0; i < numToAddBack && testedIt != tested.end(); i++){ _points.insert(*testedIt); testedIt++; } } } // We've now trimmed first set of unneeded points // Step 2: iterate through all points and add as needed unsigned expandedPoints = 0; Holder::iterator it = _points.begin(); double expandWindowEnd = -1; while(it != _points.end()){ const GeoPoint& currPt = *it; // TODO: If one point is exact, maybe not 2 * _distError // See if we're in an expand window bool inWindow = currPt.distance() <= expandWindowEnd; // If we're not, and we're done with points, break if(! inWindow && expandedPoints >= _max) break; bool expandApprox = !currPt.isExact() && (finish || inWindow); if (expandApprox) { // Add new point(s). These will only be added in a radius of 2 * _distError // around the current point, so should not affect previously valid points. int before, after; addExactPoints(currPt, _points, before, after, false); expandedPoints += before; if(_max > 0 && expandedPoints < _max) expandWindowEnd = currPt.distance() + 2 * _distError; // Iterate to the next point Holder::iterator current = it++; // Erase the current point _points.erase(current); } else{ expandedPoints++; it++; } } // Finish // TODO: Don't really need to trim? for(; expandedPoints > _max; expandedPoints--) it--; _points.erase(it, _points.end()); }
void AutonomousPeriodic() { holder->AutoHold(); }
// virtual void GAgglomerativeClusterer::cluster(const GMatrix* pData) { // Init the metric if(!m_pMetric) setMetric(new GRowDistance(), true); m_pMetric->init(&pData->relation(), false); // Find enough neighbors to form a connected graph GNeighborGraph* pNF = NULL; Holder<GNeighborGraph> hNF; size_t neighbors = 6; while(true) { GKdTree* pKdTree = new GKdTree(pData, neighbors, m_pMetric, false); pNF = new GNeighborGraph(pKdTree, true); hNF.reset(pNF); pNF->fillCache(); if(pNF->isConnected()) break; if(neighbors + 1 >= pData->rows()) throw Ex("internal problem--a graph with so many neighbors must be connected"); neighbors = std::min((neighbors * 3) / 2, pData->rows() - 1); } // Sort all the neighbors by their distances size_t count = pData->rows() * neighbors; vector< std::pair<double,size_t> > distNeighs; distNeighs.resize(count); double* pDistances = pNF->squaredDistanceTable(); size_t* pRows = pNF->cache(); size_t index = 0; vector< std::pair<double,size_t> >::iterator it = distNeighs.begin(); for(size_t i = 0; i < count; i++) { if(*pRows < pData->rows()) { it->first = *pDistances; it->second = i; it++; } else index--; pRows++; pDistances++; } std::sort(distNeighs.begin(), it); // Assign each row to its own cluster delete[] m_pClusters; m_pClusters = new size_t[pData->rows()]; // specifies which cluster each row belongs to GIndexVec::makeIndexVec(m_pClusters, pData->rows()); size_t* pSiblings = new size_t[pData->rows()]; // a cyclical linked list of each row in the cluster ArrayHolder<size_t> hSiblings(pSiblings); GIndexVec::makeIndexVec(pSiblings, pData->rows()); // init such that each row is in a cluster of 1 size_t currentClusterCount = pData->rows(); if(currentClusterCount <= m_clusterCount) return; // nothing to do // Merge until we have the desired number of clusters pRows = pNF->cache(); for(vector< std::pair<double,size_t> >::iterator dn = distNeighs.begin(); dn != it; dn++) { // Get the next two closest points size_t a = dn->second / neighbors; size_t b = pRows[dn->second]; GAssert(a != b && a < pData->rows() && b < pData->rows()); size_t clustA = m_pClusters[a]; size_t clustB = m_pClusters[b]; // Merge the clusters if(clustA == clustB) continue; // The two points are already in the same cluster if(clustB < clustA) // Make sure clustA has the smaller value { std::swap(a, b); std::swap(clustA, clustB); } for(size_t i = pSiblings[b]; true; i = pSiblings[i]) // Convert every row in clustB to clustA { m_pClusters[i] = clustA; if(i == b) break; } std::swap(pSiblings[a], pSiblings[b]); // This line joins the cyclical linked lists into one big cycle if(clustB < m_clusterCount) // Ensure that the first m_clusterCount cluster numbers are always in use { for(size_t i = 0; i < pData->rows(); i++) // rename another cluster to take the spot of clustB { if(m_pClusters[i] >= m_clusterCount) { for(size_t j = pSiblings[i]; true; j = pSiblings[j]) { m_pClusters[j] = clustB; if(j == i) break; } break; } } } if(--currentClusterCount <= m_clusterCount) return; } throw Ex("internal error--should have found the desired number of clusters before now"); }
void TeleopInit() { holder->TeleopInit(); state = WAIT_FOR_BUTTON; pButton = false; }