问:
Why can't I declare new tokens in flex/bison?
I just added a set of new tokens to my parser, and each of the new ones is reported as undeclared. The first line of tokens were included in the last working build.

```<code>%token <token> NUMCONST STRINGCONST IDENT CHARCONST BOOLCONST
%token <token> BEGIN END IF THEN ELSE WHILE DO FOR TO BY RETURN BREAK OR AND NOT STATIC BOOL CHAR INT
%token <token> DPLUS DMINUS LASSIGN PLUSEQ MINUSEQ TIMEEQ DIVEQ NOTEQ
</code>```

The error messages I get after running my makefile indicate that none of the new tokens are properly declared, although all of the old ones are still functioning.

```<code>cScan.l:44:9: error: ‘STATIC’ undeclared (first use in this function)
 static  {return STATIC;}
         ^
cScan.l:44:9: note: each undeclared identifier is reported only once for each function it appears in
cScan.l:45:9: error: ‘BOOL’ undeclared (first use in this function)
 bool    {return BOOL;}
         ^
cScan.l:46:9: error: ‘CHAR’ undeclared (first use in this function)
 char    {return CHAR;}
         ^
cScan.l:47:10: error: ‘INT’ undeclared (first use in this function)
 int     { return INT; }
          ^
cScan.l:48:15: error: expected expression before ‘;’ token
 begin    { return BEGIN;}
               ^
cScan.l:49:9: error: ‘END’ undeclared (first use in this function)
 end    {return END;}
         ^
cScan.l:50:9: error: ‘IF’ undeclared (first use in this function)
 if    {return IF;}
         ^
cScan.l:51:9: error: ‘THEN’ undeclared (first use in this function)
 then    {return THEN;}
         ^
cScan.l:52:9: error: ‘ELSE’ undeclared (first use in this function)
 else    {return ELSE;}
         ^
cScan.l:53:9: error: ‘WHILE’ undeclared (first use in this function)
 while    {return WHILE;}
         ^
cScan.l:54:9: error: ‘DO’ undeclared (first use in this function)
 do    {return DO;}
         ^
cScan.l:55:9: error: ‘FOR’ undeclared (first use in this function)
 for    {return FOR;}
         ^
cScan.l:56:9: error: ‘TO’ undeclared (first use in this function)
 to    {return TO;}
         ^
cScan.l:57:9: error: ‘BY’ undeclared (first use in this function)
 by    {return BY;}
         ^
cScan.l:58:9: error: ‘RETURN’ undeclared (first use in this function)
 return    {return RETURN;}
         ^
cScan.l:59:9: error: ‘BREAK’ undeclared (first use in this function)
 break    {return BREAK;}
         ^
cScan.l:60:9: error: ‘OR’ undeclared (first use in this function)
 or    {return OR;}
         ^
cScan.l:61:9: error: ‘AND’ undeclared (first use in this function)
 and    {return AND;}
         ^
cScan.l:62:10: error: ‘NOT’ undeclared (first use in this function)
 not { return NOT;}
          ^
cScan.l:64:10: error: ‘DPLUS’ undeclared (first use in this function)
 "++" { return DPLUS; }
          ^
cScan.l:65:10: error: ‘DMINUS’ undeclared (first use in this function)
 "--" { return DMINUS; }
          ^
cScan.l:66:10: error: ‘LASSIGN’ undeclared (first use in this function)
 "<-" { return LASSIGN; }
          ^
cScan.l:67:10: error: ‘PLUSEQ’ undeclared (first use in this function)
 "+=" { return PLUSEQ; }
          ^
cScan.l:68:10: error: ‘MINUSEQ’ undeclared (first use in this function)
 "-=" { return MINUSEQ; }
          ^
cScan.l:69:10: error: ‘TIMEEQ’ undeclared (first use in this function)
 "*=" { return TIMEEQ; }
          ^
cScan.l:70:10: error: ‘DIVEQ’ undeclared (first use in this function)
 "/=" { return DIVEQ; }
          ^
cScan.l:71:10: error: ‘NOTEQ’ undeclared (first use in this function)
 "!=" { return NOTEQ; }

</code>```

Here's the flex file where I return each of the tokens:

```<code>%{
/*
 * cScan.l
 */
 #include "scanType.h"
 #include "cScan.tab.h"

%}

%option yylineno

LETTER   [A-Za-z]
ID       {LETTER}[_A-Za-z0-9]*
NUMCONST [0-9]+
STRINGCONST \"([^\\\"]|\\.)*\"
CHARCONST '\\?.'
BOOLCONST true|false

%%

{BOOLCONST} {
    struct TokenData boolToken;
    yylval.token = &boolToken;
    yylval.token->tokenclass = 5;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    if(yytext[0] == 't') {
        yylval.token->nvalue = 1;
    } else {
        yylval.token->nvalue = 0;
    }
    return BOOLCONST;
}

static  { return STATIC; }
bool    { return BOOL; }
char    { return CHAR; }
int     { return INT; }
begin    { return BEGIN;}
end    { return END;}
if    { return IF;}
then    { return THEN;}
else    { return ELSE;}
while    { return WHILE;}
do    { return DO;}
for    { return FOR;}
to    { return TO;}
by    { return BY;}
return    { return RETURN;}
break    { return BREAK;}
or    { return OR; }
and    { return AND; }
not { return NOT;}

"++" { return DPLUS; }
"--" { return DMINUS; }
"<-" { return LASSIGN; }
"+=" { return PLUSEQ; }
"-=" { return MINUSEQ; }
"*=" { return TIMEEQ; }
"/=" { return DIVEQ; }
"!=" { return NOTEQ; }

{ID}        {
    struct TokenData idToken;
    yylval.token = &idToken;
    yylval.token->tokenclass = 1;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    yylval.token->svalue = yytext;
    return IDENT;
}

{NUMCONST} {
    struct TokenData numToken;
    yylval.token = &numToken;
    yylval.token->tokenclass = 2;
    yylval.token->linenum = yylineno;
    yylval.token->nvalue = atoi(yytext);
    yylval.token->tokenstr = yytext;
    return NUMCONST;
}

{STRINGCONST}   {
    struct TokenData stringToken;
    yylval.token = &stringToken;
    yylval.token->tokenclass = 3;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    yylval.token->svalue = yytext;
    yylval.token->nvalue = yyleng-2;
    return STRINGCONST;
}

{CHARCONST}   {
    struct TokenData charToken;
    yylval.token = &charToken;
    yylval.token->tokenclass = 4;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    yylval.token->svalue = yytext;

    return CHARCONST;
}

"="|"<"|">"|"+"|"-"|"*"|"/"|"%"|"["|"]"|"*"|"-"|"?"|"("|")"|";"|","|":" { return yytext[0]; }

[ \t\r]         ;

##.*\n          ;

\n              { ; /*option to add stuff*/ }

.               { printf("ERROR(%d): Invalid or misplaced input character: '%c'. Character Ignored.\n", yylineno, yytext[0]); }
%%

/*
 * When the end of an input file is encountered, exit with success (1).
 */
int yywrap() {
    return 1;
}
</code>```

The tokens are all listed in the cScan.tab.h file, which is included in cScan.l. Here's their definition.

```<code>/* Token type.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
  enum yytokentype
  {
    NUMCONST = 258,
    STRINGCONST = 259,
    IDENT = 260,
    CHARCONST = 261,
    BOOLCONST = 262,
    BEGIN = 263,
    END = 264,
    IF = 265,
    THEN = 266,
    ELSE = 267,
    WHILE = 268,
    DO = 269,
    FOR = 270,
    TO = 271,
    BY = 272,
    RETURN = 273,
    BREAK = 274,
    OR = 275,
    AND = 276,
    NOT = 277,
    STATIC = 278,
    BOOL = 279,
    CHAR = 280,
    INT = 281,
    DPLUS = 282,
    DMINUS = 283,
    LASSIGN = 284,
    PLUSEQ = 285,
    MINUSEQ = 286,
    TIMEEQ = 287,
    DIVEQ = 288,
    NOTEQ = 289
  };
#endif

</code>```

This is the make file I'm running. I've deleted each of the generated files and run it again, but that doesn't seem to be the issue.

```<code>cc = gcc
ccopts = #-ly
lex = flex
lexopts =
lexgens = lex.yy.c
yacc = bison
yaccopts = -d
yaccgens = cScan.tab.c cScan.tab.h
prj = cScan

$(prj): $(lexgens) $(yaccgens)
    $(cc) $(lexgens) $(yaccgens) $(ccopts) -o $(prj)

clean:
    rm $(lexgens) $(yaccgens) $(prj)

$(yaccgens): $(prj).y
    $(yacc) $(yaccopts) $(prj).y

$(lexgens): $(prj).l $(yaccgens)
    $(lex) $(lexopts) $(prj).l
</code>```

Here's the whole bison file, for completeness.

```<code>%{
#include "scanType.h"
#include "treeType.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void yyerror(char*);
int yylex(void);
extern FILE *yyin;

%}

%define parse.error verbose

%union {
    struct TokenData *token;//for terminals, from yylex
    struct TreeNode *tree;//for nonterminals, to build the tree
    char op;
}

%token <token> NUMCONST STRINGCONST IDENT CHARCONST BOOLCONST
%token <token> BEGIN END IF THEN ELSE WHILE DO FOR TO BY RETURN BREAK OR AND NOT STATIC BOOL CHAR INT
%token <token> DPLUS DMINUS LASSIGN PLUSEQ MINUSEQ TIMEEQ DIVEQ NOTEQ

%%

program :
    declList
    ;

declList
    : declList decl
    | decl
    ;

decl
    : varDecl
    | funDecl
    ;

varDecl
    : typeSpec varDeclList ';'
    ;

scopedVarDecl
    : STATIC typeSpec varDeclList ';'
    | typeSpec varDeclList ';'
    ;

varDeclList
    : varDeclList ',' varDeclInit
    | varDeclInit
    ;

varDeclInit
    : varDeclId
    | varDeclId ':' simpleExp
    ;

varDeclId
    : IDENT
    | IDENT '[' NUMCONST ']'
    ;

typeSpec
    : BOOL
    | CHAR
    | INT
    ;

funDecl
    : typeSpec IDENT '(' parms ')' compoundStmt
    | IDENT '(' parms ')' compoundStmt
    ;

parms
    : parmList
    | {/*Epsilon*/}
    ;

parmList
    : parmList ';' parmTypeList
    | parmTypeList
    ;

parmTypeList
    : typeSpec parmIdList
    ;

parmIdList
    : parmIdList ',' parmId
    | parmId
    ;

parmId
    : IDENT
    | IDENT '['']'
    ;

stmt
    : matchStmt
    | unmatchStmt
    ;

matchStmt
    : selectStmt_M
    | iterStmt_M
    | otherStmt
    ;

unmatchStmt
    : selectStmt_U
    | iterStmt_U
    ;

selectStmt_M
    : IF simpleExp THEN matchStmt ELSE matchStmt
    ;

selectStmt_U
    : IF simpleExp THEN stmt
    | IF simpleExp THEN matchStmt ELSE unmatchStmt
    ;

iterStmt_U
    : WHILE simpleExp DO unmatchStmt
    | FOR IDENT LASSIGN iterRange DO unmatchStmt
    ;

iterStmt_M
    : WHILE simpleExp DO matchStmt
    | FOR IDENT LASSIGN iterRange DO matchStmt
    ;

iterRange
    : simpleExp TO simpleExp iterRangeStmtPr
    ;

iterRangeStmtPr
    : BY simpleExp
    | {/*Addition to stop ambiguity*/}
    ;

otherStmt
    : expStmt
    | returnStmt
    | breakStmt
    | compoundStmt
    ;

compoundStmt
    :  BEGIN localDecls stmtList END
    ;

localDecls
    : localDecls scopedVarDecl
    | {/*Epsilon*/}
    ;

stmtList
    : stmtList stmt
    | {/*Epsilon*/}
    ;

expStmt
    : exp ';'
    | ';'
    ;

returnStmt
    : RETURN ';'
    | RETURN exp ';'
    ;

breakStmt
    : BREAK ';'
    ;

exp
    : mutExp
    | simpleExp
    ;

mutExp
    : mutable assignop exp
    | mutable DPLUS
    | mutable DMINUS
    ;

assignop
    : LASSIGN | PLUSEQ | MINUSEQ | TIMEEQ | DIVEQ
    ;

simpleExp
    : simpleExp OR andExp
    | andExp
    ;

andExp
    : andExp AND unaryRelExp
    | unaryRelExp
    ;

unaryRelExp
    : NOT unaryRelExp
    | relExp
    ;

relExp
    : sumExp relop sumExp
    | sumExp
    ;

relop
    : '<' | '<' '=' | '>' | '>' '=' | '=' | NOTEQ
    ;

sumExp
    : sumExp sumop mulExp
    | mulExp
    ;

sumop
    : '+' | '-'
    ;

mulExp
    : mulExp mulop unaryExp
    | unaryExp
    ;

mulop
    : '*' | '/' | '%'
    ;

unaryExp
    : unaryop unaryExp
    | factor
    ;

unaryop
    : '-' | '*' | '?'
    ;

factor
    : mutable
    | immutable
    ;

mutable
    : IDENT
    | IDENT '[' exp ']'
    ;

immutable
    : '(' exp ')'
    | call
    | constant
    ;

call
    : IDENT '(' args ')'
    ;

args
    : argList
    | {/*Epsilon*/}
    ;

argList
    : argList ',' exp
    | exp
    ;

constant
    : NUMCONST | STRINGCONST | CHARCONST | BOOLCONST
    ;

%%

int main(int argc, char *argv[])
{
    FILE * fp;
    if(argc > 1) {
        fp = fopen (argv[1], "r");
        yyin = fp;
    } else {
        yyin = stdin;
    }

    yyparse();
    return 0;
}

void yyerror(char* s)
{
    printf("yyerror: \"%s\"\n", s);
}
</code>```

