ANTLR4 extraneous input - antlr4

I have a problem with my ANTLR4. I'm trying to print AST from python 3 code but there are some errors and I don't know how to fix them.
I wrote simple code for test:
a=(1,2,3)
print(a)
I ran the program but this errors appeared:
line 1:1 extraneous input '=' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '#'}
line 2:0 extraneous input '\n' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '#'}
line 3:0 extraneous input '\n' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '#'}
My main class :
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.*;
public class Main {
public static void main(String[] args) {
try {
ANTLRInputStream input = new ANTLRFileStream("/home/grzegorz/Desktop/Python3/input.txt");
Python3Lexer lexer = new Python3Lexer(input);
CommonTokenStream token = new CommonTokenStream(lexer);
Python3Parser parser = new Python3Parser(token);
ParseTree parseTree = parser.expr();
System.out.println(parseTree.toStringTree(parser));
}catch (Exception ex){
ex.printStackTrace();
}
}
}
I have the grammar from this site:
https://github.com/antlr/grammars-v4/tree/master/python3

Explanation
Your input file consists of two statements and you are parsing the file as if it was an expression (with line ParseTree parseTree = parser.expr();; rule expr from Python 3 grammar).
This also exaplains the first error: an identificator a is accepted as a part of expression but = sign is not. That's because = is a part of assignment statement.
Solution
Parse the input using another grammar rule for example file_input rule which will accept many statements. Change the abovementioned line to ParseTree parseTree = parser.file_input();.

Related

Unique nested dictionary from the 'for' loop Python3

