CATIA V5 C# how to get AxisSystem from Active Document - c#

I'm trying to update XAxis on Active CATIA document using C#. Anyone knows how to do that? somehowGetActiveAxisSysObject() is placeholder in pseudo code:
Array xMatrix = Array.CreateInstance(typeof(double), 3);
xMatrix.SetValue(5.0, 0);
xMatrix.SetValue(0.0, 1);
xMatrix.SetValue(0.0, 2);
MECMOD.AxisSystem targetAxisSys = **somehowGetActiveAxisSysObject();**
targetAxisSys.PutXAxis(xMatrix);
THANK YOU!

It's been a while since I worked with Catia in C# so the code below may not run properly.
First, I will assume you are working in a part document and that you have created an axis system from the menu: Insert->AxisSystems->AxisSystem (or named something similar). Next, I will also assume that you went into this items properties and renamed it to "Larry".
MECMOD.AxisSystems thisPartsAxisSysCollection = (MECMOD.AxisSystems)Part.AxisSystems;
MECMOD.AxisSystem oneAxisSys = thisPartsAxisSysCollection(1); //Index is name unknown
//or
MECMOD.AxisSystem oneAxisSys = thisPartsAxisSysCollection("Larry");
oneAxisSys.PutXAxis("your data");
If this is not what you are trying to do, but instead are trying to move the part's origin then you will need to access Part.OriginElements instead and use that object's PlaneXY, PlaneYZ, and PlaneZX. Unfortunately those are read only if I remember correctly.

Related

How to store placeholder value in xamarin.forms entry

I would like it so my users do not have to type in wifi credentials everytime they are filling out this form on my xamarin.forms app. I'm trying to figure a way where I can store the value that the user last inputted into an entry. Any suggestions?
I thought it could be as easy as storing it to a field if not null but i get an error stating "Only assignment, call, increment, decrement, await, and new obect expresions can be used as a statement"
At the top of my class I have field.
string WifiNamePlaceholder;
Then later in the page I have my entry
if (WifiNamePlaceholder == null)
{
WifiNamePlaceholder = "Enter in your wifi credentials"
}
wifi_name = new Xamarin.Forms.Entry
{
BackgroundColor = Color.White,
Placeholder = WifiNamePlaceholder,
Margin = new Thickness(0, 0, 10, 0),
FontFamily = Fonts.HelveticaNeueBold,
FontSize = labelSize
}
//Attempt to set new value here but get error
//Doing this in hopes it can save their entry for next time.
wifi_name.Placeholder == WifiNamePlaceholder;
If you have any suggestions it would be greatly appreciated! Thank you!
Use Xamarin.Essentials.Preferences or Xamarin.Essentials.SecureStorage. They're easy to use and don't require a bunch of overhead.
Xamarin.Essentials.Preferences.Get("Key", default(string));
Xamarin.Essentials.Preferences.Set("Key", "stringToSave")
Then just set your Entry.Text using the stored value.
See documentation: Xamarin.Essentials.Preferences
Entry.Placeholder is actually only useful for empty Entry's. It's just an informational text that is shown when Entry.Text is empty. So once the user has entered a value you would set Entry.Text the next time the page is shown.
You should really take some time to familiarize yourself with the way data binding works in Xamarin.Forms and MVVM in general.
You could save it in a local database on the user's phone and then fill the placeholder with the value you get from the database
try this link:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases
Try saving it in the database or in an xml file.
This way you can use it in your whole application.
if you are using api calls then try to save that password in the backend , so that you can fetch the password by calling that api whenever user open the app.
Otherwise just save the password in shared prefernces so that it ll remain save even if the app closed as explained in previous answers.

TensorflowSharp - TFException: Attempting to use uninitialized value

