/**
 * The entry function of bada application called by the operating system.
 */
int
OspMain(int argc, char *pArgv[])
{
	result r = E_SUCCESS;

	AppLog("Application started.");
	ArrayList* pArgs = new ArrayList();
	pArgs->Construct();
	for (int i = 0; i < argc; i++)
		pArgs->Add(*(new String(pArgv[i])));

	r = Osp::App::Application::Execute(AntiMoustique::CreateInstance, pArgs);
	if (IsFailed(r))
	{
		AppLogException("Application execution failed-[%s].", GetErrorMessage(r));
		r &= 0x0000FFFF;
	}

	pArgs->RemoveAll(true);
	delete pArgs;
	AppLog("Application finished.");

	return static_cast<int>(r);
}
Exemplo n.º 2
0
void eighthTestCase01(void)
{
    int i, r;
    ArrayList* list;
    Employee* pAux[LENGTH];

    list = al_newArrayList();

    for(i=0; i < LENGTH; i++)
    {
        pAux[i] = newEmployee(id[i],unsortedList[i],unsortedList[i],salary[i],sector[i]);
        list->add(list,pAux[i]);
    }

    for(i=LENGTH-1; i >=0 ; i--)
    {
        r = list->remove(list,i);
        utest_assertEqualsIntMsg(r,0,"Error in return value <remove> if ok the correct value to return is 0");
    }

    free(list);
    for(i=0; i < LENGTH; i++)
        free(pAux[i]);
}
Exemplo n.º 3
0
/** \brief LISTAR: Realiza un solo listado de los comentarios (mostrando por pantalla el comentario y la cantidad de “Me gusta”) ordenados por los siguientes criterios:
 * Nombre de usuario (descendentemente) && Nick (ascendentemente).
 * \param usuarios: arraylist donde se guardan los usuarios
 * \param comentarios: arraylist donde se guardan los comentarios
 */
void listar(ArrayList *usuarios,ArrayList *comentarios)
{
    ArrayList *cloneUsuarios;
    EComments *comentario;
    User *userAux;
    int i,j;

    cloneUsuarios=usuarios->clone(usuarios);
    al_sort(cloneUsuarios,compareUser,0);

    for(i=0; i<cloneUsuarios->size; i++)
    {
        userAux=al_get(cloneUsuarios,i);
        for(j=0; j<comentarios->size; j++)
        {
            comentario = (comentarios->get(comentarios,j));
            if(userAux->id == comentario->idComentador)
            {
                printf("Comentario %d:%s Nick:%s Cantidad de likes:%d\r\n\n",j+1,comentario->comments,userAux->nick,comentario->likes);
            }
        }
    }
    cloneUsuarios->deleteArrayList(cloneUsuarios);
}
Exemplo n.º 4
0
void BatchRenderThread::start_rendering()
{
	if(is_rendering) return;

	is_rendering = 1;
	char path[BCTEXTLEN];
	path[0] = 0;
	save_jobs(path);
	save_defaults(mwindow->defaults);
	gui->new_batch->disable();
	gui->delete_batch->disable();

// Test EDL files for existence
	if(test_edl_files()) return;

// Predict all destination paths
	ArrayList<char*> paths;
	calculate_dest_paths(&paths,
		mwindow->preferences,
		mwindow->plugindb);

// Test destination files for overwrite
	int result = ConfirmSave::test_files(mwindow, &paths);
	paths.remove_all_objects();

// User cancelled
	if(result)
	{
		is_rendering = 0;
		gui->new_batch->enable();
		gui->delete_batch->enable();
		return;
	}

	mwindow->render->start_batches(&jobs);
}
Exemplo n.º 5
0
StringList_struct* CompilerTools_loadWarningList()
{
	String fileContents;
	String filePath = (String)FileTools_getExecutableDirectory() + "/CompilerWarnings.txt";
	
	if(!FileTools::loadFileIntoString(filePath, fileContents))
	{
		return NULL;
	}
	
	String currentLine;
	ArrayList<String>* lines = new ArrayList<String>();
	
	for(int i=0; i<fileContents.length(); i++)
	{
		char c = fileContents.charAt(i);
		if(c<' ')
		{
			if(currentLine.length()>0)
			{
				lines->add(currentLine);
				currentLine.clear();
			}
		}
		else
		{
			currentLine += c;
		}
	}
	
	fileContents.clear();
	
	StringList_struct* list = new StringList_struct();
	list->data = (void*)lines;
	return list;
}
Exemplo n.º 6
0
TEST(TestArrayList, move_constructor_test001)
{
	Counter call_count;
	TestCls v1(&call_count, 1);
	TestCls v2(&call_count, 2);
	TestCls v3(&call_count, 3);

	call_count.reset();
	{
		ArrayList<TestCls> list;
		list.PushBack(v1);
		list.PushBack(v2);
		list.PushBack(v3);

		ArrayList<TestCls> list2(std::move(list));
		ASSERT_EQ(3, list2.size());
		ASSERT_EQ(1, list2[0].value());
		ASSERT_EQ(2, list2[1].value());
		ASSERT_EQ(3, list2[2].value());
	}
	ASSERT_EQ(call_count.constructor, call_count.destructor); 
	// 5 because the list will reserve 5 and the std::move is a simple pointer swap
	ASSERT_EQ(3, call_count.constructor); 
}
Exemplo n.º 7
0
/**
 * takes next digital_input_s from the registeredIcus pool
 */
