示例#1
0
int main(int argc, char* argv[]){
  


   int i, s, max, min, d, n=35;
   List  C = newList(); // central vertices 
   List  P = newList(); // peripheral vertices 
   List  E = newList(); // eccentricities 
   Graph G = NULL;

   // Build graph G 
   G = newGraph(n);
   for(i=1; i<n; i++){ 
     if( i%7!=0 ) addEdge(G, i, i+1);
      if( i<=28  ) addEdge(G, i, i+7);
   }
   addEdge(G, 9, 31);
   addEdge(G, 17, 13);
   addEdge(G, 14, 33);

   // Print adjacency list representation of G
   printGraph(stdout, G);

   // Calculate the eccentricity of each vertex 
   for(s=1; s<=n; s++){
      BFS(G, s);
      max = getDist(G, 1);
      for(i=2; i<=n; i++){
         d = getDist(G, i);
         max = ( max<d ? d : max );
      }
      append(E, max);
   }
   
   // Determine the Radius and Diameter of G, as well as the Central and 
   // Peripheral vertices.
   append(C, 1);
   append(P, 1);
   min = max = front(E);
   moveTo(E,0);
   moveNext(E);
   for(i=2; i<=n; i++){
      d = getElement(E);
      if( d==min ){
         append(C, i);
      }else if( d<min ){
         min = d;
         clear(C);
         append(C, i);
      }
      if( d==max ){
         append(P, i);
      }else if( d>max ){
         max = d;
         clear(P);
         append(P, i);
      }
      moveNext(E);
   }

   // Print results 
   printf("\n");
   printf("Radius = %d\n", min);
   printf("Central vert%s: ", length(C)==1?"ex":"ices");
   printList(stdout, C);
   printf("\n");
   printf("Diameter = %d\n", max);
   printf("Peripheral vert%s: ", length(P)==1?"ex":"ices");
   printList(stdout, P);
   printf("\n");
   printf("--------------This concludes the given test by professor\n");
   // recomputes BFS with source vertex
   BFS(G, 2);
   clear(C);
   clear(P);
   getPath(C, G, 35);
   getPath(P, G, 2);
   // prints out computed paths and distances
   printf("The path from source to vertex 35(the source vertex): ");
   printList(stdout, C);
   printf("\nThe distance from source to vertex 35( the source vertex): ");
   printf("%d\n", getDist(G, 35));
   printf("\nThe path from source to vertex 2: ");
   printList(stdout, P);
   printf("\nThe distance from source to vertex 2( the source vertex): ");
   printf("%d\n", getDist(G, 2));
   printf("\n");
   
   // Free objects
   
   clear(C);
   clear(P);
   freeGraph(&G);
   //re-build graph G
   n = 100;
   G = newGraph(n);
   for(i = 1; i<n; i++){
     if(i%10 !=0) addEdge(G,i,i+1);
     if(i<=50) addArc(G, i, i+10);
   }
   addArc(G,9,31);
   addEdge(G,17,13);
   addArc(G,14,33);
   
   // recomputes BFS with source vertex
   BFS(G, 50);

   getPath(C, G, 50);
   getPath(P, G, 99);
   printGraph(stdout, G);
   printf("The path from source to vertex 50(the source vertex):");
   printList(stdout, C);
   printf("\nThe distance from source to vertex 50 (the source vertex):");
   printf("%d\n", getDist(G, 50));
   printf("\nThe path from source to vertex 99: ");
   printList(stdout, P);
   printf("\nThe distance from source to vertex 99: ");
   printf("%d\n", getDist(G,99));
   printf("\n");

   freeList(&C);

   
   freeList(&P);

   
   freeList(&E);
   freeGraph(&G);
   
   return(0);
}
示例#2
0
const SkMemberInfo* SkAnimator::getField(const char* elementID, const char* field) {
    const SkDisplayable* element = getElement(elementID);
    return getField(element, field);
}
 bool perform()
 {
     showCorrectTab();
     getElement()->setFillType (newState, false);
     return true;
 }
