VSCode Rego Plugin opa evaluate not working as expected - visual-studio-code

I'm learning OPA and rego.
I'm trying to write a simple policy and have the same evaluated through VSCode Plugin.
Folder Structure:
learning.rego
package learning
test {
a := "test"
a == "test"
}
input.json
{}
And when I choose "OPA: Evaluate Selection" option from the command pallete, I get the below error.
{
"errors": [
{
"message": "expected body but got *ast.Package"
}
],
"metrics": {
"timer_rego_load_bundles_ns": 919639,
"timer_rego_module_compile_ns": 481890,
"timer_rego_module_parse_ns": 55722,
"timer_rego_query_parse_ns": 22773
}
}
But the same policy is working as expected in rego playground and evaluates to "true" as expected. What am I missing here?

Try running "Evaluate Package" instead of "Evaluate Selection", and it should work.
The Open Policy Agent extension for VSCode offers three ways of evaluating Rego code:
Evaluate Package
This seems to be the one you want. This parses the selected Rego code as an entire package. It expects the selection to begin with a Package declaration (e.g. package learning). If you select the entire Rego package and run "Evaluate Packages", it should work.
Evaluate Selection
This option evaluates part of a Rego package, so it expects the selection to begin with a Body (e.g. your test definition). If you just select test and its definition, it should work.
Partially Evaluate Selection
This final option is a bit more complex. In essence, rather than evaluating the policy it returns the conditions under which the policy is satisfied. This is useful for building queries for external datastores, or for interacting with complex data.

In vs code press ctrl+p and search for >OPA: Evaluate Package and enter you'll see the result.

To use Evaluate Selection
Double click on the policy name, in your case, test
Now run Evaluate Selection
It should work fine.
Refer to this website for more info: link
For your specific case, read up Chapter 2.

Related

Agenda Group not working with drools 8.29.FINAL version

We have java rules service microservice & Using drools 7.X version to process the dynamic rules process. business rules (.xlsx) file using the Agenda-groups which is working fine.
After upgrading to drools 8.29.FINAL. kiesession.getAgenda().setAgendaFocus("1") is returning null.
NOTE :
Drools 7.49 is giving me list of agenda's
kieContainer.getKieBase().getKiePackages().parallelStream()
.forEach(obj -> obj.getRules().stream().forEach(innerObj -> {
agendaGroups.add(KieRuleMetaData.builder().agendaGroup(((RuleImpl) innerObj).getAgendaGroup())
.ruleName(innerObj.getName()).build());
}));
After upgrading to 8.29.FINAL - it's notworking
Appreciate if any help
As per the documentation, changed only drools version on pom.xml file.
Without some reproducer, it is difficult to support you effectively; next time kindly consider providing a reproducer (on GitHub for example) and share it here or via mailing-list on drools-usage or kogito-development
To me, this snippet returns as expected the agenda-group(s) defined in the rules, using 8.33.0.Final in this little reproducer here: https://github.com/tarilabs/demo20230212-so75416633/blob/main/src/test/java/org/drools/demo/RuleTest.java#L32-L34
kContainer.getKieBase().getKiePackages().stream().forEach(obj -> obj.getRules().stream().forEach(innerObj -> {
LOG.info("Rules contain this Agenda group: {}", ((RuleImpl) innerObj).getAgendaGroup() );
}));
I've used some simplified logging as you didn't provide details of KieRuleMetaData in your snippet, but as you can see with rules defining
rule "will execute per each Measurement having ID color"
agenda-group "mygroup"
when
...
The snippet above correctly prints:
2023-02-12 10:51:45,868 [main] INFO Rules contain this Agenda group: mygroup
Then, in the test code, as you can see I'm using the agenda-group I wanted by locating it on the agenda and setting it in-focus: https://github.com/tarilabs/demo20230212-so75416633/blob/main/src/test/java/org/drools/demo/RuleTest.java#L58-L69
session.getAgenda().getAgendaGroup("mygroup").setFocus();
session.fireAllRules();
So to me I cannot reproduce any error in using agenda-groups using latest Drools available at the time of writing.
You mention you are using Spreadsheet (.xlsx) for defining the rules, and the agenda group "1" is very suspicious it might be interpreted wrongly as number Vs string.
I hope with my very first snippet above, you are able to re-instate the inspection of all the agenda-groups defined in all rules in all packages, so to verify your agenda-group "1" is really present.
If not, suggesting you try by writing in Excel as "aaa1" instead of the simple digit for one, so to make sure it is correctly saved in the Excel as a string.

