HI this is my code.
public static KieContainer createKieContainerForProject() {
KieServices ks = KieServices.Factory.get();
// Create a module model
KieModuleModel kieModuleModel = ks.newKieModuleModel();
// Base Model from the module model
KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel( "KBase" )
.setDefault( true )
.setEqualsBehavior( EqualityBehaviorOption.EQUALITY)
.setEventProcessingMode( EventProcessingOption.STREAM );
// Create session model for the Base Model
KieSessionModel ksessionModel = kieBaseModel.newKieSessionModel( "KSession" )
.setDefault( true )
.setType( KieSessionModel.KieSessionType.STATEFUL )
.setClockType( ClockTypeOption.get("realtime") );
// Create File System services
KieFileSystem kFileSystem = ks.newKieFileSystem();
File file = new File("src/main/resources/rules/Sample.drl");
Resource resource = ks.getResources().newFileSystemResource(file).setResourceType(ResourceType.DRL);
kFileSystem.write( resource );
KieBuilder kbuilder = ks.newKieBuilder( kFileSystem );
// kieModule is automatically deployed to KieRepository if successfully built.
kbuilder.buildAll();
if (kbuilder.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
throw new RuntimeException("Build time Errors: " + kbuilder.getResults().toString());
}
KieContainer kContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());
return kContainer;
}
}
it's dont work when I call the fucntion, and my rules no work too.
my rule is
rule "Sound the alarm in case temperature rises above threshold"
when
TemperatureThreshold( $max : max )
Number( doubleValue > $max ) from accumulate(
SensorReading( $temp : temperature ) over window:time( 10m ),
average( $temp ) )
then
// sound the alarm
end
when I run the program, He says it has error, mode not stream and the code dont work.
how do I put a program in stream mode?
REduce your code, and add -KieBase and KieSession creation:
KieServices ks = KieServices.Factory.get();
KieFileSystem kFileSystem = ks.newKieFileSystem();
FileInputStream fis = new FileInputStream( "...drl" );
kFileSystem.write("src/main/resources/somename.drl",
ks.getResources().newInputStreamResource( fis ) ); //XXX
KieBuilder kbuilder = ks.newKieBuilder( kFileSystem );
kbuilder.buildAll();
if (kbuilder.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
throw new RuntimeException("Build time Errors: " + kbuilder.getResults().toString());
}
KieContainer kContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());
KieBaseConfiguration config = ks.newKieBaseConfiguration();
config.setOption(EventProcessingOption.STREAM);
KieBase kieBase = kContainer.newKieBase( config );
KieSession kieSession = kieBase.newKieSession();
This should give you a session that's capable of running your rule. (
According to the docs, it's as follows:
KieBaseConfiguration config = KieServices.Factory.get().newKieBaseConfiguration();
config.setOption( EventProcessingOption.STREAM );
But it's probably worth taking a look at this Drools test for a working example.
Related
I have tried milo, but I found it hard to create the data object one by one.
Can milo just generate the corresponding codes by reading the xml files? And how?
Many Thanks!
yes you can
private void addCustomStructTypeVariable(UaFolderNode rootFolder) throws Exception {
NodeId dataTypeId = CustomStructType.TYPE_ID
.localOrThrow(getServer().getNamespaceTable());
NodeId binaryEncodingId = CustomStructType.BINARY_ENCODING_ID
.localOrThrow(getServer().getNamespaceTable());
UaVariableNode customStructTypeVariable = UaVariableNode.builder(getNodeContext())
.setNodeId(newNodeId("HelloWorld/CustomStructTypeVariable"))
.setAccessLevel(AccessLevel.READ_WRITE)
.setUserAccessLevel(AccessLevel.READ_WRITE)
.setBrowseName(newQualifiedName("CustomStructTypeVariable"))
.setDisplayName(LocalizedText.english("CustomStructTypeVariable"))
.setDataType(dataTypeId)
.setTypeDefinition(Identifiers.BaseDataVariableType)
.build();
CustomStructType value = new CustomStructType(
"foo",
uint(42),
true
);
ExtensionObject xo = ExtensionObject.encodeDefaultBinary(
getServer().getSerializationContext(),
value,
binaryEncodingId
);
customStructTypeVariable.setValue(new DataValue(new Variant(xo)));
getNodeManager().addNode(customStructTypeVariable);
customStructTypeVariable.addReference(new Reference(
customStructTypeVariable.getNodeId(),
Identifiers.Organizes,
rootFolder.getNodeId().expanded(),
false
));
}
1) My Environment:
. Windows 10 Pro (licensed) - 64 bits - 8GB Ram;
. AutoCAD (licensed) 2014/2015/2016/2017 64 bits (all HOTFIX and SERVICEPACK installed);
. Visual Studio 2010 Express Edition (for AutoCAD 2014);
. Visual Studio 2013 (for AutoCAD 2015/2016/2017);
. Antivirus : only Windows Defender.
2) Visual Studio 2013 Solution
nuGet packages:
System.Data.SQLite
SpatialiteSharp
Target: .NET 4.5
3) Database used for this test
. Database name : 'dbtest.sqlite', download here and save to c:\temp
. Database table : 'tb_test'
. Database table tb_test fields:
featureName : TEXT
geometry : POLYGON
4) Code Running on AutoCAD 2015 : OK
In Visual Lisp, I call dbQuery .NET method (file MyCommands.cs):
(setq result_query (dbQuery))
and will return a list:
[0] "FeatureName=first test area , MinX=101.23 , MinY=101.5 , MaxX=215.7 , MaxY=201.953 , Area=5532.771185"
[1] "FeatureName=second test area , MinX=100 , MinY=50 , MaxX=200 , MaxY=100 , Area=5000"
5) P R O B L E M :: Code running on Autocad 2016/2017 ::
Error : "Autodesk application has stopped working"
My plugin run ok on AutoCAD 2014 (.NET 4.0) and AutoCAD 2015 (.NET 4.5), but don't running on AutoCAD 2016/2017.
The code is the same, but changed only AcMgd/AcCoreMgd/AcDbMgd and Target DotNet Framework.
When debug my plugin, crash occurs on
connection.LoadExtension("mod_spatialite");
Then I receive a AutoCAD crash message window, saying:
Autodesk applicaton has stopped working
6) My AutoCAD 2017 plugin code
clique here to download VisualStudio 2013 "AutoCAD2017SpatialiteTest" Solution
MyCommands.cs code
// Test (System.Data.SQLite + SpatialiteSharp) in AutoCAD 2017 plugin
// Date: March, 7, 2017.
//
//==============================================================
using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using System.Data.SQLite;
using SpatialiteSharp;
using System.IO;
using System.Reflection;
// This line is not mandatory, but improves loading performances
[assembly: CommandClass ( typeof ( AutoCAD2017SpatialiteTest.MyCommands ) )]
namespace AutoCAD2017SpatialiteTest
{
// This class is instantiated by AutoCAD for each document when
// a command is called by the user the first time in the context
// of a given document. In other words, non static data in this class
// is implicitly per-document!
public class MyCommands
{
private static readonly object Lock = new object ();
private static bool _haveSetPath;
//*******************************************************************
// LispFunction is similar to CommandMethod but it creates a lisp
// callable function. Many return types are supported not just string
// or integer.
//
//
//
[LispFunction ( "dbQuery", "dbQuery" )]
public ResultBuffer dbQuery ( ResultBuffer args ) // This method can have any name
{
try
{
// Create Spatialite SQL Connection
//
string databaseName = #"c:\temp\dbtest.sqlite";
string connectString = #"Data Source=" + databaseName + ";Version=3;";
SQLiteConnection connection = new SQLiteConnection ( connectString );
/// Open the database and load in the Spatialite extension
connection.Open ();
/// Loads mod_spatialite.dll on the given connection
///
lock ( Lock )
{
//Need to work out where the file is and add it to the path so it can load all the other dlls too
if ( !_haveSetPath )
{
var spatialitePath = Path.Combine ( Path.GetDirectoryName ( Assembly.GetExecutingAssembly ().Location ), (Environment.Is64BitProcess ? "x64" : "x86"), "spatialite" );
Environment.SetEnvironmentVariable ( "PATH", spatialitePath + ";" + Environment.GetEnvironmentVariable ( "PATH" ) );
_haveSetPath = true;
}
}
connection.EnableExtensions ( true );
connection.LoadExtension ( "mod_spatialite" );
// Make some Spatialite function calls
string sql = "SELECT featureName, ST_MINX(geometry), ST_MINY(geometry), ST_MAXX(geometry), ST_MAXY(geometry), ST_AREA(geometry) FROM tb_test ";
double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0, area = 0.0;
string featureName = "";
string result_query = "";
// initialize resBuf list
//
ResultBuffer resBufCatch = new ResultBuffer ();
resBufCatch.Add ( new TypedValue ( (int)LispDataType.ListBegin ) );
// execute sql query
//
using ( SQLiteCommand command = new SQLiteCommand ( sql, connection ) )
{
using ( SQLiteDataReader reader = command.ExecuteReader () )
{
while ( reader.Read () )
{
featureName = reader.GetString ( 0 );
minX = reader.GetDouble ( 1 );
minY = reader.GetDouble ( 2 );
maxX = reader.GetDouble ( 3 );
maxY = reader.GetDouble ( 4 );
area = reader.GetDouble ( 5 );
// define string with fields values from 'tb_test'
//
result_query = String.Format ( "FeatureName={0} , MinX={1} , MinY={2} , MaxX={3} , MaxY={4} , Area={5}", featureName, minX.ToString (), minY.ToString (), maxX.ToString (), maxY.ToString (), area );
// add result_query to buffer
//
resBufCatch.Add ( new TypedValue ( (int)LispDataType.Text, result_query ) );
}
}
}
// finalize resBuf list
//
resBufCatch.Add ( new TypedValue ( (int)LispDataType.ListEnd ) );
// Close and clean up the database connection
//
connection.Close ();
connection.Dispose ();
// return result_query value to lisp function...
//
return resBufCatch;
}
catch ( System.Exception ex )
{
string exception_message = String.Format ( "Error : {0}", ex.Message );
ResultBuffer resBufCatch = new ResultBuffer ();
resBufCatch.Add ( new TypedValue ( (int)LispDataType.Text, exception_message ) );
return resBufCatch;
}
}
}
}
7) Question
Anybody help me run this AutoCAD2017 plugin?
Thank you very much.
Do you have an error report dialog like this one after the crash?
If yes, don't close the dialog and go to the folder C:\Users\\AppData\Local\Temp (%temp%). There must be a file named dumpdata.zip. In the archive, there is an xml file which can give you more details on the error and a .dmp file you can open in Visual Studio.
I am not good at English so i will try to be as clear as possible:
I have a project in Yii2 that has an advanced template, in the database i have a recursive table that represents a tree of categories and entries, you can imagine it as a folder tree that can have unlimited docs and folders (a folder inside another folder is possible), i have created the url in this format;
localhost://my-project/root-category/sub-cat-A/sub-cat-B/25-document
i need tho get the last section of the current Url because, the entire Url can have N levels before the entry that is located in the last section of the Url in the format below:
<id:\d+>-<slug:[A-Za-z0-9-_.]+>
But i don't know about any Url rule that could resolve this.
Appreciate your answers.
Thank you.
I solved it by myself and i am going to tell you how to solve or if any of you can improve this answer:
i am using the codemix/yii2-localeurls extension, i means that i had to extend the codemix\localeurls\UrlManager class and overwrite the parseRequest method like this:
public function parseRequest( $request ) {
$pathInfo = $request->getPathInfo();
$matches = 0;
$has_matches = preg_match( '%(bussiness-lines|lineas-de-negocio)\/(.)+\/%', $pathInfo, $matches );
if ( $has_matches ) {
/*
* GET THE LAST SECTION FROM THE URL
*/
$explode_patInfo = explode( '/', $pathInfo );
$tree_element = end( $explode_patInfo );
/*
* SEPARATES THE ID AND THE SLUG FROM THE URL
*/
$tree_element_explode = explode( '-', $tree_element );
$tree_element_id = reset( $tree_element_explode );
unset( $tree_element_explode[0] );
$tree_element_slug = implode( '-', $tree_element_explode );
/*
* RETURN THE CONTROLLER/ACTION AND ITS PARAMS TO PROCESS THE REQUEST
*/
if ( $tree_element !== false ) {
return [
'site/get-tree-element',
[
'id' => $tree_element_id,
'slug' => $tree_element_slug
]
];
}
}
//IF THE REQUEST DOES NOT CORRESPOND TO MY CUSTOM URL RULE, LETS THE PARENT DO THE JOB
return parent::parseRequest( $request );
}
I am sharing this hoping that can help any of you guys.
Peace.
I have a 20 minute FLV which streams just fine on server. Client would like to preserve user's locations between sessions so time() is saved to mySQL and passed back in as a FlashVar and is (if set) fed to seek() and to a text field for testing. Thing is the seek() works fine locally but on the server I always get a NetStream.Seek.InvalidTime error no matter what the seek() is set to. Docs are here; it's a dead simple function.
// EDIT Just added keyframes to FLV using http://www.buraks.com/flvmdi/ but this did not resolve issue
src = "videos/LivingProof.flv";
nc = new NetConnection();
nc.connect(null);
nets = new NetStream(nc);
mc_flv.attachVideo(nets);
//Attach your netstream audio to a movielcip:
snd.attachAudio(nets);
// create a sound object
my_snd = new Sound(snd);
// to adjust the volume
my_snd.setVolume(50);
nets.play(src);
if (starttime) {
var dest:Number = Math.floor(starttime);
nets.seek(dest);
this.test.text = 'target time = ' + dest;
}
nets.onStatus = function(infoObject:Object) {
if( infoObject.level == "status" && infoObject.code == "NetStream.Play.Stop" ) {
getURL("javascript:setTime('9999999999');", "_self");
nets.seek(0);
nets.pause();
mc_play.gotoAndStop(1);
trace('onStatus listener fired');
} else if (infoObject.code == "NetStream.Seek.InvalidTime") {
_root.test.text = "NetStream.Seek.InvalidTime";
nets.seek(infoObject.details);
}
_root.status.text = infoObject.code;
};
Anyone ever seen this before?
Try adding an if statement to your onStatus handler to check for the NetStream.Play.Start code and move the seek logic to that:
src = "videos/LivingProof.flv";
nc = new NetConnection();
nc.connect(null);
nets = new NetStream(nc);
mc_flv.attachVideo(nets);
//Attach your netstream audio to a movielcip:
snd.attachAudio(nets);
// create a sound object
my_snd = new Sound(snd);
// to adjust the volume
my_snd.setVolume(50);
nets.play(src);
nets.onStatus = function(infoObject:Object) {
if( infoObject.level == "status" && infoObject.code == "NetStream.Play.Stop" ) {
getURL("javascript:setTime('9999999999');", "_self");
nets.seek(0);
nets.pause();
mc_play.gotoAndStop(1);
trace('onStatus listener fired');
} else if (infoObject.code == "NetStream.Play.Start) {
if (starttime) {
var dest:Number = Math.floor(starttime);
nets.seek(dest);
this.test.text = 'target time = ' + dest;
}
} else if (infoObject.code == "NetStream.Seek.InvalidTime") {
_root.test.text = "NetStream.Seek.InvalidTime";
nets.seek(infoObject.details);
}
_root.status.text = infoObject.code;
};
Good day,
I have recently started playing with RingoJS along with Stick middleware and I am now stuck with sessions. I can't make it work.
main.js
var {Application} = require( "./_lib_/stick" ),
app = exports.app = Application();
app.configure( "mount" );
app.mount( "/", require( "./actions" ) );
if ( require.main === module ) {
require( "ringo/httpserver" ).main( module.directory );
}
actions.js
var {Application, helpers} = require( "./_lib_/stick" ),
Response = require( "ringo/jsgi/response" );
export( "app" );
var app = Application();
app.configure( "route", "render", "session" );
app.render.base = module.resolve( "templates" );
app.render.master = "page.html";
app.get("/session.htm", function( request ) {
//request.session.data.foo = "bar";
request.session.data.put("foo", "bar");
return Response.redirect( "session2.htm" );
});
app.get("/session2.htm", function( request ) {
var value = request.session;
return Response.html( "Session: " + value );
});
I've tested many combinaison but none of them worked as espected.
Most errors I get is about reading the data from the session. For example:
TypeError: Cannot read property "data" from undefined
Any tips?
"session" needs to come before "mount" in app.configure.
On the fourth line of main.js:
app.configure( "session", "mount" );
Then, remove "session" from the later call to app.configure since there's no point in running the middleware twice.