Exemplo n.º 1
0
 CompletionType evaluate()
 {
     Register<Value> value;
     switch (method)
     {
     case ToString:
     case ValueOf:
         if (!getThis()->isObject())
         {
             throw getErrorInstance("TypeError");
         }
         value = static_cast<ObjectValue*>(getThis())->getValueProperty();
         if (!value->isString())
         {
             throw getErrorInstance("TypeError");
         }
         break;
     case CharAt:
         value = charAt();
         break;
     case CharCodeAt:
         value = charCodeAt();
         break;
     case Concat:
         value = concat(getThis());
         break;
     case IndexOf:
         value = indexOf(getThis());
         break;
     case LastIndexOf:
         value = lastIndexOf(getThis());
         break;
     case LocaleCompare:
         value = localeCompare(getThis());
         break;
     case Match:
         value = stringMatch();
         break;
     case Replace:
         value = stringReplace();
         break;
     case Search:
         value = stringSearch();
         break;
     case Slice:
         value = slice(getThis());
         break;
     case Split:
         value = stringSplit();
         break;
     case Substring:
         value = substring(getThis());
         break;
     case Substr:
         value = substr(getThis());
         break;
     case ToLowerCase:
     case ToLocaleLowerCase:
         value = toLowerCase(getThis());
         break;
     case ToUpperCase:
     case ToLocaleUpperCase:
         value = toUpperCase(getThis());
         break;
     }
     return CompletionType(CompletionType::Return, value, "");
 }