digital_input_s * addWaveAnalyzerDriver(const char *msg, brain_pin_e brainPin) {
	ICUDriver *driver = getInputCaptureDriver(msg, brainPin);
	if (driver == NULL) {
		warning(CUSTOM_ERR_INVALID_INPUT_ICU_PIN, "w_not input pin");
		return NULL;
	}

	digital_input_s *hw = registeredIcus.add();
	hw->widthListeners.clear();
	hw->periodListeners.clear();
	hw->started = false;
	hw->brainPin = brainPin;
	hw->driver = driver;
	turnOnCapturePin(msg, brainPin);
	return hw;
}
Exemplo n.º 8
0
int setAllItems() {

    SyncItem item;
    WCHAR name[64];
    char data[128];

    for (int i = 0; i < 4; ++i) {

        wsprintf(name, TEXT("%s%d"), TEXT("item"), i);
        sprintf(data, "This is item %d", i);

        item.setKey(name);
        item.setData(data  , (strlen(data))*sizeof(char));
        items.add(item);
    }
    return 0;
}
Exemplo n.º 9
0
ArrayList<GameModel> EnemyModel::GetGameModels()
{

	ArrayList<GameModel> list;

	list.add(m_Head);
	list.add(m_Torso);
	list.add(m_LeftArm);
	list.add(m_RightArm);
	list.add(m_LeftLeg);
	list.add(m_RightLeg);

	return list;

}
Exemplo n.º 10
0
	//Called when the mouse position changes. Forwards the event to all the MouseEventListeners
	void Mouse_callListeners_move(Window*window, unsigned int mouseIndex, const Vector2d&pos, const Vector2d&dif)
	{
		Mouse_changedListeners_mutex.lock();
		Mouse_changedListeners.clear();
		Mouse_changedListeners_mutex.unlock();

		Mouse_callingListeners = true;
		Mouse_eventListeners_mutex.lock();
		ArrayList<MouseEventListener*> listeners = Mouse_eventListeners;
		Mouse_eventListeners_mutex.unlock();

		for(unsigned int i = 0; i<listeners.size(); i++)
		{
			MouseEventListener* listener = listeners.get(i);
			//check to make sure that the listener hasn't been removed during a MouseEventListener event
			bool listener_notremoved = true;
			Mouse_changedListeners_mutex.lock();
			for(unsigned int j=0; j<Mouse_changedListeners.size(); j++)
			{
				Pair<MouseEventListener*,bool>& cmp = Mouse_changedListeners.get(j);
				if(cmp.first == listener)
				{
					if(!cmp.second)
					{
						listener_notremoved = false;
						j = Mouse_changedListeners.size();
					}
				}
			}
			Mouse_changedListeners_mutex.unlock();

			//call MouseEventListener event
			if(listener_notremoved)
			{
				listener->onMouseMove(window, mouseIndex, pos, dif);
			}
		}
		Mouse_callingListeners = false;
		Mouse_changedListeners_mutex.lock();
		Mouse_changedListeners.clear();
		Mouse_changedListeners_mutex.unlock();
	}
Exemplo n.º 11
0
void
ShareMenu::LoadMsgWnd(void)
{
	ArrayList* pDataList = null;
	pDataList = new ArrayList();
	pDataList->Construct();

	String* pData = null;
	if(__isLink == true)
	{
		pData = new String(L"type:SMS");
	}
	else
	{
		pData = new String(L"type:MMS");
	}
	pDataList->Add(*pData);

	String* pData2 = null;
	pData2 = new String(L"text:");

	pData2->SetCapacity(pData2->GetCapacity() + __shareContent.GetLength());
	pData2->Append(__shareContent);
	pDataList->Add(*pData2);

	String* pData3 = null;
	pData3 = new String(L"to:");
	pDataList->Add(*pData3);

	if(__isLink == false)
	{
	   String* pData4 = null;
	   pData4 = new String(L"attachImage:");
	   pData4->SetCapacity(pData4->GetCapacity() + __shareContent.GetCapacity());
	   pData4->Append(__shareContent);
	   pDataList->Add(*pData4);
	}

	AppControl* pAc = AppManager::FindAppControlN(APPCONTROL_PROVIDER_MESSAGE, APPCONTROL_OPERATION_COMPOSE);
	if(pAc)
	{
	  pAc->Start(pDataList, null);
	  delete pAc;
	}
	pDataList->RemoveAll(true);
	delete pDataList;
}
Exemplo n.º 12
0
	//Called when a touch position is moved. Forwards the event to all the MultitouchEventListeners
	void Multitouch_callListeners_move(const MultitouchData&touchData, const Vector2d&touchdif)
	{
		Multitouch_changedListeners_mutex.lock();
		Multitouch_changedListeners.clear();
		Multitouch_changedListeners_mutex.unlock();
		
		Multitouch_callingListeners = true;
		Multitouch_eventListeners_mutex.lock();
		ArrayList<MultitouchEventListener*> listeners = Multitouch_eventListeners;
		Multitouch_eventListeners_mutex.unlock();
		
		for(unsigned int i = 0; i<listeners.size(); i++)
		{
			MultitouchEventListener* listener = listeners.get(i);
			//check to make sure that the listener hasn't been removed during a MultitouchEventListener event
			bool listener_notremoved = true;
			Multitouch_changedListeners_mutex.lock();
			for(unsigned int j=0; j<Multitouch_changedListeners.size(); j++)
			{
				Pair<MultitouchEventListener*,bool>& cmp = Multitouch_changedListeners.get(j);
				if(cmp.first == listener)
				{
					if(!cmp.second)
					{
						listener_notremoved = false;
						j = Multitouch_changedListeners.size();
					}
				}
			}
			Multitouch_changedListeners_mutex.unlock();
			
			//call MultitouchEventListener event
			if(listener_notremoved)
			{
				listener->onMultitouchMove(touchData.window, touchData.touchID, touchData.position, touchdif);
			}
		}
		Multitouch_callingListeners = false;
		Multitouch_changedListeners_mutex.lock();
		Multitouch_changedListeners.clear();
		Multitouch_changedListeners_mutex.unlock();
	}
