/** Constructor.
 * @param service_name service name to announce for each group we join, this
 * must be unique in the group and should identify the robot
 * @param service_publisher service discovery publisher to announce groups
 * @param initial_groups initial group configurations to join
 */
GossipGroupManager::GossipGroupManager(std::string &service_name,
				       ServicePublisher *service_publisher,
				       std::map<std::string, GossipGroupConfiguration> &initial_groups)
  : service_name_(service_name), service_publisher_(service_publisher)
{
#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  for (auto g : initial_groups) {
    create_group(g.second);
  }
#else
  std::map<std::string, GossipGroupConfiguration>::iterator g;
  for (g = initial_groups.begin(); g != initial_groups.end(); ++g) {
    create_group(g->second);
  }
#endif
}
Exemple #2
0
  void DatabaseIO::create_groups(const std::string &property_name, EntityType type,
                                 const std::string &type_name, const T *set_type)
  {
    if (!properties.exists(property_name)) {
      return;
    }

    std::string              prop   = properties.get(property_name).get_string();
    std::vector<std::string> groups = tokenize(prop, ":");
    for (auto &group : groups) {
      std::vector<std::string> group_spec = tokenize(group, ",");

      // group_spec should contain the name of the new group as
      // the first location and the members of the group as subsequent
      // locations.  OK to have a single member
      if (group_spec.size() < 2) {
        std::ostringstream errmsg;
        errmsg << "ERROR: Invalid " << type_name << " group specification '" << group << "'\n"
               << "       Correct syntax is 'new_group,member1,...,memberN' and "
                  "their must "
               << "       be at least 1 member of the group";
        IOSS_ERROR(errmsg);
      }

      create_group(type, type_name, group_spec, set_type);
    }
  }
Exemple #3
0
void main(){
	malloc_init();
	
	// Alloc memory for thread&group lists
	main_memarea = kolibri_new_named_memory(KOBRA_MEMAREA_NAME, KOBRA_MEM_SIZE, KOLIBRI_ACCESS_READ|KOLIBRI_CREATE);
	halMemHeapInit(&memarea_heap, &return_0, main_memarea.addr, KOBRA_MEM_SIZE);
	
	// Init main group list
	create_group("main");
	main_group_list->next = main_group_list->previos = main_group_list;
	main_group_list->thread_list = main_thread_list = new_thread_list(kolibri_get_my_tid());
	main_thread_list->next = main_thread_list->previos = main_thread_list;
	
	IPCInit();
// 	kolibri_IPC_unlock();
	
	// Set event mask
// 	kolibri_event_set_mask(KOLIBRI_IPC_EVENT_MASK);
	
	while (1) {
		Message *msg = IPCWaitMessage(-1);
// 		if (kolibri_event_wait() != KOLIBRI_IPC_EVENT) {		// Just ignore this error
// 			continue;
// 		}
		message_handle(msg);
		free(msg);
// 		kolibri_IPC_clear_buff();
	}
}
int lucky(char *argn){
	int i,j;
	long int input = atol(argn);
	int length = find_length(input);
	float *number = (float *)malloc(length*sizeof(float));
	init(number,length,input);
	float *number1 = (float *)malloc(length*sizeof(float));
	int **oper2;
	oper2 = (int **)malloc(Pow(4,(length-1))*sizeof(int *));	
	for (i=0; i<Pow(4,(length-1)); i++){
		oper2[i] = (int *)malloc(length*sizeof(int));
	}
	int *oper3 = (int *)malloc(length*sizeof(int));
	float *number3 = (float *)malloc(length*sizeof(float));
	create_opers(oper2,length);
	int length1;
	for (i=0; i<Pow(2,(length-1)); i++){
		length1 = create_group(i,number,length,number1);
		for (j=0; j<Pow(4,(length1-1)); j++){
			copy_arrays(number1,number3,oper2[j],oper3,length1);
			if (check(length1,number3,oper3)){
				return 0;
			}
		}
	}
	return 1;
}
    void initialize(void*)
    {
        _loop = 0;

        _proxyCounter = 0;

        _group = create_group();

        lemon::timer_t timer;

        for(size_t i =0; i < maxTaxis; ++ i)
        {
            _taxis.push_back(iTaxi::create(runQ(),&_group));
        }

        time_duration duration = timer.duration();

        std::cout << "create taxis (" << _taxis.size() << ")"

                  << " -- success(" << duration / 10000000 << "."

                  << std::setw(6) << std::setfill('0') <<(duration % 10000000) / 10

                  << " s)" << std::endl;

        beat();
    }
Exemple #6
0
    ///Get internal QSettings by \p uid. Group is created if no group found.
    qsettings_p get_settings(const QString & uid)
    {
        settings_map::const_iterator it = registered_.find(uid);
        if (it == registered_.end())
            it = registered_.insert(std::make_pair(uid, create_group(uid))).first;

        return it->second;
    }