示例#4
0
bool vesUniform::get(bool &value) const
{
  return isScalar() ? getElement(0, value) : false;
}
示例#5
0
const char* ConfigXml::getVersion()
{
    return getElementText(getElement("version"));
}
示例#6
0
int main (int argc, char* argv[]){
  // temporary string holder
  char line[MAX_LEN];
  // checks for correct command line inputs
  if(argc != 3) {
    printf("Invalid number of inputs");
    exit(1);
  }

  // opens the file
  FILE* input = fopen(argv[1], "r");
  FILE* output = fopen(argv[2], "w");

  // checks if files have been open and or created
  if(input == NULL){ 
    printf("Unable to open file %s for reading\n", argv[1]);
    return 1;
  } else if (output == NULL){
    printf("Unable to open file %s for reading\n", argv[2]);
    return 1;
  }
    
  // read each line of input file, then count and print tokens
  fgets(line, MAX_LEN, input);
  int numVertex = 0;
  sscanf(line, "%d", &numVertex);
  List S = newList();
  for (int i = 1; i <= numVertex; i++) append(S, i);
  // Graph creation
  Graph G = newGraph(numVertex);
  while( fgets(line, MAX_LEN, input) != NULL) {
    int vert1 = 0;
    int vert2 = 0;
    sscanf(line, "%d %d", &vert1, &vert2);
    if(vert1 == 0 && vert2 == 0) break;
    addArc(G, vert1, vert2);
  }

  DFS(G, S);
  fprintf(output, "Adjacency list representation of G:\n");
  printGraph(output, G);

  Graph T = transpose(G);
  DFS(T, S);

  //counts the number of Scc
  int numScc = 0;
  for(moveTo(S, 0); getIndex(S) >= 0; moveNext(S)){
    if(getParent(T, getElement(S)) == NIL) numScc ++ ;
  }
  // puts the components into array list of size # of scc
  List Scc[numScc];
  int i = numScc;
  for(moveTo(S, 0); getIndex(S) >= 0; moveNext(S)){
    if(getParent(T, getElement(S)) == NIL){
      i--;
      Scc[i] = newList();
    }
    if(i == numScc) break;
    append(Scc[i], getElement(S));
  }

  // prints out scc's
  fprintf(output, "\nG contains %d strongly connected components:", numScc);
  for(int j = 0; j < numScc; j++){
    fprintf(output, "\n");
    fprintf(output, "Component %d: ", j + 1);
    printList(output, Scc[j]);
    freeList(&(Scc[j]));
  }
  // frees all the necessary items
  fprintf(output, "\n");
  freeGraph(&G);
  freeGraph(&T);
  freeList(&S);
  fclose(input);
  fclose(output);
  return(0);
}
示例#7
0
bool vesUniform::get(vesVector3f &vector) const
{
  return isScalar() ? getElement(0, vector) : false;
}
示例#8
0
int main(int argc, char *argv[])
{
	ApplicationsLib::LogogSetup logog_setup;

	TCLAP::CmdLine cmd("Query mesh information", ' ', BaseLib::BuildInfo::git_describe);
	TCLAP::UnlabeledValueArg<std::string> mesh_arg("mesh-file","input mesh file",true,"","string");
	cmd.add( mesh_arg );
	TCLAP::MultiArg<std::size_t> eleId_arg("e","element-id","element ID",false,"number");
	cmd.add( eleId_arg );
	TCLAP::MultiArg<std::size_t> nodeId_arg("n","node-id","node ID",false,"number");
	cmd.add( nodeId_arg );

	cmd.parse( argc, argv );

	const std::string filename(mesh_arg.getValue());

	// read the mesh file
	auto const mesh = std::unique_ptr<MeshLib::Mesh>(
		MeshLib::IO::readMeshFromFile(filename));
	if (!mesh)
		return EXIT_FAILURE;

	auto materialIds = mesh->getProperties().getPropertyVector<int>("MaterialIDs");

	for (auto ele_id : eleId_arg.getValue())
	{
		std::stringstream out;
		out << std::scientific
		    << std::setprecision(std::numeric_limits<double>::digits10);
		out << "--------------------------------------------------------" << std::endl;
		auto* ele = mesh->getElement(ele_id);
		out << "# Element " << ele->getID() << std::endl;
		out << "Type : " << CellType2String(ele->getCellType()) << std::endl;
		if (materialIds)
			out << "Mat ID : " << (*materialIds)[ele_id] << std::endl;
		out << "Nodes: " << std::endl;
		for (unsigned i=0; i<ele->getNNodes(); i++)
			out <<  ele->getNode(i)->getID() << " " << *ele->getNode(i) << std::endl;
		out << "Content: " << ele->getContent() << std::endl;
		out << "Neighbors: ";
		for (unsigned i=0; i<ele->getNNeighbors(); i++)
		{
			if (ele->getNeighbor(i))
				out << ele->getNeighbor(i)->getID() << " ";
			else
				out << "none ";
		}
		out << std::endl;
		INFO("%s", out.str().c_str());
	}

	for (auto node_id : nodeId_arg.getValue())
	{
		std::stringstream out;
		out << std::scientific
		    << std::setprecision(std::numeric_limits<double>::digits10);
		out << "--------------------------------------------------------" << std::endl;
		auto* node = mesh->getNode(node_id);
		out << "# Node" << node->getID() << std::endl;
		out << "Coordinates: " << *node << std::endl;
		out << "Connected elements: " ;
		for (unsigned i=0; i<node->getNElements(); i++)
			out << node->getElement(i)->getID() << " ";
		out << std::endl;
		INFO("%s", out.str().c_str());
	}
}
示例#9
0
 bool perform()
 {
     showCorrectTab();
     getElement()->enableStroke (newState, false);
     return true;
 }