Exemplo n.º 13
0
	void Mouse::handleMouseMovement(Window*window, unsigned int mouseIndex, const Vector2d&pos, const Vector2d&dif)
	{
		if(window!=nullptr)
		{
			Mouse_state_mutex.lock();
			unsigned int index = Mouse_indexOfData(Mouse_states, window, mouseIndex);
			if(index == ARRAYLIST_NOTFOUND)
			{
				MouseData mouseData = Mouse_createMouseData(window, mouseIndex, pos);
				Mouse_states.add(mouseData);
			}
			else
			{
				Mouse_states[index].position = pos;
			}
			Mouse_state_mutex.unlock();
		}
		Mouse_callListeners_move(window, mouseIndex, pos, dif);
	}
Exemplo n.º 14
0
// ---------------------------------------------------------
void test05()
{
    ArrayList<float> a;
    ArrayList<int> b;

    cout << endl << endl;
    cout << " ***************** " << endl;
    cout << " *  TEST SET #5  * " << endl;
    cout << " ***************** " << endl;


    cout << endl;
    for (unsigned int k=0; k<10; k++) {
        a.insert_back(3.14 * k);
    }
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    //TEST : Graceful PANIC
    cout << endl << "TEST : checking for graceful error handling" << endl;
    cout << "b.first() : " << endl;
    b.first();
    cout << "a[5] = " << a[5] << endl;
    cout << "a[50] = " << a[50] << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    //TEST : More Graceful PANIC
    cout << endl << "TEST : More checking for graceful error handling" << endl;
    cout << "a.insert(9.9, 20) : " << endl;
    a.insert(9.9, 20);
    cout << "a.remove(555) :" << endl;
    a.remove(555);
    cout << "a.swap(1,100) :" << endl;
    a.swap(1,100);
    cout << "a.swap(40,41) :" << endl;
    a.swap(40,41);

    cout << "a = " << a << endl;
}
Exemplo n.º 15
0
StringList ArrayList::GetStringList(const string& lName)
{
    //Look for ann array list whose first item is a string with lName and second item is a stringlist, i.e. {{string, {string string string}}
    StringList aList;
    for(u_int i = 0; i < Count(); i++)
    {
        ArrayListItemBase* listPtr = const_cast<ArrayListItemBase*>(mList[i]);

        //Check for a list which first element is a string, i.e. a {{string}, {string, string}} list
        if(dynamic_cast< ArrayListItem<ArrayList> *>(listPtr))
        {
            ArrayList list = (ArrayList) *(dynamic_cast< ArrayListItem<ArrayList> *>(listPtr));
            if(list.Count())
            {
                ArrayListItemBase* anItem = &list[0];
                if(dynamic_cast<ArrayListItem<string>*>(anItem))
                {
                    string str = (string) *dynamic_cast<ArrayListItem<string>*>(anItem);

                    if(str == lName && list.Count() > 1)
                    {
                        ArrayListItemBase* anItem = &list[1];
                        if(dynamic_cast<ArrayListItem<StringList> *>(anItem))
                        {
                            //This is a stringList
                            StringList  list = (StringList) *(dynamic_cast<ArrayListItem<StringList>*>(anItem));
                            for(int i = 0; i < list.Count(); i++)
                            {
                                string str = list[i];
                                aList.add(str);
                            }
                        }
                        if(dynamic_cast<ArrayListItem<ArrayList> *>(anItem))
                        {
                            //Assume this list only contains strings!
                            ArrayList  list = (ArrayList) *(dynamic_cast<ArrayListItem<ArrayList>*>(anItem));
                            for(int i = 0; i < list.Count(); i++)
                            {
                                string str = list.GetString(i);
                                aList.add(str);
                            }
                        }

                    }
                }
            }
        }
    }
    return aList;
}
Exemplo n.º 16
0
	boolean ScriptManager::loadScriptEntity(const ScriptEntityInfo& entityInfo, String& error)
	{
		String entityPath = entityInfo.getPath();

		String errorMessage;
		
		ScriptData* mainScriptData = new ScriptData(entityInfo);
		boolean success = mainScriptData->loadFromFile(entityPath + '/' + entityInfo.getMainScript().script, errorMessage);
		if(!success)
		{
			delete mainScriptData;
			error = (String)"Unable to load file \"" + entityPath + '/' + entityInfo.getMainScript().script + "\": " + errorMessage;
			return false;
		}

		const ArrayList<ScriptEntityInfo::ScriptInfo>& otherScripts = entityInfo.getScripts();

		ArrayList<ScriptData*> otherScriptData;

		for(int i=0; i<otherScripts.size(); i++)
		{
			ScriptEntityInfo::ScriptInfo scriptInfo = otherScripts.get(i);
			ScriptData* scriptData = new ScriptData(entityInfo);
			if(scriptData->loadFromFile(entityPath + '/' + scriptInfo.script, errorMessage))
			{
				otherScriptData.add(scriptData);
			}
			else
			{
				delete mainScriptData;
				delete scriptData;
				for(int j=0; j<otherScriptData.size(); j++)
				{
					delete otherScriptData.get(j);
				}
				error = (String)"Unable to load file \"" + entityPath + '/' + scriptInfo.script + "\": " + errorMessage;
				return false;
			}
		}

		loadedScripts.add(mainScriptData);
		for(int i=0; i<otherScriptData.size(); i++)
		{
			loadedScripts.add(otherScriptData.get(i));
		}

		Console::WriteLine((String)"Loaded Script Entity: " + entityInfo.getMainScript().name);

		return true;
	}