I'm attempting to import a model created in Keras/Tensorflow and use it for inference in a Unity project.
I have successfully imported the model and validated by printing names of input and output nodes in the graph. Though, when I try to get the output value from the runner, I get this exception.
TFException: Attempting to use uninitialized value action_W
[[Node: action_W/read = IdentityT=DT_FLOAT, _class=["loc:#action_W"], _device="/job:localhost/replica:0/task:0/cpu:0"]]
TensorFlow.TFStatus.CheckMaybeRaise (TensorFlow.TFStatus incomingStatus, System.Boolean last) (at <6ed6db22f8874deba74ffe3e566039be>:0)
TensorFlow.TFSession.Run (TensorFlow.TFOutput[] inputs, TensorFlow.TFTensor[] inputValues, TensorFlow.TFOutput[] outputs, TensorFlow.TFOperation[] targetOpers, TensorFlow.TFBuffer runMetadata, TensorFlow.TFBuffer runOptions, TensorFlow.TFStatus status) (at <6ed6db22f8874deba74ffe3e566039be>:0)
TensorFlow.TFSession+Runner.Run (TensorFlow.TFStatus status) (at <6ed6db22f8874deba74ffe3e566039be>:0)
RecordArbitraryData.ModelPredict (System.Single[,] input) (at Assets/Scripts/Spells/RecordArbitraryData.cs:230)
RecordArbitraryData.FixedUpdate () (at Assets/Scripts/Spells/RecordArbitraryData.cs:95)
Here are the two functions I use. InstantiateModel is called OnStart() in my unity script. And ModelPredict is called when the user passes an input to the script.
void InstantiateModel(){
string model_name = "simple_as_binary";
//Instantiate Graph
graphModel = Resources.Load (model_name) as TextAsset;
graph = new TFGraph ();
graph.Import (graphModel.bytes);
session = new TFSession (graph);
}
void ModelPredict(float[,] input){
using (graph) {
using (session) {
//Assign input tensors
var runner = session.GetRunner ();
runner.AddInput (graph [input_node_name] [0], input);
//Calculate and access output of graph
runner.Fetch (graph[output_node_name][0]);
Debug.Log ("Output node name: " + graph [output_node_name].Name);
float[,] recurrent_tensor = runner.Run () [0].GetValue () as float[,];
//var results = runner.Run();
//Debug.Log("Prediciton: " + results);
}
}
}
Any help appreciated - TensorflowSharp is very new to me.
I was able to figure out most of my problems. I'm currently at a point where my model is predicting in unity, but only predicting the first of four classes. My guess is it has something to do with the weights not getting initialized correctly from the checkpoint files? Edit: My values weren't being normalized before being passed to neural network.
Preface: Mozilla Firefox works best for displaying tensorboard; it took me a long time to realize that google chrome was causing my graph to be invisible (tensorboard is how I was able to figure out the nodes that needed to be used for input and output).
First Issue: I was renaming a .pb file into a .bytes file. This is incorrect because the model’s weights come from the checkpoint file, and are given to the nodes held in the .pb file. This was causing the uninitialized variables. These variables were used for training, which were removed after using the freeze_graph function.
Second Issue: I was using the file created called ‘checkpoint’, which was throwing an error. I then changed the name of the checkpoint to ‘test’ and used this in the freeze_graph function. When calling the checkpoints file, I was required to use ‘test.ckpt’. I assume this function knows to grab the three files automatically based on the .ckpt? ‘Test’ without ‘.ckpt’ did not work.
Third Issue: when using the freeze_graph function, I needed to export the .pb file in keras/tf with text=False. I tested True and False; True threw an error about “bad wiring”.
Fourth Issue: Tensorboard was very difficult to use without any organization. Using tf.name_scope helped a lot with not only visualization, but making sure I was using/referencing the correct nodes in TensorFlowSharp. In keras I found it helpful to separate the final Dense layer and Activation into their own scopes so I could find the correct output node. The rest of my network was put into a ‘body’ scope, and the sole input layer in ‘input’ scope. The name_scope function prepends ‘scopename/’ to the node name. I don't think it’s necessary, but it helped me.
Fifth Issue: The version of tensorflowsharp released as a unity package is not up to date. This caused an issue with a keras placeholder for ‘keras_training_phase’. In keras, you pass this along with an input like [0] + input. I tried to do the same by creating a new TFTensor(bool), but I was getting an error ‘inaccessible due to its protection level. This was an error with the implicit conversion between bool and TFTensor in my unity TensorFlowSharp version. To fix this I had to use a function found in this stackoverflow solution where the .bytes file is read in, the placeholder for keras_training_phase is found, and is swapped out for a bool constant set to false. This worked for me because my model was pretrained in python, so it may not be a great fix for someone that’s trying to train and test the model. A condition for removing this node with the freeze_graph function would really be useful.
Hope someone finds this useful!