static __uint _on_add_edit_tags(PCRTK_PACKET p)
{
	ONLINE_CONFIG::reload_tags_ack *ack;
	RTK_CURSOR	hNode, hTag, hGroup;
	RTK_TAG		*pTag;
	RTK_GROUP	grp;
	__bool		bEdit;
	
	__uint tagcount, i;

	ack = (ONLINE_CONFIG::reload_tags_ack *)p->data;
	tagcount = p->data_size / sizeof(*ack);
	if(p->data_size % sizeof(*ack)){
		return 0;
	}
	ZeroMemory(&grp, sizeof(grp));

	if( !lock_rtdb(__true, 100) ){
		return 0;
	}

	hNode = HNODE_LOCAL_MACHINE;
	hTag = hGroup = 0;
	host_to_node(&g_ThisNode->key, &grp.node);

	if(PACKET_TYPE(p) == PT_EditTag){
		bEdit = __true;
	}else{
		bEdit = __false;
	}

	for(i=0; i<tagcount; i++){
		hGroup = open_group(hNode, &ack[i].tag.group);
		grp.key = ack[i].tag.group;
		if(!hGroup){
			hGroup = create_group(hNode, &grp);
		}
		if(hGroup){
			hTag = create_tag(hGroup, &ack[i].tag.key, &ack[i].tag.s);
			pTag  = (RTK_TAG*)cursor_get_item(hTag);
			if(pTag){
				*pTag = ack[i].tag;
				mark_expired(pTag);
				close_handle(hTag);
				if(bEdit){
					// add-tag event is auto-fired
					fire_rtdb_event(EV_ModifyTag, pTag);
				}				
			}					
		}
		close_handle(hGroup);
	}

	unlock_rtdb();

	return tagcount;
}
void dispatch_group_function() {
	long res;
	dispatch_group_t group;

	MU_BEGIN_TEST(dispatch_group_function);

	group = create_group(100, 0);
	MU_ASSERT_NOT_NULL(group);

	dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
	
	// should be OK to re-use a group
	dispatch_group_async_f(group, dispatch_get_global_queue(0, 0), 0, foo);
	dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

	dispatch_release(group);
	group = NULL;
	
	group = create_group(3, 7);
	MU_ASSERT_NOT_NULL(group);

	res = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC));
    MU_ASSERT_EQUAL(!res, 0);

	// retry after timeout (this time succeed)
	res = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC));
    MU_ASSERT_EQUAL(res, 0);

	dispatch_release(group);
	group = NULL;

	group = create_group(100, 0);
	MU_ASSERT_NOT_NULL(group);

	dispatch_group_notify_f(group, dispatch_get_main_queue(), 0, group_notify);
	
	dispatch_release(group);
	group = NULL;

	dispatch_main();

	MU_FAIL("Should never reach this");
	MU_END_TEST
}
LEMON_UNITTEST_CASE(RunQUnittest,GroupTest)
{
    runQ_service Q;

    job_id group = create_group(Q);

    LEMON_CHECK(LEMON_JOBID_IS_MULTICAST(group));

    GroupServer::create(Q,&group);

    Q.run();
}
Exemple #10
0
void groupadd(char* argv) {
    char* firstSpace = strchr(argv, ' ');
    if (firstSpace == NULL || strchr(firstSpace + 1, ' ') != NULL || strcmp(firstSpace + 1, "") == 0) {
        printf("Usage: groupadd GROUP\n"); 
        return;
    }
    
    if (create_group(firstSpace + 1) == -1) {
        printf("groupadd: could not create group\n");
        printf("groupadd: it seems as if maximum amount of groups have reached\n");
        printf("groupadd: try deleting some groups to make some room\n");
        return;
    }

    printf("Successfully created group.\n");
}
static __uint _on_add_edit_groups(PCRTK_PACKET p)
{
	RTK_CURSOR hNode, hGroup;
	PRTK_GROUP png, pg=0;
	__bool		bEdit;
	__uint count;

	if(p->data_size % sizeof(RTK_GROUP)){
		return 0;
	}
	if( !lock_rtdb(__true, 100) ){
		return 0;
	}
	hNode = HNODE_LOCAL_MACHINE;
	
	count = p->data_size / sizeof(RTK_GROUP);
	png = (PRTK_GROUP)p->data;
	bEdit = PACKET_TYPE(p) == PT_EditGroup? __true : __false;
	for(__uint i=0; i<count; i++, png++){
		hGroup = open_group(hNode, &png->key);
		pg = (PRTK_GROUP)cursor_get_item(hGroup);
		if(pg){
			memcpy(
				pg->description, 
				png->description, 
				sizeof(pg->description)
				);
			pg->period = png->period;
			fire_rtdb_event(EV_ModifyGroup, pg);
		}else{
			hGroup = create_group(hNode, png);
			pg = (PRTK_GROUP)cursor_get_item(hGroup);
		}
		if(pg){
			pg->d.flags = png->d.flags;
		}
		DEBUG_PRINTF((
			"Got group %s, flag=%08x\n", 
			(char *)CGroupName(png->key), 
			png->d.flags
			));
		close_handle(hGroup);		
	}
	unlock_rtdb();

	return count;
}
Exemple #12
0
void pim_router::created_group(group *grp) {
	pim_groupconf_node *ent =
		(pim_groupconf_node *)grp->conf()->create_child("pim");

	if (!ent)
		return;

	pim_group_node *node = create_group(grp->id(), grp->conf());
	if (node) {
		node->set_rp();
		if (!node->attach(grp, ent)) {
			if (should_log(WARNING)) {
				log().xprintf("Failed to attach pim node to "
					      "group %{Addr}\n", grp->id());
			}
		}
	} else if (should_log(WARNING)) {
		log().xprintf("Failed to attach pim node to group %{Addr}\n", grp->id());
	}
}
int main()
{
  int totalTime;
  totalTime = 0;
  int quantum;
  int op;
  int cpp = 0;
  pcbCtrl *ctrl;
  pcbStates *states;
  groupsCtrl *ctrlG;
  usersCtrl *ctrlU;
  ctrl = malloc(sizeof(pcbCtrl));
  states = malloc(sizeof(pcbStates));
  states->readys = malloc(sizeof(pcbCtrl));
  states->waiting = malloc(sizeof(pcbCtrl));
  states->sleeping = malloc(sizeof(pcbCtrl));
  ctrlG = malloc(sizeof(groupsCtrl));
  ctrlU = malloc(sizeof(usersCtrl));

  printf("\n");

  quantum = set_int("Quantum del programa", 1);

  if(val_npos(quantum, 1) != FAIL)
  {
    do
    {
      printf("\n \t\t<< SIMULACION DE ALGORITMO DE DESPACHO RONUD-ROBIN >>\n");
      print_options(0);
      printf("\n>");
      scanf("%i",&op);
      getchar();

      switch(op)
      {
        case 1:
        printf("\n");
          create_group(ctrlG);
          break;
        case 2:
        printf("\n");
          create_user(ctrlU);
          break;
        case 3:
        printf("\n");
          create_process(cpp,ctrl,states,ctrlG,ctrlU);
          cpp++;
          break;
        case 4:
        printf("\n");
          state_change(ctrl,states);
          break;
        case 5:
        printf("\n");
          show_everything(ctrl,states,ctrlG,ctrlU);
          break;
        case 6:
        printf("\n");
          rr(states, ctrl, quantum, &totalTime);
          break;
        case 7:
        printf("\n");
          del_option(ctrl,states,ctrlG,ctrlU);
          break;
        case 8:
          break;
        default:
          printf("Opcion invalida, vuelva a intentarlo.\n");
      }
    }while(op != 8);

    if(ctrl->front != NULL)
    {
      pcb *aux = ctrl->front;
      while( next_pcb(&aux,ctrl->front) != FAIL )
      free(aux);
    }

    if(ctrlG->front != NULL)
    {
      groups *aux = ctrlG->front;
      while( next_group(&aux,ctrlG->front) != FAIL )
      free(aux);
    }

    if(ctrlU->front != NULL)
    {
      users *aux = ctrlU->front;
      while( next_user(&aux,ctrlU->front) != FAIL )
      free(aux);
    }

    free(ctrl->front);
    free(ctrlG->front);
    free(ctrlU->front);
    free(ctrl);
    free(ctrlG);
    free(ctrlU);
  }

  return 0;
}
Exemple #14
0
void GUser_Data_Tools::loaddata(std::string filename, int rename_onfail)
{
	struct user_data * u_data;
	char *tmpdata;
	int count = 0;
	FILE *myfile;
	struct stat fileinfo;

	clear();

	if (!filename.length()) {
		ng_slogerror(log_str,"can not load - got emtpy filename");
		return;
	}
	
	ng_slogext(log_str,2500,"loading data from %s",filename.c_str());	

	if (stat(filename.c_str(),&fileinfo)) {
		ng_slogerror(log_str,"cant stat data file %s",filename.c_str());
		return;
	}
	myfile = fopen(filename.c_str(), "r");
	if (!myfile) {
		ng_slogerror(log_str,"cant open data file %s",filename.c_str());
		return;
	}

	tmpdata = (char*)malloc(sizeof(unsigned char)*(strlen(GACC_DATA_VERSION_MAGIC)+1));
	tmpdata[strlen(GACC_DATA_VERSION_MAGIC)] = 0;

	count = fread(&tmpdata[0],strlen(GACC_DATA_VERSION_MAGIC),1,myfile);
	if ((count != 1) || strcmp(tmpdata,GACC_DATA_VERSION_MAGIC) ) {
		ng_slogerror(log_str,"cant read group data from %s - illegal format (%s <> %s)",filename.c_str(),(char *)tmpdata,GACC_DATA_VERSION_MAGIC);

		if (rename_onfail)
		{
			free(tmpdata);
			tmpdata = (char*)malloc(sizeof(unsigned char)*(strlen(filename.c_str())+20));
			time_t now;
			time(&now);		/* get the current time */
			sprintf(tmpdata,"%s_%d",filename.c_str(),(int)now);
			ng_slogerror(log_str,"renaming file to %s",tmpdata);
			rename(filename.c_str(),tmpdata);
		}
		free(tmpdata);
		return;
	}

	ng_slogext(log_str,2500,"loading %lu bytes data",fileinfo.st_size);

	off_t f_pos =  ftell(myfile);
	int counter = 0;
	while ( (unsigned int)(fileinfo.st_size - f_pos - strlen(GACC_DATA_VERSION_MAGIC)) >= sizeof(struct user_data) ) {
		NetGuard_Config mydata;

		if (!mydata.loaddata(myfile)) {
			ng_slogerror(log_str,"cant group data file from %s - illegal format - additonal data - renaming file",filename.c_str());
			clear();
			free(tmpdata);
			return;
		};

		Group_Data *gdata = create_group(mydata.GetStr("name"));
		unsigned int mc;
		fread(&mc,sizeof(unsigned int),1, myfile);

		for(unsigned int i=1;i<=mc;i++) {
			struct guser_data_idx myudata;
			fread(&myudata,sizeof(struct guser_data_idx),1, myfile);
			gdata->add_member(myudata.saddr,myudata.vlan_id);
		}

		//load traffic data
		u_data = gdata->GetData();
		fread(u_data,sizeof(struct user_data),1, myfile);		
		//loaded module data is not assigned yet modules have to take care about this
		memset(&u_data->module_data,0,MAX_MODULES * sizeof(void *));

		//load limits
		user_limit_data *ldata=  gdata->GetLimits();
		fread(ldata,sizeof(struct user_limit_data),1, myfile);

		ng_slogext(log_str,2500,"loaded group s%",gdata->name.c_str());

		counter++;
		f_pos =  ftell(myfile);
	}

	count = fread(tmpdata,strlen(GACC_DATA_VERSION_MAGIC),1,myfile);
	if ((count != 1) || strcmp(tmpdata,GACC_DATA_VERSION_MAGIC) ) {
		ng_slogerror(log_str,"cant traffic data file (end) from %s - illegal format - renaming file",filename.c_str());

		if (rename_onfail)
		{
			free(tmpdata);
			tmpdata = (char*)malloc(sizeof(unsigned char)*(strlen(filename.c_str())+20));
			time_t now;
			time(&now);		/* get the current time */
			sprintf(tmpdata,"%s_%d",filename.c_str(),(int)now);
			ng_slogerror(log_str,"renaming file to %s",tmpdata);
			rename(filename.c_str(),tmpdata);
		}

		clear();
		free(tmpdata);
		return;
	}

	ng_slogext(log_str,2100,"loaded %d groups",counter);

	fclose(myfile);
	free(tmpdata);
}
Exemple #15
0
/***********************
        Main
 **********************/