示例#10
0
	type_index NEIndexedNodeSet::insert(type_index index, const NENode* const source)
	{
		if( ! &source)
		{
			KERNAL_ERROR(" : 주어진 원본이 없습니다.");
			return NE_INDEX_ERROR;
		}
		if(_occupiedset[index])
		{
			type_result result = setElement(index, source);
			if(NEResult::hasError(result))
			{
				KERNAL_ERROR(" : ");
				return result;
			}
		}



		//	가상생성자로 인스턴스 생성:
		//		인스턴스 복사 알고리즘:
		//			뭐가 문제인가:
		//				1. 주어진 source는 _manager를 가지고 있다. 
		//				2. 주어진 source의 타입은 NEModule로써 이는 ADT이다. 따라서 source의
		//				실제 타입이 무엇인지는 알 수 없다.
		//				3. source의 실제타입에 상관없이 제대로 복사를 하는 함수로는 현재,
		//				clone(가상복사생성자)가 유일하다.
		//				4. clone은 어떠한 파라메터도 받지 않도록 작성되어있다.
		//				5. SuperClass::insert에서는 clone로 생성된 T*를 보관해 두는데, 
		//				source.keyset은 clone을 통해서도 복사가 불가능하다.
		//				복사가 되려면, 복사생성된 객체에 manager가 할당되어 있어야 keyset이
		//				manager 포인터를 갖고 인스턴스를 등록하기 때문이다.
		//				6. clone은 원자연산이다.
		//				즉, 생성하고->manager를 set하고->복사한다는 식으로 구성할 수 없다.
		//
		//			어떤 해결방법이 있었는가:
		//				기존의 생성과 동시에 복사한다.----> 생성->manager set-> 복사
		//				의 형태로 중간에 manager를 set 할 수 있도록 하면 된다.
		//				따라서, 생각해보면, "생성과 동시에 set. 이후 복사" 나
		//				"생성 이후, manager set과 동시에 복사"를 생각해 볼 수 있다.
		//				전자의 경우는 생성자에서 manager를 넘겨준 이후에 복사시
		//				가상할당자(예를 들면 virtual assign(module))등을 새로 추가하는 
		//				방법이 되겠다.
		//				아니면 기존 virtual clone() 이외에도 virtual clone(manager)로 하나 더
		//				만드는 방법도 생각해 볼 수 있다.
		//				복사생성자에서 source의 _manager도 같이 복사하는 방법도 생각해 볼 수
		//				있겠으나, 이렇게 하면 복사된 인스턴스가 내쪽의 manager가 아닌, source쪽
		//				manager에 속해있게 되버리므로 적합치 못하다.
		//				이러한 방법도 있다. clone을 호출하면 멤버변수(keyset)은 할당되지 않더라도
		//				source의 모듈은 정확하게 복사 할 수 있다.
		//				그 이후에 manager를 set하고, 다시한번 operator=를 하는 방법이다.
		//					NEModule& cloned = source.clone();	//	모듈의 객체만 가상생성
		//					cloned.manager is my manager;		//	매니져 할당
		//					cloned.operator=(source)			//	이제 멤버변수를 복사
		//				다만 이 방법의 가장 큰 단점은 keyset에 속하지 않는 멤버변수는 복사 할 수 
		//				없다는 제약이 있다는 것이다.
		//			
		//			최종 해결방법은 무엇인가:
		//				객체 생성시, 상속계층을 거꾸로 올라가면서 생성자를 호출해간다.
		//				그 중간쯤에 manager를 관리하는 클래스가 있을 것이다. 그 생성자가 호출되었
		//				을때 외부에서 특정한 manager값을 전달하는 이벤트 핸들러만 있으면 될것이다.
		//				그래서 이를 해결하기 위해 static으로 global_manager라는 방법을 사용한다.
		//					static Manager* getGlobalManager();
		//					static setGlobalManager(Manager*);
		//				의 함수를 이용해서 해당하는 manager 멤버변수를 소유한 클래스가 호출 되었을때
		//				특별히 주어진 manager가 없을때 global_manager를 할당하는 방법이다.
		//				다만 이 globalmanager를 사용하는 생성자는 복사생성자로 제한한다.
		//				일반 생성자는 manager를 할당할 수 있는 함수가 이미 있으므로, 사용자가 manager
		//				외부로부터 할당하고 싶었는지 아닌지 의도를 파악할 수 있기 때문이다.
		//				
		//			예상되는 문제점:
		//				이 문제에 예상되는 문제점은 다음과 같다.
		//					1. static이긴 하나 생성자에서 메소드를 호출한다는 점에서 예상치못한 에러가
		//					있을 수 있다.	-> push pop의 개념을 적용하여 일정 부분 해결
		//					2. 할당한 global manager값을 해제해주지 않으면 전혀다른 객체가 생성될때도
		//					내 manager가 할당되버리는 오류가 발생할 것이다.	-> 코드 작성에 주의하면 
		//																	안정성 확보 가능
		//					3. 내가 소유할 하나의 객체를 위해 global_manager를 할당한다 하더라도 내부적으로
		//					다른 manager 영역에 있는 객체를 생성하고자 할때가 있을 수도 있다.
		//
		//			적용시점:
		//				SuperClass인 IndexedArrayTemplate에서 clone이 사용되기 직전마다 _setGlobalManager
		//				를 해줘야한다. 최종적으로 적용 대상은 다음과 같다.
		//					1. insert
		//					2. resize
		//					3. setElement

		//	생성자 핸들러:	보다 자세한 내용은 NEIndexedModuleSet.cpp 참조하라
		//		전역 manager 셋:		
		//			타겟팅:
		NEEnlistableManager& push = NEGlobalManagerOffer::getGlobalManager();
		//			연산:
		NEGlobalManagerOffer::_setGlobalManager(getManager());
		//		복사:
		type_index inputed_index = SuperClass::insert(index, source);
		//		아이디 할당:
		//			타겟팅:
		NENode& node = getElement(inputed_index);
		if(&node)
			node._id = _generateId();
		//		되돌리기:
		NEGlobalManagerOffer::_setGlobalManager(push);

		//		모듈 초기화 여부 판단:	
		//			주어진 모듈이 초기화가 되어있는 지를 판단하고, 초기화가
		//			안되어있을때에는 초기화를 수행해야 키셋이 제대로 존재하게 된다.
		//
		//			왜 초기화를 해야 하는가:
		//				모듈이 enlist되지 않은 채로 키셋에 키를 넣을 수는 없기 때문이다.
		//				모듈의 키셋(코드)은 실제 인스턴스가 담겨야 하는 키셋(인스턴스)
		//				을 소유하는 매니져를 알고 있어야 한다.
		//				그러나 외부에서 정의된 모듈의 경우는 매니져가 없으므로 키셋에 
		//				어떠한 키도 넣을 수 없다.
		//					
		//			모듈 매니져는 모듈을 초기화를 수행할 수 없다:
		//				모듈매니져는 숏컷이나 instance 셋을 소유하지 않는다.
		//				이는 EnlistableManager로부터 상속을 받아야 하나, 모듈매니져는
		//				노드가 등록가능한 매니져의 일종이 아니므로 불가능하다.
		//				
		//			어떻게 초기화가 되었는지를 확인 하는가:
		//				검사 대상은 이미 추가된 인스턴스다. 따라서 요점은 "주어진 모듈이
		//				가지고 있는 키셋이 이미 초기화가 수행되었는지를 알 수 있는가"
		//				가 된다. 
		//					1. 모든 모듈은 NEKeyCodeSet을 가지고 있다.
		//					2. 모든 CodeSet은 enlist될때 반드시 자신의 Manager값을 할당받는다.
		//				따라서 위의 같은 사실을 이용하여, 모듈의 키셋의 매니져가 할당이
		//				되어 있지 않은 경우는 초기화가 필요한 경우라는 것을 알 수 있다.
		//
		//			시나리오 점검:
		//				모듈매니져로부터 push한 경우:
		//					1. 모듈매니져로부터 모듈을 하나 가져옴(복사X)
		//						모듈매니져의 모듈은 초기화가 안 되어있으므로, KeyCodeSet.manager 
		//						is 0x00이다.
		//					2. 해당 모듈을 enlisted 모듈셋에 push.
		//						모듈셋에서는 주어진 모듈을 복사생성. 복사생성시에 _manager 값은
		//						복사되지 않는 "인스턴스 우선"정책을 가지고 있다.
		//						(_is_rootnode)와 동일
		//					3. 성공적으로 모듈을 push되고 _onEnlist(Module) 호출
		//						주어진 모듈의 키셋의 manager = 0x00이므로 매니져를 셋 하면서,
		//						모듈을 초기화.


		return inputed_index;
	}
