Verilog function result different from expected - function

I'm using this function snippet to make my 7 segment display more readable. Why does it print '00' and not '0E'?
module main;
function disp;
input [6:0] a;
begin
case (a)
7'b0000001 : disp=4'h0;
7'b1001111 : disp=4'h1;
7'b0010010 : disp=4'h2;
7'b0000110 : disp=4'h3;
7'b1001100 : disp=4'h4;
7'b0100100 : disp=4'h5;
7'b0100000 : disp=4'h6;
7'b0001111 : disp=4'h7;
7'b0000000 : disp=4'h8;
7'b0001100 : disp=4'h9;
7'b0001000 : disp=4'hA;
7'b1100000 : disp=4'hB;
7'b0110001 : disp=4'hC;
7'b1000010 : disp=4'hD;
7'b0110000 : disp=4'hE;
7'b0111000 : disp=4'hF;
default : disp=4'bxxxx;
endcase
end
endfunction
initial
begin
$display("%h%h", disp(7'b0000001), disp(7'b0110000)); //expecting 0E
$finish;
end
endmodule

You are missing the size of the output from the function. It defaults to 1 bit and because the first bit of 'hE is 0 it returns zero.
Change the function declaration to:
function [3:0] disp;

Related

Antlr How to avoid reportAttemptingFullContext and reportAmbiguity

In my java program im parsing many lines of code and to avoid ambiguous lines i used:
ParseTreeWalker walker = new ParseTreeWalker ();
if (!(lexerErrorListener.hasError() || parserErrorListener.hasError ()))
walker.walk (listener, tree);
else
line error
with the listener:
#Override
public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact,
BitSet ambigAlts, ATNConfigSet configs) {
hasError = true;
}
#Override
public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
BitSet conflictingAlts, ATNConfigSet configs) {
hasError = true;
}
input like: |U1,0 = comment generate ambiguity and fullcontext error with my grammar.
is a wrong approach or is there a way to handle these errors?
My Lexer:
lexer grammar LexerGrammar;
SINGLE_COMMENT : '|' -> pushMode(COMMENT);
NUMBER : [0-9];
VIRGOLA : ',';
WS : [ \t] -> skip ;
EOL : [\r\n]+;
// ------------ Everything INSIDE a COMMENT ------------
mode COMMENT;
COMMENT_NUMBER : NUMBER -> type(NUMBER);
COMMENT_VIRGOLA : VIRGOLA -> type(VIRGOLA);
TYPE : 'I'| 'U'| 'Q';
EQUAL : '=';
COMMENT_TEXT: ('a'..'z' | 'A'..'Z')+;
WS_1 : [ \t] -> skip ;
COMMENT_EOL : EOL -> type(EOL),popMode;
my parser:
parser grammar Parser;
options {
tokenVocab = LexerGrammar;
}
prog : (line? EOL)+;
line : comment;
comment: SINGLE_COMMENT (defComm | genericComment);
defComm: TYPE arg EQUAL COMMENT_TEXT;
arg : (argument1) (VIRGOLA argument2)?;
argument1 : numbers ;
argument2 : numbers ;
numbers : NUMBER+ ;
genericComment: .*?;
reportAmbiguity and reportAttemptingFullContext are not an indication that there was a syntax error. You can listen in on these events to know if they happen, but ANTLR has a deterministic approach to resolving this ambiguity (it uses the first alternative).
If you do not treat those as errors, you will get a proper parse tree out of your parse.

PYTHON3 | Parsing JSON | index out of range | can't access to 1st column of an array