int
main(int argc, char *argv[])
{
    setup_home();

    int g = 0;
    int x = 0;
    int V = 0;
    int c = 0;
    int l = 0;
    int e = 0;
    int d = 0;
    int u = 0;
    int h = 0;
    int G = 0;
    int T = 0;
    int C = 0;
    int M = 0;
    int N = 0;
    char * group;
    char * label;
    char * content;
    int opt ;
    while((opt= getopt(argc,argv, "V(verbose)g:x(execute)c(create)l(list)e(echo):d(drop):u(edit):h(help)G(group):T(template):C(command)::M(macro)::N(note)::"))!= -1)
    {
        switch(opt)
        {
        case 'g':
            g=1;
            group = optarg;
            break;
        case 'V':
            V = 1;
            break;
        case 'x':
            x = 1;
            break;
        case 'c':
            c = 1;
            break;
        case 'l':
            l = 1;
            break;
        case 'e':
            e = 1;
            label = argv[optind];
            break;
        case 'd':
            d = 1;
            label = argv[optind];
            break;
        case 'u':
            u = 1;
            label = argv[optind];
            break;
        case 'h':
            h = 1;
            break;
        case 'G':
            G = 1;
            label = argv[optind];
            break;
        case 'T':
            T = 1;
            label = argv[optind];
            break;
        case 'C':
            C = 1;
            label = argv[optind];
            content = argv[optind+1];
            break;
        case 'N':
            N = 1;
            label = argv[optind];
            content = argv[optind+1];
            break;
        default:
            puts("test");
            break;


        }
    }
    if(g == 1)
    {
        if(c == 1)
        {
            if(G ==1)
            {
                create_group(label);
                //break;
            }
            else if(N == 1)
            {
                create_note(group, label, content);
                //break;
            }

            else if(C == 1)
            {
                create_command(label,group,content);
                //break;
            }
            else if(T == 1)
            {
                create_template_from_current(group,label);
                //break;
            }
            else
            {
                puts("Invalid Command");
                return -1;
            }
        }

        if(e == 1)
        {
            if(N == 1)
            {
                echo_note(group,label);
            }
            else if( C == 1)
            {
                echo_command(label, group);
            }
            else if (T == 1)
            {
                echo_template(label, group);
            }
        }
        else if(l == 1)
        {
            if(N == 1)
            {
                list_notes(group);
                //break;
            }
            else if(C == 1)
            {
                list_commands(group);
                //break;
            }
            else if(T == 1)
            {
                list_templates(group);
            }
            else
            {
                puts("Invalid Command");
                return -1;
            }
        }
        else if(x == 1)
        {
            if(C == 1)
            {
                execute_command(group,label);
                //break;
            }
            else if(T == 1)
            {
                execute_template(group,label);
            }
            else
            {
                puts("Invalid Command");
                return -1;
            }
        }

    }
    else if(c == 1)
    {
        if(G == 1)
        {
            create_group(label);
            //break;
        }
        else
        {
            puts("Invalid Command");
            return -1;
        }
    }
    else if(e == 1)
    {
        if(G == 1)
        {
            echo_group(label);
        }
    }




    return 0;
}
__uint _on_add_edit_tags(PCRTK_PACKET p, bool bGenerateEvents)
{
	ONLINE_CONFIG::reload_tags_ack *ack;
	RTK_CURSOR	hNode, hTag, hGroup;
	RTK_TAG		*pTag;
	NODE_KEY	nodekey;
	TAG_NAME	name;
	RTK_GROUP	grp;
	__bool bEditing;
	
	__uint tagcount, i;

	ack = (ONLINE_CONFIG::reload_tags_ack *)p->data;
	tagcount = p->data_size / sizeof(*ack);
	if(p->data_size % sizeof(*ack)){
		return 0;
	}
	if(!tagcount){
		return 0;
	}
	ZeroMemory(&grp, sizeof(grp));

	if((PACKET_TYPE(p) == PT_DiscoverTags) && g_Worker){
		TAG_NAME tn;
		memset(&tn, 0, sizeof(tn));
		tn.node = ack[0].tag.node;
		tn.sname.group = ack[0].tag.group;
		g_Worker->cancel_load(&tn);
	}

	if(!lock_rtdb(__true, 100)){
		return 0;
	}

	host_to_node(&p->src.host, &nodekey);
	hNode = create_node(&nodekey, 0);
	hTag = hGroup = 0;
	name.node = nodekey;
	grp.node = nodekey;
	if(hNode){
		for(i=0; i<tagcount; i++){
			hGroup = open_group(hNode, &ack[i].tag.group);
			grp.key = ack[i].tag.group;
			if(!hGroup){
				hGroup = create_group(hNode, &grp);
			}
			if(hGroup){
				bEditing = query_tag_g(hGroup, &ack[i].tag.key)? __true : __false;
				hTag = create_tag(hGroup, &ack[i].tag.key, &ack[i].tag.s);
				pTag  = (RTK_TAG*)cursor_get_item(hTag);
				if(pTag){
					*pTag = ack[i].tag;
					/*
						2003/5/27, leave tag's dynamic flags as they were
						2003/6/24, mark tag as newly received, but the valid flag
						is kept as set by server
					*/
					mark_fresh(pTag);
					close_handle(hTag);
					if(bGenerateEvents){
						name.sname.group = ack[i].tag.group;
						name.sname.tag   = ack[i].tag.key;
						rtk_queue_event(PT_AddTag, &name, &p->src);
					}
					if(bEditing){
						fire_rtdb_event(EV_ModifyTag, pTag);
					}
				}					
			}
			close_handle(hGroup);
		}
		close_handle(hNode);
	}

	unlock_rtdb();

	return tagcount;
}
Exemple #17
0
void message_handle(kolibri_IPC_message_t *message){
	char *msg = (char *)message+sizeof(kolibri_IPC_message_t);
	char cmd = msg[0];
	thread_list_t *thread = find_tid(main_group_list, message->tid);
	group_list_t *group;
	int i;
	
	if (cmd == KOBRA_CMD_REGISTER && !thread) {
		kobra_register(message->tid);
	} else if (thread) {
		switch (cmd) {
			case KOBRA_CMD_JOIN:
				if (message->length < 3 || msg[message->length-1] != '\0') {
					// Here should be some error handler
					return;
				}
				
				if (!(group = find_group(msg+1))){
					group = create_group(msg+1);
				}
				add_to_group(group, message->tid);
				break;
			case KOBRA_CMD_UNJOIN:
				if (message->length < 3 || msg[message->length-1] != '\0') {
					// Here should be some error handler
					return;
				}
				
				if ((group = find_group(msg+1)) && (thread = find_tid(group, message->tid))) {
					remove_from_group(group, thread);
				}
				break;
			case KOBRA_CMD_SEND:
				if (message->length < 4) {
					// Here should be some error handler
					return;
				}
				
				// Check if group name is correct
				for (i = 1; i < message->length-1 && msg[i]; ++i);
				if (msg[i]) {
					// Here should be some error handler
					return;
				}
				
				group = find_group(msg+1);
				if (!group) {
					// Here should be some error handler
					return;
				}
				
				send_group_message(group, message->tid, msg+i+1, message->length-i-1);
				break;
			case KOBRA_CMD_GET_LIST_NAME:
				// This is temporary realisation
				kolibri_IPC_send(message->tid, KOBRA_MEMAREA_NAME, KOBRA_MEMAREA_NAME_LENGTH);
			default:
				// Here should be some error handler
				return;
		}
	}
}
/* The worker thread function with all the complex
 * logic in it! Big fat beast! Please watch your
 * children ... */