Edit:
ScanType.h

```<code>#ifndef TOKNDATA_H
#define TOKNDATA_H __DATE__" "__TIME__

struct TokenData {
    int tokenclass; // token class
    int linenum; // line where found
    char *tokenstr; // what string was actually read
    char cvalue; // any character value
    int nvalue; // any numeric value or Boolean value
    char *svalue; // any string value e.g. an id
} * useToken;

#endif /*TOKNDATA_H*/
</code>```

Edit 2:

Swapping the position of the tokens in the bison file meant that the old tokens also were undeclared.

After changing the order like so

```<code>%token <token> BEGIN END IF THEN ELSE WHILE DO FOR TO BY RETURN BREAK OR AND NOT STATIC BOOL CHAR INT
%token <token> DPLUS DMINUS LASSIGN PLUSEQ MINUSEQ TIMEEQ DIVEQ NOTEQ
%token <token> NUMCONST STRINGCONST IDENT CHARCONST BOOLCONST
</code>```

I got the following error log.

```<code>cScan.l:44:10: error: ‘STATIC’ undeclared (first use in this function)
 static  { return STATIC; }
          ^
cScan.l:45:10: error: ‘BOOL’ undeclared (first use in this function)
 bool    { return BOOL; }
          ^
cScan.l:46:10: error: ‘CHAR’ undeclared (first use in this function)
 char    { return CHAR; }
          ^
cScan.l:47:10: error: ‘INT’ undeclared (first use in this function)
 int     { return INT; }
          ^
cScan.l:48:15: error: expected expression before ‘;’ token
 begin    { return BEGIN;}
               ^
cScan.l:49:10: error: ‘END’ undeclared (first use in this function)
 end    { return END;}
          ^
cScan.l:50:10: error: ‘IF’ undeclared (first use in this function)
 if    { return IF;}
          ^
cScan.l:51:10: error: ‘THEN’ undeclared (first use in this function)
 then    { return THEN;}
          ^
cScan.l:52:10: error: ‘ELSE’ undeclared (first use in this function)
 else    { return ELSE;}
          ^
cScan.l:53:10: error: ‘WHILE’ undeclared (first use in this function)
 while    { return WHILE;}
          ^
cScan.l:54:10: error: ‘DO’ undeclared (first use in this function)
 do    { return DO;}
          ^
cScan.l:55:10: error: ‘FOR’ undeclared (first use in this function)
 for    { return FOR;}
          ^
cScan.l:56:10: error: ‘TO’ undeclared (first use in this function)
 to    { return TO;}
          ^
cScan.l:57:10: error: ‘BY’ undeclared (first use in this function)
 by    { return BY;}
          ^
cScan.l:58:10: error: ‘RETURN’ undeclared (first use in this function)
 return    { return RETURN;}
          ^
cScan.l:59:10: error: ‘BREAK’ undeclared (first use in this function)
 break    { return BREAK;}
          ^
cScan.l:60:10: error: ‘OR’ undeclared (first use in this function)
 or    { return OR; }
          ^
cScan.l:61:10: error: ‘AND’ undeclared (first use in this function)
 and    { return AND; }
          ^
cScan.l:62:10: error: ‘NOT’ undeclared (first use in this function)
 not { return NOT;}
          ^
cScan.l:64:10: error: ‘DPLUS’ undeclared (first use in this function)
 "++" { return DPLUS; }
          ^
cScan.l:65:10: error: ‘DMINUS’ undeclared (first use in this function)
 "--" { return DMINUS; }
          ^
cScan.l:66:10: error: ‘LASSIGN’ undeclared (first use in this function)
 "<-" { return LASSIGN; }
          ^
cScan.l:67:10: error: ‘PLUSEQ’ undeclared (first use in this function)
 "+=" { return PLUSEQ; }
          ^
cScan.l:68:10: error: ‘MINUSEQ’ undeclared (first use in this function)
 "-=" { return MINUSEQ; }
          ^
cScan.l:69:10: error: ‘TIMEEQ’ undeclared (first use in this function)
 "*=" { return TIMEEQ; }
          ^
cScan.l:70:10: error: ‘DIVEQ’ undeclared (first use in this function)
 "/=" { return DIVEQ; }
          ^
cScan.l:71:10: error: ‘NOTEQ’ undeclared (first use in this function)
 "!=" { return NOTEQ; }
          ^
cScan.l:80:12: error: ‘IDENT’ undeclared (first use in this function)
     return IDENT;
            ^
cScan.l:90:12: error: ‘NUMCONST’ undeclared (first use in this function)
     return NUMCONST;
            ^
cScan.l:101:12: error: ‘STRINGCONST’ undeclared (first use in this function)
     return STRINGCONST;
            ^
cScan.l:112:12: error: ‘CHARCONST’ undeclared (first use in this function)
     return CHARCONST;
</code>```

Undoing this change returned the old tokens to functionality.

答:
You can't use BEGIN as a token name, because token names are used as C values, and BEGIN is a macro defined by flex (you use it to switch start states).

That causes a syntax error in the enum declaration which you quote in your answer, with the result that all the enum members after BEGIN are undeclared. But the most important error message was the one referring to the syntax error in the enum declaration itself:

```<code>lex.yy.c:117:15: error: expected identifier before ‘(’ token
 #define BEGIN (yy_start) = 1 + 2 *
               ^
cScan.tab.h:62:5: note: in expansion of macro ‘BEGIN’
     BEGIN = 263,                   /* BEGIN  */
     ^~~~~
</code>```

which for some reason you omitted from your question.

The same would be true for any macro, including ones in system library headers, if you use any of those. I generally prefer to prefix my token names with something like T_, and then use bison aliases to make the grammar look prettier:

```<code>%token T_BEGIN "begin"
       T_END   "end"
// ...
%%
// ...
compoundStmt
    :  "begin" localDecls stmtList "end"
</code>```