I've got the host which executes commands via 'subprocess' and gets output list of several parameters. The problem is that output can not be correctly modified to be translated to the dictionary, whether it's yaml or json. After list is received Regexp takes part to match valuable information and to perform grouping. I am interested in getting a unique dictionary, where crossing keys are put into nested dictionary.
Here is the code and the example of output list:
from re import compile,match
# Output can differ from request to request, the "keys" from the #
# list_of_values can dublicate or appear more than two times. The values #
# mapped to the keys can differ too. #
list_of_values = [
"paramId: '11'", "valueId*: '11'",
"elementId: '010_541'", 'mappingType: Both',
"startRng: ''", "finishRng: ''",
'DbType: sql', "activeSt: 'false'",
'profile: TestPr1', "specificHost: ''",
'hostGroup: tstGroup10', 'balance: all',
"paramId: '194'", "valueId*: '194'",
"elementId: '010_541'", 'mappingType: Both',
"startRng: '1020304050'", "finishRng: '1020304050'",
'DbType: sql', "activeSt: 'true'",
'profile: TestPr1', "specificHost: ''",
'hostGroup: tstGroup10', 'balance: all']
re_compile_valueId = compile(
"valueId\*:\s.(?P<valueId>\d{1,5})"
"|elementId:\s.(?P<elementId>\d{3}_\d{2,3})"
"|startRng:\s.(?P<startRng>\d{1,10})"
"|finishRng:\s.(?P<finishRng>\d{1,10})"
"|DbType:\s(?P<DbType>nosql|sql)"
"|activeSt:\s.(?P<activeSt>true|false)"
"|profile:\s(?P<profile>[A-z0-9]+)"
"|hostGroup:\s(?P<hostGroup>[A-z0-9]+)"
"|balance:\s(?P<balance>none|all|priority group)"
)
iterator_loop = 0
uniq_dict = dict()
next_dict = dict()
for element in list_of_values:
match_result = match(re_compile_valueId,element)
if match_result:
temp_dict = match_result.groupdict()
for key, value in temp_dict.items():
if value:
if key == 'valueId':
uniq_dict['valueId'+str(iterator_loop)] = ''
iterator_loop +=1
next_dict.update({key: value})
else:
next_dict.update({key: value})
uniq_dict['valueId'+str(iterator_loop-1)] = next_dict
print(uniq_dict)
This code right here responses with:
{
'valueId0':
{
'valueId': '194',
'elementId': '010_541',
'DbType': 'sql',
'activeSt': 'true',
'profile': 'TestPr1',
'hostGroup': 'tstGroup10',
'balance': 'all',
'startRng': '1020304050',
'finishRng': '1020304050'
},
'valueId1':
{
'valueId': '194',
'elementId': '010_541',
'DbType': 'sql',
'activeSt': 'true',
'profile': 'TestPr1',
'hostGroup': 'tstGroup10',
'balance': 'all',
'startRng': '1020304050',
'finishRng': '1020304050'
}
}
And I was waiting for something like:
{
'valueId0':
{
'valueId': '11',
'elementId': '010_541',
'DbType': 'sql',
'activeSt': 'false',
'profile': 'TestPr1',
'hostGroup': 'tstGroup10',
'balance': 'all',
'startRng': '',
'finishRng': ''
},
'valueId1':
{
'valueId': '194',
'elementId': '010_541',
'DbType': 'sql',
'activeSt': 'true',
'profile': 'TestPr1',
'hostGroup': 'tstGroup10',
'balance': 'all',
'startRng': '1020304050',
'finishRng': '1020304050'
}
}
I've also got another code below, which runs and puts values as expected. But the structure breaks the idea of having this all looped around, because each dictionary result key has its own order number mapped. The example below. The list_of_values and re_compile_valueId can be used from previous example.
for element in list_of_values:
match_result = match(re_compile_valueId,element)
if match_result:
temp_dict = match_result.groupdict()
for key, value in temp_dict.items():
if value:
if key == 'balance':
key = key+str(iterator_loop)
uniq_dict.update({key: value})
iterator_loop +=1
else:
key = key+str(iterator_loop)
uniq_dict.update({key: value})
print(uniq_dict)
The output will look like:
{
'valueId1': '11', 'elementId1': '010_541',
'DbType1': 'sql', 'activeSt1': 'false',
'profile1': 'TestPr1', 'hostGroup1': 'tstGroup10',
'balance1': 'all', 'valueId2': '194',
'elementId2': '010_541', 'startRng2': '1020304050',
'finishRng2': '1020304050', 'DbType2': 'sql',
'activeSt2': 'true', 'profile2': 'TestPr1',
'hostGroup2': 'tstGroup10', 'balance2': 'all'
}
Would appreciate any help! Thanks!
It appeared that some documentation reading needs to be performed :D
The copy() of the next_dict under else statement needs to be applied. Thanks to thread:
Why does updating one dictionary object affect other?
Many thanks to answer's author #thefourtheye (https://stackoverflow.com/users/1903116/thefourtheye)
The final code:
for element in list_of_values:
match_result = match(re_compile_valueId,element)
if match_result:
temp_dict = match_result.groupdict()
for key, value in temp_dict.items():
if value:
if key == 'valueId':
uniq_dict['valueId'+str(iterator_loop)] = ''
iterator_loop +=1
next_dict.update({key: value})
else:
next_dict.update({key: value})
uniq_dict['valueId'+str(iterator_loop-1)] = next_dict.copy()
Thanks for the involvement to everyone.

How we can check the the variable text is number or not in Azure logic app without inline

I have variables a = "hhddj"; Variable b = "1234";. I need an expression that gives a is type string and b is type int. Like we have Isnumeric(a) needs to return false, and Isnumeric(b) needs to return true.
The following expression can be used for checking whether the text in variables('a') is in fact an integer:
equals(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(variables('a'), '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', ''), '')

Syntax Error: TypeError: Cannot read property 'kind' of null for Enum using Vue 3 and TypeScript