Show DevExpress waitform dialog without designer

I'm trying to display a Loading Please Wait dialog form using devex controls and I can't seem to do it. (using winforms, c#)
I'm using an older version of devex - not the latest. I can't do
SplashScreenManager.ShowDefaultWaitForm()
I need to do this in code without the designer.
1.
I tried:
SplashScreenManager.ShowForm(typeof(WaitDialogForm));
It looks right when it loads, but then it throws an error:
Unable to cast object of type 'DevExpress.Utils.WaitDialogForm' to type 'DevExpress.XtraSplashForm.SplashFormBase'
I tried:
SplashScreenManager.ShowForm(typeof(WaitForm));
This shows an empty form thats too big with no image and no text
I tried:
WaitDialogForm mWaitDialog = new WaitDialogForm() {Visible = false};
mWaitDialog.Show();
The wait form doesn't look right. There are white spaces instead of the image.
I tried:
WaitDialogForm mWaitDialog = new WaitDialogForm() {Visible = false};
mWaitDialog.ShowDialog();
The code doesn't continue executing.
I saw examples of
SplashScreenManager.ShowForm(typeof(WaitForm1));
I don't know how to do this without designer.
Can somebody please assist? I thought I'm doing something simple, but I can't seem to figure it out!
Probably this help u ;)
using (new DevExpress.Utils.WaitDialogForm("Please wait"))
{
//Do your stuff here
}
I don't know if this is in your 13.2 version but from looking at documentation you should be using ShowWaitForm instead of just ShowForm.
SplashScreenManager ssm = new SplashScreenManager();
ssm.ActiveSplashFormTypeInfo = typeof(WaitForm1);
ssm.ShowWaitForm();
If that does not work then i would just try preparing a working solution in the designer and then extracting the code from the designer.cs file.
Found a specific documentation example here

C# code completion with NRefactory 5

I just found out about NRefactory 5 and I would guess, that it is the most suitable solution for my current problem. At the moment I'm developing a little C# scripting application for which I would like to provide code completion. Until recently I've done this using the "Roslyn" project from Microsoft. But as the latest update of this project requires .Net Framework 4.5 I can't use this any more as I would like the app to run under Win XP as well. So I have to switch to another technology here.
My problem is not the compilation stuff. This can be done, with some more effort, by .Net CodeDomProvider as well. The problem ist the code completion stuff. As far as I know, NRefactory 5 provides everything that is required to provide code completion (parser, type system etc.) but I just can't figure out how to use it. I took a look at SharpDevelop source code but they don't use NRefactory 5 for code completion there, they only use it as decompiler. As I couldn't find an example on how to use it for code completion in the net as well I thought that I might find some help here.
The situation is as follows. I have one single file containing the script code. Actually it is not even a file but a string which I get from the editor control (by the way: I'm using AvalonEdit for this. Great editor!) and some assemblies that needs to get referenced. So, no solution files, no project files etc. just one string of source code and the assemblies.
I've taken a look at the Demo that comes with NRefactory 5 and the article on code project and got up with something like this:
var unresolvedTypeSystem = syntaxTree.ToTypeSystem();
IProjectContent pc = new CSharpProjectContent();
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(unresolvedTypeSystem);
// Add referenced assemblies:
pc = pc.AddAssemblyReferences(new CecilLoader().LoadAssemblyFile(
System.Reflection.Assembly.GetAssembly(typeof(Object)).Location));
My problem is that I have no clue on how to go on. I'm not even sure if it is the right approach to accomplish my goal. How to use the CSharpCompletionEngine? What else is required? etc. You see there are many things that are very unclear at the moment and I hope you can bring some light into this.
Thank you all very much in advance!
I've just compiled and example project that does C# code completion with AvalonEdit and NRefactory.
It can be found on Github here.
Take a look at method ICSharpCode.NRefactory.CSharp.CodeCompletion.CreateEngine. You need to create an instance of CSharpCompletionEngine and pass in the correct document and the resolvers. I managed to get it working for CTRL+Space compltition scenario. However I am having troubles with references to types that are in other namespaces. It looks like CSharpTypeResolveContext does not take into account the using namespace statements - If I resolve the references with CSharpAstResolver, they are resolved OK, but I am unable to correctly use this resolver in code completition scenario...
UPDATE #1:
I've just managed to get the working by obtaining resolver from unresolved fail.
Here is the snippet:
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var resolver3 = unresolvedFile.GetResolver(cmp, loc); // get the resolver from unresolvedFile
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
Update #2:
Here is the complete method. It references classes from unit test projects, sou you would need to reference/copy them into your project:
public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
{
var doc = new ReadOnlyDocument(editorText);
var location = doc.GetLocation(offset);
string parsedText = editorText; // TODO: Why there are different values in test cases?
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze();
var unresolvedFile = syntaxTree.ToTypeSystem();
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
IProjectContent pctx = new CSharpProjectContent();
var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value};
pctx = pctx.AddAssemblyReferences(refs);
pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation();
var resolver3 = unresolvedFile.GetResolver(cmp, location);
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
var data = engine.GetCompletionData(offset, controlSpace: false);
return data;
}
}
Hope it helps,
Matra
NRefactory 5 is being used in SharpDevelop 5. The source code for SharpDevelop 5 is currently available in the newNR branch on github. I would take a look at the CSharpCompletionBinding class which has code to display a completion list window using information from NRefactory's CSharpCompletionEngine.