int main(int argc, char* argv[]){
   int i, s, max, min, d, n=35;
   List  C = newList(); // central vertices 
   List  P = newList(); // peripheral vertices 
   List  E = newList(); // eccentricities 
   Graph G = NULL;

   // Build graph G 
   G = newGraph(n);
   for(i=1; i<n; i++){
      if( i%7!=0 ) addEdge(G, i, i+1);
      if( i<=28  ) addEdge(G, i, i+7);
   }
   addEdge(G, 9, 31);
   addEdge(G, 17, 13);
   addEdge(G, 14, 33);

   // Print adjacency list representation of G
   printGraph(stdout, G);

   // Calculate the eccentricity of each vertex 
   for(s=1; s<=n; s++){
      BFS(G, s);
      max = getDist(G, 1);
      for(i=2; i<=n; i++){
         d = getDist(G, i);
         max = ( max<d ? d : max );
      }
      append(E, max);
   }

   // Determine the Radius and Diameter of G, as well as the Central and 
   // Peripheral vertices.
   append(C, 1);
   append(P, 1);
   min = max = front(E);
   moveTo(E,0);
   moveNext(E);
   for(i=2; i<=n; i++){
      d = getElement(E);
      if( d==min ){
         append(C, i);
      }else if( d<min ){
         min = d;
         clear(C);
         append(C, i);
      }
      if( d==max ){
         append(P, i);
      }else if( d>max ){
         max = d;
         clear(P);
         append(P, i);
      }
      moveNext(E);
   }

   // Print results 
   printf("\n");
   printf("Radius = %d\n", min);
   printf("Central vert%s: ", length(C)==1?"ex":"ices");
   printList(stdout, C);
   printf("\n");
   printf("Diameter = %d\n", max);
   printf("Peripheral vert%s: ", length(P)==1?"ex":"ices");
   printList(stdout, P);
   printf("\n");

   // Free objects 
   freeList(&C);
   freeList(&P);
   freeList(&E);
   freeGraph(&G);

   return(0);
}
示例#12
0
文件: Lex.c 项目: UVERkill/CMPS101
int main(int argc, char * argv[]) {
	if(argc != 3) {
		printf("Usage: %s <input file> <output file>\n", argv[0]);
		exit(1);
	}

	FILE *in, *out;	

	// read input with fopen "r"
	in = fopen(argv[1], "r");
	// write to output with fopen "w"
	out = fopen(argv[2], "w");
	if(in == NULL) {
		printf("Unable to open file %s for reading\n", argv[1]);
		exit(1);
	}
	if(out == NULL) {
		printf("Unable to open file %s for writing\n", argv[2]);
		exit(1);
	}

	// Count number of lines in file and then reopen file
	char line[MAX_LEN];
	int lines = 0;
	while(fgets(line, MAX_LEN, in) != NULL) {
		lines++;
	}

	fclose(in);
	in = fopen(argv[1], "r");

	// Initialize the word array
	// Read the words into an array while allocating memory for each
	// word from the input file
	int n = 0;
	char **words = (char **)malloc(lines * sizeof(char*));
	char* word;
	while(fgets(line, MAX_LEN, in) != NULL) {
		word = malloc((strlen(line)+1) * sizeof(char));
		strcpy(word, line);
		words[n++] = word;
		free(word);
	}

	// Insertion Sort to alphabetize file
	List sorted = newList();
	append(sorted, 0);
	char* current;
	int j;
	int flag;
	// Insertion Sort on the String array of words into List
	for(int i=1; i<lines; i++) {
		flag = 0;
		current = words[i];
		moveTo(sorted, 0);
		j = 0;
		while(!flag && j<i) {
			printf("%s", current);
			if(strcmp(current, words[getElement(sorted)])<0) {
				insertBefore(sorted, i);
				flag = 1;
			} else {
				moveNext(sorted);
				j++;
			}
		}
		if(!flag) {
			append(sorted, i);
		}
	}

	// Print words alphabetically to output file
	for(int i=0; i<lines; i++) {
		moveTo(sorted, i);
		fprintf(out, "%s", words[getElement(sorted)]);
	}

	// free memory
	free(words);
	freeList(&sorted);

	// close files
	fclose(in);
	fclose(out);

	return(0);
}
示例#13
0
 /// Returns value for row rowName and column columnName
 inline double operator()(const char *rowName, const char *columnName) const
 {
   return getElement(rowName, columnName);
 }
