I'm trying to check for each movement in a different task and after checking if there was a collision, in some iterations it generates an Exception "A source matrix was not long or sufficient. Check the index and length, as well as the lower limits of the matrix."
If you try to run sequentially in a "for" the error does not occur, I need to run in parallel to increase performance.
In debugging tests I notice that the error always occurs when trying to run cd.DoWork()
private void btn_Tasks_Click(object sender, EventArgs e)
{
// The source of your work items, create a sequence of Task instances.
Task[] tasks = Enumerable.Range(0,tabelaPosicao.Count).Select(i =>
// Create task here.
Task.Run(() =>
{
VerifiCollision(i);
})
// No signalling, no anything.
).ToArray();
// Wait on all the tasks.
Task.WaitAll(tasks);
}
private void VerifiCollision(object x)
{
int xx = (int)x;
int AuxIncrMorsa = Convert.ToInt32(tabelaPosicao[xx].Posicao) * -1;
bRef_BaseMorsa.Transformation = new Translation(0, AuxIncrMorsa, 0);
CollisionDetection cd = new CollisionDetection(new List<Entity>() { bRef_BaseMorsa }, new List<Entity>() { bRef_Matriz }, model1.Blocks, true, CollisionDetection2D.collisionCheckType.OBWithSubdivisionTree, maxTrianglesNumForOctreeNode: 5);
{
if (cd != null)
{
try
{
cd.DoWork();
}
catch (Exception e)
{
e.StackTrace;
}
catch (AggregateException ae)
{
var messege = ae.Message;
}
}
model1.Entities.ClearSelection();
if (cd3.Result != null && cd3.Result.Count > 0)
{
tabelaPosicao[xx].Tuple = new Tuple<string, string>(cd3.Result[0].Item1.ParentName,
cd3.Result[0].Item2.ParentName);
}
}
}
Before applying the transformation you need to clone the entity.
You can have a look at the "WORKFLOW" topic of this article.
I solved it by cloning the Bloks and BlockReference, so each iteration with its transformation performed separately, so there was no possibility that the transformation of one iteration would interfere with another. Grateful for the help.
Related
This is related to is there any way to cancel a dart Future?
In my case, there are no HTTP, just expensive calculations. I have a table/list which I scroll through. As the elements become visible, I generate futures to show the calculation results. But if I (the end user) scroll quickly, some results will have "scrolled out of view" and will no longer required. This could be a large number, and would seriously delay the return of futures (results) that are to be usefully :-) displayed in currently visible elements. Can something be done about that? cheers, Steve
You could just set a flag which indicates to the delayed code (run from futures) that the result isn't needed anymore.
When the delayed code is called it just returns.
library cancel_future;
import 'dart:async' show Future, Timer;
import 'dart:math' show Random;
typedef void TaskFunction(Task task);
// Container for a task
class Task {
// an assigned task id
final id;
// data to process
int data;
// Indicate to the task function, that it should stop processing
bool isCanceled = false;
// The task function must set this flat to true when all work is done.
bool isFinished = false;
// The task function which processed the data and sets the result.
TaskFunction fn;
// The result set by the task function when it finished processing.
int result;
Task(this.id, this.data, this.fn);
// Start processing the task.
void execute() => fn(this);
}
final rnd = new Random();
void main(List<String> args) {
// create tasks
final tasks = new List<Task>.from(generate());
// start all tasks
tasks.forEach((t) => t.execute());
// after random delay cancel all unfinished tasks
new Future.delayed(new Duration(seconds: rnd.nextInt(10)), () {
tasks.forEach((t) {
if (!t.isFinished) {
t.isCanceled = true;
}
});
}).then((_) {
// check results
int done = 0;
int canceled = 0;
tasks.forEach((t) {
print(
'Task id: ${t.id}; isCanceled: ${t.isCanceled}; isFinished: ${t.isFinished}; data: ${t.data}; result: ${t.result}');
if (t.isFinished) {
done++;
}
if (t.isCanceled) {
canceled++;
}
});
print('Canceled: $canceled.');
print('Done: $done.');
});
}
// geneator for job 100 jobs
Iterable<Task> generate() sync* {
int i = 0;
while (i++ < 100) {
yield new Task(i, rnd.nextInt(100), calc);
}
}
// job function
void calc(Task t) {
// do a bit of work every 100ms to simulate longer processing
new Timer.periodic(new Duration(milliseconds: 100), (timer) {
var result = 0;
// check if jost was canceled and stop processing in case it was.
if (t.isCanceled) {
timer.cancel();
return;
}
// while not finished do a chunk of work
if (result < t.data) {
result++;
} else {
// finished - clean up and store result
t.isFinished = true;
t.result = result;
timer.cancel();
}
});
}
I think I've gotten the most simplest scenario built. I just want to pass it by everyone for a sanity check. Here's the idea:
GetErrorCodes.cfm does the following:
<cfscript>
response = new ErrorCodes().WhereXXX(); // ACF or Railo, doesn't matter
</cfscript>
ErrorCodes.cfc:
function WhereXXX() {
return new sproc().exec('app.GetErrorCodes'); // All my functions will do this instead of executing the sproc themselves.
}
sproc.cfc:
component {
function exec(procedure) {
local.result = {};
if (server.ColdFusion.productname == 'Railo') {
return new Railo().exec(arguments.procedure); // Has to be outside of sproc.cfc because ColdFusion throws a syntax error otherwise.
}
local.svc = new storedProc();
local.svc.setProcedure(arguments.procedure);
local.svc.addProcResult(name='qry');
try {
local.obj = local.svc.execute();
local.result.Prefix = local.obj.getPrefix();
local.result.qry = local.obj.getProcResultSets().qry;
} catch(any Exception) {
request.msg = Exception.Detail;
}
return local.result;
}
Railo.cfc:
component {
function exec(procedure) {
local.result = {};
try {
storedproc procedure=arguments.procedure result="local.result.Prefix" returncode="yes" {
procresult name="local.result.qry";
}
} catch(any Exception) {
request.msg = Exception.Message;
}
return local.result;
}
}
So I've been working on this all day, but tell me, is this a sane way to keep the source code the same if it's to be run on either a ColdFusion server or a Railo server?
Um... just use <cfstoredproc> instead of trying to use two different CFScript approaches that are mutually exclusive to each other of the CFML platforms.
I used this code in order to Read & Update a value in database which indicate Pageviews of a website.
void Session_Start(object sender, EventArgs e)
{
intPageView++;
Session.Add("Online", intPageView);
DataLayer.MainFunction.UpdateOnlineUser();
}
public static void UpdateOnlineUser()
{
try
{
int intCount = 0;
TaffyPetEntities db = new TaffyPetEntities();
T_Setting t_s = db.T_Setting.SingleOrDefault(i => i.ID == 1);
intCount = Convert.ToInt32(t_s.Page_counter);
intCount++;
t_s = new T_Setting();
t_s = db.T_Setting.First(i => i.ID == 1);
t_s.Page_counter = intCount;
db.SaveChanges();
}
catch (Exception err)
{
DataLayer.Error.RegisterError("MainFunction.cs", err.Message);
}
}
in local system every thing was good also running speed was good, but when website published and uploaded on the server every thing is changed. The problem is, at the first we haven't any data outout and when you clicked on each link on the website it takes too long to show another page.
to find out problem, i used Performance Analysis of VIsual Studio. at the result page of this analysis i found that this part of above code use 70% of total process:
T_Setting t_s = db.T_Setting.SingleOrDefault(i => i.ID == 1);
The questions is:
1. Is it correct syntax for fetching data in Entity FrameWork at the Data Layer (DAL) of a website?
2. Can i change this code with another method in order to reduce process speed?
Thanks.
Can we call a webservice from the scheduled periodic task class firstly, if yes,
Am trying to call a webservice method with parameters in scheduled periodic task agent class in windows phone 7.1. am getting a null reference exception while calling the method though am passing the expected values to the parameters for the webmethod.
am retrieving the id from the isolated storage.
the following is my code.
protected override void OnInvoke(ScheduledTask task)
{
if (task is PeriodicTask)
{
string Name = IName;
string Desc = IDesc;
updateinfo(Name, Desc);
}
}
public void updateinfo(string name, string desc)
{
AppSettings tmpSettings = Tr.AppSettings.Load();
id = tmpSettings.myString;
if (name == "" && desc == "")
{
name = "No Data";
desc = "No Data";
}
tservice.UpdateLogAsync(id, name,desc);
tservice.UpdateLogCompleted += new EventHandler<STservice.UpdateLogCompletedEventArgs>(t_UpdateLogCompleted);
}
Someone please help me resolve the above issue.
I've done this before without a problem. The one thing you need to make sure of is that you wait until your async read processes have completed before you call NotifyComplete();.
Here's an example from one of my apps. I had to remove much of the logic, but it should show you how the flow goes. This uses a slightly modified version of WebClient where I added a Timeout, but the principles are the same with the service that you're calling... Don't call NotifyComplete() until the end of t_UpdateLogCompleted
Here's the example code:
private void UpdateTiles(ShellTile appTile)
{
try
{
var wc = new WebClientWithTimeout(new Uri("URI Removed")) { Timeout = TimeSpan.FromSeconds(30) };
wc.DownloadAsyncCompleted += (src, e) =>
{
try
{
//process response
}
catch (Exception ex)
{
// Handle exception
}
finally
{
FinishUp();
}
};
wc.StartReadRequestAsync();
}
private void FinishUp()
{
#if DEBUG
try
{
ScheduledActionService.LaunchForTest(_taskName, TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("relaunching in 30 seconds");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
NotifyComplete();
}
Scriptable envGlobals;
InputStreamReader envReader = new InputStreamReader(getClass()
.getResourceAsStream("env.rhino.js"));
// InputStreamReader jqueryReader = new InputStreamReader(getClass()
// .getResourceAsStream("jquery-1.6.2.js"));
try {
Context cx = ContextFactory.getGlobal().enterContext();
try {
Global global = new Global();
global.init(cx);
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_7);
envGlobals = cx.initStandardObjects(global);
try {
cx.evaluateReader(envGlobals, envReader,
"env.rhino.js", 1, null);
// cx.evaluateReader(envGlobals, jqueryReader,
// "jquery-1.6.2.js", 1, null);
} catch (IOException e) {
}
} finally {
Context.exit();
}
} finally {
try {
envReader.close();
} catch (IOException e) {
}
}
/**
* the above code nicely evaluates env.rhino.js and provides a scope
* object (envGlobals). Then for each script I want to evaluate
* against env.rhino.js's global scope:
*/
Context scriptContext = ContextFactory.getGlobal().enterContext();
try {
// Create a global scope for the dependency we're processing
// and assign our prototype to the environment globals
// (env.js defined globals, the console globals etc.). This
// then allows us to (a) not have to re-establish commonly
// used globals i.e. we can re-use them in our loop; and (b)
// any global assignments are guaranteed to have come from
// the dependency itself (which is what we're trying to
// determine here).
Scriptable globalScope = scriptContext.newObject(envGlobals);
globalScope.setPrototype(envGlobals);
globalScope.setParentScope(null);
scriptContext.setOptimizationLevel(-1);
scriptContext.setLanguageVersion(Context.VERSION_1_7);
try {
//scriptContext.evaluateString(globalScope, "window.location='http://www.amazon.com'", "location", 1, null);
scriptContext.evaluateString(globalScope, tree.toSource(), "script document", 1, null);
System.out.println(scriptContext.toString());
// TODO: Do something useful with the globals.
} finally {
Context.exit();
}
....
Function f = (Function)fObj;
Object result = f.call(scriptContext, globalScope, globalScope, params);
throught this format,i always get the Exception info:
Exception in thread "main" java.lang.NullPointerException
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:849)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:426)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3178)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:162)
at org.sdc.food.parse.util.JavaScriptParser.getExecutableJS(JavaScriptParser.java:244)
at org.sdc.food.parse.util.JavaScriptParser.main(JavaScriptParser.java:349)
pls,someone help me!!
I have solved this. The reason is that the params passed to the called function is wrong.