Exemplo n.º 2
0
bool String::equalsIgnoreCase(const char* string) const {
	sp<String> tmp = String::valueOf(string);
	return toLowerCase()->equals(tmp->toLowerCase());
}
Exemplo n.º 3
0
std::string getContentType(const std::string& extension) {
    static Map<std::string, std::string> CONTENT_TYPE_MAP;   // extension => MIME type

    if (extension.empty()) {
        return STATIC_VARIABLE(CONTENT_TYPE_DEFAULT);
    }

    // populate map of content types, if needed
    if (CONTENT_TYPE_MAP.isEmpty()) {
        CONTENT_TYPE_MAP["bmp"] = "image/bmp";
        CONTENT_TYPE_MAP["bz"] = "application/x-bzip";
        CONTENT_TYPE_MAP["bz2"] = "application/x-bzip2";
        CONTENT_TYPE_MAP["c"] = "text/plain";
        CONTENT_TYPE_MAP["cc"] = "text/plain";
        CONTENT_TYPE_MAP["com"] = "application/octet-stream";
        CONTENT_TYPE_MAP["cpp"] = "text/plain";
        CONTENT_TYPE_MAP["css"] = "text/css";
        CONTENT_TYPE_MAP["doc"] = "application/msword";
        CONTENT_TYPE_MAP["dot"] = "application/msword";
        CONTENT_TYPE_MAP["exe"] = "application/octet-stream";
        CONTENT_TYPE_MAP["gif"] = "image/gif";
        CONTENT_TYPE_MAP["gz"] = "application/x-gzip";
        CONTENT_TYPE_MAP["gzip"] = "application/x-gzip";
        CONTENT_TYPE_MAP["h"] = "text/plain";
        CONTENT_TYPE_MAP["hh"] = "text/plain";
        CONTENT_TYPE_MAP["hpp"] = "text/plain";
        CONTENT_TYPE_MAP["htm"] = "text/html";
        CONTENT_TYPE_MAP["html"] = "text/html";
        CONTENT_TYPE_MAP["htmls"] = "text/html";
        CONTENT_TYPE_MAP["ico"] = "image/x-icon";
        CONTENT_TYPE_MAP["inf"] = "text/plain";
        CONTENT_TYPE_MAP["jar"] = "application/octet-stream";
        CONTENT_TYPE_MAP["jav"] = "text/plain";
        CONTENT_TYPE_MAP["java"] = "text/plain";
        CONTENT_TYPE_MAP["jpe"] = "image/jpeg";
        CONTENT_TYPE_MAP["jpeg"] = "image/jpeg";
        CONTENT_TYPE_MAP["jpg"] = "image/jpeg";
        CONTENT_TYPE_MAP["mid"] = "audio/midi";
        CONTENT_TYPE_MAP["midi"] = "audio/midi";
        CONTENT_TYPE_MAP["mod"] = "audio/mod";
        CONTENT_TYPE_MAP["mov"] = "video/quicktime";
        CONTENT_TYPE_MAP["mp3"] = "text/plain";
        CONTENT_TYPE_MAP["mpg"] = "video/mpeg";
        CONTENT_TYPE_MAP["o"] = "application/octet-stream";
        CONTENT_TYPE_MAP["odc"] = "application/vnd.oasis.opendocument.chart";
        CONTENT_TYPE_MAP["odp"] = "application/vnd.oasis.opendocument.presentation";
        CONTENT_TYPE_MAP["ods"] = "application/vnd.oasis.opendocument.spreadsheet";
        CONTENT_TYPE_MAP["odt"] = "application/vnd.oasis.opendocument.text";
        CONTENT_TYPE_MAP["pct"] = "image/x-pict";
        CONTENT_TYPE_MAP["pcx"] = "image/x-pcx";
        CONTENT_TYPE_MAP["pdf"] = "application/pdf";
        CONTENT_TYPE_MAP["pl"] = "text/plain";
        CONTENT_TYPE_MAP["pm"] = "text/plain";
        CONTENT_TYPE_MAP["ppt"] = "application/powerpoint";
        CONTENT_TYPE_MAP["ps"] = "application/postscript";
        CONTENT_TYPE_MAP["psd"] = "application/octet-stream";
        CONTENT_TYPE_MAP["py"] = "text/plain";
        CONTENT_TYPE_MAP["qt"] = "video/quicktime";
        CONTENT_TYPE_MAP["ra"] = "audio/x-realaudio";
        CONTENT_TYPE_MAP["rb"] = "text/plain";
        CONTENT_TYPE_MAP["rm"] = "application/vnd.rn-realmedia";
        CONTENT_TYPE_MAP["rtf"] = "application/rtf";
        CONTENT_TYPE_MAP["s"] = "text/x-asm";
        CONTENT_TYPE_MAP["sh"] = "text/plain";
        CONTENT_TYPE_MAP["shtml"] = "text/html";
        CONTENT_TYPE_MAP["swf"] = "application/x-shockwave-flash";
        CONTENT_TYPE_MAP["tcl"] = "application/x-tcl";
        CONTENT_TYPE_MAP["tex"] = "application/x-tex";
        CONTENT_TYPE_MAP["tgz"] = "application/x-compressed";
        CONTENT_TYPE_MAP["tif"] = "image/tiff";
        CONTENT_TYPE_MAP["tiff"] = "image/tiff";
        CONTENT_TYPE_MAP["txt"] = "text/plain";
        CONTENT_TYPE_MAP["voc"] = "audio/voc";
        CONTENT_TYPE_MAP["wav"] = "audio/wav";
        CONTENT_TYPE_MAP["xls"] = "application/excel";
        CONTENT_TYPE_MAP["xlt"] = "application/excel";
        CONTENT_TYPE_MAP["xpm"] = "image/xpm";
        CONTENT_TYPE_MAP["z"] = "application/x-compressed";
        CONTENT_TYPE_MAP["zip"] = "application/zip";
    }

    // "foo.BAZ.BaR" => "bar"
    std::string ext = toLowerCase(extension);
    int dot = stringLastIndexOf(ext, ".");
    if (dot >= 0) {
        ext = ext.substr(dot + 1);
    }

    if (CONTENT_TYPE_MAP.containsKey(ext)) {
        return CONTENT_TYPE_MAP[ext];
    } else {
        return STATIC_VARIABLE(CONTENT_TYPE_DEFAULT);
    }
}
Exemplo n.º 4
0
void AppEditMenu::createEditAdvancedMenu(QToolBar *toolbar)
{
    editAdvancedMenu = new QMenu(tr("Advanced"));

    editCommentAction=editAdvancedMenu->addAction(IconUtil::getIcon("comment"), tr("Co&mment/Uncomment"), this, SLOT(comment()), QKeySequence("Ctrl+/"));
    editCommentAction->setStatusTip(tr("Comment/Uncomment line(s)"));
    toolbar->addAction(editCommentAction);

    editMoveUpAction=editAdvancedMenu->addAction(IconUtil::getIcon("move_up"), tr("Move &up"), this, SLOT(moveUp()), QKeySequence("Ctrl+Up"));
    editMoveUpAction->setStatusTip(tr("Move lines(s) up"));
    toolbar->addAction(editMoveUpAction);

    editMoveDownAction=editAdvancedMenu->addAction(IconUtil::getIcon("move_down"), tr("Move &down"), this, SLOT(moveDown()), QKeySequence("Ctrl+Down"));
    editMoveDownAction->setStatusTip(tr("Move lines(s) down"));
    toolbar->addAction(editMoveDownAction);

    editSelectBlockAction=editAdvancedMenu->addAction(tr("Select current block"), this, SLOT(selectBlock()), QKeySequence("Ctrl+B"));
    editSelectBlockAction->setStatusTip(tr("Select current block"));

    editToUpperCaseAction=editAdvancedMenu->addAction(tr("To upper case"), this, SLOT(toUpperCase()), QKeySequence("Ctrl+U"));
    editToUpperCaseAction->setStatusTip(tr("Change selection or current word text to upper case"));

    editToLowerCaseAction=editAdvancedMenu->addAction(tr("To lower case"), this, SLOT(toLowerCase()), QKeySequence("Ctrl+L"));
    editToLowerCaseAction->setStatusTip(tr("Change selection or current word text to lower case"));

    editCreateDuplicateAction=editAdvancedMenu->addAction(tr("Make duplicate"), this, SLOT(makeDuplicate()), QKeySequence("Ctrl+D"));
    editCreateDuplicateAction->setStatusTip(tr("Create duplicate of current line or selection"));

    editRemoveEmptyLinesAction=editAdvancedMenu->addAction(tr("Remove empty lines"), this, SLOT(removeEmptyLines()), QKeySequence("Ctrl+R"));
    editRemoveEmptyLinesAction->setStatusTip(tr("Remove empty lines"));

    editApplyCaseFoldingAction=editAdvancedMenu->addAction(tr("Apply case folding"), this, SLOT(applyCaseFolding()), QKeySequence("Ctrl+Shift+U"));
    editApplyCaseFoldingAction->setStatusTip(tr("Apply automatic case folding rules to selection"));

    editFormatCodeAction=editAdvancedMenu->addAction(tr("Format"), this, SLOT(formatCode()), QKeySequence("Ctrl+Shift+F"));
    editFormatCodeAction->setStatusTip(tr("Auto format code to make it more readable"));
}
void parseConfigFile(char* filename, Configfile* cfg) 
{
  FILE *pFile;
  char line[90];
  char *tok;
  char *newline;

  memset(cfg,'\0',sizeof(Configfile));
  /* open file */
  if((pFile =fopen(filename,"r"))==NULL)
  {
      fprintf(stderr,"Could not open '%s'.\n",filename);  
      exit(0);
  }

  /* readin line by line */
  while(fgets(line,sizeof(line),pFile)!=NULL)
  {
	 tok = strtok(line,DELIM);
	 toLowerCase(tok);
      while(tok!=NULL)
      {  
        if(strchr(tok,'#')!=NULL || strcmp(tok,"\r\n") == SUCCESS ||
			  strcmp(tok,"") == SUCCESS) {
          break;
        }
        else if(strcmp(tok,"server_address") == SUCCESS || 
                strcmp(tok,"address") == SUCCESS) {
           tok = strtok(NULL, DELIM);
			  if((newline = strstr(tok,"\r\n")) != NULL)
				 newline[0] = '\0';
           strcpy(cfg->address,tok);
           break;
        }
        else if(strcmp(tok,"server_name") == SUCCESS) {
           tok = strtok(NULL, DELIM);
        if((newline = strstr(tok,"\r\n")) != NULL)
				 newline[0] = '\0';
           strcpy(cfg->address,tok);
           break;
        }
        else if(strcmp(tok,"server_port") == SUCCESS || 
                strcmp(tok,"port") == SUCCESS ) {
           tok = strtok(NULL, DELIM);
           cfg->port = atoi(tok);
           break;
        }
        else if(strcmp(tok,"print_message_details") == SUCCESS) {
           tok = strtok(NULL, DELIM);
           toLowerCase(tok);
           if(strcmp(tok,"on") == SUCCESS) {
            cfg->print_message_details = TRUE;
            break;
           }
           else if(strcmp(tok,"off") == SUCCESS) {
            cfg->print_message_details = FALSE;
            break;
           }
           
            fprintf(stderr,"please use 'ON' or 'OFF' ");
            fprintf(stderr,"for 'print_message_details'\n");
            break;
        }
        else if(strcmp(tok,"request_count") == SUCCESS) {
           tok = strtok(NULL, DELIM);
           cfg->request_count = atoi(tok);
           break;
        }
        else if(strcmp(tok,"request_timeout") == SUCCESS) {
           tok = strtok(NULL, DELIM);
           cfg->request_timeout = atoi(tok);
           break;
        }
        else if(strcmp(tok,"support_timeout") == SUCCESS) {
           tok = strtok(NULL, DELIM);
           toLowerCase(tok);
           if(strcmp(tok,"on") == SUCCESS) {
            cfg->support_timeout = TRUE;
            break;
           }
           else if(strcmp(tok,"off") == SUCCESS) {
            cfg->support_timeout = FALSE;
            break;
           }
           
            fprintf(stderr,"please use 'ON' or 'OFF' ");
            fprintf(stderr,"for 'support_timeout'\n");
            break;
        }
    
      }
  }  
  fclose(pFile);
}
Exemplo n.º 6
0
	void INIParser::process(const wstring& line, bool eof)
	{
		static const RegExp re1 = L"/^(\\w+)=(.*)$/";
		static const RegExp re2 = L"/^\\s*\\[(.+)\\]\\s*$/";
		static const RegExp re3 = L"/\\\\\\[/g";

		static const wstring strTitle = L"title";
		static const wstring strDisabled = L"disabled";
		static const wstring strTrue = L"true";
		static const wstring strLeftBracket = L"[";

		RegExpMatch match;
		bool ret = false;
		if (wantObj && re1.exec(match, line))
		{
			curObj[match.substrings[1]] = match.substrings[2];
		}
		else if (eof || (ret = re2.exec(match, line)))
		{
			wstring strSection;
			if (ret)
			{
				strSection = toLowerCase(match.substrings[1]);
			}
			if (wantObj ? curObj.size() : curList.size())
			{
				// Process current object before going to next section
				switch (curSection)
				{
				case FILTER:
				case PATTERN:
					// create the filter, with certain properties set up
					// do not insert it into the filters set
					// if it's active, it'll be inserted in some subscription we'll later parse
					persistedFilters.insert(Filter::fromObject(curObj));
					break;
				case SUBSCRIPTION:
					// not supported, just record whether the whole subscription is disabled or not
					{
						auto iter = curObj.find(strDisabled);
						subscriptionDisabled =
							iter != curObj.end() && iter->second == strTrue;

						if (hasExcludedSubscriptions)
						{
							auto iterTitle = curObj.find(strTitle);
							subscriptionExcluded = iterTitle != curObj.end() &&
								reExcludedSubscriptions.test(iterTitle->second);
						}
						else
						{
							subscriptionExcluded = false;
						}
					}
					break;
				case SUBSCRIPTION_FILTERS:
				case SUBSCRIPTION_PATTERNS:
				case USER_PATTERNS:
					if (!subscriptionDisabled && !subscriptionExcluded)
					{
						for (size_t i = 0; i < curList.size(); i++)
						{
							const wstring& text = curList[i];
							Filter* filter = Filter::fromText(text);
							// need to reset the disabled property since we don't clear
							// the global filter list between reloads
							ActiveFilter* activeFilter = filter->toActiveFilter();
							if (activeFilter)
							{
								// Only reset disabled property for those not persisted yet
								if (persistedFilters.find(filter) == persistedFilters.end())
									activeFilter->setDisabled(false);
								// just put the filter in INIParser::filters
								filters.insert(activeFilter);
							}
						}
					}
					subscriptionDisabled = false;
					subscriptionExcluded = false;
				}
			}

			// Do clean-up
			curSection = OTHER;
			if (wantObj)
				curObj.clear();
			else
				curList.clear();

			if (eof)
			{
				subscriptionDisabled = false;
				subscriptionExcluded = false;
				return;
			}

			auto iter = sectionMapper.find(strSection);
			if (iter != sectionMapper.end())
			{
				curSection = iter->second;
				switch (curSection)
				{
				case FILTER:
				case PATTERN:
				case SUBSCRIPTION:
					wantObj = true;
					break;
				case SUBSCRIPTION_FILTERS:
				case SUBSCRIPTION_PATTERNS:
				case USER_PATTERNS:
				default:
					wantObj = false;
				}
			}
		}
		else if (!wantObj && line.length() && !subscriptionDisabled && !subscriptionExcluded)
		{
			curList.push_back(replace(line, re3, strLeftBracket));
		}
	}