示例#14
0
 /// Returns value for row i and column j
 inline double operator()(int i, int j) const
 {
   return getElement(i, j);
 }
示例#15
0
 bool undo()
 {
     showCorrectTab();
     getElement()->setPosition (oldState, false);
     return true;
 }
示例#16
0
 bool undo()
 {
     showCorrectTab();
     getElement()->enableStroke (oldState, false);
     return true;
 }
示例#17
0
bool
MediaSink::linkPad (std::shared_ptr<MediaSrc> mediaSrc, GstPad *src)
{
  std::shared_ptr<MediaSrc> connectedSrcLocked;
  GstPad *sink;
  bool ret = false;

  mutex.lock();

  try {
    connectedSrcLocked = connectedSrc.lock();
  } catch (const std::bad_weak_ptr &e) {
  }

  if ( (sink = gst_element_get_static_pad (getElement(), getPadName().c_str() ) ) == NULL)
    sink = gst_element_get_request_pad (getElement(), getPadName().c_str() );

  if (gst_pad_is_linked (sink) ) {
    unlink (connectedSrcLocked, sink);
  }

  if (mediaSrc->parent == parent) {
    GstBin *container;
    GstElement *filter, *parent;
    GstPad *aux_sink, *aux_src;

    GST_DEBUG ("Connecting loopback, adding a capsfilter to allow connection");
    parent = GST_ELEMENT (GST_OBJECT_PARENT (sink) );

    if (parent == NULL)
      goto end;

    container = GST_BIN (GST_OBJECT_PARENT (parent) );

    if (container == NULL)
      goto end;

    filter = gst_element_factory_make ("capsfilter", NULL);

    aux_sink = gst_element_get_static_pad (filter, "sink");
    aux_src = gst_element_get_static_pad (filter, "src");

    g_signal_connect (G_OBJECT (aux_sink), "unlinked", G_CALLBACK (sink_unlinked), filter );
    g_signal_connect (G_OBJECT (aux_src), "unlinked", G_CALLBACK (src_unlinked), filter );

    gst_bin_add (container, filter);
    gst_element_sync_state_with_parent (filter);

    if (gst_pad_link (aux_src, sink) == GST_PAD_LINK_OK) {
      if (gst_pad_link (src, aux_sink) == GST_PAD_LINK_OK)
        ret = true;
      else
        gst_pad_unlink (aux_src, sink);

    }

    g_object_unref (aux_sink);
    g_object_unref (aux_src);

    gst_debug_bin_to_dot_file_with_ts (GST_BIN (container), GST_DEBUG_GRAPH_SHOW_ALL, "loopback");

  } else {
    if (gst_pad_link (src, sink) == GST_PAD_LINK_OK)
      ret = true;
  }

  if (ret == true) {
    connectedSrc = std::weak_ptr<MediaSrc> (mediaSrc);
  } else {
    gst_element_release_request_pad (getElement(), sink);
  }

end:

  g_object_unref (sink);

  mutex.unlock();

  return ret;
}
示例#18
0
void *ApoloPort::handleConnections(void *server)
{
	Socket *aux_sock= (Socket*) server;
	Socket socket=*aux_sock;
	PositionableEntity *pos;
	RobotSim *robot;
	WheeledBaseSim *wb;
	static int valid=0, total=0;
	
	while(1)
	{
		Socket *temp=socket.acceptConnection();
		
		
		while(temp->IsConnected())
		{	
			
			
			char buffer[10000];
			int size=0;
			if(0<(size=temp->Receive(buffer,10000,-1)))
			{
				
				ApoloMessage *m=0;
				char *pbuffer=buffer;//recorrepbuffer
				while(m=ApoloMessage::getApoloMessage(&pbuffer,size))
				{
					size-=m->getSize();
					total++;
					char *nworld=m->getWorld();
					char *name=m->getObjectName();
					int worldindex=0;
					PositionableEntity *element=getElement(nworld,name,&worldindex);

					switch(m->getType())
					{
						case AP_CHECKJOINTS:
						case AP_SETJOINTS:
							if(element){
							robot=dynamic_cast<RobotSim*>(element);
							int numJoints=m->getCharAt(0);
							for(int i=0;i<numJoints;i++)
							   if(robot)robot->setJointValue(i,m->getDoubleAt(1+8*i));
							if(m->getType()==AP_CHECKJOINTS){
								bool res=false;
								if(robot){
									res=robot->checkRobotColision();
								}
								char resp[50];
								int tam=ApoloMessage::writeBOOL(resp,res);
								temp->Send(resp,tam);
							}

							valid++;
							}
							
							break;
						case AP_GETLOCATION:
						case AP_GETLOCATION_WB:
							if(element){
								double d[6];
								Vector3D p=element->getRelativePosition();
								double o[3];
								element->getRelativeOrientation(d[3],d[4],d[5]);
								for(int i=0;i<3;i++)d[i]=p[i];
	
								char resp[70];
								int tam;
								if(m->getType()==AP_GETLOCATION)tam=ApoloMessage::writeDoubleVector(resp,6,d);
								else {
									d[3]=d[5];
									tam=ApoloMessage::writeDoubleVector(resp,4,d);
								}
								temp->Send(resp,tam);
								valid++;
							}
							break;
						case AP_PLACE:
							if(element){
								double d[6];
								for(int i=0;i<6;i++)d[i]=m->getDoubleAt(8*i);
								element->setAbsoluteT3D(Transformation3D(d[0],d[1],d[2],d[3],d[4],d[5]));
								valid++;
							}
							break;
						case AP_PLACE_WB: //place a wheeled based robot. computes the grounded location and collision
							if(element){
								wb=dynamic_cast<WheeledBaseSim *>(element);
								bool res=false;
								double d[4];
								for(int i=0;i<4;i++)d[i]=m->getDoubleAt(8*i);
								Transformation3D taux(d[0],d[1],d[2],mr::Z_AXIS,d[3]);
								if(wb)res=wb->dropWheeledBase(taux);
								if(res){

									res=!(wb->getWorld()->checkCollisionWith(*wb));
							
								}
								
								char resp[50];
								int tam=ApoloMessage::writeBOOL(resp,res);
								temp->Send(resp,tam);
								valid++;
							}
							break;
						case AP_MOVE_WB:
							
							if(element){
								wb=dynamic_cast<WheeledBaseSim *>(element);
								double d[3];
								for(int i=0;i<3;i++)d[i]=m->getDoubleAt(8*i);
								wb->move(d[0],d[1]);
								wb->simulate(d[2]);
								wb->move(0,0);
								valid++;
							}
							break;
						case AP_UPDATEWORLD:
							if(worldindex>=0){//updates one world
								(*world)[worldindex]->getChild()->RefreshChild();
							}else //updates all worlds
							{
								for(int i=0; i<world->size();i++)
									(*world)[i]->getChild()->RefreshChild();
							}
							valid++;
							break;
						case AP_LINK_TO_ROBOT_TCP:
						if(element){
							robot=dynamic_cast<RobotSim*>(element);
							char *objectname=m->getStringAt(0);
							PositionableEntity *target=getElement(nworld,objectname,&worldindex);
							if(target&&robot){
								target->LinkTo(robot->getTcp());
							}
							

							valid++;
							}
							break;

					}

					delete m;//aseguro limpieza
				}
				char messageLog[150];
				sprintf(messageLog,"Commands Executed: %d/%d",valid,total);
				wxLogStatus(messageLog);
				//temp->Send(request,50);

					
	
								
			}		
		}

		temp->close();
		delete temp;
	
	}
	

}
示例#19
0
/// inverse of matrix
CMat44 CMat44::inv(void){
    CMat44 temp;
	//R'
	temp.setElement(getElement(1,1),1,1);
	temp.setElement(getElement(1,2),2,1);
	temp.setElement(getElement(1,3),3,1);

	temp.setElement(getElement(2,1),1,2);
	temp.setElement(getElement(2,2),2,2);
	temp.setElement(getElement(2,3),3,2);

	temp.setElement(getElement(3,1),1,3);
	temp.setElement(getElement(3,2),2,3);
	temp.setElement(getElement(3,3),3,3);

	//R'*p
	temp.setElement(-(temp.getElement(1,1)*getElement(1,4)+temp.getElement(1,2)*getElement(2,4)+temp.getElement(1,3)*getElement(3,4)),1,4);
	temp.setElement(-(temp.getElement(2,1)*getElement(1,4)+temp.getElement(2,2)*getElement(2,4)+temp.getElement(2,3)*getElement(3,4)),2,4);
	temp.setElement(-(temp.getElement(3,1)*getElement(1,4)+temp.getElement(3,2)*getElement(2,4)+temp.getElement(3,3)*getElement(3,4)),3,4);

	return temp;
}
void* UniformAligner::addElement() {
	_buffer.insert(_buffer.end(), alignSize(_dataSize, _requiredAlignment), 0);
	++_numElements;

	return getElement(_numElements - 1);
}
示例#21
0
bool vesUniform::get(vesMatrix4x4f &matrix) const
{
  return isScalar() ? getElement(0, matrix) : false;
}
void mitk::DICOMDCMTKTagScanner::Scan()
{
  this->PushLocale();

  try
  {
    DcmPathProcessor processor;
    processor.setItemWildcardSupport(true);

    DICOMGenericTagCache::Pointer newCache = DICOMGenericTagCache::New();

    for (const auto& fileName : this->m_InputFilenames)
    {
      DcmFileFormat dfile;
      OFCondition cond = dfile.loadFile(fileName.c_str());
      if (cond.bad())
      {
        MITK_ERROR << "Error when scanning for tags. Cannot open given file. File: " << fileName;
      }
      else
      {
        DICOMGenericImageFrameInfo::Pointer info = DICOMGenericImageFrameInfo::New(fileName);

        for (const auto& path : this->m_ScannedTags)
        {
          std::string tagPath = DICOMTagPathToDCMTKSearchPath(path);
          cond = processor.findOrCreatePath(dfile.getDataset(), tagPath.c_str());
          if (cond.good())
          {
            OFList< DcmPath * > findings;
            processor.getResults(findings);
            for (const auto& finding : findings)
            {
              auto element = dynamic_cast<DcmElement*>(finding->back()->m_obj);
              if (!element)
              {
                auto item = dynamic_cast<DcmItem*>(finding->back()->m_obj);
                if (item)
                {
                  element = item->getElement(finding->back()->m_itemNo);
                }
              }

              if (element)
              {
                OFString value;
                cond = element->getOFStringArray(value);
                if (cond.good())
                {
                  info->SetTagValue(DcmPathToTagPath(finding), std::string(value.c_str()));
                }
              }
            }
          }
        }
        newCache->AddFrameInfo(info);
      }
    }

    m_Cache = newCache;

    this->PopLocale();
  }
  catch (...)
  {
    this->PopLocale();
    throw;
  }
}
示例#23
0
void ConfigXml::createDefaultConfig()
{
    setElementText(getElement("version", 0, true), CONFIG_VERSION);
    saveXmlFile();
}
示例#24
0
			element_type operator[](uint64_t const i) const
			{
				element_type element;
				getElement(element,i);
				return element;
			}