I have this JSON (I don't give you the whole thing because it's freaking long but you don't need the rest.)
cve" : {
"data_type" : "CVE",
"data_format" : "MITRE",
"data_version" : "4.0",
"CVE_data_meta" : {
"ID" : "CVE-2018-9991",
"ASSIGNER" : "cve#mitre.org"
},
"affects" : {
"vendor" : {
"vendor_data" : [ {
"vendor_name" : "frog_cms_project",
"product" : {
"product_data" : [ {
"product_name" : "frog_cms",
"version" : {
"version_data" : [ {
"version_value" : "0.9.5"
} ]
}
} ]
}
} ]
}
},
What I want to do is to print the vendor name of this cve.
So, what I did is :
with open("nvdcve-1.0-2018.json", "r") as file:
data = json.load(file)
increment = 0
number_cve = data["CVE_data_numberOfCVEs"]
while increment < int(number_cve):
print (data['CVE_Items'][increment]['cve']['CVE_data_meta']['ID'])
print (',')
print (data['CVE_Items'][increment]['cve']['affects']['vendor']['vendor_data'][0]['vendor_name'])
print ("\n")
increment +=
The reason I did a while is because in the JSON file, there is a lot of CVEs, this is why I did data['CVE_Items'][increment]['cve'] (and this part works fine, the line `print (data['CVE_Items'][increment]['cve']['CVE_data_meta']['ID'] is working well).
My error is in the print (data['CVE_Items'][increment]['cve']['affects']['vendor']['vendor_data'][0]['vendor_name']) line, python returns a list index out of range error.
But if I'm reading this JSON well, vendor_data is an array of 1 column so vendor_name is the ['vendor_data'][0]['vendor_name'] isn't it ?
The only way to parse the vendor_name i found is :
for value in data['CVE_Items'][a]['cve']['affects']['vendor']['vendor_data']:
print (value['vendor_name'])
instead of print (data['CVE_Items'][increment]['cve']['affects']['vendor']['vendor_data'][0]['vendor_name'])
And doing a for just for one iteration is pretty disgusting :s, but at least, value is the data['CVE_Items'][a]['cve']['affects']['vendor']['vendor_data'][0] that I wanted....
Anyone knows something about it ?
Make sure every CVE_Item has an vender_data.
Example:
with open("nvdcve-1.0-2018.json", "r") as file:
data = json.load(file)
increment = 0
number_cve = data["CVE_data_numberOfCVEs"]
while increment < int(number_cve):
print (data['CVE_Items'][increment]['cve']['CVE_data_meta']['ID'])
print (',')
if (len(data['CVE_Items'][increment]['cve']['affects']['vendor']['vendor_data']) > 0) :
print (data['CVE_Items'][increment]['cve']['affects']['vendor']['vendor_data'][0]['vendor_name'])
print ("\n")
increment +=
Thanks to Ron Nabuurs' answer i found that all my vendor_data does not always have a vendor_name. So it is why the for works and not the print.
(the for check if the object is non null, else it stops).
So what I did is :
try:
print (data['CVE_Items'][increment]['cve']['affects']['vendor']['vendor_data'][0]['vendor_name'])
print (',')
except:
pass

Extract specific info from json-list

In my system from json-call http://192.168.1.6:8080/json.htm?type=devices&rid=89 I get the output below.
{
"ActTime" : 1501360852,
"ServerTime" : "2017-07-29 22:40:52",
"Sunrise" : "05:50",
"Sunset" : "21:28",
"result" : [
{
"AddjMulti" : 1.0,
"AddjMulti2" : 1.0,
"AddjValue" : 0.0,
"AddjValue2" : 0.0,
"BatteryLevel" : 255,
"CustomImage" : 0,
"Data" : "73 Lux",
"Description" : "",
"Favorite" : 1,
"HardwareID" : 4,
"HardwareName" : "Dummies",
"HardwareType" : "Dummy (Does nothing, use for virtual switches only)",
"HardwareTypeVal" : 15,
"HaveTimeout" : true,
"ID" : "82089",
"LastUpdate" : "2017-07-29 21:16:22",
"Name" : "ESP8266C_Licht1",
"Notifications" : "false",
"PlanID" : "0",
"PlanIDs" : [ 0 ],
"Protected" : false,
"ShowNotifications" : true,
"SignalLevel" : "-",
"SubType" : "Lux",
"Timers" : "false",
"Type" : "Lux",
"TypeImg" : "lux",
"Unit" : 1,
"Used" : 1,
"XOffset" : "0",
"YOffset" : "0",
"idx" : "89"
}
],
"status" : "OK",
"title" : "Devices"
}
'Automating' such call by the below scripttime lua-script is aimed at extraction of specific information, to be further used in applications.
The first 11 lines run without problems, but further extraction of the information is a problem.
I have tried various scriptlines to get a solution for A), B), C), D) and E), but either they generate error-report, or they don't give results: see further below for the 'best' trial-scriptlines and related results.
To avoid misunderstanding: those dashed commentlines in the script just below this question with A), B), C), D) and E) are only describing the desired actions/functions and are in no way meant as scriptlines!
Question:
Help requested in the form of better applicable scriptlines for A) till E) in the trialscript at the end of this message, or hints where to find applicable example scriptlines.
-- Lua-script to determine staleness, time-out and value for data from Json-call
print('Start of Timeout-script')
commandArray = {}
TimeOutLimit = 10 -- Allowed timeout in seconds
json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")() -- For Linux
-- json = (loadfile "D:\\Domoticz\\scripts\\lua\\json.lua")() -- For Windows
-- Line 07
local content=assert(io.popen('curl "http://192.168.1.6:8080/json.htm?type=devices&rid=89"')) -- notice double quotes
local list = content:read('*all')
content:close()
local jsonList = json:decode(list)
-- Line 12 Next scriptlines describe desired actions
-- A) Extract ServerTime as numeric value (not as string)
-- B) Extract LastUpdate as numeric value (not as string)
-- Staleness = ServerTime - LastUpdate
-- C) Extract HaveTimeout as boolean (not as string)
-- If HaveTimeout and (Staleness > TimeOutlimit) then
-- Print('TimeOutLimit exceeded by ' .. (Staleness - TimeOutLimit) .. 'seconds')
-- End
-- D) Extract textstring from Type or Data
-- E) Extract numeric value from Data
print('End of Timeout-script')
return commandArray
For lines 11 etc, the following trial-scriptlines gave 'best' results (= no errors):
-- Line 11
-- local Servertime = json:decode(ServerTime)
-- print('Servertime : '..Servertime)
-- Line 14
-- CheckTimeOut =jsonValue.result[1].HaveTimeout -- value from "HaveTimeout", inside "result" bloc number 1 (even if it's the only one)
CurrentServerTime =jsonValue.Servertime -- value from "ServerTime"
CurrentLastUpdate = jsonValue.result[1].LastUpdate
CurrentData = jsonValue.result[1].Data
-- Line 19
print('TimeOut : '..CheckTimeOut)
print('Servertime : '..CurrentServerTime)
print('LastUpdate : '..CurrentLastUpdate)
print('Data-content : '..CurrentData)
print('End of Timeout-script')
return commandArray
Results:
Without dashes before the lines 12 and 13, respectively 15, then the following error reports:
660: nil passed to JSON:decode()
lua:15: attempt to index global 'jsonValue' (a nil value)
With dashes before lines 12, 13 and 15 for the trial-scriptlines shown above, according to the log no errors exist (as demonstrated by the 2 prints)
2017-07-31 16:30:02.520 LUA: Start of Timeout-script
2017-07-31 16:30:02.563 LUA: End of Timeout-script
But why no print-results in the log from Lines 20 till 23?
Not having those print-results makes it difficult to determine next steps in data-extraction, to achieve the objectives described under A) till E).
;-) Error reports generally are more useful information than "no errors, but no results"
Without downloading content over the network, the working script looks like this:
local json = require("json")
local jj = [[
{
"ActTime" : 1501360852,
"ServerTime" : "2017-07-29 22:40:52",
"Sunrise" : "05:50",
"Sunset" : "21:28",
"result" : [
{
"AddjMulti" : 1.0,
"AddjMulti2" : 1.0,
"AddjValue" : 0.0,
"AddjValue2" : 0.0,
"BatteryLevel" : 255,
"CustomImage" : 0,
"Data" : "73 Lux",
"Description" : "",
"Favorite" : 1,
"HardwareID" : 4,
"HardwareName" : "Dummies",
"HardwareType" : "Dummy (Does nothing, use for virtual switches only)",
"HardwareTypeVal" : 15,
"HaveTimeout" : true,
"ID" : "82089",
"LastUpdate" : "2017-07-29 21:16:22",
"Name" : "ESP8266C_Licht1",
"Notifications" : "false",
"PlanID" : "0",
"PlanIDs" : [ 0 ],
"Protected" : false,
"ShowNotifications" : true,
"SignalLevel" : "-",
"SubType" : "Lux",
"Timers" : "false",
"Type" : "Lux",
"TypeImg" : "lux",
"Unit" : 1,
"Used" : 1,
"XOffset" : "0",
"YOffset" : "0",
"idx" : "89"
}
],
"status" : "OK",
"title" : "Devices"
}
]]
print('Start of Timeout-script')
local jsonValue = json.decode(jj)
CheckTimeOut =jsonValue.result[1].HaveTimeout
CurrentServerTime =jsonValue.Servertime
CurrentLastUpdate = jsonValue.result[1].LastUpdate
CurrentData = jsonValue.result[1].Data
print('TimeOut : '.. (CheckTimeOut and "true" or "false") )
print('Servertime : '.. (CurrentServerTime or "nil") )
print('LastUpdate : '.. (CurrentLastUpdate or "nil") )
print('Data-content : '.. (CurrentData or "nil") )
print('End of Timeout-script')
result:
Start of Timeout-script
TimeOut : true
Servertime : nil
LastUpdate : 2017-07-29 21:16:22
Data-content : 73 Lux
End of Timeout-script

How can I convert dictionary in list to dictionary in Python 3?

import urllib.request as request
import json
api = "https://kr.api.pvp.net/championmastery/location/KR/player/38281748/topchampions?api_key=RGAPI-6bdee369-a91d-485a-9280-444de0e37afe"
api_data = request.urlopen(api).read().decode("utf-8")
apiload = json.loads(api_data)
print(apiload)
I want to print my League of Legends champion Points.
So I use https://developer.riotgames.com/api/methods#!/1091/3768 this API, and
convert to Python object. but this API's Return Value is List[ChampionMasteryDTO],
which means I can't use it as dictionary.
apiload contain [{"key" : "value"}, ... {"key" : "value"}]
how can I make apiload as dictionary?
The apiload variable prints two dictionaries within a list.
If you would like to create a new dictionary using the apiload you can do the following:
#create a new dictionary
my_dict = {}
#now iterate through the list
for item in apiload:
#now iterate through the dictionaries that are in the list:
for key, value in item.items():
#assign the key value to the new declared dictionary
new_dict[key] = value
This will create a new dictionary with the following output:
championId : 91
tokensEarned : 0
championPointsSinceLastLevel : 339079
chestGranted : True
lastPlayTime : 1478451844000
playerId : 38281748
championLevel : 7
championPoints : 360679
championPointsUntilNextLevel : 0
championId : 5
tokensEarned : 0
championPointsSinceLastLevel : 129110
chestGranted : True
lastPlayTime : 1478454752000
playerId : 38281748
championLevel : 7
championPoints : 150710
championPointsUntilNextLevel : 0
championId : 21
tokensEarned : 0
championPointsSinceLastLevel : 2018
chestGranted : False
lastPlayTime : 1476197348000
playerId : 38281748
championLevel : 4
championPoints : 14618
championPointsUntilNextLevel : 6982
Hope that helps.
Regarding the structure of your response, the easy one if you just want to print your points, would be to just use a loop actually :
for el in apiload:
print(el["championPoints"])
If your problem is to print the total of points collected, use a collections.Counter :
from collections import Counter
cnt = Counter()
for col in apiload:
for k in col.keys():
cnt[k] += c.get(k, 0)
print(cnt['championPoints']) # should print the sum of championPoints

Dymola getExperiment() access

Does anyone know how to access specific outputs of the Dymola built-in function getExperiment();?
Unfortunately it only returns the Real scalar StartTime.
The function seems to be defined as follows:
function getExperiment "Get current experiment setting"
output Real StartTime := 0.0 "Start of simulation";
output Real StopTime := 1.0 "End of simulation";
output Integer NumberOfIntervals := 0 "Number of output points";
output Real OutputInterval := 0.0 "Distance between output points";
output String Algorithm := "" "Integration method";
output Real Tolerance := 0.0001 "Tolerance of integration";
output Real FixedStepSize := 0.0 "Fixed step size for Euler";
end getExperiment;
My test model is:
model GetExpTest
Real staTime;
Real outInterval;
equation
(staTime,outInterval)=receiveInfo();
end GetExpTest;code here
With the function:
function receiveInfo
output Real startT;
output Real outputInterv;
algorithm
(startT,,,outputInterv,,,):=getExperiment();
end receiveInfo;
And the error message I get is:
Compiling and linking the model (Visual C++).
dsmodel.c
dsmodel.c(32) : error C2079: 'dummy_mult_' uses undefined struct 'getExperiment_struct'
dsmodel.c(32) : warning C4013: 'getExperiment' undefined; assuming extern returning int
dsmodel.c(33) : error C2224: left of '.StartTime0_0_0member' must have struct/union type
dsmodel.c(34) : error C2224: left of '.OutputInterval0_0_0member' must have struct/union type
Error generating Dymosim.
Thank you in Advance for help!
If I do: getExperiment(), the following is returned:
= 0.0, 1.0, 500, 0.0, "dassl", 0.0001, 0.0
So you can access the values using a regular assignment taking multiple outputs. For example:
(StartTime,,NumberOfIntervals) := getExperiment()
Which returns:
Declaring variable: Real StartTime ;
Declaring variable: Integer NumberOfIntervals ;
StartTime
= 0.0
NumberOfIntervals
= 500