Why isn't info popping up when the mouse hovers over a function in a package

When the mouse pointer hovers over the name of a function created in my code a box pops up in the editor with information about that function. However, if the function is in a package nothing happens. For example, if the mouse pointer hovers over the word "DataFrame" in the second line of the code below no box with info pops up. This is not specific to package DataFrames.
using DataFrames
DataFrame(:A => [0])
In VSCode Settings the following is set:
Editor > Hover:Delay
200
Editor > Hover:Enabled
Checked
The IDE is Visual Studio Code version 1.71.2 and the OS is Windows 11. The programming language is Julia, version 1.8.1.
It used to work, something changed, I do not know what.
Any hints on why this is happening?
I believe I found the solution. I created a function that adds a package to the environment. It has the package name as its single argument.
function load_package(package_name::String; used = true, report = true)
str_ui = used ? "Using " : "Importing "
report && println(str_ui * "package $package_name")
if used
eval(Meta.parse("using $package_name"))
end
eval(Meta.parse("import $package_name"))
end
It works fine. The package is loaded. For example,
load_package("DataFrames")
does (almost) the same thing as
using DataFrames
The only difference is that Visual Code does not seem to notice that the package was loaded when the package is loaded with the loaded_package function but it does notice it when the package is loaded with the using command.
So to fix the problem I had to load my packages with using and import comands. After doing that the tooltips became visible upon hovering over the function names.
The reason I was using the function load_packages was to load sets of packages whose names were in string vectors.

Create custom key binding for VSCode with args pre-defined

Summary
I am trying to create custom key bindings for Microsoft Visual Studio Code. When I invoke one of the VSCode commands, I would like to specify arguments, so that I am not prompted to select an item from a list.
Example Use Case: I want SHIFT+ALT+X to delete a Docker container image named alpine.
Take a look at the vscode-docker extension for VSCode, which has a registered command named vscode-docker.images.remove. Here is the command definition from GitHub. As you can see, it has a node and nodes argument. I assume that if I pass in a value of alpine for the node argument, that it will simply delete the alpine container image.
export async function removeImage(context: IActionContext, node?: ImageTreeItem, nodes?: ImageTreeItem[]): Promise<void> {
.............
}
The command is registered with VSCode in this file.
The documentation for VSCode doesn't describe how to discover VSCode commands or arguments for those commands, so I went into the source code for the vscode-docker extension to find out.
What I've Tried
I've tried using the following configuration in keybindings.json.
// Place your key bindings in this file to override the defaults
[
{
"key": "SHIFT+ALT+X",
"command":"vscode-docker.images.remove",
"args": {
"node": "alpine"
}
}
]
Expected Result
The selected Docker image is removed / deleted from the system.
Actual Result
I get a popup in the lower-right corner of the VSCode window saying:
This action is invalid for some selected items. These items will be ignored.
A Google search for "This action is invalid for some selected items" yields zero results. It seems I am the first person to come across this error and post about it online.
Question: How do I properly pass in args into the vscode-docker.images.remove command?
It arguments need to be TreeItems.
The command is connected to a button on a line in a TreeView.
Looking at the source of vscode-docker.images.remove passing in a string (name) does not work.
Or the function registerCommandAzUI from vscode-azureextensionui must do some name to TreeItem transform.

How to resolve ambiguous problem in cucumberjs?