示例#25
0
SkElementType SkAnimator::getElementType(const char* id) {
    const SkDisplayable* element = getElement(id);
    return getElementType(element);
}
示例#26
0
bool CToggleRemoteGlyph::setup(CPetControl *petControl, CPetGlyphs *owner) {
	CPetGlyph::setup(petControl, owner);
	if (owner)
		_gfxElement = getElement(0);
	return true;
}
int main(int argc, char * argv[]){
   int count=0;
   int u, v, index, sccNum;
   FILE *in, *out;
   char line[MAX_LEN];
   char* token;
   Graph G = NULL;
   Graph T = NULL;
   List S = newList(); // This list is our stack that determins the order of the vertices
   List R = newList();
   // check command line for correct number of arguments
   if( argc != 3 ){
      printf("Usage: %s <input file> <output file>\n", argv[0]);
      exit(1);
   }

   // open files for reading and writing 
   in = fopen(argv[1], "r");
   out = fopen(argv[2], "w");
   if( in==NULL ){
      printf("Unable to open file %s for reading\n", argv[1]);
      exit(1);
   }
   if( out==NULL ){
      printf("Unable to open file %s for writing\n", argv[2]);
      exit(1);
   }

   /* read each line of input file, then count and print tokens */
   // Assemble a graph object G using newGraph() and addArc()
   while(fgets(line, MAX_LEN, in) != NULL)  {
      count++;
	  // char *strtok(char *str, const char *delim) breaks string str into
	  // a series of tokens using the delimitrer delim. This function returns a pointer to the
	  // last token found in string. A null pointer is returned if there are no tokens left to retrieve.
      token = strtok(line, " \n");
	  
	  // int atoi(const char *str), This function returns the converted integral number as an int value.
	  // If no valid conversion could be performed, it returns zero.
	  // It converts char to int.
	  if(count == 1) {
	     // Takes in the first number as a token, sets a graph of that size
	     G = newGraph(atoi(token));
	  }
	  else {
	     // Here we want to read in both numbers
		 u = atoi(token);
		 token = strtok(NULL, " \n");
		 v = atoi(token);
		 if( u != 0 || v != 0) {
		       addArc(G, u, v);
	     }		   
         else if (u == 0 && v == 0) {
		       break;
         }			   
      } 
   }
   // Print the adjacency list representation of G to the output file
   printGraph(out, G);
   fprintf(out, "\n");
   
   // creating our Stack
   for(int i = 1; i <= getOrder(G); i++) {
      append(S, i);
   }
   
   // Run DFS on G and G-Transpose, processing the vertices in the second call
   // by decreasing finish times from the first call
   DFS(G, S);
   T = transpose(G);
   DFS(T, S);
   
   // Determine the strong components of G
   // Print the strong components of G to the output file in topologically sorted order.
   // Everytime a vertex has a NIL parent in the transpose of G, we have a SCC
   sccNum = 0;
   for(int i = 1; i <= getOrder(G); i++) {
      if(getParent(T, i) == NIL) sccNum++;
   }
   
   
   fprintf(out, "G contains %d strongly connected components:\n", sccNum);
   index = 1;
   moveTo(S, length(S) - 1 );
   while(getIndex(S) != -1 && index <= sccNum) {  
	  fprintf(out, "Component %d:", index);
	  while(getParent(T, getElement(S)) != NIL) {
		 prepend(R, getElement(S));
		 movePrev(S);
	  }
	  prepend(R, getElement(S));
	  printReverse(out, T, R);
	  movePrev(S);
	  index++;   
	  fprintf(out, "\n");
   }

   
   freeList(&S);
   freeList(&R);   
   freeGraph(&G);
   freeGraph(&T);   

   /* close files */
   fclose(in);
   fclose(out);

   return(0);
}
示例#28
0
 bool perform()
 {
     showCorrectTab();
     getElement()->setPosition (newState, false);
     return true;
 }
 bool undo()
 {
     showCorrectTab();
     getElement()->setFillType (oldState, false);
     return true;
 }