Exemplo n.º 17
0
void LinkedHashSetTest::testConstructorCollection() {

    ArrayList<int> intList;
    intList.add(1);
    intList.add(1);
    intList.add(2);
    intList.add(3);
    intList.add(4);

    LinkedHashSet<int> set(intList);
    for (int counter = 0; counter < intList.size(); counter++) {
        CPPUNIT_ASSERT_MESSAGE("LinkedHashSet does not contain correct elements",
                               set.contains(intList.get(counter)));
    }

    CPPUNIT_ASSERT_MESSAGE("LinkedHashSet created from collection incorrect size",
                           set.size() == intList.size() - 1);
}
Exemplo n.º 18
0
void ToDo::setXProp(ArrayList& list) {
    if (xProp) {
        xProp->clear();
    } else {
        xProp = new ArrayList();
    }
    for(int i = 0, m = propertiesCount(); i < m ; i++)
        if(wcsstr(getProperty(i)->getName(),TEXT("X-")) == getProperty(i)->getName()) {
            removeProperty(i);
            --i;
            --m;
        }
    int s = list.size();
    for (int j=0; j<s; ++j) {
        xProp->add(*list[j]);
        insertProperty(new VProperty(
                           ((WKeyValuePair*)list[j])->getKey(),
                           ((WKeyValuePair*)list[j])->getValue()));
    }
}
Exemplo n.º 19
0
void LogApplicationTraffic(NetworkObject* ContactPoint)
{
	LogLegitimateTraffic(ContactPoint);
	for(int i=0;i<AnonymitySets.Count();i++)
	{
		AnonymitySet* CurrentSet=AnonymitySets[i];
		if(SimulationTime<CurrentSet->k_resume_t){continue;}
		int VehiclesInSet=CurrentSet->Count();
		for(int io=0;io<VehiclesInSet;io++)
		{
			Vehicle* CurrentVehicle=CurrentSet->AnonymousVehicles[io];
			for(int ie=0;ie<VehiclesInSet-1;ie++)
			{
				if(io==ie){continue;}
				LogTraffic(CurrentVehicle,DUMMY);
				if(ContactPoint!=NULL){LogTraffic(ContactPoint,DUMMY);}
			}
			//Each vehicle sends one application message as a dummy event for every other vehicle in the same set, and one real message for itself.
		}
	}
}
Exemplo n.º 20
0
void actorMouseMove (Float x, Float y)
{
  for (UintSize c=0; c < actorCallbacks.size(); ++c)
  {
    ActorCallback &cb = actorCallbacks[ c ];
    if (cb.evt == ActorMouseEvent::Enter)
    {
      bool hit = actorHitTest( cb.actor, x, y );
      if ((!cb.on) && hit)
      {
        cb.func( ActorMouseEvent::Enter, cb.actor );
        cb.on = true;
      }
      else if (cb.on && (!hit))
      {
        cb.func( ActorMouseEvent::Leave, cb.actor );
        cb.on = false;
      }
    }
  }
}
Exemplo n.º 21
0
int SymbolType::getSymbol(const char *s){
    if(strlen(s)>MAXSYMBOLLEN)
        throw RUNT("ex$symbol","").set("symbol too long: %s",s);
    
    int n;
    
    // unpleasant - see
    // https://groups.google.com/forum/#!topic/comp.programming.threads/QsJI57oQZKc
    WriteLock l=WL(Types::tSymbol);
    
    if(locations.find(s)){
        n=locations.found();
    } else {
        n = symbolCtr;
        locations.set(s,symbolCtr++);
        SymbolName *ss = strings.set(n);
        strcpy(ss->s,s);
    }
    
    return n;
}
bool DXShaderManager::loadShaderProgram( const string& name, const ArrayList<ShaderInfo> shaders )
{
	DXShaderProgram program;
	for (unsigned int i = 0; i < shaders.getSize(); ++i)
	{
		const ShaderInfo& shader = shaders[i];

		switch (shader.Type)
		{
		case WOE_SHADER_TYPE_VERTEX:

			program.pVertexShader = (ID3D11VertexShader*)loadVertexShaderFromFile(name);

			break;
		case WOE_SHADER_TYPE_FRAGMENT:

			program.pPixelShader = (ID3D11PixelShader*)loadPixelShaderFromFile(name);

			break;
		}
	}
}
Exemplo n.º 23
0
	Bitmap *AddSubscriber(Control *control) {
		AppLog("BITMAPCACHE: add subscriber %ls", _url.GetPointer());

		_subscribers.Add(control);
		switch(_state) {
		case CACHE_ENTRY_STATE_NOT_FOUND:
			AppLog("new subscriber on cache entry, entry not found, downloading...");
			StartDownloading();
			break;
		case CACHE_ENTRY_STATE_FILE:
			AppLog("new subscriber on cache entry, entry in file, loading...");
			StartLoading();
			break;
		case CACHE_ENTRY_STATE_MEMORY:
			AppLog("new subscriber on cache entry, entry in memory, send bitmap...");
			//SendEvent(control);
			return _bitmap;
			break;
		default:
			break;
		}

		return null;
	}