I am using protractor-cucumber framework, When going to execute more than file with similar any single step in file both are going to skip and getting error ambiguous step definition.
feature 1
Given goto google world
When Send "Mike" to text box
Then verify result should be appear
feature 2
Given goto google world
When Send "Samp" to text box
Then verify result should be appear
config file
cucumberOpts = {
require: ['./Test_Scripts/*.js',
'./Support/hooks.js'],
format: 'json:Reports/results.json',
strict: true
}
suites = [
'/feature/*.feature'
]
How to execute both file without ambiguity?
Similar problem with ambiguous step definition was already elaborated here:
Multiple Step Definitions match error in Cucumber
Try using below code line in configurations.
specs:['./feature/*.feature'],

Is there auto-import functionality for typescript in Visual Studio Code?

Is there any shortcut that will allow me to auto generate my typescript imports? Like hitting ctrl+space next to the type name and having the import declaration placed at the top of the file. If not, what about intellisense for filling out the module reference path so that I wont have to do it manually? I would really love to use vscode but having to do manual imports for typescript is killing me.
There are rumors of making it support tsconfig.json (well, better than rumors). This will allow us to be able to use all files for our references.
Your feature would be to create an auto import of all commonly used 3rd party libs into the typings. Perhaps auto scan the files and create a list of ones to go gather. Wouldn't it be fine to just have a quick way to add several of these using tsd directly from Code (interactively)?
I believe the plugin called "TypeScript Importer" does exactly what You mean: https://marketplace.visualstudio.com/items?itemName=pmneo.tsimporter .
Automatically searches for TypeScript definitions in workspace files and provides all known symbols as completion item to allow code completion.
With it You can truly use Ctrl+Space to choose what exactly You would like to be imported.
You can find and install it from Ctrl+Shift+X menu or just by pasting ext install tsimporter in Quick Open menu opened with Ctrl+P.
I know a solution for Visual Studio (not Visual Studio Code, I'm using the 2015 Community edition, which is free), but it needs some setup and coding -- however, I find the results to be adequate.
Basically, in Visual Studio, when using the Web-Essentials extension, .ts files can be dragged into the active document to automatically generate a relative reference path comment:
/// <reference path="lib/foo.ts" />
With which of course we might as well wipe it, because it's an import statement we need, not a reference comment.
For this reason, I recently wrote the following command snippet for Visual Commander, but it should be easily adaptable to other use casese as well. With Visual Commander, your drag the needed imports into the open document, then run the following macro:
using EnvDTE;
using EnvDTE80;
using System.Text.RegularExpressions;
public class C : VisualCommanderExt.ICommand
{
// Called by Visual Commander extension.
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
TextDocument doc = (TextDocument)(DTE.ActiveDocument.Object("TextDocument"));
var p = doc.StartPoint.CreateEditPoint();
string s = p.GetText(doc.EndPoint);
p.ReplaceText(doc.EndPoint, this.ReplaceReferences(s), (int)vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers);
}
// Converts "reference" syntax to "ES6 import" syntax.
private string ReplaceReferences(string text)
{
string pattern = "\\/\\/\\/ *<reference *path *= *\"([^\"]*)(?:\\.ts)\" *\\/>";
var regex = new Regex(pattern);
var matches = Regex.Matches(text, pattern);
return Regex.Replace(text, pattern, "import {} from \"./$1\";");
}
}
When running this snippet, all reference comments in the active document will be replaced with import statements. The above example is converted to:
import {} from "./lib/foo";
This has just been released in version 1.18.
From the release notes:
Auto Import for JavaScript and TypeScript
Speed up your coding with auto imports for JavaScript and TypeScript. The suggestion list now includes all exported symbols in the current project. Just start typing:
If you choose one of the suggestion from another file or module, VS Code will automatically add an import for it. In this example, VS Code adds an import for Hercules to the top of the file:
Auto imports requires TypeScript 2.6+. You can disable auto imports by setting "typescript.autoImportSuggestions.enabled": false.
The files attributes in the tsconfig.json file allows you to set your reference imports in your whole project. It is supported with Visual Studio Code, but please note that if you're using a specific build chain (such as tsify/browserify) it might not work when compiling your project.