By the way, your struct TokenData will lead to undefined behaviour if you ever actually use the data (which really should not be necessary for anything. Bison has lots of debugging mechanisms which don't require much effort on your part.)

As an example, consider

 {BOOLCONST} {
    struct TokenData boolToken;
    yylval.token = &boolToken;
    yylval.token->tokenclass = 5;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    if(yytext[0] == 't') {
        yylval.token->nvalue = 1;
    } else {
        yylval.token->nvalue = 0;
    }
    return BOOLCONST;
}
```
<p><code>boolToken</code> is an automatic ("local") variable, so its lifetime ends when the <code>return BOOLCONST</code> executes. The address stored in <code>yylval</code> (<code>yylval.token = &boolToken;</code>) is a dangling pointer, and the contents of whatever <code>yylval.token</code> points to are completely unpredictable as soon as <code>yylex</code> returns. Moreover, if the contents of that memory region happen to still be intact, one of the other pointers you store:</p>
<pre class="lang-c prettyprint-override"><code>yylval.token->tokenstr = yytext;
</code>```

is a pointer into Flex's internal input buffer, whose contents are modified by yylex the next time it is called (which almost certainly happens before the semantic value of the BOOLCONST can be used, since the bison-generated parser usually reads one token ahead.)

Body:
I just added a set of new tokens to my parser, and each of the new ones is reported as undeclared. The first line of tokens were included in the last working build.

%token <token> NUMCONST STRINGCONST IDENT CHARCONST BOOLCONST
%token <token> BEGIN END IF THEN ELSE WHILE DO FOR TO BY RETURN BREAK OR AND NOT STATIC BOOL CHAR INT
%token <token> DPLUS DMINUS LASSIGN PLUSEQ MINUSEQ TIMEEQ DIVEQ NOTEQ

The error messages I get after running my makefile indicate that none of the new tokens are properly declared, although all of the old ones are still functioning.

cScan.l:44:9: error: ‘STATIC’ undeclared (first use in this function)
 static  {return STATIC;}
         ^
cScan.l:44:9: note: each undeclared identifier is reported only once for each function it appears in
cScan.l:45:9: error: ‘BOOL’ undeclared (first use in this function)
 bool    {return BOOL;}
         ^
cScan.l:46:9: error: ‘CHAR’ undeclared (first use in this function)
 char    {return CHAR;}
         ^
cScan.l:47:10: error: ‘INT’ undeclared (first use in this function)
 int     { return INT; }
          ^
cScan.l:48:15: error: expected expression before ‘;’ token
 begin    { return BEGIN;}
               ^
cScan.l:49:9: error: ‘END’ undeclared (first use in this function)
 end    {return END;}
         ^
cScan.l:50:9: error: ‘IF’ undeclared (first use in this function)
 if    {return IF;}
         ^
cScan.l:51:9: error: ‘THEN’ undeclared (first use in this function)
 then    {return THEN;}
         ^
cScan.l:52:9: error: ‘ELSE’ undeclared (first use in this function)
 else    {return ELSE;}
         ^
cScan.l:53:9: error: ‘WHILE’ undeclared (first use in this function)
 while    {return WHILE;}
         ^
cScan.l:54:9: error: ‘DO’ undeclared (first use in this function)
 do    {return DO;}
         ^
cScan.l:55:9: error: ‘FOR’ undeclared (first use in this function)
 for    {return FOR;}
         ^
cScan.l:56:9: error: ‘TO’ undeclared (first use in this function)
 to    {return TO;}
         ^
cScan.l:57:9: error: ‘BY’ undeclared (first use in this function)
 by    {return BY;}
         ^
cScan.l:58:9: error: ‘RETURN’ undeclared (first use in this function)
 return    {return RETURN;}
         ^
cScan.l:59:9: error: ‘BREAK’ undeclared (first use in this function)
 break    {return BREAK;}
         ^
cScan.l:60:9: error: ‘OR’ undeclared (first use in this function)
 or    {return OR;}
         ^
cScan.l:61:9: error: ‘AND’ undeclared (first use in this function)
 and    {return AND;}
         ^
cScan.l:62:10: error: ‘NOT’ undeclared (first use in this function)
 not { return NOT;}
          ^
cScan.l:64:10: error: ‘DPLUS’ undeclared (first use in this function)
 "++" { return DPLUS; }
          ^
cScan.l:65:10: error: ‘DMINUS’ undeclared (first use in this function)
 "--" { return DMINUS; }
          ^
cScan.l:66:10: error: ‘LASSIGN’ undeclared (first use in this function)
 "<-" { return LASSIGN; }
          ^
cScan.l:67:10: error: ‘PLUSEQ’ undeclared (first use in this function)
 "+=" { return PLUSEQ; }
          ^
cScan.l:68:10: error: ‘MINUSEQ’ undeclared (first use in this function)
 "-=" { return MINUSEQ; }
          ^
cScan.l:69:10: error: ‘TIMEEQ’ undeclared (first use in this function)
 "*=" { return TIMEEQ; }
          ^
cScan.l:70:10: error: ‘DIVEQ’ undeclared (first use in this function)
 "/=" { return DIVEQ; }
          ^
cScan.l:71:10: error: ‘NOTEQ’ undeclared (first use in this function)
 "!=" { return NOTEQ; }

Here's the flex file where I return each of the tokens:

%{
/*
 * cScan.l
 */
 #include "scanType.h"
 #include "cScan.tab.h"

%}

%option yylineno

LETTER   [A-Za-z]
ID       {LETTER}[_A-Za-z0-9]*
NUMCONST [0-9]+
STRINGCONST \"([^\\\"]|\\.)*\"
CHARCONST '\\?.'
BOOLCONST true|false

%%

{BOOLCONST} {
    struct TokenData boolToken;
    yylval.token = &boolToken;
    yylval.token->tokenclass = 5;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    if(yytext[0] == 't') {
        yylval.token->nvalue = 1;
    } else {
        yylval.token->nvalue = 0;
    }
    return BOOLCONST;
}

static  { return STATIC; }
bool    { return BOOL; }
char    { return CHAR; }
int     { return INT; }
begin    { return BEGIN;}
end    { return END;}
if    { return IF;}
then    { return THEN;}
else    { return ELSE;}
while    { return WHILE;}
do    { return DO;}
for    { return FOR;}
to    { return TO;}
by    { return BY;}
return    { return RETURN;}
break    { return BREAK;}
or    { return OR; }
and    { return AND; }
not { return NOT;}

"++" { return DPLUS; }
"--" { return DMINUS; }
"<-" { return LASSIGN; }
"+=" { return PLUSEQ; }
"-=" { return MINUSEQ; }
"*=" { return TIMEEQ; }
"/=" { return DIVEQ; }
"!=" { return NOTEQ; }

{ID}        {
    struct TokenData idToken;
    yylval.token = &idToken;
    yylval.token->tokenclass = 1;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    yylval.token->svalue = yytext;
    return IDENT;
}

{NUMCONST} {
    struct TokenData numToken;
    yylval.token = &numToken;
    yylval.token->tokenclass = 2;
    yylval.token->linenum = yylineno;
    yylval.token->nvalue = atoi(yytext);
    yylval.token->tokenstr = yytext;
    return NUMCONST;
}

{STRINGCONST}   {
    struct TokenData stringToken;
    yylval.token = &stringToken;
    yylval.token->tokenclass = 3;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    yylval.token->svalue = yytext;
    yylval.token->nvalue = yyleng-2;
    return STRINGCONST;
}

{CHARCONST}   {
    struct TokenData charToken;
    yylval.token = &charToken;
    yylval.token->tokenclass = 4;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    yylval.token->svalue = yytext;

    return CHARCONST;
}

"="|"<"|">"|"+"|"-"|"*"|"/"|"%"|"["|"]"|"*"|"-"|"?"|"("|")"|";"|","|":" { return yytext[0]; }

[ \t\r]         ;

##.*\n          ;

\n              { ; /*option to add stuff*/ }

.               { printf("ERROR(%d): Invalid or misplaced input character: '%c'. Character Ignored.\n", yylineno, yytext[0]); }
%%

/*
 * When the end of an input file is encountered, exit with success (1).
 */
int yywrap() {
    return 1;
}

The tokens are all listed in the cScan.tab.h file, which is included in cScan.l. Here's their definition.

/* Token type.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
  enum yytokentype
  {
    NUMCONST = 258,
    STRINGCONST = 259,
    IDENT = 260,
    CHARCONST = 261,
    BOOLCONST = 262,
    BEGIN = 263,
    END = 264,
    IF = 265,
    THEN = 266,
    ELSE = 267,
    WHILE = 268,
    DO = 269,
    FOR = 270,
    TO = 271,
    BY = 272,
    RETURN = 273,
    BREAK = 274,
    OR = 275,
    AND = 276,
    NOT = 277,
    STATIC = 278,
    BOOL = 279,
    CHAR = 280,
    INT = 281,
    DPLUS = 282,
    DMINUS = 283,
    LASSIGN = 284,
    PLUSEQ = 285,
    MINUSEQ = 286,
    TIMEEQ = 287,
    DIVEQ = 288,
    NOTEQ = 289
  };
#endif

This is the make file I'm running. I've deleted each of the generated files and run it again, but that doesn't seem to be the issue.

cc = gcc
ccopts = #-ly
lex = flex
lexopts =
lexgens = lex.yy.c
yacc = bison
yaccopts = -d
yaccgens = cScan.tab.c cScan.tab.h
prj = cScan

$(prj): $(lexgens) $(yaccgens)
    $(cc) $(lexgens) $(yaccgens) $(ccopts) -o $(prj)

clean:
    rm $(lexgens) $(yaccgens) $(prj)

$(yaccgens): $(prj).y
    $(yacc) $(yaccopts) $(prj).y

$(lexgens): $(prj).l $(yaccgens)
    $(lex) $(lexopts) $(prj).l

Here's the whole bison file, for completeness.

%{
#include "scanType.h"
#include "treeType.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void yyerror(char*);
int yylex(void);
extern FILE *yyin;

%}

%define parse.error verbose

%union {
    struct TokenData *token;//for terminals, from yylex
    struct TreeNode *tree;//for nonterminals, to build the tree
    char op;
}

%token <token> NUMCONST STRINGCONST IDENT CHARCONST BOOLCONST
%token <token> BEGIN END IF THEN ELSE WHILE DO FOR TO BY RETURN BREAK OR AND NOT STATIC BOOL CHAR INT
%token <token> DPLUS DMINUS LASSIGN PLUSEQ MINUSEQ TIMEEQ DIVEQ NOTEQ

%%

program :
    declList
    ;

declList
    : declList decl
    | decl
    ;

decl
    : varDecl
    | funDecl
    ;

varDecl
    : typeSpec varDeclList ';'
    ;

scopedVarDecl
    : STATIC typeSpec varDeclList ';'
    | typeSpec varDeclList ';'
    ;

varDeclList
    : varDeclList ',' varDeclInit
    | varDeclInit
    ;

varDeclInit
    : varDeclId
    | varDeclId ':' simpleExp
    ;

varDeclId
    : IDENT
    | IDENT '[' NUMCONST ']'
    ;

typeSpec
    : BOOL
    | CHAR
    | INT
    ;

funDecl
    : typeSpec IDENT '(' parms ')' compoundStmt
    | IDENT '(' parms ')' compoundStmt
    ;

parms
    : parmList
    | {/*Epsilon*/}
    ;

parmList
    : parmList ';' parmTypeList
    | parmTypeList
    ;

parmTypeList
    : typeSpec parmIdList
    ;

parmIdList
    : parmIdList ',' parmId
    | parmId
    ;

parmId
    : IDENT
    | IDENT '['']'
    ;

stmt
    : matchStmt
    | unmatchStmt
    ;

matchStmt
    : selectStmt_M
    | iterStmt_M
    | otherStmt
    ;

unmatchStmt
    : selectStmt_U
    | iterStmt_U
    ;

selectStmt_M
    : IF simpleExp THEN matchStmt ELSE matchStmt
    ;

selectStmt_U
    : IF simpleExp THEN stmt
    | IF simpleExp THEN matchStmt ELSE unmatchStmt
    ;

iterStmt_U
    : WHILE simpleExp DO unmatchStmt
    | FOR IDENT LASSIGN iterRange DO unmatchStmt
    ;

iterStmt_M
    : WHILE simpleExp DO matchStmt
    | FOR IDENT LASSIGN iterRange DO matchStmt
    ;

iterRange
    : simpleExp TO simpleExp iterRangeStmtPr
    ;

iterRangeStmtPr
    : BY simpleExp
    | {/*Addition to stop ambiguity*/}
    ;

otherStmt
    : expStmt
    | returnStmt
    | breakStmt
    | compoundStmt
    ;

compoundStmt
    :  BEGIN localDecls stmtList END
    ;

localDecls
    : localDecls scopedVarDecl
    | {/*Epsilon*/}
    ;

stmtList
    : stmtList stmt
    | {/*Epsilon*/}
    ;

expStmt
    : exp ';'
    | ';'
    ;

returnStmt
    : RETURN ';'
    | RETURN exp ';'
    ;

breakStmt
    : BREAK ';'
    ;

exp
    : mutExp
    | simpleExp
    ;

mutExp
    : mutable assignop exp
    | mutable DPLUS
    | mutable DMINUS
    ;

assignop
    : LASSIGN | PLUSEQ | MINUSEQ | TIMEEQ | DIVEQ
    ;

simpleExp
    : simpleExp OR andExp
    | andExp
    ;

andExp
    : andExp AND unaryRelExp
    | unaryRelExp
    ;

unaryRelExp
    : NOT unaryRelExp
    | relExp
    ;

relExp
    : sumExp relop sumExp
    | sumExp
    ;

relop
    : '<' | '<' '=' | '>' | '>' '=' | '=' | NOTEQ
    ;

sumExp
    : sumExp sumop mulExp
    | mulExp
    ;

sumop
    : '+' | '-'
    ;

mulExp
    : mulExp mulop unaryExp
    | unaryExp
    ;

mulop
    : '*' | '/' | '%'
    ;

unaryExp
    : unaryop unaryExp
    | factor
    ;

unaryop
    : '-' | '*' | '?'
    ;

factor
    : mutable
    | immutable
    ;

mutable
    : IDENT
    | IDENT '[' exp ']'
    ;

immutable
    : '(' exp ')'
    | call
    | constant
    ;

call
    : IDENT '(' args ')'
    ;

args
    : argList
    | {/*Epsilon*/}
    ;

argList
    : argList ',' exp
    | exp
    ;

constant
    : NUMCONST | STRINGCONST | CHARCONST | BOOLCONST
    ;

%%

int main(int argc, char *argv[])
{
    FILE * fp;
    if(argc > 1) {
        fp = fopen (argv[1], "r");
        yyin = fp;
    } else {
        yyin = stdin;
    }

    yyparse();
    return 0;
}

void yyerror(char* s)
{
    printf("yyerror: \"%s\"\n", s);
}

Edit:
ScanType.h

#ifndef TOKNDATA_H
#define TOKNDATA_H __DATE__" "__TIME__

struct TokenData {
    int tokenclass; // token class
    int linenum; // line where found
    char *tokenstr; // what string was actually read
    char cvalue; // any character value
    int nvalue; // any numeric value or Boolean value
    char *svalue; // any string value e.g. an id
} * useToken;