I'm defining an enum within a Vue 3 component like so:
<script lang="ts">
import { defineComponent } from 'vue'
export enum PieceType
{
None,
Pawn,
Rook,
Knight,
Bishop,
Queen,
King
}
export interface Piece
{
position: Position,
type: PieceType,
}
export interface Position
{
row: number,
col: number
}
export default defineComponent({
props: {
type: String,
row: Number,
col: Number
},
setup(props) {
const getPiece = (piece: string) =>
{
console.log("Piece is:", piece)
switch(piece)
{
case "R": return PieceType.Rook;
case "K": return PieceType.Knight;
case "B": return PieceType.Bishop;
case "Q": return PieceType.Queen;
case "K": return PieceType.King;
case "P": return PieceType.Pawn;
case "-": return PieceType.None;
default: throw new Error("Invalid piece.")
}
}
return {
type: getPiece(props.type),
position: {row: props.row, col: props.col}
}
}
})
</script>
When I import the component into another component (the component equals Piece):
<script lang="ts">
import { defineComponent } from '#vue/composition-api';
import { Piece } from "../components/Piece";
export default defineComponent({
components: [Piece],
props: {
},
setup() {
const board =
[
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
];
return { board }
}
})
</script>
I get the following error:
Syntax Error: TypeError: Cannot read property 'kind' of null
Occurred while linting > .\components\Piece.vue:39
at Array.forEach (<anonymous>)
at Array.forEach (<anonymous>)
# ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/Board.vue?vue&type=script&lang=ts 3:0-44 6:15-20
# ./src/components/Board.vue?vue&type=script&lang=ts
# ./src/components/Board.vue
# ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js
# ./src/App.vue?vue&type=script&lang=js
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.3.235:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
The error is occurring at the line:
case "R": return PieceType.Rook
I noticed that if I get rid of the Enum and replace it with strings then it works, but I don't see why the Enum isn't working. The error isn't showing up in my intellisense in vscode and I'm not using the component in a for loop anywhere to trigger the "Array.ForEach" in the error. Any help would be appreciated!
My issue was I didn't run "vue add typescript" to add typescript to the project. I had other issues with how I declared the components, but that was ultimately the issue.

how to make parse of list(string) not list(char) in parse argument of list?

I use flask_restful in flask
My code like:
from flask_restful import Resource, reqparse
apilink_parser = reqparse.RequestParser()
apilink_parser.add_argument('provider_id', type=int,required=True)
apilink_parser.add_argument('name', type=str, required=True)
apilink_parser.add_argument('func_id', type=int)
apilink_parser.add_argument('method', type=str)
apilink_parser.add_argument('url', type=str)
apilink_parser.add_argument('parameter',type=list)
apilink_parser.add_argument("expectreturn", type=list)
#marshal_with(apilink_fields)
def post(self):
args = apilink_parser.parse_args()
print(args)
# user owns the task
task = APILink.create(**args)
return task, 201
My json post data like:
{
"name":"riskiqwhois",
"provider_id":1,
"func_id":1,
"url":"myurl",
"parameter":["query"], //******//
"expectreturn":[],
"method":"post"
}
but when I print the arrgs the result is:
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['q', 'u', 'e', 'r', 'y'], //******//
'expectreturn': None
}
I want
You can see I want parameter is list of string which is only one element named "query", but the real parameter tranlate into the database is ['q', 'u', 'e', 'r', 'y'], How to make the parameter is list of string not list of char? how to make sure the data is list(string)?
Well, you forgot to set action="append" and you should change from type=list to type=str.
If not, you will still be getting a result like [['q', 'u', 'e', 'r', 'y']].
...
apilink_parser.add_argument('parameter',type=str, action='append')
apilink_parser.add_argument("expectreturn", type=str, action='append')
You can solve this problem by adding action="append" to your request parser
like below
apilink_parser.add_argument('parameter',type=str,action="append")
apilink_parser.add_argument("expectreturn", type=list,action="append")
this will return you below output
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['query'],
'expectreturn': None
}

MacVim NERDCommenter, how to specify alternative delimiters

When I'm editing html and xhtml files in MacVim, sometimes I need to comment embedded css styles, so when I try to switch to the alternative set of delimiters ( ca ), the plugin warns me with:
NERDCommenter:cannot use alternative delimiters, none are specified
My question is:
how can I specify these alternative delimiters?
These can be specified in the config variable g:NERDCustomDelimiters (before the plugin is sourced, e.g. in your ~/.vimrc):
:let g:NERDCustomDelimiters = {
\ 'html': { 'left': '<!-- ', 'right': '-->', 'leftAlt': '/*', 'rightAlt': '*/' }
\ }
Added these lines to my .vimrc :
let g:NERDCustomDelimiters = {
\ 'html': { 'left': '<!-- ', 'right': '-->', 'leftAlt': '/*','rightAlt': '*/' },
\ 'xhtml': { 'left': '<!-- ', 'right': '-->', 'leftAlt': '/*','rightAlt': '*/'},
\}
let NERD_html_alt_style=1
NOTE: Don't forget about the commas after the curly braces!! :)

Resources