Exemplo n.º 24
0
	void Multitouch::handleTouchDown(Window*window, long long givenID, const Vector2d&pos)
	{
		if(window!=nullptr)
		{
			Multitouch_state_mutex.lock();
			MultitouchData touchData;
			unsigned int index = Multitouch_indexOfData_byGivenID(Multitouch_activeTouches, window, givenID);
			if(index == ARRAYLIST_NOTFOUND)
			{
				unsigned int touchID = Multitouch_currentID;
				touchData = Multitouch_createTouchData(window, touchID, givenID, pos);
				Multitouch_activeTouches.add(touchData);
				Multitouch_incrementID();
			}
			else
			{
				touchData = Multitouch_activeTouches[index];
				Multitouch_activeTouches[index].position = pos;
			}
			Multitouch_state_mutex.unlock();
			
			Multitouch_callListeners_press(touchData,true);
		}
	}
Exemplo n.º 25
0
void
ShareMenu::LoadEmailWnd(void)
{
	ArrayList* pDataList = null;
	String text(__shareContent);

	pDataList = new ArrayList();
	pDataList->Construct();

	String* pData = null;
	pData = new String(L"subject:");

	String emailText;
	Application::GetInstance()->GetAppResource()->GetString(L"IDS_SHARE_SUBJECT", emailText);
	pData->SetCapacity(pData->GetCapacity() + emailText.GetCapacity());
	pData->Append(emailText);
	pDataList->Add(*pData);

	String* pData2 = null;
	pData2 = new String(L"text:");
	pData2->SetCapacity(pData2->GetCapacity() + __shareContent.GetCapacity());
	pData2->Append(__shareContent);
	pDataList->Add(*pData2);

	if(__isLink == false)
	{
	   String* pData3 = null;
	   pData3 = new String(L"attachments:");
	   pData3->SetCapacity(pData3->GetCapacity() + __shareContent.GetCapacity());
	   pData3->Append(__shareContent);
	   pDataList->Add(*pData3);
	}

	AppControl* pAc = AppManager::FindAppControlN(APPCONTROL_PROVIDER_EMAIL, APPCONTROL_OPERATION_EDIT);
	if(pAc)
	{
	  pAc->Start(pDataList, null);
	  delete pAc;
	}
	pDataList->RemoveAll(true);
	delete pDataList;
}
Exemplo n.º 26
0
// ---------------------------------------------------------
void test02()
{
    ArrayList<int> a;

    cout << endl << endl;
    cout << " ***************** " << endl;
    cout << " *  TEST SET #2  * " << endl;
    cout << " ***************** " << endl;

    cout << "ArrayList a" << endl;
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;

    //TEST : Inserting 8 elements to a
    cout << endl << "TEST : Inserting 8 elements to a" << endl;
    for (unsigned int k=0; k<8; k++) {
        a.insert_back(k*8);
    }
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;


    // TEST : Clearing the list
    cout << endl << "TEST : Clearing a" << endl;
    a.clear();
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;


    // TEST : Inserting 10 elements
    cout << endl << "TEST : Inserting 10 elements to a" << endl;
    for (unsigned int k=0; k<10; k++) {
        a.insert_back(k*5);
    }
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;


    // TEST : Removing Elements in the middle
    cout << endl << "TEST : Removing elements" << endl;
    a.remove(2);
    cout << a << endl;
    a.remove(4);
    cout << a << endl;
    a.remove(6);
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;


    // TEST : Removing first and last Elements
    cout << endl << "TEST : Removing last and first elements" << endl;
    cout << a << endl;
    a.remove(6);
    cout << a << endl;
    a.remove(0);
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;


    // TEST : Finding Particular elements
    cout << endl << "TEST : Finding particular elements" << endl;
    cout << a << endl;
    cout << "Size of a = " << a.size() << endl;
    cout << "15 is at location " << a.find(15) << endl;
    cout << "30 is at location " << a.find(30) << endl;
    cout << "50 is at location " << a.find(50) << endl;


    // TEST : Shrinking the underlaying array.
    cout << endl << "TEST : Shrinking the underlaying array" << endl;
    a.clear();
    for (unsigned int k=0; k<1000; k++) {
        a.insert_back(k*2);
    }
    cout << "Size of a = " << a.size() << endl;
    cout << "Capacity of a = " << a.max() << endl;
    cout << "deleting 950 elements" << endl;
    for (unsigned int k=0; k<950; k++) {
        a.remove(a.size()-1);
    }
    cout << "Size of a = " << a.size() << endl;
    cout << "Capacity of a = " << a.max() << endl;
    cout << "so ArrayList is memory efficient :-)" << endl;

} // Destructor Called Here!!
Exemplo n.º 27
0
int main()
{
	cout<<"test";
	/*
	int x;
	ArrayList<int> a(10);

	a.insertAtFront( 7);
	a.printList();

	a.insertAtFront( 15);
	
	a.insertAtBack( 9);
	a.printList();
	
	a.insertAtBack( 15);
	a.printList();
	
	a.insertAtLocation( 1, 8);
	a.printList();
	
	a.insertAtLocation( 1, 10);
	a.printList();

	// a.removeFromLocation( 3, x);
	// a.printList();

	a.removeFromFront( x);
	a.printList();

	a.removeFromBack( x);
	a.printList();
	
*/
	Complex a( 2, 3), b( 1, -5), c( 9, 0), d, e;

	a.printComplex();
	b.printComplex();
	c.printComplex();
	d.printComplex();

	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
	cout << d << endl;

	d = a + c;
	cout << d << endl;

	if( a + c == d)
		cout << a + c << " = " << d << endl;
	else
		cout << a + c << " != " << d << endl;

	Complex g( 2, 3), h( 1, -5), m( 9, 0), j, k;
	ArrayList<Complex> x;

	cout << "Enter 2 integers: "<< endl;
	cin >> e; 
	x.insertAtFront( e);
	x.printList();

	x.insertAtBack( g);
	x.printList();

	x.insertAtBack( h);
	x.printList();

	x.insertAtFront( g + h);
	x.printList();

	return 0;
}
PHP_METHOD(ArrayList, toValue) {
	array_init(return_value);
	list_object* obj = (list_object*) zend_object_store_get_object(getThis() TSRMLS_CC);
    if (obj->object != NULL) {
		if(obj->type == TYPE_LONG) {
			ArrayList<long>* list = (ArrayList<long>*) obj->object;
	    	for (auto it=list->begin(); it!=list->end(); ++it) {
				add_next_index_long(return_value,*it);
			}
		} else if (obj->type == TYPE_DOUBLE) {
			ArrayList<double>* list = (ArrayList<double>*) obj->object;
	    	for (auto it=list->begin(); it!=list->end(); ++it) {
				add_next_index_double(return_value,*it);
			}
		} else if (obj->type == TYPE_BOOLEAN) {
			ArrayList<char>* list = (ArrayList<char>*) obj->object;
	    	for (auto it=list->begin(); it!=list->end(); ++it) {
				add_next_index_bool(return_value,*it);
			}
		} else if (obj->type == TYPE_STRING) {
			ArrayList<char*>* list = (ArrayList<char*>*) obj->object;
	    	for (auto it=list->begin(); it!=list->end(); ++it) {
				add_next_index_string(return_value,*it,1);
			}
		} else {
			ArrayList<zval*>* list = (ArrayList<zval*>*) obj->object;
	    	for (auto it=list->begin(); it!=list->end(); ++it) {
				Z_ADDREF_P(*it);
				add_next_index_zval(return_value,*it);
			}
		}
    }
}
Exemplo n.º 29
0
int MailMessage::parseHeaders(StringBuffer &rfcHeaders) {

    ArrayList lines;
    const StringBuffer *line;
    StringBuffer strReceived;
    bool receivedExtracted = false;
    LOG.debug("parseHeaders START");

    // Join header parts using \t or 8 blank
    StringBuffer joinlinetab("\t");
    rfcHeaders.replaceAll(joinlinetab, " ");

    StringBuffer joinlinespaces(newline);
    joinlinespaces+=" ";  // 8 blanks

    rfcHeaders.replaceAll(joinlinespaces, " ");

    rfcHeaders.split(lines, newline);

    // importance is set to "0" by default. Then there isn't anything modification
    // in the header, at the end of the loop the importance will be set to "3", default normal
    importance = "0";

    for ( line=(StringBuffer *)lines.front();
          line;
          line=(StringBuffer *)lines.next() ) {

        if( *line == "\r" )
            break;
        // The first empty line marks the end of the header section
        if( line->empty() ){
            break;
        }
        // Process the headers

        if( line->ifind(TO) == 0 ){
            to = MailMessage::decodeHeader(line->substr(TO_LEN));
        }
        else if( line->ifind(FROM) == 0 ) {
            from = MailMessage::decodeHeader(line->substr(FROM_LEN));
        }
        else if( line->ifind(CC) == 0 ) {
            cc = MailMessage::decodeHeader(line->substr(CC_LEN));
        }
        else if( line->ifind(BCC) == 0 ) {
            bcc = MailMessage::decodeHeader(line->substr(BCC_LEN));
        }
        else if ( line->ifind(DATE) == 0 ) {
            //subjectParsing = false;
            if( date.parseRfc822(line->substr(DATE_LEN)) ) {
                LOG.error("Error parsing date");
                return 500;
            }
        }
        else if( line->ifind(SUBJECT) == 0 ) {

            subject = MailMessage::decodeHeader(line->substr(SUBJECT_LEN));
            LOG.debug("SUBJECT: %s", subject.c_str());
        }
        else if( line->ifind(ENCODING) == 0 ) {  // it is here for single part only
            body.setEncoding(line->substr(ENCODING_LEN));
        }
        else if(line->ifind(MIMEVERS) == 0 ) {
            mimeVersion = line->substr(MIMEVERS_LEN);
        }
        else if(line->ifind(MESSAGEID) == 0 ) {
            messageId = line->substr(MESSAGEID_LEN);
        }
        else if(line->ifind(IMPORTANCE) == 0 ) {
            StringBuffer data = line->substr(IMPORTANCE_LEN);
            data.lowerCase();
            importance = convertImportance(data);
        }
        else if(line->ifind(X_PRIORITY) == 0 ) {
            if (importance == "0") {
                StringBuffer data = line->substr(X_PRIORITY_LEN);
                data.lowerCase();
                importance = convertXPriority(data);
            }            
        }
        else if( line->ifind(MIMETYPE) == 0 ) {

            StringBuffer sb = getTokenValue(line, MIMETYPE);

            if (sb.length() > 0)
                contentType = sb;

            sb.reset();
            sb = getTokenValue(line, "boundary=", false);

            if (sb.length() > 0) {
                boundary = sb;
            } else {
                body.setCharset(getTokenValue(line, CT_CHARSET));
            }
            /*

            size_t len = line->find(";") - MIMETYPE_LEN ;
            contentType = line->substr(MIMETYPE_LEN, len);

            // Save boundary for multipart
            size_t begin = line->ifind("boundary=");
            size_t end = StringBuffer::npos;

            if( begin != StringBuffer::npos ) {
                begin += strlen("boundary=\"");
                end = line->find("\"", begin) ;
                boundary = line->substr( begin, end-begin );
            }
            else {
                    begin=line->ifind(CT_CHARSET);
                if( begin != StringBuffer::npos ) {
                    begin += strlen(CT_CHARSET);
                    size_t end = begin;
                    size_t quote = line->find("\"", begin);
                    if (quote != StringBuffer::npos){
                        begin = quote + 1;
                        end = line->find("\"", begin) ;
                    }
                    else {
                        end = line->find(";", begin) ;
                        if (end == StringBuffer::npos) {
                            end = line->find(" ", begin);
                        }
                    }
                    body.setCharset( line->substr( begin, end-begin ) );
                }
            }
            */
        }
        else if(line->ifind(RECEIVED) == 0) {
            if (!receivedExtracted) {
                strReceived = line->substr(line->rfind(";") );

                if (!strReceived.empty()) {
                    received.parseRfc822(strReceived.substr(2));
                    receivedExtracted = true;
                }
                /*
                while (!strReceived.empty()) {
                    if (received.parseRfc822(strReceived.substr(2)) == 0) {
                        receivedExtracted = true;
                        break;
                    } else {
                        StringBuffer s(line->substr(line->rfind(strReceived.c_str())));
                        strReceived = line->substr(s.rfind(";"));
                    }
                }
                */

            }
        }
        else {
            headers.add(*(StringBuffer *)line);
        }

    }
    // If received was not found, copy send date
    if( received == BasicTime() ){
        received = date;
    }

    // if the importance is never set we put the importance to 3, normal
    if (importance == "0") {
        importance = "3";
    }

    LOG.debug("parseHeaders END");

    // FIXME: should check for mandatory headers before return 0
    return 0;
}
Exemplo n.º 30
0
/**
 * Get the next bodypart from the message body string.
 *
 * @param rfcBody  (in)  - message content
 * @param boundary (in)  - mime boundary string
 * @param ret      (out) - parsed BodyPart
 * @param next     (i/o) - offset of the new boundary
 * @param isAttach (in)  - says if the current body part is an attachment or not
 */