#endif /*TOKNDATA_H*/

Edit 2:

Swapping the position of the tokens in the bison file meant that the old tokens also were undeclared.

After changing the order like so

%token <token> BEGIN END IF THEN ELSE WHILE DO FOR TO BY RETURN BREAK OR AND NOT STATIC BOOL CHAR INT
%token <token> DPLUS DMINUS LASSIGN PLUSEQ MINUSEQ TIMEEQ DIVEQ NOTEQ
%token <token> NUMCONST STRINGCONST IDENT CHARCONST BOOLCONST

I got the following error log.

cScan.l:44:10: error: ‘STATIC’ undeclared (first use in this function)
 static  { return STATIC; }
          ^
cScan.l:45:10: error: ‘BOOL’ undeclared (first use in this function)
 bool    { return BOOL; }
          ^
cScan.l:46:10: error: ‘CHAR’ undeclared (first use in this function)
 char    { return CHAR; }
          ^
cScan.l:47:10: error: ‘INT’ undeclared (first use in this function)
 int     { return INT; }
          ^
cScan.l:48:15: error: expected expression before ‘;’ token
 begin    { return BEGIN;}
               ^
cScan.l:49:10: error: ‘END’ undeclared (first use in this function)
 end    { return END;}
          ^
cScan.l:50:10: error: ‘IF’ undeclared (first use in this function)
 if    { return IF;}
          ^
cScan.l:51:10: error: ‘THEN’ undeclared (first use in this function)
 then    { return THEN;}
          ^
cScan.l:52:10: error: ‘ELSE’ undeclared (first use in this function)
 else    { return ELSE;}
          ^
cScan.l:53:10: error: ‘WHILE’ undeclared (first use in this function)
 while    { return WHILE;}
          ^
cScan.l:54:10: error: ‘DO’ undeclared (first use in this function)
 do    { return DO;}
          ^
cScan.l:55:10: error: ‘FOR’ undeclared (first use in this function)
 for    { return FOR;}
          ^
cScan.l:56:10: error: ‘TO’ undeclared (first use in this function)
 to    { return TO;}
          ^
cScan.l:57:10: error: ‘BY’ undeclared (first use in this function)
 by    { return BY;}
          ^
cScan.l:58:10: error: ‘RETURN’ undeclared (first use in this function)
 return    { return RETURN;}
          ^
cScan.l:59:10: error: ‘BREAK’ undeclared (first use in this function)
 break    { return BREAK;}
          ^
cScan.l:60:10: error: ‘OR’ undeclared (first use in this function)
 or    { return OR; }
          ^
cScan.l:61:10: error: ‘AND’ undeclared (first use in this function)
 and    { return AND; }
          ^
cScan.l:62:10: error: ‘NOT’ undeclared (first use in this function)
 not { return NOT;}
          ^
cScan.l:64:10: error: ‘DPLUS’ undeclared (first use in this function)
 "++" { return DPLUS; }
          ^
cScan.l:65:10: error: ‘DMINUS’ undeclared (first use in this function)
 "--" { return DMINUS; }
          ^
cScan.l:66:10: error: ‘LASSIGN’ undeclared (first use in this function)
 "<-" { return LASSIGN; }
          ^
cScan.l:67:10: error: ‘PLUSEQ’ undeclared (first use in this function)
 "+=" { return PLUSEQ; }
          ^
cScan.l:68:10: error: ‘MINUSEQ’ undeclared (first use in this function)
 "-=" { return MINUSEQ; }
          ^
cScan.l:69:10: error: ‘TIMEEQ’ undeclared (first use in this function)
 "*=" { return TIMEEQ; }
          ^
cScan.l:70:10: error: ‘DIVEQ’ undeclared (first use in this function)
 "/=" { return DIVEQ; }
          ^
cScan.l:71:10: error: ‘NOTEQ’ undeclared (first use in this function)
 "!=" { return NOTEQ; }
          ^
cScan.l:80:12: error: ‘IDENT’ undeclared (first use in this function)
     return IDENT;
            ^
cScan.l:90:12: error: ‘NUMCONST’ undeclared (first use in this function)
     return NUMCONST;
            ^
cScan.l:101:12: error: ‘STRINGCONST’ undeclared (first use in this function)
     return STRINGCONST;
            ^
cScan.l:112:12: error: ‘CHARCONST’ undeclared (first use in this function)
     return CHARCONST;

Undoing this change returned the old tokens to functionality.

Body:
You can't use BEGIN as a token name, because token names are used as C values, and BEGIN is a macro defined by flex (you use it to switch start states).

That causes a syntax error in the enum declaration which you quote in your answer, with the result that all the enum members after BEGIN are undeclared. But the most important error message was the one referring to the syntax error in the enum declaration itself:

lex.yy.c:117:15: error: expected identifier before ‘(’ token
 #define BEGIN (yy_start) = 1 + 2 *
               ^
cScan.tab.h:62:5: note: in expansion of macro ‘BEGIN’
     BEGIN = 263,                   /* BEGIN  */
     ^~~~~

which for some reason you omitted from your question.

The same would be true for any macro, including ones in system library headers, if you use any of those. I generally prefer to prefix my token names with something like T_, and then use bison aliases to make the grammar look prettier:

%token T_BEGIN "begin"
       T_END   "end"
// ...
%%
// ...
compoundStmt
    :  "begin" localDecls stmtList "end"

By the way, your struct TokenData will lead to undefined behaviour if you ever actually use the data (which really should not be necessary for anything. Bison has lots of debugging mechanisms which don't require much effort on your part.)

As an example, consider

 {BOOLCONST} {
    struct TokenData boolToken;
    yylval.token = &boolToken;
    yylval.token->tokenclass = 5;
    yylval.token->linenum = yylineno;
    yylval.token->tokenstr = yytext;
    if(yytext[0] == 't') {
        yylval.token->nvalue = 1;
    } else {
        yylval.token->nvalue = 0;
    }
    return BOOLCONST;
}

boolToken is an automatic ("local") variable, so its lifetime ends when the return BOOLCONST executes. The address stored in yylval (yylval.token = &boolToken;) is a dangling pointer, and the contents of whatever yylval.token points to are completely unpredictable as soon as yylex returns. Moreover, if the contents of that memory region happen to still be intact, one of the other pointers you store:

yylval.token->tokenstr = yytext;

is a pointer into Flex's internal input buffer, whose contents are modified by yylex the next time it is called (which almost certainly happens before the semantic value of the BOOLCONST can be used, since the bison-generated parser usually reads one token ahead.)


来源: stackexchange

问:
Firebase CLI deploy Error: There was an error reading functions/package.json
I recently getting this error when try to deploy the firebase cloud functions using the command firebase deploy --only functions. My package.json file is shown below

```<code>{
  "name": "functions",
  "scripts": {
    "lint": "tslint --project tsconfig.json",
    "build": "tsc",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "10"
  },
  "main": "lib/index.js",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "firebase-admin": "^8.12.1",
    "firebase-functions": "^3.6.2",
    "stripe": "^8.50.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.6",
    "dotenv": "^8.2.0",
    "firebase-functions-test": "^0.2.0",
    "tslint": "^5.12.0",
    "typescript": "^3.8.0"
  },
  "private": true
}
</code>```

Using npm package firebase-tools of version 8.4.1.

Also getting error in firebase emulators

答:
Enter into functions directory

enter the following command npm run build

and then deploy / launch your emulators

ContentLicense: CC BY-SA 4.0

Body:
I recently getting this error when try to deploy the firebase cloud functions using the command firebase deploy --only functions. My package.json file is shown below

{
  "name": "functions",
  "scripts": {
    "lint": "tslint --project tsconfig.json",
    "build": "tsc",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "10"
  },
  "main": "lib/index.js",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "firebase-admin": "^8.12.1",
    "firebase-functions": "^3.6.2",
    "stripe": "^8.50.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.6",
    "dotenv": "^8.2.0",
    "firebase-functions-test": "^0.2.0",
    "tslint": "^5.12.0",
    "typescript": "^3.8.0"
  },
  "private": true
}

Using npm package firebase-tools of version 8.4.1.

Also getting error in firebase emulators


问:
Firefox change taskbar and desktop icons
I use to be able to change firefox icons by adding these files to the Firefox under the browser directory

```<code>chrome/icons/default/BrowserPreferences.ico
chrome/icons/default/CustomizeToolbarWindow.ico
chrome/icons/default/default.ico
chrome/icons/default/downloadManager.ico
chrome/icons/default/main-window.ico
chrome/icons/default/openLocation.ico
chrome/icons/default/places.ico
chrome/icons/default/printPageSetupDialog.ico
chrome/icons/default/TabMIxPreferences.ico
chrome/icons/default/unknownContentType.ico
chrome/icons/default/viewSource.ico
chrome/icons/default/Wizard.ico
</code>```

It worked in version 56 but now in version 97 and this no longer works?

答:
After version it now needs an option in prefs.js

```<code>user_pref("toolkit.legacyUserProfileCustomizations.windowIcon", true);
</code>```

to make it work

Body:
I use to be able to change firefox icons by adding these files to the Firefox under the browser directory

chrome/icons/default/BrowserPreferences.ico
chrome/icons/default/CustomizeToolbarWindow.ico
chrome/icons/default/default.ico
chrome/icons/default/downloadManager.ico
chrome/icons/default/main-window.ico
chrome/icons/default/openLocation.ico
chrome/icons/default/places.ico
chrome/icons/default/printPageSetupDialog.ico
chrome/icons/default/TabMIxPreferences.ico
chrome/icons/default/unknownContentType.ico
chrome/icons/default/viewSource.ico
chrome/icons/default/Wizard.ico

It worked in version 56 but now in version 97 and this no longer works?

Body:
After version it now needs an option in prefs.js

user_pref("toolkit.legacyUserProfileCustomizations.windowIcon", true);

to make it work


问:
Java regex issues with an exact token
In my Java app I have a "template string", say, "This record's name is : %%%NAME%%%."

I want to loop through a list and for each iteration, print out a "customized version" of this template that string-replaces the %%%NAME%%% token for a meaningful value.  For instance:

```<code>List<String> strNamesList = getNamesSomehow();
String strTemplate = "This record's name is : %%%NAME%%%.";
String strCustomized = "";
for(int i = 0; i < strNamesList.size(); i++)
{
    strCustomized = strTemplate.replaceFirst(strSomeRegex, strNamesList.get(i));
    System.out.println(strCustomized);
}
</code>```

Per usual, I am choking on the strSomeRegex. I simply need a regex that will match for the exact phrase:

%%%NAME%%%

I have Googled, Binged, Wikipediaed and more. Searches for "match regex on exact" (and their likes) turn back all sorts of things, none of which help me with this token that has punctuation (percentage signs) in it.

Regexes are just one of those things that get me every time, and this is my last resort.

Thanks to any kind StackOverflowers who can point me in the right direction!

答:
java has a function to quote a string in a regex java.util.regex.Pattern.quote(string)

what this does is surround the string with \Q and \E (replacing \E with \E\\E\Q in the string as needed)

in your example "\\Q%%%NAME%%%\\E" will do

ContentLicense: CC BY-SA 3.0

Title: Java regex issues with an exact token

Body:
In my Java app I have a "template string", say, "This record's name is : %%%NAME%%%."

I want to loop through a list and for each iteration, print out a "customized version" of this template that string-replaces the %%%NAME%%% token for a meaningful value.  For instance:

List<String> strNamesList = getNamesSomehow();
String strTemplate = "This record's name is : %%%NAME%%%.";
String strCustomized = "";
for(int i = 0; i < strNamesList.size(); i++)
{
    strCustomized = strTemplate.replaceFirst(strSomeRegex, strNamesList.get(i));
    System.out.println(strCustomized);
}

Per usual, I am choking on the strSomeRegex. I simply need a regex that will match for the exact phrase:

%%%NAME%%%

I have Googled, Binged, Wikipediaed and more. Searches for "match regex on exact" (and their likes) turn back all sorts of things, none of which help me with this token that has punctuation (percentage signs) in it.

Regexes are just one of those things that get me every time, and this is my last resort.

Thanks to any kind StackOverflowers who can point me in the right direction!


问:
C/C++ Remove Console Scrollbar on Win/Unix/MacOS
Context: I am writing a small library to output ansi formatted media to stdout (similar to ncurses).
What i want to do is to remove the scrollbar of the terminal window independently of the plattform the code is compiled on (Win / MacOS / Unix).
Heres a little example of what the window should look like (this was done with ncurses): example of scrollbar missing

To remove the scrollbar on Windows with c++, you simply set the screen buffer height to be the same size as the height of the window like so:

#include <Windows.h>
#include <iostream>

int main() {
    CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo;

    // Get console handle and get screen buffer information from that handle.
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hConsole, &screenBufferInfo);

    // Get rid of the scrollbar by setting the screen buffer size the same as
    // the console window size.
    COORD new_screen_buffer_size;

    // screenBufferInfo.srWindow allows us to obtain the width and height info
    // of the visible console in character cells.
    // That visible portion is what we want to set the screen buffer to, so that
    // no scroll bars are needed to view the entire buffer.
    new_screen_buffer_size.X = screenBufferInfo.srWindow.Right -
    screenBufferInfo.srWindow.Left + 1; // Columns
    new_screen_buffer_size.Y = screenBufferInfo.srWindow.Bottom -
    screenBufferInfo.srWindow.Top + 1; // Rows

    // Set new buffer size
    SetConsoleScreenBufferSize(hConsole, new_screen_buffer_size);

    std::cout << "There are no scrollbars in this console!" << std::endl;

    return 0;
}
```
<p>see here</p>
<p>My question now is: How could I remove the scrollbar on other plattforms and use their respective method with <code>#if defined(_whatever plattform_)</code> similar to another code snippet in my project (plain c):</p>
<pre class="lang-c prettyprint-override"><code>// writes terminal dimensions to 'rows' and 'cols'
// returns 0 if successful
int window_dimensions()
{
#if defined(__APPLE__) || defined(__linux__)
    struct winsize w;

    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

    rows = w.ws_row;
    cols = w.ws_col;
    return 0;
#elif defined(_WIN32)
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
    cols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
    return 0;
#endif
    return 1;
}
</code>```