IronPython and Nodebox in C#

My plan:
I'm trying to setup my C# project to communicate with Nodebox to call a certain function which populates a graph and draws it in a new window.
Current situation: [fixed... see Update2]
I have already included all python-modules needed, but im still getting a
Library 'GL' not found
it seems that the pyglet module needs a reference to GL/gl.h, but can't find it due to IronPython behaviour.
Requirement:
The project needs to stay as small as possible without installing new packages. Thats why i have copied all my modules into the project-folder and would like to keep it that or a similar way.
My question:
Is there a certain workaround for my problem or a fix for the library-folder missmatch.
Have read some articles about Tao-Opengl and OpenTK but can't find a good solution.
Update1:
Updated my sourcecode with a small pyglet window-rendering example. Problem is in pyglet and referenced c-Objects. How do i include them in my c# project to be called? No idea so far... experimenting alittle now. Keeping you updated.
SampleCode C#:
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);
ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
SampleCode Python (test.py):
from nodebox.graphics import *
from nodebox.graphics.physics import Vector, Boid, Flock, Obstacle
flock = Flock(50, x=-50, y=-50, width=700, height=400)
flock.sight(80)
def draw(canvas):
canvas.clear()
flock.update(separation=0.4, cohesion=0.6, alignment=0.1, teleport=True)
for boid in flock:
push()
translate(boid.x, boid.y)
scale(0.5 + boid.depth)
rotate(boid.heading)
arrow(0, 0, 15)
pop()
canvas.size = 600, 300
def main(canvas):
canvas.run(draw)
Update2:
Line 139 [pyglet/lib.py] sys.platform is not win32... there was the error. Fixed it by just using the line:
from pyglet.gl.lib_wgl import link_GL, link_GLU, link_WGL
Now the following Error:
'module' object has no attribute '_getframe'
Kind of a pain to fix it. Updating with results...
Update3:
Fixed by adding following line right after first line in C#-Code:
setup.Options["Frames"] = true;
Current Problem:
No module named unicodedata, but in Python26/DLLs is only a *.pyd file`. So.. how do i implement it now?!
Update4:
Fixed by surfing: link text and adding unicodedata.py and '.pyd to C# Projectfolder.
Current Problem:
'libGL.so not found'... guys.. im almost giving up on nodebox for C#.. to be continued
Update5:
i gave up :/ workaround: c# communicating with nodebox over xml and filesystemwatchers. Not optimal, but case solved.
-X:Frames enables the frames option as runtime (it slows code down a little to have access to the Python frames all the time).
To enable frames when hosting you just need to do:
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(new Dictionary<string, object>() {
{ "Frames", true }
});
Instead of the null that you're passing now. That's just creating a new dictionary for the options dictionary w/ the contents "Frames" set to true. You can set other options in there as well and in general the -X:Name option is the same here as it is for the command line.

Categories

Resources