static void
synch_worker (struct account_synch_msg *m)
{
    ScalixAccountSynch *sxas;
    ScalixAccountSynchPrivate *priv;
    CamelException ex;
    CamelStore *store;
    CamelFolderInfo *ftree;
    CamelFolderInfo *sf;
    CamelSession *cs;
    const char *uri;
    gboolean res;
    char *sversion;
    char *markup;

    sxas = SCALIX_ACCOUNT_SYNCH (m->sxas);
    priv = SCALIX_ACCOUNT_SYNCH_GET_PRIVATE (sxas);

    uri = e_account_get_string (priv->account, E_ACCOUNT_SOURCE_URL);

    g_print ("SxAS: starting synch for %s\n", uri);

    signal_progress (sxas, 1, _("Trying to connect to server"));

    camel_exception_init (&ex);
    cs = scalix_camel_session_get_default ();
    camel_session_set_online (cs, TRUE);

    store = camel_session_get_store (cs, uri, &ex);

    if (store == NULL) {
        signal_error (sxas, _("Authentication failed. Check for correct hostname, username and password."));
        return;
    }

    /* Must be online! */
    camel_offline_store_set_network_state (CAMEL_OFFLINE_STORE (store),
                                           CAMEL_OFFLINE_STORE_NETWORK_AVAIL,
                                           &ex);

    camel_service_connect (CAMEL_SERVICE (store), &ex);

    if (camel_exception_is_set (&ex)) {
        signal_error (sxas, _("Error while trying to connect to server."));
        return;
    }

    /* Always check for minimal required server version  */
    signal_progress (sxas, 10, _("Checking version of Scalix server"));
    g_print ("SxAS: Checking for minimal server version\n");

    sversion = NULL;
    camel_object_get (store, NULL,
                      CAMEL_SCALIX_STORE_SERVER_VERSION, &sversion, NULL);

    res = scalix_check_min_server_version (sversion);

    if (res == FALSE) {
        signal_error (sxas, _("Wrong version of Scalix server detected"));
        return;
    }

    m->sversion = g_strdup (sversion);
    g_print ("SxAS: sversion:%s\n", m->sversion);

    markup = g_markup_printf_escaped (MSG_SVER, sversion);
    signal_info (sxas, markup);
    g_free (markup);

    signal_progress (sxas, 20, _("Getting list of folders"));
    ftree = camel_store_get_folder_info (store,
                                         NULL,
                                         CAMEL_STORE_FOLDER_INFO_RECURSIVE |
                                         CAMEL_SCALIX_STORE_SHOW_SFOLDER, &ex);

    if (ftree == NULL) {
        camel_object_unref (store);
        signal_error (sxas, _("Could not obtain folder listening"));
        return;

    }

    /* Calendar  */
    signal_progress (sxas, 30, _("Loading calendar data..."));
    synch_data (sxas, ftree, CAMEL_SCALIX_FOLDER_CALENDAR, 30);

    m->esg_cals = create_group (priv->account, "Calendar");
    sync_source_group (priv->account,
                       m->esg_cals, CAMEL_SCALIX_FOLDER_CALENDAR, ftree);

    /* Contacts */
    signal_progress (sxas, 60, _("Loading contacts..."));
    synch_data (sxas, ftree, CAMEL_SCALIX_FOLDER_CONTACT, 60);

    m->esg_cnts = create_group (priv->account, "Contacts");
    sync_source_group (priv->account,
                       m->esg_cnts, CAMEL_SCALIX_FOLDER_CONTACT, ftree);

    create_ldap_source (priv->account, m->esg_cnts);

    /* Sent Items and Drafts Folder */
    if (priv->synch_dfolder) {
        char *url_str;
	CamelURL *url;

	url = camel_url_new (uri, NULL);

        signal_progress (sxas, 95, _("Synchronizing additional data"));

        sf = folder_tree_find_special (ftree, CAMEL_SCALIX_FOLDER_SENT);

        if (url && sf) {
	    url_str = url_set_path_and_get_string (url, sf->full_name);

            e_account_set_string (priv->account,
                                  E_ACCOUNT_SENT_FOLDER_URI, url_str);
            g_free (url_str);
        }

        sf = folder_tree_find_special (ftree, CAMEL_SCALIX_FOLDER_DRAFTS);

        if (url && sf) {
	    url_str = url_set_path_and_get_string (url, sf->full_name);
            e_account_set_string (priv->account,
                                  E_ACCOUNT_DRAFTS_FOLDER_URI, url_str);

            g_free (url_str);
        }

        if (url) {
            gboolean save_pw;

            camel_url_set_path (url, NULL);

            if (url->authmech == NULL) {
		    camel_url_set_authmech (url, "PLAIN");
            }

	    url_str = camel_url_to_string (url, 0);
            e_account_set_string (priv->account,
                                  E_ACCOUNT_TRANSPORT_URL, url_str);

            save_pw = e_account_get_bool (priv->account,
                                          E_ACCOUNT_SOURCE_SAVE_PASSWD);

            e_account_set_bool (priv->account,
                                E_ACCOUNT_TRANSPORT_SAVE_PASSWD, save_pw);
        }

        if (url) {
		camel_url_free (url);
        }
    }

    m->success = TRUE;

    g_print ("SxAS: DONE!\n");

    camel_object_unref (store);
    signal_progress (sxas, 100, _("Done loading"));
    signal_info (sxas, _("Initial loading complete. Please click Forward."));
    g_print ("SxAS: Freeing DONE\n");
    return;
}
Exemple #19
0
int cfg_read(Cfg *cfg) 
{ 
    CfgLoc *loc; 
    CfgLoc *loc_inc; 
    List *lines;
    List *expand; 
    List *stack; 
    Octstr *name;
    Octstr *value;
    Octstr *filename; 
    CfgGroup *grp;
    long equals;
    long lineno;
    long error_lineno;
    
    loc = loc_inc = NULL;

    /* 
     * expand initial main config file and add it to the recursion 
     * stack to protect against cycling 
     */ 
    if ((lines = expand_file(cfg->filename, 1)) == NULL) { 
        panic(0, "Failed to load main configuration file `%s'. Aborting!", 
              octstr_get_cstr(cfg->filename)); 
    } 
    stack = gwlist_create(); 
    gwlist_insert(stack, 0, octstr_duplicate(cfg->filename)); 

    grp = NULL;
    lineno = 0;
    error_lineno = 0;
    while (error_lineno == 0 && (loc = gwlist_extract_first(lines)) != NULL) { 
        octstr_strip_blanks(loc->line); 
        if (octstr_len(loc->line) == 0) { 
            if (grp != NULL && add_group(cfg, grp) == -1) { 
                error_lineno = loc->line_no; 
                destroy_group(grp); 
            } 
            grp = NULL; 
        } else if (octstr_get_char(loc->line, 0) != '#') { 
            equals = octstr_search_char(loc->line, '=', 0); 
            if (equals == -1) { 
                error(0, "An equals sign ('=') is missing on line %ld of file %s.", 
                      loc->line_no, octstr_get_cstr(loc->filename)); 
                error_lineno = loc->line_no; 
            } else  
             
            /* 
             * check for special config directives, like include or conditional 
             * directives here 
             */ 
            if (octstr_search(loc->line, octstr_imm("include"), 0) != -1) { 
                filename = octstr_copy(loc->line, equals + 1, octstr_len(loc->line)); 
                parse_value(filename); 
 
                /* check if we are cycling */ 
                if (gwlist_search(stack, filename, octstr_item_match) != NULL) { 
                    panic(0, "Recursive include for config file `%s' detected " 
                             "(on line %ld of file %s).", 
                          octstr_get_cstr(filename), loc->line_no,  
                          octstr_get_cstr(loc->filename)); 
                } else {     
                    List *files = gwlist_create();
                    Octstr *file;
                    struct stat filestat;

                    /* check if included file is a directory */
                    if (lstat(octstr_get_cstr(filename), &filestat) != 0) {
                        error(errno, "lstat failed: couldn't stat `%s'", 
                              octstr_get_cstr(filename));
                        panic(0, "Failed to include `%s' "
                              "(on line %ld of file %s). Aborting!",  
                              octstr_get_cstr(filename), loc->line_no,  
                              octstr_get_cstr(loc->filename)); 
                    }
                    
                    /* 
                     * is a directory, create a list with files of
                     * this directory and load all as part of the
                     * whole configuration.
                     */
                    if (S_ISDIR(filestat.st_mode)) {
                        DIR *dh;
                        struct dirent *diritem;

                        debug("gwlib.cfg", 0, "Loading include dir `%s' "
                              "(on line %ld of file %s).",  
                              octstr_get_cstr(filename), loc->line_no,  
                              octstr_get_cstr(loc->filename)); 

                        dh = opendir(octstr_get_cstr(filename));
                        while ((diritem = readdir(dh))) {
                            Octstr *fileitem;

                            fileitem = octstr_duplicate(filename);
                            octstr_append_cstr(fileitem, "/");
                            octstr_append_cstr(fileitem, diritem->d_name);

                            lstat(octstr_get_cstr(fileitem), &filestat);
                            if (!S_ISDIR(filestat.st_mode)) {
                                gwlist_insert(files, 0, fileitem);
                            } else {
                            	octstr_destroy(fileitem);
                            }
                        }
                        closedir(dh);
                    } 
		    
                    /* is a file, create a list with it */
                    else {
                        gwlist_insert(files, 0, octstr_duplicate(filename));
                    }

                    /* include files */
                    while ((file = gwlist_extract_first(files)) != NULL) {

                        gwlist_insert(stack, 0, octstr_duplicate(file)); 
                        debug("gwlib.cfg", 0, "Loading include file `%s' (on line %ld of file %s).",  
                              octstr_get_cstr(file), loc->line_no,  
                              octstr_get_cstr(loc->filename)); 

                        /*  
                         * expand the given include file and add it to the current 
                         * processed main while loop 
                         */ 
                        if ((expand = expand_file(file, 0)) != NULL) {
                            while ((loc_inc = gwlist_extract_first(expand)) != NULL) 
                                gwlist_insert(lines, 0, loc_inc); 
                        } else { 
                            panic(0, "Failed to load whole configuration. Aborting!"); 
                        } 
                 
                        gwlist_destroy(expand, NULL); 
                        cfgloc_destroy(loc_inc);
                        octstr_destroy(file);
                    }
                    gwlist_destroy(files, octstr_destroy_item);
                } 
                octstr_destroy(filename); 
            }  
             
            /* 
             * this is a "normal" line, so process it accodingly 
             */ 
            else  { 
                name = octstr_copy(loc->line, 0, equals); 
                octstr_strip_blanks(name); 
                value = octstr_copy(loc->line, equals + 1, octstr_len(loc->line)); 
                parse_value(value); 
 
    	    	if (grp == NULL)
                    grp = create_group(); 
                 
                if (grp->configfile != NULL) {
                    octstr_destroy(grp->configfile); 
                    grp->configfile = NULL;
                }
                grp->configfile = octstr_duplicate(cfg->filename); 

                cfg_set(grp, name, value); 
                octstr_destroy(name); 
                octstr_destroy(value); 
            } 
        } 

        cfgloc_destroy(loc); 
    }

    if (grp != NULL && add_group(cfg, grp) == -1) {
        error_lineno = 1; 
        destroy_group(grp); 
    }

    gwlist_destroy(lines, NULL); 
    gwlist_destroy(stack, octstr_destroy_item); 

    if (error_lineno != 0) {
        error(0, "Error found on line %ld of file `%s'.",  
	          error_lineno, octstr_get_cstr(cfg->filename)); 
        return -1; 
    }

    return 0;
}
Exemple #20
0
/* ADAPTIVE_SNR
 * ------------
 * Input parameters:
 *   dataCol   - the column with the data
 *   numChans  - number of channels in groupCol and qualCol
 *   snr       - the signal-to-noise ratio threshold
 *   groupCol  - the GROUPING column
 *   qualCol   - the QUALITY column
 *   tabStops  - array giving channels with tabs or stops
 *   errorCol  - optional error column
 *   useErr    - if true, use errorCol data, else use counts
 *   maxLength - maximum size of groups
 */