答:
For anyone finding this questions in the future and wondering, i have deemed it impossible in the scope of my little project.

Users who wish to hide the Scrollbar on MacOS can go to System Preferences -> General and change Show scroll bars to When scrolling.

For Linux users, the bar on most terminals isnt even that much of an inconvenience so you should be able to just live with it.

On Windows machines i've settled with this approach in c:

int remove_scrollbar(int x_, int y_)
{
#if defined(_WIN32)
    CONSOLE_SCREEN_BUFFER_INFOEX csbiex;

    csbiex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);

    GetConsoleScreenBufferInfoEx(GetStdHandle(STD_OUTPUT_HANDLE), &csbiex);

    csbiex.dwSize.X = x_;
    csbiex.dwSize.Y = y_;

    SMALL_RECT s1;
    s1.Top = 0;
    s1.Left = 0;
    s1.Bottom = y_;
    s1.Right = x_;

    csbiex.srWindow = s1;

    COORD mws1;
    mws1.X = x_;
    mws1.Y = y_;

    csbiex.dwMaximumWindowSize = mws1;

    SetConsoleScreenBufferInfoEx(GetStdHandle(STD_OUTPUT_HANDLE), &csbiex); //this also resizes the window to x_, y_
    return 0;
#endif
    return 1;
}
```

I went for CONSOLE_SCREEN_BUFFER_INFOEX because it worked better in my testing than CONSOLE_SCREEN_BUFFER_INFO but either should be fine.

Body:
Context: I am writing a small library to output ansi formatted media to stdout (similar to ncurses).
What i want to do is to remove the scrollbar of the terminal window independently of the plattform the code is compiled on (Win / MacOS / Unix).
Heres a little example of what the window should look like (this was done with ncurses): example of scrollbar missing

To remove the scrollbar on Windows with c++, you simply set the screen buffer height to be the same size as the height of the window like so:

#include <Windows.h>
#include <iostream>

int main() {
    CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo;

    // Get console handle and get screen buffer information from that handle.
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfo(hConsole, &screenBufferInfo);

    // Get rid of the scrollbar by setting the screen buffer size the same as
    // the console window size.
    COORD new_screen_buffer_size;

    // screenBufferInfo.srWindow allows us to obtain the width and height info
    // of the visible console in character cells.
    // That visible portion is what we want to set the screen buffer to, so that
    // no scroll bars are needed to view the entire buffer.
    new_screen_buffer_size.X = screenBufferInfo.srWindow.Right -
    screenBufferInfo.srWindow.Left + 1; // Columns
    new_screen_buffer_size.Y = screenBufferInfo.srWindow.Bottom -
    screenBufferInfo.srWindow.Top + 1; // Rows

    // Set new buffer size
    SetConsoleScreenBufferSize(hConsole, new_screen_buffer_size);

    std::cout << "There are no scrollbars in this console!" << std::endl;

    return 0;
}

see here

My question now is: How could I remove the scrollbar on other plattforms and use their respective method with #if defined(_whatever plattform_) similar to another code snippet in my project (plain c):

// writes terminal dimensions to 'rows' and 'cols'
// returns 0 if successful
int window_dimensions()
{
#if defined(__APPLE__) || defined(__linux__)
    struct winsize w;

    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

    rows = w.ws_row;
    cols = w.ws_col;
    return 0;
#elif defined(_WIN32)
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
    cols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
    return 0;
#endif
    return 1;
}

Body:
For anyone finding this questions in the future and wondering, i have deemed it impossible in the scope of my little project.

Users who wish to hide the Scrollbar on MacOS can go to System Preferences -> General and change Show scroll bars to When scrolling.

For Linux users, the bar on most terminals isnt even that much of an inconvenience so you should be able to just live with it.

On Windows machines i've settled with this approach in c:

int remove_scrollbar(int x_, int y_)
{
#if defined(_WIN32)
    CONSOLE_SCREEN_BUFFER_INFOEX csbiex;

    csbiex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);

    GetConsoleScreenBufferInfoEx(GetStdHandle(STD_OUTPUT_HANDLE), &csbiex);

    csbiex.dwSize.X = x_;
    csbiex.dwSize.Y = y_;

    SMALL_RECT s1;
    s1.Top = 0;
    s1.Left = 0;
    s1.Bottom = y_;
    s1.Right = x_;

    csbiex.srWindow = s1;

    COORD mws1;
    mws1.X = x_;
    mws1.Y = y_;

    csbiex.dwMaximumWindowSize = mws1;

    SetConsoleScreenBufferInfoEx(GetStdHandle(STD_OUTPUT_HANDLE), &csbiex); //this also resizes the window to x_, y_
    return 0;
#endif
    return 1;
}

I went for CONSOLE_SCREEN_BUFFER_INFOEX because it worked better in my testing than CONSOLE_SCREEN_BUFFER_INFO but either should be fine.


问:
Access same firebase user from front and backend
I'm trying to understand how to continue a user session started client side in my backend server.

I'm using NextJS for my client app and go Gin for backend api calls.

I have some client code that allows a user to login using firebase auth:

import { getAuth, signInWithRedirect, GoogleAuthProvider } from 'firebase/auth'

export default function Login() {
  const provider = new GoogleAuthProvider()
  const auth = getAuth()

  return (

          <button onClick={() => signInWithRedirect(auth, provider)}>Sign In With Google</button>

  )
}
```

This is great and works with very little work on my part. Once a user clicks the button, and follows the login instructions, my client app understands who they are using the firebase libraries.

Now I want to make a request to my go gin backend as this current user. How can I continue the session in my backend code as the user who is logged in to my client app? Ideally I would be able to:

Log in the client app as user123.

Make a request to my backend.

My backend understands that the request came from my client as user123.

My backend makes some request to other firebase services as user123 like creating or updating a Firestore document.

I'm not sure how to go about doing #3. This seems like a common thing and I'm actively looking into what I need to do. I'll answer my own question if I can, but any advice is appreciated.

答:
You'll want to pass the user's ID token from your client to the server, which can then verify the ID token and based on that determine whether the user is authorized.

But there's no way to then impersonate that user from your server in calls to Firebase. So you'll have to do the authorization checks for that yourself.

Body:
I'm trying to understand how to continue a user session started client side in my backend server.

I'm using NextJS for my client app and go Gin for backend api calls.

I have some client code that allows a user to login using firebase auth:

import { getAuth, signInWithRedirect, GoogleAuthProvider } from 'firebase/auth'

export default function Login() {
  const provider = new GoogleAuthProvider()
  const auth = getAuth()

  return (

          <button onClick={() => signInWithRedirect(auth, provider)}>Sign In With Google</button>

  )
}

This is great and works with very little work on my part. Once a user clicks the button, and follows the login instructions, my client app understands who they are using the firebase libraries.

Now I want to make a request to my go gin backend as this current user. How can I continue the session in my backend code as the user who is logged in to my client app? Ideally I would be able to:

Log in the client app as user123.

Make a request to my backend.

My backend understands that the request came from my client as user123.

My backend makes some request to other firebase services as user123 like creating or updating a Firestore document.

I'm not sure how to go about doing #3. This seems like a common thing and I'm actively looking into what I need to do. I'll answer my own question if I can, but any advice is appreciated.


问:
Potsgres SQL: select timestamp prior to max timestamp
I have a table in Postgres with timestamps:

```<code>timestamp
2022-01-01 00:52:53
2022-01-01 00:57:12
...
2022-02-13 11:00:31
2022-02-13 16:45:10
</code>```

How can I select the timestamp closest to max timestamp? Meaning, I want the timestamp 2022-02-13 11:00:31.

I am looking for something like max(timestamp)-1 so I can do on a recurring basis. Thank you

答:
I think the following query might meet your requirements:

```<code>SELECT MAX(date_col) FROM test WHERE date_col < (SELECT MAX(date_col) from test);
</code>```

See DB Fiddle

Body:
I have a table in Postgres with timestamps:

timestamp
2022-01-01 00:52:53
2022-01-01 00:57:12
...
2022-02-13 11:00:31
2022-02-13 16:45:10

How can I select the timestamp closest to max timestamp? Meaning, I want the timestamp 2022-02-13 11:00:31.

I am looking for something like max(timestamp)-1 so I can do on a recurring basis. Thank you

Body:
I think the following query might meet your requirements:

SELECT MAX(date_col) FROM test WHERE date_col < (SELECT MAX(date_col) from test);

See DB Fiddle


问:
Use a Perl Script to read a line of data from a file, and display?
I need some help with a script I am trying to create. Basically I have about 30 txt files, each with a email address field. for example:

```<code>example@hotmail.com
</code>```

I want to be able to use a Perl script to read all of the 30 txt files, returning a list of all email addresses.

Each txt file is located in the same location, and is named like this:

1.txt, 2.txt etc.

Any help is much appreciated.

答:
Do you know any Perl? I don't mind helping people with their issues, but writing code is my job, and I like to get paid for it.

Here are some hints:

To read in the files, use the File::Find module. That'll help you find all the files you need to read in.