Exemplo n.º 7
0
void dotrustgline(long unum, char *tail) {
  int res; char tmps2[TMPSSIZE], tmps3[TMPSSIZE], tmps4[TMPSSIZE], tmps5[TMPSSIZE];
  char tmps6[TMPSSIZE]; long r2; userdata *a;
  trustedgroup *tg; trustedhost *th; int i, j; long l; array listofths;
  res=sscanf(tail, "%s %s %s %s %[^\n]",tmps2,tmps3,tmps4,tmps5,tmps6);
  if (res<4) {
    msgtouser(unum,"Syntax: trustgline <groupname OR #groupID> user duration [reason]");
    msgtouser(unum,"user may contain wildcards");
    return;
  }
  if (res==4) {
    numtonick(unum,tmps2);
    sprintf(tmps6,"requested by %s",tmps2);
  }
  tmps4[USERLEN+2]='\0';
  toLowerCase(tmps3); toLowerCase(tmps4);
  r2=durationtolong(tmps5);
  if (r2<=0) {
    sprintf(tmps2,"The duration you gave is invalid.");
    msgtouser(unum,tmps2);
    return;
  }
  if (tmps3[0]=='#') {
    tg=findtrustgroupbyID(strtol(&tmps3[1],NULL,10));
  } else {
    tg=findtrustgroupbyname(tmps3);
  }
  if (tg==NULL) {
    sprintf(tmps2,"A trustgroup with that %s does not exist.",(tmps3[0]=='#') ? "ID" : "name");
    msgtouser(unum,tmps2); return;
  }
  /* First, create a list of all hosts in that trustgroup... */
  array_init(&listofths,sizeof(unsigned long));
  for (i=0;i<SIZEOFTL;i++) {
    th=trustedhosts[i];
    while (th!=NULL) {
      if (th->id==tg->id) { /* mmkay, that one belongs to our group */
        long j;
        j=array_getfreeslot(&listofths);
        ((unsigned long *)listofths.content)[j]=th->IPv4;
      }
      th=th->next;
    }
  }
  if (listofths.cursi==0) {
    msgtouser(unum,"There are no hosts in that trustgroup.");
    array_free(&listofths);
    return;
  }
  /* Now that we have the list: count number of users hit */
  l=0;
  for (j=0;j<SIZEOFUL;j++) {
    a=uls[j];
    while (a!=NULL) {
      char tmpu[USERLEN+1];
      strcpy(tmpu,a->ident);
      toLowerCase(tmpu);
      for (i=0;i<listofths.cursi;i++) {
        unsigned long *bla;
        bla=(unsigned long *)listofths.content;
        if (bla[i]==a->realip) {
          if (match2strings(tmps4,tmpu)) {
            l++; break;
          }
        }
      }
      a=(void *)a->next;
    }
  }
  if (l>GLINEMAXHIT) {
    newmsgtouser(unum,"That gline would hit more than %d (%d) Users/Channels. You probably mistyped something.",GLINEMAXHIT,l);
    if ((l<(GLINEMAXHIT*10)) && (getauthlevel(unum)>=999)) {
      msgtouser(unum,"However, your authlevel is >=999, so I hope you know what you're doing... Executing command.");
    } else {
      array_free(&listofths); return;
    }
  }
  /* OK, safety checks done - now gline the fuckers */
  numtonick(unum,tmps5);
  for (i=0;i<listofths.cursi;i++) {
    unsigned long *bla; char * mycip;
    bla=(unsigned long *)listofths.content;
    mycip=printipv4(bla[i]);
    sprintf(tmps2,"%s@%s",tmps4,mycip);
    free(mycip);
    addgline(tmps2,tmps6,tmps5,r2,1);
  }
  sprintf(tmps2,"Added GLINE for %s @ trustgroup %s (#%lu), caused %lu glines, hit %ld users",tmps4,tg->name,tg->id,
    listofths.cursi,l);
  msgtouser(unum,tmps2);
  sprintf(tmps2,"GLINE %s @ trustgroup %s (#%lu) by %s, caused %lu glines, hit %ld users",tmps4,
    tg->name,tg->id,tmps5,listofths.cursi,l);
  sendtonoticemask(NM_GLINE,tmps2);
  array_free(&listofths);
}
Exemplo n.º 8
0
void MediaDatabase::add(const MediaFile &mf) {
  remove(toLowerCase(mf.getSourceURL()));
  if(put(toLowerCase(mf.getSourceURL()),mf)) {
    m_changed = true;
  }
}
Exemplo n.º 9
0
void dotrustgroupadd(long unum, char *tail) {
  int res; char tmps2[TMPSSIZE], tmps3[TMPSSIZE], tmps4[TMPSSIZE], tmps5[TMPSSIZE];
  char tmps6[TMPSSIZE], tmps7[TMPSSIZE], tmps8[TMPSSIZE], tmps9[TMPSSIZE];
  long dur; trustedgroup *tg;
  res=sscanf(tail,"%s %s %s %s %s %s %s %[^\n]",tmps2,tmps3,tmps4,tmps5,tmps6,tmps7,tmps8,tmps9);
  if ((res<7) || (res>8)) {
    msgtouser(unum,"Syntax: trustgroupadd name howmany howlong maxperident enforceident contact [comment]");
    msgtouser(unum,"where name is a unique name for that group");
    msgtouser(unum,"      howmany gives the number of clones allowed from that group");
    msgtouser(unum,"      howlong gives how long the trust will last (e.g. '1y')");
    msgtouser(unum,"      maxperident sets how many clones are allowed from a single user.");
    msgtouser(unum,"                  0 means unlimited");
    msgtouser(unum,"      enforceident if set to 1 will kill all clients without idents");
    msgtouser(unum,"                   in that group");
    msgtouser(unum,"      contact is one or more contact-emails, seperated by commas,");
    msgtouser(unum,"              WITH NO SPACES!!!");
    msgtouser(unum,"      comment is an optional comment");
    return;
  }
  if (res==7) { strcpy(tmps9,"[no comment]"); }
  if (strlen(tmps3)>TRUSTNAMELEN) {
    msgtouser(unum,"The name you gave is too long");
    return;
  }
  if (tmps3[0]=='#') {
    msgtouser(unum,"Trustgroupname must not start with a '#'");
    return;
  }
  if (strlen(tmps8)>TRUSTCONTACTLEN) {
    msgtouser(unum,"contact-email is too long"); return;
  }
  if (strlen(tmps9)>TRUSTCOMLEN) {
    msgtouser(unum,"comment is too long"); return;
  }
  dur=durationtolong(tmps5);
  if (dur<1) {
    msgtouser(unum,"Invalid duration given");
    return;
  }
  if (((tmps7[0]!='0') && (tmps7[0]!='1')) || (tmps7[1]!='\0')) {
    msgtouser(unum,"enforceident is a boolean setting, that means it can only be 0 or 1"); return;
  }
  toLowerCase(tmps3);
  tg=findtrustgroupbyname(tmps3);
  if (tg!=NULL) { /* This group exists, modify it */
    sprintf(tmps2,"Trustgroup %s already exists, replacing values.",tmps3);
    msgtouser(unum,tmps2);
    sprintf(tmps2,"Old settings were: trusted for %lu users, max. clones per user %lu, %senforcing ident",
            tg->trustedfor,tg->maxperident,(tg->enforceident==0) ? "not " : "");
    msgtouser(unum,tmps2);
    sprintf(tmps2,"Contact-eMail: %s",tg->contact);
    msgtouser(unum,tmps2);
    sprintf(tmps2,"Comment:       %s",tg->comment);
    msgtouser(unum,tmps2);
  } else { /* New group */
    unsigned long newID;
    tg=(trustedgroup *)malloc(sizeof(trustedgroup));
    if (tg==NULL) {
      printf("!!! Out of memory in dotrustgroupadd !!!\n"); exit(0);
    }
    newID=getfreetgid();
    tg->id=newID;
    tg->currentlyon=0; tg->lastused=0; tg->maxused=0; tg->maxreset=0;
    tg->next=(void *)trustedgroups[tgshash(newID)];
    trustedgroups[tgshash(newID)]=tg;
    array_init(&(tg->identcounts),sizeof(identcounter));
  }
  tg->enforceident=(tmps7[0]=='1');
  strcpy(tg->name,tmps3);
  strcpy(tg->contact,tmps8);
  strcpy(tg->comment,tmps9);
  tg->trustedfor=strtol(tmps4,NULL,10);
  tg->maxperident=strtol(tmps6,NULL,10);
  tg->expires=getnettime()+dur;
  numtonick(unum,tmps2);
  mystrncpy(tg->creator,tmps2,AUTHUSERLEN);
  sprintf(tmps2,"%s created/updated Trustgroup %s (#%ld) - %lu / %lu / %d",
    tg->creator,tg->name,tg->id,tg->trustedfor,tg->maxperident,tg->enforceident);
  sendtonoticemask(NM_TRUSTS,tmps2);
  sprintf(tmps2,"Trustgroup %s (#%ld) created/updated",tg->name,tg->id);
  msgtouser(unum,tmps2);
}
Exemplo n.º 10
0
void dotrustlist(long unum, char *tail) {
  int res; char tmps2[TMPSSIZE], tmps3[TMPSSIZE], tmps4[TMPSSIZE];
  array listofids; long i; trustedgroup *tg; trustedhost *th; long j;
  unsigned long lastshown, showid; unsigned long numshown=0;
  char tmps5[TMPSSIZE]; unsigned int showhosts=65000;
  res=sscanf(tail,"%s %s %s",tmps2,tmps3,tmps4);
  if (res>3) {
    msgtouser(unum,"Syntax: trustlist [-h] [pattern]");
    return;
  }
  if (res>=2) {
    toLowerCase(tmps3);
    if (strcmp(tmps3,"-h")==0) {
      showhosts=0;
      if (res<3) {
        strcpy(tmps3,"*");
      } else {
        strcpy(tmps3,tmps4);
      }
    } else {
      if (res==3) {
        msgtouser(unum,"Invalid parameter");
        return;
      }
    }
  }
  if (res==1) { strcpy(tmps3,"*"); }
  toLowerCase(tmps3);
  trustgroupexpire();
  if (tmps3[0]=='#') {
    if ((!ischarinstr('*',tmps3)) && (!ischarinstr('?',tmps3))) {
      newmsgtouser(unum,"Searching trustgroup with ID %lu...",strtoul(&tmps3[1],NULL,10));
      numshown=displaytrustgroupwithid(unum,strtoul(&tmps3[1],NULL,10),showhosts);
      if (numshown==0) {
        msgtouser(unum,"A trustgroup with that ID does not exist.");
      }
      return;
    }
  }
  array_init(&listofids,sizeof(unsigned long));
  for (i=0;i<SIZEOFIDMAP;i++) {
    tg=trustedgroups[i];
    while (tg!=NULL) {
      strcpy(tmps4,tg->name); toLowerCase(tmps4);
      sprintf(tmps5,"#%lu",tg->id);
      if ((match2strings(tmps3,tmps4)) || (match2strings(tmps3,tmps5))) {
        j=array_getfreeslot(&listofids);
        ((unsigned long *)listofids.content)[j]=tg->id;
      }
      tg=(void *)tg->next;
    }
  }
  for (i=0;i<SIZEOFTL;i++) {
    th=trustedhosts[i];
    while (th!=NULL) {
      char * mycip=printipv4(th->IPv4);
      if (match2strings(tmps3,mycip)) {
        j=array_getfreeslot(&listofids);
        ((unsigned long *)listofids.content)[j]=th->id;
      }
      free(mycip);
      th=(void *)th->next;
    }
  }
  if (listofids.cursi==0) {
    msgtouser(unum,"No matches.");
    array_free(&listofids);
    return;
  }
  qsort(listofids.content, listofids.cursi, sizeof(unsigned long), trustlistsorthelper);
  lastshown=0;
  for (i=0;i<listofids.cursi;i++) {
    showid=((unsigned long *)(listofids.content))[i];
    if (showid!=lastshown) {
      lastshown=showid;
      numshown+=displaytrustgroupwithid(unum,showid,showhosts);
      if (numshown>500) {
        newmsgtouser(unum,"More than 500 lines (%lu) already shown - aborting now.",numshown);
        break;
      }
    }
  }
  array_free(&listofids);
  newmsgtouser(unum,"--- End of list - %lu lines returned from query ---",numshown);
}
Exemplo n.º 11
0
void dotrustgroupmodify(long unum, char *tail) {
  int res; signed long newv, previous;
  char tmps2[TMPSSIZE], tmps3[TMPSSIZE], tmps4[TMPSSIZE], tmps5[TMPSSIZE]; trustedgroup *tg;
  char whats[4][20] = {"Maxclones","Maxperuser","Expiration","Enforceident"}; int whatwedo;
  res = sscanf(tail, "%s %s %30[^+-=1234567890]%30[^\n]", tmps2, tmps3, tmps5, tmps4);
  if (res==2) {
    res=sscanf(tail,"%s %s %s",tmps2,tmps3,tmps5);
  }
  if (res < 3) {
    msgtouser(unum, "Syntax: trustgroupmodify <groupname OR #groupid> [what][+|-|=]number");
    msgtouser(unum, "        for the number, +20 means add 20, -15 means subtract 15,");
    msgtouser(unum, "        =35 means it to 35, 20 means add 20.");
    msgtouser(unum, "        what can be one of: maxclones, maxperuser, expire, enforceident");
    msgtouser(unum, "        and defaults to maxclones.");
    return;
  }
  toLowerCase(tmps3);
  if (tmps3[0] == '#') {
    tg = findtrustgroupbyID(strtol(&tmps3[1], NULL, 10));
  } else {
    tg = findtrustgroupbyname(tmps3);
  }
  if (tg == NULL) {
    newmsgtouser(unum, "A trustgroup with that %s does not exist.", (tmps3[0] == '#') ? "ID" : "name");
    return;
  }
  if (tg->id == 0) {
    msgtouser(unum, "Internal error: Trustgroup has ID 0");
    return;
  }
  if (res==3) { /* No "what" argument, we assume maxclones */
    strcpy(tmps4,tmps5);
    strcpy(tmps5,"maxclones");
  }
  toLowerCase(tmps5);
  whatwedo=-1;
  if (strcmp(tmps5,"maxclones")==0) { whatwedo=0; }
  if (strcmp(tmps5,"maxperuser")==0) { whatwedo=1; }
  if (strncmp(tmps5,"expir",5)==0) { whatwedo=2; }
  if (strcmp(tmps5,"maxperident")==0) { whatwedo=1; }
  if (strcmp(tmps5,"enforceident")==0) { whatwedo=3; }
  if (whatwedo<0) {
    newmsgtouser(unum,"Don't know what %s is (and of course not how to change it either).",tmps5);
    return;
  }
  switch (whatwedo) {
    case 0: previous = tg->trustedfor; break;
    case 1: previous = tg->maxperident; break;
    case 2: previous = tg->expires; break;
    case 3: previous = tg->enforceident; break;
    default: msgtouser(unum,"Internal error: programmer too dumb."); return;
  }
  if (tmps4[0] == '=') {
    if (whatwedo==2) {
      newv = durationtolong(tmps4 + 1);
      if (newv<=0) {
        msgtouser(unum,"Invalid duration.");
        return;
      }
      newv+=getnettime();
    } else {
      newv = strtol(tmps4 + 1, NULL, 10);
    }
    if (newv > previous) {
      tmps4[0] = '+';
    } else {
      tmps4[0] = '-';
    }
  } else {
    if (whatwedo==2) {
      if ((tmps4[0]=='-') || (tmps4[0]=='+')) {
        if (tmps4[0]=='-') {
          newv = previous-durationtolong(tmps4 + 1);
        } else {
          newv = previous+durationtolong(tmps4 + 1);
        }
      } else {
        newv=previous+durationtolong(tmps4);
      }
    } else {
      newv = previous + strtol(tmps4, NULL, 10);
    }
  }
  if ((newv<0) || ((newv <= 0) && (whatwedo==1))) {
    msgtouser(unum, "That would make it less or equal to 0 (zero).");
    return;
  }
  if (whatwedo==3) { newv=newv%2; }
  switch (whatwedo) {
    case 0: tg->trustedfor = newv; break;
    case 1: tg->maxperident = newv; break;
    case 2: tg->expires = newv; break;
    case 3: tg->enforceident = newv; break;
    default: msgtouser(unum,"Internal error: programmer too dumb #2."); return;
  }
  getauthedas(tg->creator,unum);
  newmsgtouser(unum, "%s %s from %d to %d.", whats[whatwedo], (tmps4[0] == '-') ? "lowered" : "raised", previous, newv);
  sprintf(tmps2,"%s created/updated Trustgroup %s (#%ld) - %lu / %lu / %d",
    tg->creator,tg->name,tg->id,tg->trustedfor,tg->maxperident,tg->enforceident);
  sendtonoticemask(NM_TRUSTS,tmps2);
}
Exemplo n.º 12
0
//This method analyses the user input string and creates the task to be added
//and adds it the Storage.
//Analyses for the name, date and time of the task which are handled by other methods.
//Returns information about the task added to Logic.
DataFeedback AddCommand::execute(Storage& container) {

	write.writeLogToFile("addCommand::execute","Enter");
	vector<Task*> taskList;
	string taskName;
	TASK_DATE taskDate;

	if(isChangeFloatTask(taskInfo)) {

		//remove "wl" from the string
		shortenInput(taskInfo);
		taskName = taskInfo;

		if(taskName.empty()) {

			DataFeedback logicFeedback(INVALID_NO_NAME);
			return logicFeedback;

		} else {

			addedTask = new Task(taskInfo);
			taskList = container.addFloatTask(addedTask);
			DataFeedback logicFeedback(ADD_SUCCESS, taskList, addedTask, CHANGED_FLOAT);
			write.writeLogToFile("addCommand::execute","Exit");
			return logicFeedback;
		}

	} else {

		taskInfo = toLowerCase(taskInfo);

		bool haveDate;
		bool haveDay;
		int dayPosition = findDayPosition(taskInfo);
		int datePosition = findDatePosition(taskInfo);

		haveDay = isPositionFound(dayPosition);
		haveDate = isPositionFound(datePosition);

		//If user inputs both a valid day of the week and date, 
		//the one that comes later in the input is taken as the task date indicator
		if(haveDay == true && haveDate == true) {
			if(dayPosition > datePosition) {
				haveDate = false;
			} else {
				haveDay = false;
			}
		}

		//Code below determines name and date of task
		if(haveDay == true) {

			try {
				taskName = determineName(taskInfo, dayPosition);
			} catch (Exception nameExcpt) {
				return nameExcpt.getFeedback();
			}

			taskDate = determineDateForDayFormat(taskInfo);

		} else if(haveDate == true) {

			try {
				taskName = determineName(taskInfo, datePosition);
			} catch (Exception nameExcpt) {
				return nameExcpt.getFeedback();
			}

			try {
				taskDate = determineDateForDateFormat(taskInfo);
			} catch (Exception dateExcpt) {
				return dateExcpt.getFeedback();
			}

			if(dateHasPassed(taskDate)) {
				DataFeedback invalidFeedback(INVALID_DATE_PASSED);
				return invalidFeedback;
			}

		} else {

			DataFeedback invalidFeedback(INVALID_DATE);
			return invalidFeedback;
		}

		//Code below determines task time and creates task
		string timeString;
		istringstream inputStream(taskInfo);
		inputStream >> timeString;

		if(taskInfo.find_first_of(HYPHEN) == NOT_FOUND) {

			TIME taskTime;

			try {
				taskTime = determineTaskTime(timeString, taskDate);
			} catch(Exception timeExcpt) {
				return timeExcpt.getFeedback();
			}

			if(inputStream >> timeString) {

				DataFeedback logicFeedback(INVALID_TIME_FORMAT);
				return logicFeedback;

			} else {

				addedTask = new DeadlineTask(taskName, taskDate, taskTime);
				taskList = container.addTimedTask(addedTask);
				DataFeedback logicFeedback(ADD_SUCCESS, taskList, addedTask, CHANGED_TIMED);
				write.writeLogToFile("addCommand::execute","Exit");
				return logicFeedback;
			}
		
		} else {
Exemplo n.º 13
0
std::string DynomiteConfig::generateConfigFile() {
    std::string localIp = getIpAddress();
    LOG( INFO ) << "Get local ip address [" << localIp << "].";

    std::string filename = getRandomTempFile();
    LOG( INFO ) << "Generate temporary configuration at [" << filename << "].";

    int token = std::rand();
    LOG( INFO ) << "Generate dynomite token [" << token << "].";

    std::string serviceName = getClusterName();
    LOG( INFO ) << "Get dynomite service name [" << serviceName << "].";

    int port = getDynomitePort();
    LOG( INFO ) << "Get dynomite port [" << port << "].";

    consul_datacenter dc;
    int ret = client->getDefaultDatacenter( dc );
    if( ret != 0 ) {
        LOG( ERROR ) << "Error in getting data center information from consul:" << ret;
        exit( ret );
    }

    std::stringstream ss;
    ss << localIp << ":" << port << ":default-rack-" << toLowerCase( dc.name )
        << ":" << dc.name << ":" << token;
    std::string tagId = ss.str();

    LOG( INFO ) << "Generate tag id [" << tagId << "].";

    consul_service dynomiteService;
    dynomiteService.service_id = serviceName + "_" + localIp;
    dynomiteService.service_name = serviceName;
    dynomiteService.service_address = localIp;
    dynomiteService.service_port = port;

    std::vector<consul_service> services;
    client->getService( serviceName, services );

    std::string seed = "";
    if( !services.empty() ) {
        std::vector<consul_service>::iterator it =
                std::find_if( services.begin(), services.end(),
                []( consul_service cs ) -> bool {
                    return cs.tags.find( "seed" ) != cs.tags.end();
                } );
        if( it != services.end() ){
            std::set<std::string>::iterator tagIt =
                    std::find_if( it->tags.begin(), it->tags.end(),
                    []( std::string tag ) -> bool {
                        return tag != "seed";
                    } );
            seed = *tagIt;
        }
    }

    std::ofstream ofstream;
    ofstream.open( filename );

    ofstream << getClusterName() << ":" << std::endl;
    ofstream << "  datacenter: " << dc.name << std::endl;
    ofstream << "  rack: default-rack-" << toLowerCase( dc.name ) << std::endl;
    ofstream << "  dyn_listen: 0.0.0.0:" << port << std::endl;
    ofstream << "  listen: 0.0.0.0:" << ( port + 1 ) << std::endl;
    ofstream << "  servers:" << std::endl;
    ofstream << "  - 127.0.0.1:6379:1" << std::endl;
    ofstream << "  tokens: '" << token << "'" << std::endl;
    ofstream << "  redis: true" << std::endl;
    ofstream << "  secure_server_option: datacenter" << std::endl;
    ofstream << "  pem_key_file: /var/dynomite/dynomite.pem" << std::endl;

    if( seed.empty() ) {
        LOG( INFO ) << "No seed server, start as seed server.";
        dynomiteService.tags.insert( "seed" );
        dynomiteService.tags.insert( tagId );
    } else {
        LOG( INFO ) << "Find seed [" << seed << "]";
        ofstream << "  dyn_seeds:" << std::endl;
        ofstream << "  - " << seed << std::endl;
        dynomiteService.tags.insert( tagId );
    }

    ofstream.close();

    ret = client->registerService( dynomiteService );
    if( ret != 0 ){
        LOG( ERROR ) << "Error to register dynomite service, return " << ret;
        exit( ret );
    }

    return filename;
}
Exemplo n.º 14
0
bool String::equalsIgnoreCase(const sp<String>& string) const {
	return toLowerCase()->equals(string->toLowerCase());
}
Exemplo n.º 15
0
void dotrustspew(long unum, char *tail) {
  int res; char tmps2[TMPSSIZE], tmps3[TMPSSIZE], tmps4[TMPSSIZE], tmps5[TMPSSIZE];
  trustedgroup *tg; trustedhost *th; int i; userdata *ud; long k, l;
  array listofths; int iamtired;
  res=sscanf(tail, "%s %s %s",tmps2,tmps3,tmps4);
  if (res<2) {
    msgtouser(unum,"Syntax: trustspew <groupname OR #groupID> [user]");
    return;
  }
  if (res==2) { strcpy(tmps4,"*"); }
  tmps4[USERLEN+2]='\0';
  toLowerCase(tmps3); toLowerCase(tmps4);
  if (tmps3[0]=='#') {
    tg=findtrustgroupbyID(strtol(&tmps3[1],NULL,10));
  } else {
    tg=findtrustgroupbyname(tmps3);
  }
  if (tg==NULL) {
    sprintf(tmps2,"A trustgroup with that %s does not exist.",(tmps3[0]=='#') ? "ID" : "name");
    msgtouser(unum,tmps2); return;
  }
  /* First, create a list of all hosts in that trustgroup... */
  array_init(&listofths,sizeof(unsigned long));
  for (i=0;i<SIZEOFTL;i++) {
    th=trustedhosts[i];
    while (th!=NULL) {
      if (th->id==tg->id) { /* mmkay, that one belongs to our group */
        long j;
        j=array_getfreeslot(&listofths);
        ((unsigned long *)listofths.content)[j]=th->IPv4;
      }
      th=(void *)th->next;
    }
  }
  if (listofths.cursi==0) {
    msgtouser(unum,"There are no hosts in that trustgroup.");
    array_free(&listofths);
    return;
  }
  /* We have the list - scan through the whole userlist, and match against our
     hostlist, and if that matches, match again against the username */
  sprintf(tmps2,"Users in Trustgroup %s (#%lu) matching %s",tg->name,tg->id,tmps4);
  msgtouser(unum,tmps2);
  l=0;
  for (i=0;i<SIZEOFUL;i++) {
    ud=uls[i];
    while (ud!=NULL) {
      for (k=0;k<listofths.cursi;k++) {
        if (((unsigned long *)listofths.content)[k]==ud->realip) {
          /* Host matches, check username */
          strcpy(tmps5,ud->ident);
          toLowerCase(tmps5);
          if (match2strings(tmps4,tmps5)) {
            /* yay ident matches too - list that loser */
            channel **d; int chanmodes; char * mycip;
            l++; /* inc counter of number of users found */
            mycip=printipv4(ud->realip);
            sprintf(tmps2,"%s!%s@%s(=%s) (%s)",ud->nick,ud->ident,ud->host,mycip,ud->realname);
            msgtouser(unum,tmps2);
            if (ud->chans.cursi>0) {
              if (ud->chans.cursi==1) {
                strcpy(tmps2,"On channel:");
              } else {
                strcpy(tmps2,"On channels:");
              }
              for (iamtired=0;iamtired<(ud->chans.cursi);iamtired++) {
                d=(channel **)(ud->chans.content);
                if ((strlen(d[iamtired]->name)+strlen(tmps2))>400) {
                  strcat(tmps2," [...]"); break;
                } else {
                  chanmodes=getchanmode2(d[iamtired],ud->numeric);
                  strcat(tmps2," ");
                  if (chanmodes<0) {
                    strcat(tmps2,"?");
                  } else {
                    if (isflagset(chanmodes,um_o)) { strcat(tmps2,"@"); } else { strcat(tmps2," "); }
                  }
                  strcat(tmps2,d[iamtired]->name);
                }
              }
            } else {
              strcpy(tmps2,"Not on any (nonlocal-)channels");
            }
            msgtouser(unum,tmps2);
          }
        }
      }
      ud=(void *)ud->next;
    }
  }
  sprintf(tmps2,"--- End of list - %ld matches ---",l);
  msgtouser(unum,tmps2);
  array_free(&listofths);
}
Exemplo n.º 16
0
void TCString::toLowerCase ()
{
    toLowerCase(string);
}
Exemplo n.º 17
0
void dotrustdenyadd(long unum, char *tail) {
  int res; long i; trustdeny *td; long expires;
  char tmps2[TMPSSIZE], tmps3[TMPSSIZE], tmps4[TMPSSIZE], tmps5[TMPSSIZE], tmps6[TMPSSIZE];
  unsigned long snet, smask;
  res=sscanf(tail,"%s %s %s %s %[^\n]",tmps2,tmps3,tmps4,tmps5,tmps6);
  if (res<5) {
    msgtouser(unum,"Syntax: trustdenyadd warn|deny subnet[/netmask] duration reason");
    msgtouser(unum,"if netmask is omitted, then /32 (a single IP) is assumed.");
    return;
  }
  toLowerCase(tmps3);
  if (strcmp(tmps3,"warn")==0) { res=TRUSTDENY_WARN; }
  if (strcmp(tmps3,"deny")==0) { res=TRUSTDENY_DENY; }
  if ((res!=TRUSTDENY_WARN) && (res!=TRUSTDENY_DENY)) {
    msgtouser(unum,"You can only warn or deny.");
    return;
  }
  if (!ischarinstr('/',tmps4)) {
    smask=32;
    snet=parseipv4(tmps4);
  } else {
    char h1[TMPSSIZE]; char h2[TMPSSIZE]; char dumc; int r2;
    r2=sscanf(tmps4,"%[0-9.]%c%[0-9]",h1,&dumc,h2);
    if (r2!=3) { msgtouser(unum,"Invalid subnetmask."); return; }
    snet=parseipv4(h1);
    smask=strtoul(h2,NULL,10);
    if (smask>32) { msgtouser(unum,"Invalid subnetmask."); return; }
  }
  expires=durationtolong(tmps5);
  if (expires<1) {
    msgtouser(unum,"Invalid duration.");
    return;
  }
  expires+=getnettime();
  td=(trustdeny *)deniedtrusts.content;
  for (i=0;i<deniedtrusts.cursi;i++) {
    if ((td[i].v4net==snet) && (td[i].v4mask=smask)) {
      longtoduration(tmps2,getnettime()-td[i].created);
      longtoduration(tmps3,td[i].expires-getnettime());
      msgtouser(unum,"a trustdeny for that hostmask already exists - replacing values");
      newmsgtouser(unum,"Old one was created by %s %s ago, expiring in %s and mode %s",
        td[i].creator,tmps2,tmps3,(td[i].type==TRUSTDENY_WARN) ? "WARN" : "DENY");
      getauthedas(tmps2,unum);
      mystrncpy(td[i].creator,tmps2,AUTHUSERLEN);
      mystrncpy(td[i].reason,tmps6,RNGREAS);
      td[i].expires=expires;
      td[i].created=getnettime();
      td[i].type=res;
      msgtouser(unum,"Done.");
      return;
    }
  }
  /* Not existing yet - allocate new entry */
  i=array_getfreeslot(&deniedtrusts);
  td=(trustdeny *)deniedtrusts.content;
  getauthedas(tmps2,unum);
  mystrncpy(td[i].creator,tmps2,AUTHUSERLEN);
  mystrncpy(td[i].reason,tmps6,RNGREAS);
  td[i].expires=expires;
  td[i].created=getnettime();
  td[i].v4net=snet;
  td[i].v4mask=smask;
  td[i].type=res;
  recreateimpsntrusts();
  msgtouser(unum,"Done.");
}
Exemplo n.º 18
0
MediaFile *MediaDatabase::search(const TCHAR *fname) {
  return get(toLowerCase(fname));
}
Exemplo n.º 19
0
// ######################################################################
ResizeSpec ResizeSpec::fromString(const std::string& origstr)
{
  const std::string str = toLowerCase(origstr);

  if (str.length() == 0
      || str.compare("none") == 0
      || str.compare("noop") == 0)
    {
      return ResizeSpec(); // no-op ResizeSpec
    }
  else if (str[0] == '*' || str[0] == '/')
    {
      const Method m = (str[0] == '*' ? SCALE_UP : SCALE_DOWN);

      std::vector<std::string> parts;
      split(str.substr(1), "x", std::back_inserter(parts));

      if (parts.size() == 1)
        {
          const double f = fromStr<double>(parts[0]);
          if (f < 0.0)
            LFATAL("while parsing '%s' as a ResizeSpec: expected "
                   "a non-negative scale factor, but got %s",
                   origstr.c_str(), parts[0].c_str());

          if (f == 0.0 || f == 1.0)
            return ResizeSpec(); // no-op ResizeSpec

          return ResizeSpec(m, Dims(), f, f);
        }
      else if (parts.size() == 2)
        {
          const double fw = fromStr<double>(parts[0]);
          const double fh = fromStr<double>(parts[1]);

          if (fw < 0.0)
            LFATAL("while parsing '%s' as a ResizeSpec: expected "
                   "a non-negative scale factor, but got %s",
                   origstr.c_str(), parts[0].c_str());

          if (fh < 0.0)
            LFATAL("while parsing '%s' as a ResizeSpec: expected "
                   "a non-negative scale factor, but got %s",
                   origstr.c_str(), parts[1].c_str());

          if ((fw == 0.0 || fw == 1.0) && (fh == 0.0 || fh == 1.0))
            return ResizeSpec(); // no-op ResizeSpec

          return ResizeSpec(m, Dims(), fw, fh);
        }
      else
        LFATAL("while parsing '%s' as a ResizeSpec: after '%c', "
               "expected either one floating-point value or "
               "two values separated by 'x', but got '%s'",
               origstr.c_str(), str[0], str.substr(1).c_str());
    }
  else
    {
      const Dims d = fromStr<Dims>(str);
      if (d.isEmpty())
        return ResizeSpec(); // no-op ResizeSpec
      return ResizeSpec(FIXED, d, 0.0, 0.0);
    }

  conversion_error::raise<ResizeSpec>(origstr);
  ASSERT(0); /* can't happen */ return ResizeSpec();
}
char* _NativeFrameworkDSString::toLowercase(){
	return toLowerCase();
}
Exemplo n.º 21
0
  void State::parse(Ref<TokenStream> cin)
  {
    /* parse until end of stream */
    while (cin->peek() != Token::Eof())
    {
      const Token tok = cin->get();

      if (tok == Token::Id("threads") && cin->trySymbol("=")) 
        numThreads = cin->get().Int();
      
      else if (tok == Token::Id("set_affinity")&& cin->trySymbol("=")) 
        set_affinity = cin->get().Int();
      
      else if (tok == Token::Id("isa") && cin->trySymbol("=")) {
        std::string isa = toLowerCase(cin->get().Identifier());
        enabled_cpu_features = string_to_cpufeatures(isa);
      }

      else if (tok == Token::Id("max_isa") && cin->trySymbol("=")) {
        std::string isa = toLowerCase(cin->get().Identifier());
        enabled_cpu_features &= string_to_cpufeatures(isa);
      }

      else if (tok == Token::Id("float_exceptions") && cin->trySymbol("=")) 
        float_exceptions = cin->get().Int();

      else if ((tok == Token::Id("tri_accel") || tok == Token::Id("accel")) && cin->trySymbol("="))
        tri_accel = cin->get().Identifier();
      else if ((tok == Token::Id("tri_builder") || tok == Token::Id("builder")) && cin->trySymbol("="))
        tri_builder = cin->get().Identifier();
      else if ((tok == Token::Id("tri_traverser") || tok == Token::Id("traverser")) && cin->trySymbol("="))
        tri_traverser = cin->get().Identifier();
      else if (tok == Token::Id("tri_builder_replication_factor") && cin->trySymbol("="))
        tri_builder_replication_factor = cin->get().Int();

      else if ((tok == Token::Id("tri_accel_mb") || tok == Token::Id("accel_mb")) && cin->trySymbol("="))
        tri_accel_mb = cin->get().Identifier();
      else if ((tok == Token::Id("tri_builder_mb") || tok == Token::Id("builder_mb")) && cin->trySymbol("="))
        tri_builder_mb = cin->get().Identifier();
      else if ((tok == Token::Id("tri_traverser_mb") || tok == Token::Id("traverser_mb")) && cin->trySymbol("="))
        tri_traverser_mb = cin->get().Identifier();

      else if ((tok == Token::Id("quad_accel")) && cin->trySymbol("="))
        quad_accel = cin->get().Identifier();
      else if ((tok == Token::Id("quad_builder")) && cin->trySymbol("="))
        quad_builder = cin->get().Identifier();
      else if ((tok == Token::Id("quad_traverser")) && cin->trySymbol("="))
        quad_traverser = cin->get().Identifier();

      else if ((tok == Token::Id("quad_accel_mb")) && cin->trySymbol("="))
        quad_accel_mb = cin->get().Identifier();
      else if ((tok == Token::Id("quad_builder_mb")) && cin->trySymbol("="))
        quad_builder_mb = cin->get().Identifier();
      else if ((tok == Token::Id("quad_traverser_mb")) && cin->trySymbol("="))
        quad_traverser_mb = cin->get().Identifier();

      else if ((tok == Token::Id("line_accel")) && cin->trySymbol("="))
        line_accel = cin->get().Identifier();
      else if ((tok == Token::Id("line_builder")) && cin->trySymbol("="))
        line_builder = cin->get().Identifier();
      else if ((tok == Token::Id("line_traverser")) && cin->trySymbol("="))
        line_traverser = cin->get().Identifier();

      else if ((tok == Token::Id("line_accel_mb")) && cin->trySymbol("="))
        line_accel_mb = cin->get().Identifier();
      else if ((tok == Token::Id("line_builder_mb")) && cin->trySymbol("="))
        line_builder_mb = cin->get().Identifier();
      else if ((tok == Token::Id("line_traverser_mb")) && cin->trySymbol("="))
        line_traverser_mb = cin->get().Identifier();
      
      else if (tok == Token::Id("hair_accel") && cin->trySymbol("="))
        hair_accel = cin->get().Identifier();
      else if (tok == Token::Id("hair_builder") && cin->trySymbol("="))
        hair_builder = cin->get().Identifier();
      else if (tok == Token::Id("hair_traverser") && cin->trySymbol("="))
        hair_traverser = cin->get().Identifier();
      else if (tok == Token::Id("hair_builder_replication_factor") && cin->trySymbol("="))
        hair_builder_replication_factor = cin->get().Int();

      else if (tok == Token::Id("hair_accel_mb") && cin->trySymbol("="))
        hair_accel_mb = cin->get().Identifier();

      else if (tok == Token::Id("object_accel_min_leaf_size") && cin->trySymbol("="))
        object_accel_min_leaf_size = cin->get().Int();
      else if (tok == Token::Id("object_accel_max_leaf_size") && cin->trySymbol("="))
        object_accel_max_leaf_size = cin->get().Int();

      else if (tok == Token::Id("object_accel_mb_min_leaf_size") && cin->trySymbol("="))
        object_accel_mb_min_leaf_size = cin->get().Int();
      else if (tok == Token::Id("object_accel_mb_max_leaf_size") && cin->trySymbol("="))
        object_accel_mb_max_leaf_size = cin->get().Int();

      else if (tok == Token::Id("subdiv_accel") && cin->trySymbol("="))
        subdiv_accel = cin->get().Identifier();
      
      else if (tok == Token::Id("verbose") && cin->trySymbol("="))
        verbose = cin->get().Int();
      else if (tok == Token::Id("benchmark") && cin->trySymbol("="))
        benchmark = cin->get().Int();
      
      else if (tok == Token::Id("flags")) {
        scene_flags = 0;
        if (cin->trySymbol("=")) {
          do {
            Token flag = cin->get();
            if      (flag == Token::Id("static") ) scene_flags |= RTC_SCENE_STATIC;
            else if (flag == Token::Id("dynamic")) scene_flags |= RTC_SCENE_DYNAMIC;
            else if (flag == Token::Id("compact")) scene_flags |= RTC_SCENE_COMPACT;
            else if (flag == Token::Id("coherent")) scene_flags |= RTC_SCENE_COHERENT;
            else if (flag == Token::Id("incoherent")) scene_flags |= RTC_SCENE_INCOHERENT;
            else if (flag == Token::Id("high_quality")) scene_flags |= RTC_SCENE_HIGH_QUALITY;
            else if (flag == Token::Id("robust")) scene_flags |= RTC_SCENE_ROBUST;
          } while (cin->trySymbol("|"));
        }
      }
      else if (tok == Token::Id("memory_preallocation_factor") && cin->trySymbol("=")) 
        memory_preallocation_factor = cin->get().Float();
      
      else if (tok == Token::Id("regression") && cin->trySymbol("=")) 
        regression_testing = cin->get().Int();
      
      else if (tok == Token::Id("tessellation_cache_size") && cin->trySymbol("="))
        tessellation_cache_size = cin->get().Float() * 1024 * 1024;

      cin->trySymbol(","); // optional , separator
    }
  }
Exemplo n.º 22
0
//******************************************************************************
// Mask the Fasta file based on the coordinates in the BED file.
//******************************************************************************
void MaskFastaFromBed::MaskFasta() {

    /* Make sure that we can open all of the files successfully*/

    // open the fasta database for reading
    ifstream fa(_fastaInFile.c_str(), ios::in);
    if ( !fa ) {
        cerr << "Error: The requested fasta file (" << _fastaInFile << ") could not be opened. Exiting!" << endl;
        exit (1);
    }

    // open the fasta database for reading
    ofstream faOut(_fastaOutFile.c_str(), ios::out);
    if ( !faOut ) {
        cerr << "Error: The requested fasta output file (" << _fastaOutFile << ") could not be opened. Exiting!" << endl;
        exit (1);
    }


    /* Read the fastaDb chromosome by chromosome*/
    string fastaInLine;
    string currChromFull;
    string currChrom;
    string currDNA = "";
    currDNA.reserve(500000000);
    CHRPOS fastaWidth = -1;
    bool widthSet  = false;
    CHRPOS start, end, length;
    string replacement;

    while (getline(fa,fastaInLine)) {

        if (fastaInLine.find(">",0) != 0 ) {
            if (widthSet == false) {
                fastaWidth = fastaInLine.size();
                widthSet = true;
            }
            currDNA += fastaInLine;
        }
        else {
            if (currDNA.size() > 0) {

                vector<BED> bedList = _bed->bedMapNoBin[currChrom];

                /*
                    loop through each BED entry for this chrom and
                    mask the requested sequence in the FASTA file.
                */
                for (unsigned int i = 0; i < bedList.size(); i++) {
                    start = bedList[i].start;
                    end = bedList[i].end;
                    length = end - start;

                    /*
                       (1) if soft masking, extract the sequence, lowercase it,
                           then put it back
                       (2) otherwise replace with Ns
                    */
                    if (_softMask) {
                        replacement = currDNA.substr(start, length);
                        toLowerCase(replacement);
                        currDNA.replace(start, length, replacement);
                    }
                    else {
                        string hardmask(length, _maskChar);
                        currDNA.replace(start, length, hardmask);
                    }
                }
                // write the masked chrom to the output file
                PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth);
            }

            // reset for the next chromosome.
            currChromFull = fastaInLine.substr(1);
            currChrom = split(currChromFull, " \t").at(0);
            currDNA = "";
        }
    }

    // process the last chromosome.
    // exact same logic as in the main loop.
    if (currDNA.size() > 0) {

        vector<BED> bedList = _bed->bedMapNoBin[currChrom];

        for (unsigned int i = 0; i < bedList.size(); i++) {
            start = bedList[i].start;
            end = bedList[i].end;
            length = end - start;

            if (_softMask) {
                replacement = currDNA.substr(start, length);
                toLowerCase(replacement);
                currDNA.replace(start, length, replacement);
            }
            else {
                string hardmask(length, _maskChar);
                currDNA.replace(start, length, hardmask);
            }
        }
        PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth);
    }

    // closed for business.
    fa.close();
    faOut.close();
}
Exemplo n.º 23
0
Arquivo: strlib.c Projeto: cs50/spl
static void testConvertToLowerCase(void) {
   test(toLowerCase("ABC"), "abc");
   test(toLowerCase("#A1"), "#a1");
}