int grp_do_adaptive_snr(double *dataCol, long numChans, double snr,
                        short *groupCol, short *qualCol,
                        short *tabStops, double *errorCol,
                        short useErr, double maxLength,
                        dsErrList *errList){

   long ii, jj, tempLength, tempMax, counter = 0;
   long curWidth = 0;
   double runningSnr    = 0.0;
   double runningSignal = 0.0;
   double runningNoise  = 0.0;
   short *usedChans;
   int returnVal = GRP_SUCCESS;

    /* Check for obviously bad inputs */
    if(!dataCol || (numChans <= 0) || (snr <= 0) || !groupCol
       || !qualCol || !tabStops || !errorCol){
        if(errList)
            dsErrAdd(errList, dsDMGROUPBADPARAMERR, Accumulation,
                     Generic);
        else
            err_msg("ERROR: At least one input parameter has an "
                    "invalid value.\n");
        return(GRP_ERROR);
    }
    
    if(maxLength <= 0.0)
       maxLength = MAX_BIN_LENGTH;
   
   /* Create used channel list */
   usedChans = (short *) calloc(numChans, sizeof(short));
   for(ii = 0; ii < numChans; ii++){
      if(tabStops[ii] || (qualCol[ii] != 0))
         usedChans[ii] = GRP_TRUE;
      else
         usedChans[ii] = GRP_FALSE;
   }
   /* Main loop through adaptive group sizes */
   while((curWidth + 1) <= maxLength){
      curWidth++;

      /* Determine maxLength each time as it might be limited */
      tempLength = 0;
      tempMax = 0;
      for(ii = 0; ii < numChans; ii++){
         if(!usedChans[ii]){
            tempLength++;
            if(tempLength > tempMax)
               tempMax = tempLength;
         }
         else
            tempLength = 0;
      }
      if(tempMax < maxLength)
         maxLength = tempMax;

      /* Iterate over each row for each group size */
      for(ii = 0; ii < (numChans - curWidth); ii++){
         if(usedChans[ii]) continue;
         runningSnr = 0.0;
	 runningSignal = 0.0;
	 runningNoise = 0.0;
         /* Try to make groups of the current width */
         for(jj = 0; jj < curWidth; jj++){
            if(usedChans[ii + jj]){
               runningSnr = 0.0;
	       runningSignal = 0.0;
	       runningNoise = 0.0;
               break;
            }
            if(useErr){
                if(!errorCol[ii + jj]){
                    if(errList)
                        dsErrAdd(errList, dsDMGROUPZEROERRORERR,
                                 Accumulation, Generic);
                    else
                        err_msg("WARNING: The supplied error column "
                                "contains zero-valued data.");
                    returnVal = GRP_WARNING;
                }
                else {
                    runningSnr += pow((dataCol[ii + jj] /
                                       errorCol[ii + jj]), 2);
		    runningSignal += dataCol[ii+jj];
		    runningNoise += (errorCol[ii+jj]*errorCol[ii+jj]);
		    runningSnr = runningSignal/runningNoise;
		    runningSnr *= runningSnr;

		}
            }
            else if(dataCol[ii + jj]) {
	      runningSignal += dataCol[ii];
	      runningSnr = runningSignal;
	    }
            if(jj == (curWidth - 1)){
               if(sqrt(runningSnr) > snr){
                  /* Enough counts - let's group it */
                  mark_used(usedChans, ii, ii + jj);
                  create_group(groupCol, ii, ii + jj);
                  set_quality(qualCol, GRP_GOOD, ii, ii + jj);
               }
            }
         } /* end for(jj) */
      } /* end for(ii) */
   } /* end while() */

   /* Put unused channels into "bad" groups */
   for(ii = 0; ii < numChans; ii++){
      /* Are we in a used channel? */
      if(usedChans[ii]){
         if(counter != 0){
            set_incomplete(groupCol, qualCol, ii - counter, ii - 1);
            counter = 0;
         }
      }
      /* Are we at the end of the table? */
      else if(ii == (numChans - 1)){
         /* Does this complete a group? */
         if(counter != 0)
            set_incomplete(groupCol, qualCol, ii - counter, ii);
         else
            set_incomplete(groupCol, qualCol, ii, ii);
      }
      /* Are we at the end of a group */
      else if(usedChans[ii + 1]){
         set_incomplete(groupCol, qualCol, ii - counter, ii);
         counter = 0;
      }
      /* Are we at the beginning of a group? */
      else{
         counter++;
      }
   } /* end for(ii) */

   free(usedChans);
   return(GRP_SUCCESS);
}
Exemple #21
0
/* ADAPTIVE
 * --------
 * Input parameters:
 *   dataCol   - the column with the data
 *   numChans  - number of channels in groupCol and qualCol
 *   minCounts - the minimum number of counts desired in each group
 *   groupCol  - the GROUPING column
 *   qualCol   - the QUALITY column
 *   tabStops  - array giving channels with tabs or stops
 *   maxLength - maximum size of groups
 */
int grp_do_adaptive(double *dataCol, long numChans, double minCounts,
                    short *groupCol, short *qualCol, short *tabStops,
                    double maxLength, dsErrList *errList){
    
    short *usedChans;
    long ii, jj, tempLength, tempMax, curWidth = 0;
    long counter = 0;
    double groupCounts = 0.0;

    /* Check for obviously bad inputs */
    if(!dataCol || (numChans <= 0) || (minCounts <= 0) || !groupCol
       || !qualCol || !tabStops){
        if(errList)
            dsErrAdd(errList, dsDMGROUPBADPARAMERR, Accumulation,
                     Generic);
        else
            err_msg("ERROR: At least one input parameter has an "
                    "invalid value.\n");
        return(GRP_ERROR);
    }
    
    if(maxLength <= 0.0)
        maxLength = MAX_BIN_LENGTH;
   
    /* Create and initialize used channel list */
    usedChans = (short *) calloc(numChans, sizeof(short));
    for(ii = 0; ii < numChans; ii++){
        if(tabStops[ii] || (qualCol[ii] != 0))
            usedChans[ii] = GRP_TRUE;
        else
            usedChans[ii] = GRP_FALSE;
    }
    
    /* Main loop through adaptive group sizes */
    while((curWidth + 1) <= maxLength){
        curWidth++;
        
        /* Determine maxLength each time as it might be limited */
        tempLength = 0;
        tempMax = 0;
        for(ii = 0; ii < numChans; ii++){
            if(!usedChans[ii]){
                tempLength++;
                if(tempLength > tempMax)
                    tempMax = tempLength;
            }
            else
                tempLength = 0;
        }
        if(tempMax < maxLength)
            maxLength = tempMax;
        
        /* Iterate over each row for each group size */
        for(ii = 0; ii < (numChans - curWidth); ii++){
            if(usedChans[ii]) continue;
            groupCounts = 0.0;
            /* Try to make groups of the current width */
            for(jj = 0; jj < curWidth; jj++){
                if(usedChans[ii + jj])
                    break;
                groupCounts += dataCol[ii + jj];
                if(jj == curWidth - 1){
                    if(groupCounts >= minCounts){
                        /* Enough counts - let's group it */
                        mark_used(usedChans, ii, ii + jj);
                        create_group(groupCol, ii, ii + jj);
                        set_quality(qualCol, GRP_GOOD, ii, ii + jj);
                    }
                }
            } /* end for(jj) */
        } /* end for(ii) */
    } /* end while() */
    
    /* Put unused channels into "bad" groups */
    for(ii = 0; ii < numChans; ii++){
        /* Are we in a used channel? */
        if(usedChans[ii]){
            if(counter != 0){
                set_incomplete(groupCol, qualCol, ii - counter,
                               ii - 1);
                counter = 0;
            }
        }
        /* Are we at the end of the table? */
        else if(ii == (numChans - 1)){
            /* Does this complete a group? */
            if(counter != 0)
                set_incomplete(groupCol, qualCol, ii - counter, ii);
            else
                set_incomplete(groupCol, qualCol, ii, ii);
        }
        /* Are we at the end of a group */
        else if(usedChans[ii + 1]){
            set_incomplete(groupCol, qualCol, ii - counter, ii);
            counter = 0;
        }
        /* Are we at the beginning of a group? */
        else{
            counter++;
        }
    } /* end for(ii) */
    
    free(usedChans);
    return(GRP_SUCCESS);
}
Exemple #22
0
/* MAX_SLOPE
 * ---------
 * Input parameters:
 *   dataCol   - the column representing the independent axis
 *   binCol    - the column with the data values
 *   numChans  - number of channels in groupCol and qualCol
 *   slope     - the maximum slope threshold
 *   groupCol  - the GROUPING column
 *   qualCol   - the QUALITY column
 *   tabStops  - array giving channels with tabs or stops
 *   maxlength - maximum size of groups
 */