You can use a hash to guarantee unique email addresses.

For example:

```<code>my %emailHash;
while (my $line = <FILE>) {
    chomp $line;
    if ($line =~ /[^[^\@]+\@[^\@]+\.[\w+]$/) {   #Email address
        $email{$line} = 1;
    }
}
</code>```

Now, you can use the keys function to print them out:

```<code> foreach my $email (sort keys %emailHash) {
    print "Email: $email\n";
 }
</code>```

Body:
I need some help with a script I am trying to create. Basically I have about 30 txt files, each with a email address field. for example:

example@hotmail.com

I want to be able to use a Perl script to read all of the 30 txt files, returning a list of all email addresses.

Each txt file is located in the same location, and is named like this:

1.txt, 2.txt etc.

Any help is much appreciated.

Body:
Do you know any Perl? I don't mind helping people with their issues, but writing code is my job, and I like to get paid for it.

Here are some hints:

To read in the files, use the File::Find module. That'll help you find all the files you need to read in.

You can use a hash to guarantee unique email addresses.

For example:

my %emailHash;
while (my $line = <FILE>) {
    chomp $line;
    if ($line =~ /[^[^\@]+\@[^\@]+\.[\w+]$/) {   #Email address
        $email{$line} = 1;
    }
}

Now, you can use the keys function to print them out:

 foreach my $email (sort keys %emailHash) {
    print "Email: $email\n";
 }


问:
Convert DateTime 1/20/2022 8:48:30 PM to 20/01/2022 8:48:30 PM C#
I basically have two DateTime variables

```<code> DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
 DateTime dateFinish;
</code>```

dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:

```<code>if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}
</code>```

I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.

答:
You can try the ParseExact method</p>
```<code>DateTime dateToday = DateTime.Now;
DateTime dateFinish = DateTime.ParseExact("20/01/2022 10:56:09", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (dateToday > dateFinish)
{
    // do something
}
</code>```

Body:
I basically have two DateTime variables

 DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
 DateTime dateFinish;

dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:

if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}

I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.

Body:
You can try the ParseExact method