static bool getBodyPart(StringBuffer &rfcBody, StringBuffer &boundary,
                       BodyPart &ret, size_t &next, bool isAttach)
{
    LOG.debug("getBodyPart START");
    StringBuffer newline;

    // The part starts on the next line
    size_t begin = findNewLine(rfcBody, next);
    if (begin == StringBuffer::npos)
       return false;
    // find the end of the part
    next = rfcBody.find(boundary, begin);
    if (next == StringBuffer::npos)
       return false;
    // get the part
    StringBuffer part = rfcBody.substr(begin, next-begin);
    // If it is a multipart alternative part, get the text part only.
    // check only until the first new line not on all the message (it could be
    // a message inside another message)
    size_t headers_len = getHeadersLen(part, newline);
    StringBuffer headers_part = part.substr(0, headers_len);
    if (headers_part.ifind("Content-Type: multipart/alternative") != StringBuffer::npos) {
        if(part.ifind("Content-Type: multipart/alternative") != StringBuffer::npos) {
            size_t b_pos = part.ifind("boundary=");
            if( b_pos != StringBuffer::npos ) {
                size_t begin = part.find("=\"", b_pos) + 2 ;
                size_t end = part.find("\"", begin) ;

                StringBuffer inner_boundary("\n--");
                inner_boundary += part.substr( begin, end-begin );

                begin = part.find(inner_boundary, end);
                begin += inner_boundary.length();
                end = part.find(inner_boundary, begin);
                if (begin != StringBuffer::npos && end != StringBuffer::npos) {
                    part = part.substr(begin, end-begin);
                    LOG.debug("Bodypart is multipart/alternative: "
                        "getting first alternative only: \n%s\n", part.c_str() );
                }
            }
        }
    }

    // Split headers and body
    size_t hdrlen = getHeadersLen(part, newline);

    // Get headers
    StringBuffer headers = part.substr(0, hdrlen);

    // Join header parts using \t or 8 blank
    StringBuffer joinlinetab("\t");
    headers.replaceAll(joinlinetab, " ");
    StringBuffer joinlinespaces(newline);
    joinlinespaces+=" ";  // 8 blanks
    headers.replaceAll(joinlinespaces, " ");

    ArrayList lines;
    const StringBuffer *line;

    // parse the bodypart headers
    headers.split(lines, newline);

    for ( line=(StringBuffer *)lines.front();
          line;
          line=(StringBuffer *)lines.next() ) {
        if( *line == "\r" )
            continue;
        // The first empty line marks the end of the header section
        //if( line->empty() ){
        //    break;
        //}
        // Process the headers
        if( line->ifind(MIMETYPE) == 0 ) {  // it must at the beginning
            ret.setMimeType(getTokenValue(line, MIMETYPE));
            if (line->ifind(CT_NAME) != StringBuffer::npos) {
                ret.setName(MailMessage::decodeHeader(getTokenValue(line, CT_NAME,false)));
            }
            if (line->ifind(CT_CHARSET) != StringBuffer::npos ) {
                ret.setCharset(getTokenValue(line, CT_CHARSET));
            }
        }   
        else if( line->ifind(DISPOSITION) == 0 ) {
            ret.setDisposition( getTokenValue(line, DISPOSITION));
            if (line->ifind(CD_FILENAME) != StringBuffer::npos ) {
                ret.setFilename( MailMessage::decodeHeader(  getTokenValue(line, CD_FILENAME, false) ) );
            }
        }

        else if( line->ifind(ENCODING) == 0 ) {
            ret.setEncoding( getTokenValue(line, ENCODING));
        }

    }
    // move to the beginning of the content
    hdrlen += strlen(newline) + strlen(newline); // added 2 new line that separate the bodyparts
    // get bodypart content
    if( isAttach == false) { // || !ret.getFilename() ) {
        // this is not an attachment
        if(ret.getEncoding() && strcmp(ret.getEncoding(), "quoted-printable") == 0 ) {
            char *decoded = qp_decode( part.substr(hdrlen) );
            ret.setContent ( decoded );
            delete [] decoded;
        }
        else if (ret.getEncoding() && strcmp(ret.getEncoding(), "base64") == 0 ) {
            char *decoded = "";
            size_t len = 0;
            if( uudecode( part.substr(hdrlen), &decoded, &len ) ) {
                LOG.error("Error decoding content");
            }
            ret.setContent ( decoded );
            delete [] decoded;
        }
        else {
            bool found = true;
            if (part.substr(hdrlen).length() < 6) {
                StringBuffer s(part.substr(hdrlen));
                for (unsigned int i = 0; i < s.length(); i++) {
                    if (s.c_str()[i] != '\r' && s.c_str()[i] != '\n') {
                        found = true;
                        break;
                    } else {
                        found = false;
                    }
                }
            }
            if (found) {
                ret.setContent ( part.substr(hdrlen) );
            }
        }
    }
    else {
        LOG.debug("Attachment");
        ret.setContent( mkTempFileName( ret.getFilename() ) );
        LOG.debug("%s", ret.getContent());
        StringBuffer p = part.substr(hdrlen);
        if (p.length()) {
            LOG.debug("Saving...");
            if( convertAndSave(ret.getContent(), p.c_str(), ret.getEncoding()) ) {
                LOG.error("Error in convertAndSave");
            }
            else {
                LOG.debug("convertAndSave success");
            }
        }
    }
    LOG.debug("getBodyPart END");

    // return true if there are more parts
    return (next != StringBuffer::npos);
}