int grp_do_max_slope(double *dataCol, double *binCol, long numChans,
                     double slope, short *groupCol, short *qualCol,
                     short *tabStops, double maxlength,
                     dsErrList *errList){
    
    long ii, jj, counter = 0;
    double range = 0.0;
    double tempSlope = 0.0;
    short *usedChans;
    
    /* Check for obviously bad inputs */
    if(!dataCol || !binCol || (numChans < 2) || (slope <= 0)
       || !groupCol || !qualCol || !tabStops){
        if(errList)
            dsErrAdd(errList, dsDMGROUPBADPARAMERR, Accumulation,
                     Generic);
        else
            err_msg("ERROR: At least one input parameter has an "
                    "invalid value.\n");
        return(GRP_ERROR);
    }
    
    if(maxlength <= 0.0)
        maxlength = MAX_BIN_LENGTH;
    
    /* Create and initialize used channel list */
    usedChans = (short *) calloc(numChans, sizeof(short));
    for(ii = 0; ii < numChans; ii++){
        if(tabStops[ii] || (qualCol[ii] != 0))
            usedChans[ii] = GRP_TRUE;
        else
            usedChans[ii] = GRP_FALSE;
    }
    
    ii = 0;
    jj = 1;
    while(ii < (numChans - 1)){
        
        /* Are we in a tab or stop? */
        if(tabStops[ii]){
            ii++;
            jj = (ii + 1);
        }
        else{
            while(jj < numChans){
                
                /* Calculate current slope */
                tempSlope = fabs(((binCol[jj] - binCol[ii])
                                  / (dataCol[jj] - dataCol[ii])));
                
                range = (dataCol[jj] - dataCol[ii]);
                
                /* Are we in a tab or stop? */
                if(tabStops[jj]){
                    ii++;
                    jj = (ii + 1);
                    break;
                }
                /* Are we at the end of the table? */
                else if(jj == (numChans - 1)){
                    /* Does this complete a group? */
                    if((tempSlope >= slope) ||
                       (range >= maxlength)){
                        mark_used(usedChans, ii, jj);
                        create_group(groupCol, ii, jj);
                        set_quality(qualCol, GRP_GOOD, ii, jj);
                        ii = jj;
                        break;
                    }
                    else{
                        ii++;
                        jj = (ii + 1);
                        break;
                    }
                }
                /* Are we at the end of a group or have reached
                 * maxlength? */
                else if((tempSlope >= slope) ||
                        (range >= maxlength)){
                    mark_used(usedChans, ii, jj);
                    create_group(groupCol, ii, jj);
                    set_quality(qualCol, GRP_GOOD, ii, jj);
                    ii = (jj + 1);
                    jj = (ii + 1);
                    break;
                }
                /* Keep looking */
                else jj++;
                
            } /* end while(jj) */
        } /* end if */
    } /* end while(ii) */
    
    /* Put unused channels into "bad" groups */
    for(ii = 0; ii < numChans; ii++){
        /* Are we in a used channel? */
        if(usedChans[ii]){
            if(counter != 0){
                set_incomplete(groupCol, qualCol, ii - counter,
                               ii - 1);
                counter = 0;
            }
        }
        /* Are we at the end of the table? */
        else if(ii == (numChans - 1)){
            /* Does this complete a group? */
            if(counter != 0)
                set_incomplete(groupCol, qualCol, ii - counter, ii);
            else
                set_incomplete(groupCol, qualCol, ii, ii);
        }
        /* Are we at the end of a group */
        else if(usedChans[ii + 1]){
            set_incomplete(groupCol, qualCol, ii - counter, ii);
            counter = 0;
        }
        /* Are we at the beginning of a group? */
        else{
            counter++;
        }
    } /* end for(ii) */
    
    free(usedChans);
    return(GRP_SUCCESS);
}
Exemple #23
0
static bool UseIShellLink( bool uninstall )
/*****************************************/
{
    WORD                dir_index, icon_number;
    int                 i, num_icons, num_groups;
    int                 num_installed, num_total_install;
    DWORD               temp;
    char                prog_name[_MAX_PATH], prog_desc[_MAX_PATH];
    char                icon_name[_MAX_PATH], working_dir[_MAX_PATH];
    char                group[_MAX_PATH], prog_arg[_MAX_PATH], tmp[_MAX_PATH];
    BOOL                rc;

    if( uninstall ) {
        num_groups = SimGetNumPMGroups();
        for( i = 0; i < num_groups; i++ ) {
            SimGetPMGroupName( i, group );
            if( *group != '\0' ) {
                // Delete the PM Group box
                remove_group( group );
            }
        }
        return( TRUE );
    }

    SimGetPMGroup( group );
    if( group[0] == '\0' ) {
        return( TRUE );
    }

    CoInitialize( NULL );

    // Create the PM Group box.
    if( !create_group( group ) ) {
        CoUninitialize();
        return( FALSE );
    }

    // Add the individual PM files to the Group box.
    num_icons = SimGetNumPMProgs();
    StatusLines( STAT_CREATEPROGRAMFOLDER, "" );
    num_total_install = 0;
    for( i = 0; i < num_icons; i++ ) {
        if( SimCheckPMCondition( i ) ) {
            ++num_total_install;
        }
    }
    num_installed = 0;
    StatusAmount( 0, num_total_install );
    for( i = 0; i < num_icons; i++ ) {
        if( !SimCheckPMCondition( i ) ) {
            continue;
        }
        SimGetPMDesc( i, prog_desc );
        dir_index = SimGetPMProgName( i, prog_name );
        if( strcmp( prog_name, "GROUP" ) == 0 ) {
            /* creating a new group */
            strcpy( group, prog_desc );
            if( !create_group( group ) ) {
                CoUninitialize();
                return( FALSE );
            }
        } else {
            // Adding item to group
            if( dir_index == SIM_INIT_ERROR ) {
                working_dir[ 0 ] = '\0';
                ReplaceVars( tmp, prog_name );
                strcpy( prog_name, tmp );
            } else {
                SimDirNoSlash( dir_index, working_dir );
            }

            // Get parameters
            SimGetPMParms( i, tmp );
            ReplaceVars( prog_arg, tmp );

            // Append the subdir where the icon file is and the icon file's name.
            temp = SimGetPMIconInfo( i, icon_name );
            dir_index = LOWORD( temp );
            icon_number = HIWORD( temp );
            if( icon_number == SIM_INIT_ERROR ) icon_number = 0;
            if( dir_index != SIM_INIT_ERROR ) {
                SimGetDir( dir_index, tmp );
                strcat( tmp, icon_name );
                strcpy( icon_name, tmp );
            }
            // Add the new file to the already created PM Group.
            rc = create_icon( group, prog_name, prog_desc, prog_arg, working_dir,
                              icon_name, icon_number );
            if( rc == FALSE ) {
                CoUninitialize();
                return( FALSE );
            }
        }
        ++num_installed;
        StatusAmount( num_installed, num_total_install );
        if( StatusCancelled() )
            break;
    }
    StatusAmount( num_total_install, num_total_install );

    CoUninitialize();
    return( TRUE );
}
Exemple #24
0
int
main(int argc, char *argv[])
{
	gfarm_error_t e;
	char op = OP_GROUPNAME, *groupname;
	int c;
	const char *path = ".";
	char *realpath = NULL;

	e = gfarm_initialize(&argc, &argv);
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: gfarm_initialize: %s\n",
		    program_name, gfarm_error_string(e));
		exit(1);
	}

	while ((c = getopt(argc, argv, "P:cdlm?")) != -1) {
		switch (c) {
		case 'P':
			path = optarg;
			break;
		case OP_CREATE_GROUP:
		case OP_DELETE_GROUP:
		case OP_MODIFY_GROUP:
		case OP_LIST_LONG:
			op = c;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (gfarm_realpath_by_gfarm2fs(path, &realpath) == GFARM_ERR_NO_ERROR)
		path = realpath;
	if ((e = gfm_client_connection_and_process_acquire_by_path(path,
	    &gfm_server)) != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: metadata server for \"%s\": %s\n",
		    program_name, path, gfarm_error_string(e));
		exit(1);
	}
	free(realpath);

	switch (op) {
	case OP_GROUPNAME:
	case OP_LIST_LONG:
		if (argc == 0)
			e = list_all(op);
		else
			e = list(op, argc, argv);
		break;
	case OP_CREATE_GROUP:
	case OP_MODIFY_GROUP:
		if (argc < 1)
			usage();
		groupname = *argv++;
		--argc;
		e = create_group(op, groupname, argc, argv);
		break;
	case OP_DELETE_GROUP:
		if (argc != 1)
			usage();
		e = delete_group(*argv);
		break;
	}
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: %s\n",
		    program_name, gfarm_error_string(e));
		exit(1);
	}

	gfm_client_connection_free(gfm_server);

	e = gfarm_terminate();
	if (e != GFARM_ERR_NO_ERROR) {
		fprintf(stderr, "%s: gfarm_terminate: %s\n",
		    program_name, gfarm_error_string(e));
		exit(1);
	}
	exit(0);
}
__uint _on_add_edit_groups(PCRTK_PACKET p, bool /* bGenerateEvents */)
{
	RTK_CURSOR hNode, hGroup;
	NODE_KEY nk;
	PRTK_GROUP png, pg=0;
	__uint count;

	if(p->data_size % sizeof(RTK_GROUP)){
		return 0;
	}
	if(!lock_rtdb(__true, 100)){
		return 0;
	}
	host_to_node(&p->src.host, &nk);
	hNode = open_node(&nk);
	if(!hNode){
		unlock_rtdb();
		return 0;
	}
	
	count = p->data_size / sizeof(RTK_GROUP);
	png = (PRTK_GROUP)p->data;
	for(__uint i=0; i<count; i++, png++){
		hGroup = open_group(hNode, &png->key);
		pg = (PRTK_GROUP)cursor_get_item(hGroup);
		if(pg){
			memcpy(
				pg->description, 
				png->description, 
				sizeof(pg->description)
				);
			pg->period = png->period;			
		}else{
			hGroup = create_group(hNode, png);
			pg = (PRTK_GROUP)cursor_get_item(hGroup);
		}
		if(pg){
			pg->d.flags = png->d.flags;
		}
		DEBUG_PRINTF((
			"Got group %s, flag=%08x\n", 
			(char *)CGroupName(png->key), 
			png->d.flags
			));
		close_handle(hGroup);
		if(pg /* && bGenerateEvents */){
			TAG_NAME name;
			name.node = nk;
			name.sname.group = png->key;
			rtk_queue_event(
				PT_AddGroup,
				&name,
				&p->src
				);
		}
	}
	close_handle(hNode);
	unlock_rtdb();

	return count;
}
Exemple #26
0
int main(int argc, char **argv)
{
	int status;
	struct sched_param thread_param;
	int i;
	int retval = FAILURE;
	int core;
	int nthreads;

	/* Make sure we see all message, even those on stdout.  */
	setvbuf(stdout, NULL, _IONBF, 0);

	/* get the number of processors */
	num_processors = sysconf(_SC_NPROCESSORS_ONLN);

	/* calculate the number of inversion groups to run */
	ngroups = num_processors == 1 ? 1 : num_processors - 1;

	/* process command line arguments */
	process_command_line(argc, argv);

	/* lock memory */
	if (lockall)
		if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
			error("mlockall failed\n");
			return FAILURE;
		}
	/* boost main's priority (so we keep running) :) */
	prio_min = sched_get_priority_min(policy);
	thread_param.sched_priority = MAIN_PRIO();
	status = pthread_setschedparam(pthread_self(), policy, &thread_param);
	if (status) {
		error("main: boosting to max priority: 0x%x\n", status);
		return FAILURE;
	}
	/* block unwanted signals */
	block_signals();

	/* allocate our groups array */
	groups = calloc(ngroups, sizeof(struct group_parameters));
	if (groups == NULL) {
		error("main: failed to allocate %d groups\n", ngroups);
		return FAILURE;
	}
	/* set up CPU affinity masks */
	if (set_cpu_affinity(&test_cpu_mask, &admin_cpu_mask))
		return FAILURE;

	nthreads = ngroups * NUM_TEST_THREADS + NUM_ADMIN_THREADS;

	/* set up our ready barrier */
	if (barrier_init(&all_threads_ready, NULL, nthreads,
			 "all_threads_ready"))
		return FAILURE;

	/* set up our done barrier */
	if (barrier_init(&all_threads_done, NULL, nthreads, "all_threads_done"))
		return FAILURE;

	/* create the groups */
	info("Creating %d test groups\n", ngroups);
	for (core = 0; core < num_processors; core++)
		if (CPU_ISSET(core, &test_cpu_mask))
			break;
	for (i = 0; i < ngroups; i++) {
		groups[i].id = i;
		groups[i].cpu = core++;
		if (core >= num_processors)
			core = 0;
		if (create_group(&groups[i]) != SUCCESS)
			return FAILURE;
	}

	/* prompt if requested */
	if (prompt) {
		printf("Press return to start test: ");
		getchar();
	}
	/* report */
	banner();
	start = time(NULL);

	/* turn loose the threads */
	info("Releasing all threads\n");
	status = pthread_barrier_wait(&all_threads_ready);
	if (status && status != PTHREAD_BARRIER_SERIAL_THREAD) {
		error("main: pthread_barrier_wait(all_threads_ready): 0x%x\n",
		      status);
		set_shutdown_flag();
		return FAILURE;
	}

	reporter(NULL);

	if (!quiet) {
		fputs(DOWN_ONE, stdout);
		printf("Stopping test\n");
	}
	set_shutdown_flag();

	/* wait for all threads to notice the shutdown flag */
	if (have_errors == 0 && interrupted == 0) {
		info("waiting for all threads to complete\n");
		status = pthread_barrier_wait(&all_threads_done);
		if (status && status != PTHREAD_BARRIER_SERIAL_THREAD) {
			error
			    ("main: pthread_barrier_wait(all_threads_ready): 0x%x\n",
			     status);
			return FAILURE;
		}
		info("All threads terminated!\n");
		retval = SUCCESS;
	} else
		kill(0, SIGTERM);
	finish = time(NULL);
	summary();
	if (lockall)
		munlockall();
	exit(retval);
}
PROXY_API __bool PMC_API init_proxy(HWND hWnd, __uint flags)
{
	char * szWarning = "没有找到软件狗,进入演示状态,数据库最大规模32点";

	if(!_g_InitLock){
		_g_InitLock = new CLock;
	}
	
	g_InitLock.Lock();
	if(g_iInitCount){
		g_iInitCount++;
		g_InitLock.UnLock();
		return __true;
	}

	g_iInitCount++;

	g_iInitFlag = flags;
	
	_load_settings(__false);
	
	g_DBDispatchTable.OnAddNode = _on_add_node;
	g_DBDispatchTable.OnDropNode = _on_del_node;
	hook_rtdb_events(&g_DBDispatchTable);
	
	if(!(g_iInitFlag & PROXY_INIT_AS_SERVER)){
		unsigned char run, dev;
		int runLevel, devLevel;
		init_key();
		get_key(&run, &runLevel, &dev, &devLevel);
		if(!dev){
			/* no dog is attached*/
			/* create_group(0x12345678,xxx) is a loophole */
			create_group((RTK_CURSOR)0x12345678, (PRTK_GROUP)32);
			if(!(flags & PROXY_SILENT)){
				MessageBox(
					hWnd,
					szWarning,
					"PMC Error",
					MB_OK
					);
			}
		}else{
			/* yes, dog is attached, set database limit */
			create_group((RTK_CURSOR)0x12345678, (PRTK_GROUP)devLevel);
		}
	}
	init_powermgr();
	init_network(0);
	init_rtdb();
	connect_vbus(BUSID_RTDB, 0, _on_rtdb, default_client_filter);
	connect_vbus(BUSID_CONFIG, 0, _on_config, default_client_filter);
	connect_vbus(BUSID_ALARM, 0, _on_alarm, default_client_filter);
	connect_vbus(BUSID_SYSTEM, 0, _on_system, default_client_filter);
	connect_vbus(BUSID_OPERATION, 0, 0, default_client_filter);
	if(flags & PROXY_ENABLE_DISPATCHER){
		start_dispatcher();
	}	

	g_Worker = new CProxyWorker(flags);
	if(!g_Worker){
		g_InitLock.UnLock();
		return __false;		
	}
	g_Worker->start();

#if defined(_WIN32) && 1
	SetThreadPriority(g_Worker->handle(), THREAD_PRIORITY_BELOW_NORMAL);
#endif
		
	g_InitLock.UnLock();
	return __true;
}
Exemple #28
0
/*解析消息线程*/
void *pthread_func()
{
       int group_fd;     //组播套接字
       group_fd = udp_link();
 
       head_user = (struct user_info *)malloc(sizeof(struct user_info));
       head_user->next = NULL;
      
       struct user_info *tmp; // 循环变量,用于便利在线用户链表将其发送给第一次登录的或者有刷新请求的客户端
       struct  servmsg *free_tmp;
 
       int ret= -1;
       while(1){
              while(H->next != NULL){
                   free_tmp = H;
                     H = H->next; //消息头,处理玩就往后移动
                   free(free_tmp);//将处理完的消息所占内存释放掉
                   free_tmp = NULL;
                    printf("消息来自:%s  IP:PORT:%s:%d\n",H->recvmsg.self_name,inet_ntoa(H->addr.sin_addr),ntohs(H->addr.sin_port));
					
					switch(H->recvmsg.type)
					{
                     case LOG_IN:
                            printf("%s登录消息\n",H->recvmsg.self_name);
                            send_message_to_all(H,LOGIN_TOALL);
                            add_user(head_user,H);
                     		break;
      				case REFRESH:
                            printf("%s刷新消息\n",H->recvmsg.self_name);
                            //usleep(50000);
                            send_all_online(H->addr);
                            break;
                     case CHAT_PRI:
                            printf("%s私聊消息\n",H->recvmsg.self_name);
                            printf("目标:%s\n",H->recvmsg.dst_name);
                            chat_private();
							break;
                     case CHAT_ALL:
                            printf("%s群聊消息\n",H->recvmsg.self_name);
						   send_message_to_all(H,CHAT_ALL);
                       		break;
					case FILE_NAME:
                            printf("%s申请下载\n",H->recvmsg.self_name);
                            send_dir_allfile(H->addr);
                     		break;
					case DOWNLOAD:
                            printf("%s 确认下载\n",H->recvmsg.self_name);
                            pthread_create(&tid2,NULL,download_send,(void *)&H->addr);
                            pthread_detach(tid2);
							break;
                     case  UPLOAD:
                            printf("%s上传文件\n",H->recvmsg.self_name);
                            pthread_create(&tid3,NULL,(void *)&upload_func,NULL);
                            pthread_detach(tid3);
                     		break;
					case OFFLINE:
                            printf("%s下线\n",H->recvmsg.self_name);
                            delete_user(H->recvmsg.self_name);
                     		break;
					case CREATE_GROUP:
                            printf("%s create group\n",H->recvmsg.self_name);
							create_group(H);						
                     		break;
					case  JOIN_GROUP:
                            printf("%s join group\n",H->recvmsg.self_name);
							join_group(H);
                     		break;
					case LIST_GROUP:
                            printf("%s list group\n",H->recvmsg.self_name);
							list_group(H);
                     		break;
					case GROUP_CHAT:
                            printf("%s group chat\n",H->recvmsg.self_name);
							group_chat(H);
                     		break;
					case GROUP_DELETE:
                            printf("%s delete group\n",H->recvmsg.self_name);
							delete_group(H);
                     		break;
					 default:
							printf("msg type error !\n");
							break;
					 }
                     printf("-----------------------------------\n");
              }
       }
}
Exemple #29
0
static void handle_add_request( GROUP_LIST* groups, char* msg, char* ip , unsigned short port_number){

    unsigned short len;
    int packet_header_offset;
    char* group_name;
    GROUP_T *group;
    GROUP_T* new_group;
    MEMBER_T* new_member;

    packet_header_offset = sizeof(unsigned short) + sizeof(char);

    memcpy(&len, msg, sizeof(unsigned short));
    len = ntohs(len);
    
    group_name = (char*) malloc( sizeof(char) * (len + 1));     // len + 1 bytes including the '\0' 
    if(!group_name){
        /*
         *  Server is out of memory.Send a negative reply.We only need to change
         *  the \type field of the packet's header
         */
        msg[2] = ADD_REPLY_NEGATIVE;
        return ;
    }

    // copy group name from the packet
    strncpy( group_name, msg + packet_header_offset, len );
    group_name[len] = '\0';

    new_member = create_member(ip , port_number);
    if( !new_member){
        // not enough memory
        free(group_name);
        msg[2] = ADD_REPLY_NEGATIVE;
        return;
    }

    group = get_group_by_name(groups, group_name);
    if(!group){

        /*
         * No such group.First create a new members list and add the new member to the 
         * list.Then create a new group and add it to the groups' list
         */
        int flag;

        MEMBER_LIST* member_list = create_member_list();
        if( !member_list){
            free(group_name);
            free(new_member);

            msg[2] = ADD_REPLY_NEGATIVE;
            return ;
        }
        // add member to the list
        flag = add_member(member_list,new_member);
        if( !flag){  
            // not added
            free(member_list);
            free(new_member);
            free(group_name);
            msg[2] = ADD_REPLY_NEGATIVE;
            return ;
        }
        // now create a new group and add it to the groups list
        new_group = create_group( group_name, member_list);
        if( !new_group){

            free(new_member);
            free(member_list);
            free(group_name);

            msg[2] = ADD_REPLY_NEGATIVE;
            return;
        }

        // add it to the groups' list
        add_group(groups, new_group);
        msg[2] = ADD_REPLY_POSITIVE;
        return;
    }
    else{
        // group is found.Add the member to the group
        
        add_member( group->members, new_member);
        // positive reply
        msg[2] = ADD_REPLY_POSITIVE;
    }

    free(group_name);
    return ;
}
Exemple #30
0
int main(int argc, char* argv[])
{
    GPU_Target* screen;

    printRenderers();

    screen = GPU_Init(800, 600, GPU_DEFAULT_INIT_FLAGS);
    if(screen == NULL)
        return -1;

    printCurrentRenderer();

    {
        Uint32 startTime;
        long frameCount;
        Uint8 done;
        SDL_Event event;

        int i = 0;

        float dt = 0.010f;

#define MAX_GROUPS 30
        Group groups[MAX_GROUPS];
        int num_groups;

        memset(groups, 0, sizeof(Group)*MAX_GROUPS);

        num_groups = 0;
        groups[num_groups] = create_first_group();
        num_groups++;

        startTime = SDL_GetTicks();
        frameCount = 0;

        done = 0;
        while(!done)
        {
            while(SDL_PollEvent(&event))
            {
                if(event.type == SDL_QUIT)
                    done = 1;
                else if(event.type == SDL_KEYDOWN)
                {
                    if(event.key.keysym.sym == SDLK_ESCAPE)
                        done = 1;
                    else if(event.key.keysym.sym == SDLK_EQUALS || event.key.keysym.sym == SDLK_PLUS)
                    {
                        for(i = 0; i < MAX_GROUPS; i++)
                        {
                            if(groups[i].target == NULL)
                            {
                                groups[i] = create_group();
                                num_groups++;
                                GPU_Log("Added window %u.  num_groups: %d\n", groups[i].target->context->windowID, num_groups);
                                break;
                            }
                        }
                    }
                    else if(event.key.keysym.sym == SDLK_MINUS)
                    {
                        if(num_groups > 0)
                        {

                            for(i = MAX_GROUPS-1; i >= 0; i--)
                            {
                                if(groups[i].target != NULL)
                                {
                                    GPU_Log("Removed window %u.  num_groups: %d\n", groups[i].target->context->windowID, num_groups-1);

                                    destroy_group(groups, i);

                                    num_groups--;
                                    break;
                                }
                            }

                            if(num_groups == 0)
                                done = 1;
                        }
                    }
                }
                else if(event.type == SDL_MOUSEBUTTONDOWN)
                {
                    GPU_Target* target = GPU_GetWindowTarget(event.button.windowID);
                    if(target == NULL)
                        GPU_Log("Clicked on window %u.  NULL target.\n", event.button.windowID);
                    else
                        GPU_Log("Clicked on window %u.  Target dims: %dx%d\n", event.button.windowID, target->w, target->h);
                }
                else if(event.type == SDL_WINDOWEVENT)
                {
                    if(event.window.event == SDL_WINDOWEVENT_CLOSE)
                    {
                        Uint8 closed = 0;
                        for(i = 0; i < MAX_GROUPS; i++)
                        {
                            if(groups[i].target != NULL && groups[i].target->context->windowID == event.window.windowID)
                            {
                                closed = 1;
                                GPU_Log("Removed window %u.  num_groups: %d\n", groups[i].target->context->windowID, num_groups-1);

                                destroy_group(groups, i);
                                num_groups--;
                                break;
                            }
                        }

                        // The last window was closed, then.
                        if(!closed || num_groups == 0)
                            done = 1;
                    }
                }
            }

            for(i = 0; i < MAX_GROUPS; i++)
            {
                if(groups[i].target == NULL)
                    continue;

                groups[i].sprite.x += groups[i].sprite.velx*dt;
                groups[i].sprite.y += groups[i].sprite.vely*dt;
                if(groups[i].sprite.x < 0)
                {
                    groups[i].sprite.x = 0;
                    groups[i].sprite.velx = -groups[i].sprite.velx;
                }
                else if(groups[i].sprite.x > screen_w)
                {
                    groups[i].sprite.x = screen_w;
                    groups[i].sprite.velx = -groups[i].sprite.velx;
                }

                if(groups[i].sprite.y < 0)
                {
                    groups[i].sprite.y = 0;
                    groups[i].sprite.vely = -groups[i].sprite.vely;
                }
                else if(groups[i].sprite.y > screen_h)
                {
                    groups[i].sprite.y = screen_h;
                    groups[i].sprite.vely = -groups[i].sprite.vely;
                }
            }

            for(i = 0; i < MAX_GROUPS; i++)
            {
                if(groups[i].target == NULL)
                    continue;

                GPU_Clear(groups[i].target);

                GPU_Blit(groups[i].sprite.image, NULL, groups[i].target, groups[i].sprite.x, groups[i].sprite.y);

                GPU_Flip(groups[i].target);
            }

            frameCount++;
            if(frameCount%500 == 0)
                GPU_Log("Average FPS: %.2f\n", 1000.0f*frameCount/(SDL_GetTicks() - startTime));
        }

        GPU_Log("Average FPS: %.2f\n", 1000.0f*frameCount/(SDL_GetTicks() - startTime));

        for(i = 0; i < MAX_GROUPS; i++)
        {
            if(groups[i].target == NULL)
                continue;

            destroy_group(groups, i);
        }

    }

    GPU_Quit();

    return 0;
}