DateTime dateToday = DateTime.Now;
DateTime dateFinish = DateTime.ParseExact("20/01/2022 10:56:09", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (dateToday > dateFinish)
{
    // do something
}


问:
AWS CodePipeline permission error on Release change action
I have started getting the following error recently on release change action int eh AWS codePipeline console. Also attaching the screenshot

Action execution failed

Insufficient permissions The provided role does not have permissions
  to perform this action. Underlying error: Access Denied (Service:
  Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID:
  CA26EF93E3DAF8F0; S3 Extended Request ID:
  mKkobqLGbj4uco8h9wDOBjPeWrRA2ybCrEsVoSq/MA4IFZqJb6QJSrlNrKk/EQK40TfLbTbqFuQ=)

I can't find any resources online anywhere for this error code.

答:
You are missing the GetBucketVersioning action in your policy, so the correct example looks like below. I don't know why it's not mentioned anywhere in the reference/documentation:

```<code>- PolicyName: AccessRequiredByPipeline
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                  - s3:PutObject
                  - s3:GetObject
                  - s3:GetObjectVersion
                Effect: Allow
                Resource: !Sub ${YouBucket.Arn}/*
              - Action:
                  - s3:GetBucketVersioning
                Resource: !Sub ${YouBucket.Arn}
                Effect: Allow
              - Action:
                  - kms:GenerateDataKey
                  - kms:Decrypt
                Effect: Allow
                Resource: !GetAtt KMSKey.Arn
</code>```

Body:
You are missing the GetBucketVersioning action in your policy, so the correct example looks like below. I don't know why it's not mentioned anywhere in the reference/documentation:

- PolicyName: AccessRequiredByPipeline
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                  - s3:PutObject
                  - s3:GetObject
                  - s3:GetObjectVersion
                Effect: Allow
                Resource: !Sub ${YouBucket.Arn}/*
              - Action:
                  - s3:GetBucketVersioning
                Resource: !Sub ${YouBucket.Arn}
                Effect: Allow
              - Action:
                  - kms:GenerateDataKey
                  - kms:Decrypt
                Effect: Allow
                Resource: !GetAtt KMSKey.Arn


问:
SwiftUI getby UUID
I'm pretty new to SwiftUI so I'm hoping someone can help me out here.
I have a UUID and I am trying to save content into that specific object, but I do not know how to call the object, like with a getbyid or something.

```<code>struct Game: Identifiable, Codable {
    let id: UUID
    var title: String
    var players: [Player]
}
extension Game {
    struct Player: Identifiable, Codable {
        let id: UUID
        var name: String
        var score: [Int32]
    }
}
</code>```

used this code in my program

```<code>@Binding var game: Game
saveScoreToPlayer(game: $game, playerID: player.id, score: Int32)

func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    //save score to player obviously doesn't work
    game.playerID.insert(score at:0)
}
</code>```

答:
There are a few of ways you can do this. None is necessarily advantageous, although the second one (with the map) may prove slower in situations with huge data sets.

Note that in the examples I changed the function to accept Binding<Game> since that's what you are passing in in your call site.

```<code>func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    guard let index = game.wrappedValue.players.firstIndex(where: { $0.id == playerID }) else {
        fatalError()
    }
    game.wrappedValue.players[index].score.append(score)
}
</code>```

or

```<code>func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    game.wrappedValue.players = game.wrappedValue.players.map {
        guard $0.id == playerID else { return $0 }
        var copy = $0
        copy.score.append(score)
        return copy
    }
}
</code>```

or:

```<code>func saveScoreToPlayer3(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    guard let player = game.players.first(where: { $0.id == playerID
    }) else {
        fatalError()
    }
    player.wrappedValue.score.append(score)
}
</code>```

Title: SwiftUI getby UUID

Body:
I'm pretty new to SwiftUI so I'm hoping someone can help me out here.
I have a UUID and I am trying to save content into that specific object, but I do not know how to call the object, like with a getbyid or something.

struct Game: Identifiable, Codable {
    let id: UUID
    var title: String
    var players: [Player]
}
extension Game {
    struct Player: Identifiable, Codable {
        let id: UUID
        var name: String
        var score: [Int32]
    }
}

used this code in my program

@Binding var game: Game
saveScoreToPlayer(game: $game, playerID: player.id, score: Int32)

func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    //save score to player obviously doesn't work
    game.playerID.insert(score at:0)
}

Body:
There are a few of ways you can do this. None is necessarily advantageous, although the second one (with the map) may prove slower in situations with huge data sets.

Note that in the examples I changed the function to accept Binding<Game> since that's what you are passing in in your call site.

func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    guard let index = game.wrappedValue.players.firstIndex(where: { $0.id == playerID }) else {
        fatalError()
    }
    game.wrappedValue.players[index].score.append(score)
}

or

func saveScoreToPlayer(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    game.wrappedValue.players = game.wrappedValue.players.map {
        guard $0.id == playerID else { return $0 }
        var copy = $0
        copy.score.append(score)
        return copy
    }
}

or:

func saveScoreToPlayer3(game: Binding<Game>, playerID: Game.Player.ID, score: Int32) {
    guard let player = game.players.first(where: { $0.id == playerID
    }) else {
        fatalError()
    }
    player.wrappedValue.score.append(score)
}


问:
How do I skip a carrierwave store callback when processing versions
I have a callback defined in my video uploader class of carrierwave

after :store, :my_method

and I have three versions of the files. original,standard,low

my_method executes when each version is processed ie, three times, I just need the callback to execute once.

答:
I needed just the same thing, and I found out that the original version (which is called nil inside carrierwave) is always processed last. I couldn't find out why in the source files, and it feels counter-intuitive when looking at the code, but simple puts with version_name reveals that it is so.

You could use this fact for your problem:

```<code>after :store, :my_method

def my_method(_file = nil)
  return if version_name

  # do something only once, after all versions are stored
end

</code>```

I used carrierwave_backgrounder gem and its process_in_background feature along with gem's optional <uploader_name>_processing column, which gave me a possibility to use the after_update callback on the model like this:

```<code># some_model.rb
class SomeModel < ActiveRecord::Base
  mount_uploader :image, ImageUploader

  after_update do
    if image_processing_changed? && image_processing == false
      # do your stuff e.g. check if the image was actually uploaded to cloud.
      # S3 client from `fog-aws` gem has a handy head_object method to do that.
    end
  end
end
</code>```

I first thought I can't rely on this callback, because I only process_in_background, not storing as well, but later I found out that even though the processing takes place in background and isn't supposed to store in background, it does include storing as a part of the recreate_versions method, and as the whole process is already happening in background, storing happens in background (though synchronously), too, and it's safe to rely on this callback.

Here's the chain of involved methods calls:
process_in_background, ProcessAsset, recreate_versions!, setting image_processing flag to false.

carrierwave 1.3.1 carrierwave_backgrounder 0.4.2

Body:
I needed just the same thing, and I found out that the original version (which is called nil inside carrierwave) is always processed last. I couldn't find out why in the source files, and it feels counter-intuitive when looking at the code, but simple puts with version_name reveals that it is so.

You could use this fact for your problem:

after :store, :my_method

def my_method(_file = nil)
  return if version_name

  # do something only once, after all versions are stored
end

I used carrierwave_backgrounder gem and its process_in_background feature along with gem's optional <uploader_name>_processing column, which gave me a possibility to use the after_update callback on the model like this:

# some_model.rb
class SomeModel < ActiveRecord::Base
  mount_uploader :image, ImageUploader

  after_update do
    if image_processing_changed? && image_processing == false
      # do your stuff e.g. check if the image was actually uploaded to cloud.
      # S3 client from `fog-aws` gem has a handy head_object method to do that.
    end
  end
end

I first thought I can't rely on this callback, because I only process_in_background, not storing as well, but later I found out that even though the processing takes place in background and isn't supposed to store in background, it does include storing as a part of the recreate_versions method, and as the whole process is already happening in background, storing happens in background (though synchronously), too, and it's safe to rely on this callback.

Here's the chain of involved methods calls:
process_in_background, ProcessAsset, recreate_versions!, setting image_processing flag to false.

carrierwave 1.3.1 carrierwave_backgrounder 0.4.2


问:
Replace text in the middle of a TextNode with an element
I want to insert html tags within a text node with TreeWalker, but TreeWalker forces my html brackets into & lt; & gt; no matter what I've tried. Here is the code:

```<code>var text;
var tree = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);
while (tree.nextNode()) {
    text = tree.currentNode.nodeValue;
    text = text.replace(/(\W)(\w+)/g, '$1<element onmouseover="sendWord(\'$2\')">$2</element>');
    text = text.replace(/^(\w+)/, '<element onmouseover="sendWord(\'$1\')">$1</element>');
    tree.currentNode.nodeValue = text;
}
</code>```

Using \< or " instead of ' won't help. My workaround is to copy all of the DOM tree to a string and to replace the html body with that. It works on very simple webpages and solves my first problem, but is a bad hack and won't work on anything more than a trivial page. I was wondering if I could just work straight with the text node rather than use a workaround. Here is the code for the (currently buggy) workaround:

```<code>var text;
var newHTML = "";
var tree = document.createTreeWalker(document.body);
while (tree.nextNode()) {
    text = tree.currentNode.nodeValue;
    if (tree.currentNode.nodeType == 3){
        text = text.replace(/(\W)(\w+)/g, '$1<element onmouseover="sendWord(\'$2\')">$2</element>');
        text = text.replace(/^(\w+)/, '<element onmouseover="sendWord(\'$1\')">$1</element>');
        }
    newHTML += text
}
document.body.innerHTML = newHTML;
</code>```

Edit: I realize a better workaround would be to custom tag the text nodes ((Customtag_Start_Here) etc.), copy the whole DOM to a string, and use my customs tags to identify text nodes and modify them that way. But if I don't have to, I'd rather not.

答:
Function that returns the parent element of any text node including partial match of passed string:

```<code>function findElByText(text, mainNode) {
    let textEl = null;
    const traverseNodes = function (n) {
        if (textEl) {
            return;
        }
        for (var nodes = n.childNodes, i = nodes.length; i--;) {
            if (textEl) {
                break;
            }
            var n = nodes[i], nodeType = n.nodeType;
            // Its a text node, check if it matches string
            if (nodeType == 3) {
                if (n.textContent.includes(text)) {
                    textEl = n.parentElement;
                    break;
                }
            }
            else if (nodeType == 1 || nodeType == 9 || nodeType == 11) {
                traverseNodes(n);
            }
        }
    }
    traverseNodes(mainNode);
    return textEl;
}
</code>```

Usage:

```<code>findElByText('Some string in document', document.body);
</code>```

Body:
I want to insert html tags within a text node with TreeWalker, but TreeWalker forces my html brackets into & lt; & gt; no matter what I've tried. Here is the code:

var text;
var tree = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);
while (tree.nextNode()) {
    text = tree.currentNode.nodeValue;
    text = text.replace(/(\W)(\w+)/g, '$1<element onmouseover="sendWord(\'$2\')">$2</element>');
    text = text.replace(/^(\w+)/, '<element onmouseover="sendWord(\'$1\')">$1</element>');
    tree.currentNode.nodeValue = text;
}

Using \< or " instead of ' won't help. My workaround is to copy all of the DOM tree to a string and to replace the html body with that. It works on very simple webpages and solves my first problem, but is a bad hack and won't work on anything more than a trivial page. I was wondering if I could just work straight with the text node rather than use a workaround. Here is the code for the (currently buggy) workaround:

var text;
var newHTML = "";
var tree = document.createTreeWalker(document.body);
while (tree.nextNode()) {
    text = tree.currentNode.nodeValue;
    if (tree.currentNode.nodeType == 3){
        text = text.replace(/(\W)(\w+)/g, '$1<element onmouseover="sendWord(\'$2\')">$2</element>');
        text = text.replace(/^(\w+)/, '<element onmouseover="sendWord(\'$1\')">$1</element>');
        }
    newHTML += text
}
document.body.innerHTML = newHTML;

Edit: I realize a better workaround would be to custom tag the text nodes ((Customtag_Start_Here) etc.), copy the whole DOM to a string, and use my customs tags to identify text nodes and modify them that way. But if I don't have to, I'd rather not.

Body:
Function that returns the parent element of any text node including partial match of passed string:

function findElByText(text, mainNode) {
    let textEl = null;
    const traverseNodes = function (n) {
        if (textEl) {
            return;
        }
        for (var nodes = n.childNodes, i = nodes.length; i--;) {
            if (textEl) {
                break;
            }
            var n = nodes[i], nodeType = n.nodeType;
            // Its a text node, check if it matches string
            if (nodeType == 3) {
                if (n.textContent.includes(text)) {
                    textEl = n.parentElement;
                    break;
                }
            }
            else if (nodeType == 1 || nodeType == 9 || nodeType == 11) {
                traverseNodes(n);
            }
        }
    }
    traverseNodes(mainNode);
    return textEl;
}

Usage:

findElByText('Some string in document', document.body);


问:
WebClientRequestException when wiremocking Spring Boot Service POST method
I'm testing my Service in Spring Boot, but I'm getting WebClientRequestException: failed to resolve 'null' after 6 queries; nested exception is java.net.UnknownHostException: failed to resolve 'null' after 6 queries.

I'm new to mocking and testing in general. I guess stubbing is properly done, but asserting is done wrong. Here's my service:

```<code>public String changeState(String ids) {
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add("ids", ids);

return webClient.post()
        .uri("/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c")
        .header(HttpHeaders.AUTHORIZATION, getSessionId())
        .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
        .bodyValue(form)
        .retrieve()
        .bodyToMono(String.class)
        .block();
}
</code>```

And here's my test, with the response from Postman as a body:

```<code>@Test
@DisplayName("Test changeState")
void changeState() {
    String body = "{\n" +
            "    \"responseStatus\": \"SUCCESS\",\n" +
            "    \"data\": [\n" +
            "        {\n" +
            "            \"responseStatus\": \"SUCCESS\",\n" +
            "                \"id\": \"V4600000001K001\",\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    wireMockServer.stubFor(post(urlEqualTo("/api/v21.3/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(body))
    );
    String vaultIds = vaultServiceTest.changeState("V4600000001K001");
    assertEquals(body, vaultIds);
}
</code>```

As I can see, asserting is obviously done wrong, because I'm asserting the whole body vs. just a single string. I'm not sure is this the right approach or my test method is wrong as a whole.

答:
WebClientRequestException: failed to resolve 'null' after 6 queries;

This error message suggests that the WebClient is being created with a null base URL when the test is run. Not sure how the WebClient is being created in the actual code, but one approach that could also make this work in the test would be to create one in the test class with localhost as the base URL so that it will work with WireMock.

For example:

```<code>@Test
@DisplayName("Test changeState")
void changeState() {
    //Create and start the WireMockServer for localhost on port 8090
    WireMockServer wireMockServer = new WireMockServer(8090);
    wireMockServer.start();

    //Create a WebClient with base URL localhost on port 8090
    WebClient localhostWebClient = WebClient.builder().baseUrl("http://localhost:8090").build();

    //Initialize VaultService with the localhost web client
    VaultService vaultService = new VaultService(localhostWebClient);

    ...
</code>```

To allow the WebClient to be injected into the Vault service, add a parameter for WebClient in the constructor:

```<code>public class VaultService {

    private WebClient webClient;

    public VaultService(WebClient webClient) {
        this.webClient = webClient;
    }
    ...
</code>```

As I can see, asserting is obviously done wrong, because I'm asserting the whole body vs. just a single string.

The JSON response can be mapped to a Java object assuming the field names and data types match up, and the JSON is syntactically valid. Here is some Java objects that could be made that matches the data model of the JSON response:

VaultResponse.java:

```<code>public class VaultResponse {
    private String responseStatus;
    private VaultResponseData[] data;

    public String getResponseStatus() {
        return responseStatus;
    }

    public void setResponseStatus(String responseStatus) {
        this.responseStatus = responseStatus;
    }

    public VaultResponseData[] getData() {
        return data;
    }

    public void setData(VaultResponseData[] data) {
        this.data = data;
    }
}
</code>```

VaultResponseData.java:

```<code>public class VaultResponseData {
    private String responseStatus;
    private String id;

    public String getResponseStatus() {
        return responseStatus;
    }

    public void setResponseStatus(String responseStatus) {
        this.responseStatus = responseStatus;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
</code>```

Now in the changeState() method, the response can be mapped to a VaultResponse object instead of a String:

```<code>return webClient.post()
        .uri("/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c")
        .header(HttpHeaders.AUTHORIZATION, getSessionId())
        .header(HttpHeaders.ACCEPT, PageAttributes.MediaType.APPLICATION_JSON_VALUE)
        .bodyValue(form)
        .retrieve()
        .bodyToMono(VaultResponse.class) //Response can be mapped to an Object instead of a raw String
        .block();
</code>```

And finally, in the assert, you can assert on just the ID string instead of the whole JSON response body. A couple of things have to be fixed as well:

There is an extra comma after the ID in the JSON body. \"id\": \"V4600000001K001\",\n" should become \"id\": \"V4600000001K001\"\n"

The WireMock URL should match the URL being used in the code.

Here is the whole test method after all of the changes:

```<code>@Test
@DisplayName("Test changeState")
void changeState() {
    //Create and start the WireMockServer for localhost on port 8090
    WireMockServer wireMockServer = new WireMockServer(8090);
    wireMockServer.start();

    //Create a WebClient with base URL localhost on port 8090
    WebClient localhostWebClient = WebClient.builder().baseUrl("http://localhost:8090").build();

    //Initialize VaultService with the localhost web client
    VaultService vaultService = new VaultService(localhostWebClient);

    String body = "{\n" +
            "    \"responseStatus\": \"SUCCESS\",\n" +
            "    \"data\": [\n" +
            "        {\n" +
            "            \"responseStatus\": \"SUCCESS\",\n" +
            "                \"id\": \"V4600000001K001\"\n" + //Extra comma here was removed to make this valid JSON
            "        }\n" +
            "    ]\n" +
            "}";

    //This URL must match the URL being called in the code
    wireMockServer.stubFor(post(urlEqualTo("/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(body))
    );

    VaultResponse vaultResponse = vaultService.changeState("V4600000001K001");
    assertEquals("V4600000001K001", vaultResponse.getData()[0].getId());
}
</code>```

Body:
I'm testing my Service in Spring Boot, but I'm getting WebClientRequestException: failed to resolve 'null' after 6 queries; nested exception is java.net.UnknownHostException: failed to resolve 'null' after 6 queries.

I'm new to mocking and testing in general. I guess stubbing is properly done, but asserting is done wrong. Here's my service:

public String changeState(String ids) {
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add("ids", ids);

return webClient.post()
        .uri("/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c")
        .header(HttpHeaders.AUTHORIZATION, getSessionId())
        .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
        .bodyValue(form)
        .retrieve()
        .bodyToMono(String.class)
        .block();
}

And here's my test, with the response from Postman as a body:

@Test
@DisplayName("Test changeState")
void changeState() {
    String body = "{\n" +
            "    \"responseStatus\": \"SUCCESS\",\n" +
            "    \"data\": [\n" +
            "        {\n" +
            "            \"responseStatus\": \"SUCCESS\",\n" +
            "                \"id\": \"V4600000001K001\",\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    wireMockServer.stubFor(post(urlEqualTo("/api/v21.3/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(body))
    );
    String vaultIds = vaultServiceTest.changeState("V4600000001K001");
    assertEquals(body, vaultIds);
}

As I can see, asserting is obviously done wrong, because I'm asserting the whole body vs. just a single string. I'm not sure is this the right approach or my test method is wrong as a whole.

Body:
WebClientRequestException: failed to resolve 'null' after 6 queries;

This error message suggests that the WebClient is being created with a null base URL when the test is run. Not sure how the WebClient is being created in the actual code, but one approach that could also make this work in the test would be to create one in the test class with localhost as the base URL so that it will work with WireMock.

For example:

@Test
@DisplayName("Test changeState")
void changeState() {
    //Create and start the WireMockServer for localhost on port 8090
    WireMockServer wireMockServer = new WireMockServer(8090);
    wireMockServer.start();

    //Create a WebClient with base URL localhost on port 8090
    WebClient localhostWebClient = WebClient.builder().baseUrl("http://localhost:8090").build();

    //Initialize VaultService with the localhost web client
    VaultService vaultService = new VaultService(localhostWebClient);

    ...

To allow the WebClient to be injected into the Vault service, add a parameter for WebClient in the constructor:

public class VaultService {

    private WebClient webClient;

    public VaultService(WebClient webClient) {
        this.webClient = webClient;
    }
    ...

As I can see, asserting is obviously done wrong, because I'm asserting the whole body vs. just a single string.

The JSON response can be mapped to a Java object assuming the field names and data types match up, and the JSON is syntactically valid. Here is some Java objects that could be made that matches the data model of the JSON response:

VaultResponse.java:

public class VaultResponse {
    private String responseStatus;
    private VaultResponseData[] data;

    public String getResponseStatus() {
        return responseStatus;
    }

    public void setResponseStatus(String responseStatus) {
        this.responseStatus = responseStatus;
    }

    public VaultResponseData[] getData() {
        return data;
    }

    public void setData(VaultResponseData[] data) {
        this.data = data;
    }
}

VaultResponseData.java:

public class VaultResponseData {
    private String responseStatus;
    private String id;

    public String getResponseStatus() {
        return responseStatus;
    }

    public void setResponseStatus(String responseStatus) {
        this.responseStatus = responseStatus;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Now in the changeState() method, the response can be mapped to a VaultResponse object instead of a String:

return webClient.post()
        .uri("/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c")
        .header(HttpHeaders.AUTHORIZATION, getSessionId())
        .header(HttpHeaders.ACCEPT, PageAttributes.MediaType.APPLICATION_JSON_VALUE)
        .bodyValue(form)
        .retrieve()
        .bodyToMono(VaultResponse.class) //Response can be mapped to an Object instead of a raw String
        .block();

And finally, in the assert, you can assert on just the ID string instead of the whole JSON response body. A couple of things have to be fixed as well:

There is an extra comma after the ID in the JSON body. \"id\": \"V4600000001K001\",\n" should become \"id\": \"V4600000001K001\"\n"

The WireMock URL should match the URL being used in the code.

Here is the whole test method after all of the changes:

@Test
@DisplayName("Test changeState")
void changeState() {
    //Create and start the WireMockServer for localhost on port 8090
    WireMockServer wireMockServer = new WireMockServer(8090);
    wireMockServer.start();

    //Create a WebClient with base URL localhost on port 8090
    WebClient localhostWebClient = WebClient.builder().baseUrl("http://localhost:8090").build();

    //Initialize VaultService with the localhost web client
    VaultService vaultService = new VaultService(localhostWebClient);

    String body = "{\n" +
            "    \"responseStatus\": \"SUCCESS\",\n" +
            "    \"data\": [\n" +
            "        {\n" +
            "            \"responseStatus\": \"SUCCESS\",\n" +
            "                \"id\": \"V4600000001K001\"\n" + //Extra comma here was removed to make this valid JSON
            "        }\n" +
            "    ]\n" +
            "}";

    //This URL must match the URL being called in the code
    wireMockServer.stubFor(post(urlEqualTo("/vobjects/ecotox_study__c/actions/Objectlifecyclestateuseraction.ecotox_study__c.study_setup_completed_state__c.change_state_to_study_contracted_useract__c"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(body))
    );

    VaultResponse vaultResponse = vaultService.changeState("V4600000001K001");
    assertEquals("V4600000001K001", vaultResponse.getData()[0].getId());
}


问:
Create Intent, but leave BottomAppBar visible
I have a standard Android app with a BottomAppBar, 3 fragments/tabs, a floating action button which opens an Intent. The intent occupies the whole screen and covers the BottomAppBar. Is there a way to make the BottomAppBar visible while the Intent is open?</p>

答:
There's two real ways to do this:

1)Have a BottomAppBar in both Activities.

2)Don't make these things Activities.  Make them Fragments, and have the top level Activity hold the bottom app bar and decide what fragment will display above it.

Really #2 sounds probably better, but it depends on exactly what you're doing.


问:
How to delete a file on the server? FilePond.revert does not pass parameters to the laravel controller
FilePond.revert does not transfer unique id files to the laravel controller.

How to delete the downloaded file by ID?

FilePond JS

```<code>var csrf = $('meta[name="csrf-token"]').attr('content');

    FilePond.setOptions({
        server: {
            url: '/file/upload/',
            process: {
                url: 'process',
                headers: {
                    'X-CSRF-TOKEN': csrf
                },
                onload: function (responce) {
                    console.log(JSON.parse(responce))
                },
            },
            revert: {
                url: 'revert',
                headers: {
                    'X-CSRF-TOKEN': csrf
                },
                onload: function (x) {

                    // X - empty, why????
                    console.log(x)

                },
            },
            load: {
                url: 'load/',
            },
        },
    })

    FilePond.create(document.querySelector('.filepond[type="file"]'), {
        files: [
            {
                source: '11',
                options: {
                    type: 'local',
                }
            },
        ]
    });
</code>```

Loading pictures work successfully.
Return unique ID file in response.

```<code>public function process(){

        $file = FilesUploadService::save();

        return response($file->collection->id, 200)
            ->header('Content-Type', 'text/plain');
    }
</code>```

Empty here I can't find the file id. Which need to be removed

```<code>public function revert(Request $request){
        return response()->json($request->all());
    }
</code>```

答:
i have faced the exact same problem. i did 2 thing to fix it.

must have the process.onload function and return the object Id/path. this  Id/path will automatically pass to revert function.

in the controller method which handle the revert call. the Id/path from step 1, can be obtain from calling $request->getContent(), notice that $request->all() can not grab the value.

Body:
FilePond.revert does not transfer unique id files to the laravel controller.

How to delete the downloaded file by ID?

FilePond JS

var csrf = $('meta[name="csrf-token"]').attr('content');

    FilePond.setOptions({
        server: {
            url: '/file/upload/',
            process: {
                url: 'process',
                headers: {
                    'X-CSRF-TOKEN': csrf
                },
                onload: function (responce) {
                    console.log(JSON.parse(responce))
                },
            },
            revert: {
                url: 'revert',
                headers: {
                    'X-CSRF-TOKEN': csrf
                },
                onload: function (x) {

                    // X - empty, why????
                    console.log(x)

                },
            },
            load: {
                url: 'load/',
            },
        },
    })

    FilePond.create(document.querySelector('.filepond[type="file"]'), {
        files: [
            {
                source: '11',
                options: {
                    type: 'local',
                }
            },
        ]
    });

Loading pictures work successfully.
Return unique ID file in response.

public function process(){

        $file = FilesUploadService::save();

        return response($file->collection->id, 200)
            ->header('Content-Type', 'text/plain');
    }

Empty here I can't find the file id. Which need to be removed

public function revert(Request $request){
        return response()->json($request->all());
    }


问:
Multi Column Select Menu with Header React
Please advise if any suggestions or code examples for multi column select/drop down menu as per picture. Also, I'm looking for any libraries for React that can present such select menus with multiple column + headers.

答:
You can do that with Material-Ui, a good way and prowerfull tool.

The documentation says everything.

To see the concept:
https://mui.com/components/data-grid/getting-started/#main-content

To see demo main component :
https://mui.com/components/data-grid/#mit-version

If something is not exactly what you want, you can customize, add other component...

Doc is solid and community is big with MUI


问:
Shopify white bar which i cant remove
I've been trying to remove this white bar that show between two sections on Shopify. The code i see that impact this is:

.section + .section {
  margin-top: var(--spacing-sections-mobile);
}

@media screen and (min-width: 750px) {
  .section + .section {
    margin-top: var(--spacing-sections-desktop);
  }
}```

enter image description here

Can someone please help me understand how to remove this white bar?

Thanks

答:
assuming you're with some 2.0 theme, try something like this:</p>
```<code>body .section + .section {
 margin-top:0;
 margin-bottom:0;
}
</code>```

Title: Shopify white bar which i cant remove

Body:
I've been trying to remove this white bar that show between two sections on Shopify. The code i see that impact this is:

.section + .section {
  margin-top: var(--spacing-sections-mobile);
}

@media screen and (min-width: 750px) {
  .section + .section {
    margin-top: var(--spacing-sections-desktop);
  }
}

enter image description here

Can someone please help me understand how to remove this white bar?

Thanks

Body:
assuming you're with some 2.0 theme, try something like this:

body .section + .section {
 margin-top:0;
 margin-bottom:0;
}


问:
C#: Using reflection to get access to all fields within a class, returns error
can anyone help me?

I have some reflection code that i have written and it seems to work well but it gives me an error when trying to pass in "this" to the GetValue.

I am a little stuck, i think the problem is that i am running the reflection code in frmMain adn the AbCCompany is defined in another project but i have a reference.

I get the error

Field 'AbcCompany' defined on type 'MyApp.Companies.Config' is not a
  field on the target object which is of type 'MyApp.frmMain'.

Here is the code..

```<code>        var companies = MyIems.Companies.GetType().GetFields();

        foreach (var list in companies )
        {

            List<CompanyBase> thisCompanyCollection = (List<CompanyBase>)list.GetValue(this);
            foreach (var company in thisCompanyCollection )
            {
                Console.WriteLine();
            }
        }
</code>```

EDIT

I forgot to mention that Inside "Companies" is lots of List where xxx is a class.. all classes inherit from CompanyBase.  i.e AbcCompany

答:
Instead of passing in this to GetValue you need to pass an instance of MyApp.Companies.Config.

If you look at the documentation, you can see that the exception your getting is because the obj parameter isn't of the type (or inherits from it) that the current field is declared on.

Assuming that MyApp.Companies.Config has a parameterless constructor, the following should work:

```<code>var type = MyItems.Companies.GetType();

var instance = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);

foreach(var list in type.GetFields())
{
    List<CompanyBase> thisCompanyCollection = (List<CompanyBase>)list.GetValue(instance);
    foreach(var company in thisCompanyCollection)
    {
        Console.WriteLine(company);
    }
}
</code>```

Body:
can anyone help me?

I have some reflection code that i have written and it seems to work well but it gives me an error when trying to pass in "this" to the GetValue.

I am a little stuck, i think the problem is that i am running the reflection code in frmMain adn the AbCCompany is defined in another project but i have a reference.

I get the error

Field 'AbcCompany' defined on type 'MyApp.Companies.Config' is not a
  field on the target object which is of type 'MyApp.frmMain'.

Here is the code..

        var companies = MyIems.Companies.GetType().GetFields();

        foreach (var list in companies )
        {

            List<CompanyBase> thisCompanyCollection = (List<CompanyBase>)list.GetValue(this);
            foreach (var company in thisCompanyCollection )
            {
                Console.WriteLine();
            }
        }

EDIT

I forgot to mention that Inside "Companies" is lots of List where xxx is a class.. all classes inherit from CompanyBase.  i.e AbcCompany

Body:
Instead of passing in this to GetValue you need to pass an instance of MyApp.Companies.Config.

If you look at the documentation, you can see that the exception your getting is because the obj parameter isn't of the type (or inherits from it) that the current field is declared on.

Assuming that MyApp.Companies.Config has a parameterless constructor, the following should work:

var type = MyItems.Companies.GetType();

var instance = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);

foreach(var list in type.GetFields())
{
    List<CompanyBase> thisCompanyCollection = (List<CompanyBase>)list.GetValue(instance);
    foreach(var company in thisCompanyCollection)
    {
        Console.WriteLine(company);
    }
}


问:
Progamming inside a Attiny85 with rust

Introduction

I created a small project that uploads C++ code to an Attiny85, for this I used arduino.

Question

But I would have liked to know if it was possible to download and run rust code in Attiny85 or other Attiny.
If we can, how do we do it?

Details

I found this GitHub repo to do this, but it is not explicit on how can export the rust code to Attiny.
The GitHub repo in question: https://github.com/q231950/avr-attiny85-rust?ref=https://githubhelp.com

答:
C++ is cross-compiled to AVR machine code on your development host.  What you are loading is not C++ code; that is the source code used to generate the machine executable binary code, which is what you load..

You can develop for AVR using any language for which a cross compiler exists.  Rust is certainly such a language. This article discusses using Rust on Arduino Uno hardware.

Whether ATTiny85 with only 8Kb of Flash and 512 bytes of SRAM will support a Rust runtime environment and any useful code I cannot tell; I am not familiar with Rust's runtime requirements, but it does not seem like an efficient use of limited resources to me, and I would treat it as an academic challenge rather than a practical development approach. I would expect Rust to have a considerably larger run-time footprint than C or even C++.

Title: Progamming inside a Attiny85 with rust