示例#30
0
	//	---------------------------------------------------------------------------------
	//	설명:		모듈을 파일로부터 로드한다.
	//				PC의 환경이 바뀌면 모듈이 존재하지 않게 되고, 이때 존재하지 않는 모듈의
	//				멤버변수를 파일로부터 읽어들이는 건 불가능하다.
	//				또한, 존재하지 않는 모듈의 메모리 크기를 알기도 힘들다.
	//				그래서 Case By Skip Load을 사용한다.
	//	동작조건:	이미 모듈셋의 인스턴스가 외부로부터 발생했어야 한다.
	//					1. 스크립트 파일의 경우	:	NENode::serialize로부터 인스턴스 발생
	//					2. 노드 파일의 경우		:	NENodeSet::serialize로부터 인스턴스 발생
	//	메모:		Case By Skip Load란?
	//					:	모듈을 로드하기 전에, "모듈이 존재하지 않을 경우, 이동할 주소"를
	//						기록한다. 그래서 모듈이 존재하지 않는다면 파일의 포인터를 바로
	//						그쪽으로 이동하는 방법이다.
	//	히스토리:	2011-07-07	이태훈	개발 완료
	//				2011-07-10	이태훈	추가
	//					:	Case By Skip Load를 추가해서 모듈의 보다 독립적인 환경을 만들었다.
	//	---------------------------------------------------------------------------------
	NEBinaryFileLoader& NEIndexedModuleSet::serialize(NEBinaryFileLoader& loader)
	{
		//	TEST: 아무런 조치를 취하지 않고도 insert, remove에 넣은 enlist, unlist로 
		//			serialize 도중에 무사히 enlist, unlist가 동작되는지?
		//	pre:
		//		타겟팅:
		const NEModuleManager& moduler = Kernal::getInstance().getModuleManager();
		//		상위 함수 호출:
		SuperClass::serialize(loader);



		//	main:
		type_index size = getSize();
		//		길이 정보 초기화:	push를 사용하기 위해서
		_length = 0;
		//		Occupied 탐색 인덱스 초기화:
		//			occupiedSet에서 index로부터 순서대로 올림차순으로 검색한다.
		//			가장 가까운 것중에 OccupiedSet[index] == true인 것이 모듈을 추가해야하는 
		//			부분이 된다.
		type_index occupied_index = -1;

		for(int n=0; n < size ;n++)
		{
			if( ! _occupiedset[n])
				continue;
			//		스킵 주소 획득:	만약 모듈이 현재 PC에 존재하지 않았다면 더미 모듈일 테고,
			//						더미 모듈이라면 스킵주소로 바로 이동한다.
			long int next_module_to_skip = 0;
			loader >> next_module_to_skip;
			//		로드가능한 모듈 판단:	식별자를 로드해서 만약, 존재하지 않는다면, 로드하지 못하는 
			//								모듈이라는 게 된다.
			//								즉, 스크립트 파일에 해당 모듈의 데이터가 존재하나, 현재 PC에는
			//								모듈이 존재하지 않는 상태.
			//								따라서, 파일포인터를 스킵해야한다.
			//			식별자 로드:
			NEExportable::Identifier identifier;
			loader >> identifier;
			//			식별자로 인스턴스 fetch:	만약 더미모듈이 나오면, fetch에 실패 했다는 걸 말한다.
			const NEModule& module = moduler.getModule(identifier);
			//			만약 더미모듈이라면:
		
			if( ! &module							||
				module.getType() == NEType::UNDEFINED)
			{
				//	더미 삽입:				
				KERNAL_ERROR(" : 더미 모듈을 삽입해야하는데, 현재 설계로는 삽입이 쵸금 곤란함");
			}
			else	//	로드한 모듈중 하나라면:
			{
				//			모듈 로드:	정상적으로 모듈을 로드한다.
				//				모듈 삽입을 위해서 소유권을 박탈:
				_occupiedset[n] = false;
				//				주어진 모듈 삽입: 
				//					push에서 NEModule::clone을 호출
				//					NEModule::NEModuleCodeSet이 복사되면서 push(NEModuleCodeSet&)을 호출
				//					push(NEModuleCodeSet&)에서 NEIndexedKeySet으로부터 clone으로 키를 복제
				NEEnlistableManager* nullpointer = NE_NULL;
				insert(n, module);				
				//				데이터 로드:
				//					여기서 NEModuleCodeSet::serialize를 호출
				//					serialize에서 NEKeyCodeSetjuyhg
				loader >> getElement(n); // 여기서 다시 NEModule::serialize()에서 initialize를 호출한다
			}
			//	스킵로드:
			//		스킵을 사용하는가?:	파일포인터가 다음 모듈시작점과 다르다면
			if(loader.getPosition() != next_module_to_skip)
			{
				//		스킵:	
				//			주소를 스킵하고 다음 위치로 이동한다.
				//			만약 이 모듈이 마지막 모듈이었다면, 파일 포인터가 위치한 지점부터, 
				//			다음 NENode 혹은, NENode를 로드할 것이다.
				//			참고 : 더미 모듈은 로드가 필요없다.
				KERNAL_ERROR("E100031C77 : 모듈셋의 어긋난 파일포인터\n모듈셋에서 모듈의 인스턴스를 생성하는 중, 파일포인터가 어긋났습니다.\n파일포인터가 어긋나면 다음 모듈을 로드할 수 없으므로, 파일포인터를 강제로 보정합니다.\n현재 파일포인터 위치: %d\n예상했던 파일포인터 위치 : %d\n에러가 발생한 모듈의 식별자 : \n\t이름 : %s\n\t개발자 : %s\n\t개정번호 : %d",loader.getPosition(), next_module_to_skip, identifier.getName().toCharPointer(), identifier.getDeveloper().toCharPointer(), identifier.getRevision());

				loader.setPosition(next_module_to_skip);
			}			
		}

		return loader >> _last_generated_id;
	}