This is my first Q# program and i'm following this getting started link.https://learn.microsoft.com/en-us/quantum/quantum-writeaquantumprogram?view=qsharp-preview
Error is
The name 'BellTest' does not exist in the current context
but its defined in the Bell.cs
I followed the steps and when building its having errors. I'm not sure how to import the operations from .qs file to driver c# file as this error looks like it can't find that operation.
Any help is really appreciated
Here is the code
Driver.cs
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Quantum.Bell
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator())
{
// Try initial values
Result[] initials = new Result[] { Result.Zero, Result.One };
foreach (Result initial in initials)
{
var res = BellTest.Run(sim, 1000, initial).Result;
var (numZeros, numOnes) = res;
System.Console.WriteLine(
$"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4}");
}
}
System.Console.WriteLine("Press any key to continue...");
System.Console.ReadKey();
}
}
}
Bell.qs
namespace Quantum.Bell
{
open Microsoft.Quantum.Primitive;
open Microsoft.Quantum.Canon;
operation Set (desired:Result,q1:Qubit) : ()
{
body
{
let current = M(q1);
if (desired != current)
{
X(q1);
}
}
}
operation BellTest (count : Int, initial: Result) : (Int,Int)
{
body
{
mutable numOnes = 0;
using (qubits = Qubit[1])
{
for (test in 1..count)
{
Set (initial, qubits[0]);
let res = M (qubits[0]);
// Count the number of ones we saw:
if (res == One)
{
set numOnes = numOnes + 1;
}
}
Set(Zero, qubits[0]);
}
// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}
}
}
I also got the same error, but I was able to do it by pressing the F5 key.
Perhaps the Visual Studio editor is not yet fully support to the .qs file.
Namespace sharing does not seem to be working properly between .cs file and .qs file.
I was able to execute using your code in my development environment.
--
IDE: Visual Studio Community 2017 (Version 15.5.2)
Dev Kit: Microsoft Quantum Development Kit (0 and 1)
I engage the same problem in microsoft.quantum.development.kit/0.3.1811.203-preview version.
The BellTest operation cannot recognised by VSC Pic of VSCode
What I do is,
save all but keep VSCode open
go to directory and delete anything in bin/ obj/ by /bin/rm -rf bin obj
dotnet run
you go back to check VSCode, the BellTest recognised by VSC now.
Related
I want to add a Product Version to a Form.[assembly: AssemblyVersion("1.0.*")]
string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
This is the solution I found, and which will work. But the Version will be like "1.0.6262.26540".
Can I change the Rule or can I get the Publish Version which Visual Studio generates programmatically?
You could use ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(). However, this will only work if you are running a version of your program that was installed by the ClickOnce publisher installer (ApplicationDeployment.IsNetworkDeployed returns true).
When you start the compiled assembly directly (e.g. during debugging), you will get an InvalidDeploymentException when trying to access the CurrentDeployment property. To safeguard against this, you can use something like this:
string CurrentVersion
{
get
{
return ApplicationDeployment.IsNetworkDeployed
? ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString()
: "1.0.0.0"; // Fallback version string, or retrieve from assembly as in your question
}
}
If you are not using the ClickOnce Publish function to distribute your software I am not sure that you can expect to access the "Publish Version".
using System;
using System.IO;
using System.Linq;
namespace MyAssemblyInfoPatcher
{
internal class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
string path = args[0].ToString();
Console.WriteLine(string.Format("Current App version is set to: {0}", path));
string now_date = DateTime.Now.ToString("yyyy.MM.dd.HHmm");
if (File.Exists(path))
{
string _AssemblyVersion = string.Empty;
string _AssemblyFileVersion = string.Empty;
var lines = File.ReadLines(string.Format(path));
for (int i = 0; i < lines.Count(); i++)
{
if (lines.ElementAt(i).ToString().StartsWith("[assembly: AssemblyVersion"))
{
_AssemblyVersion = lines.ElementAt(i).ToString();
}
else if (lines.ElementAt(i).ToString().StartsWith("[assembly: AssemblyFileVersion"))
{
_AssemblyFileVersion = lines.ElementAt(i).ToString();
}
}
string _replace_assembly = File.ReadAllText(path);
if (_AssemblyVersion != string.Empty)
{
_replace_assembly = _replace_assembly.Replace(_AssemblyVersion, string.Format("[assembly: AssemblyVersion(\"{0}\")]", now_date));
}
if (_AssemblyFileVersion != string.Empty)
{
_replace_assembly = _replace_assembly.Replace(_AssemblyFileVersion, string.Format("[assembly: AssemblyFileVersion(\"{0}\")]", now_date));
}
File.WriteAllText(path, _replace_assembly);
}
}
}
}
}
Above the programs code, you can create a console application and in Project Properties > Build Events, add a "Pre-build event command line" like this: "D:\SomePath\MyAssemblyInfoPatcher.exe" "$(ProjectDir)Properties\AssemblyInfo.cs"
i just started to develop applications for AutoCAD 2016. I want to load my dLLs into a separate AppDomain, so that i don't have to restart ACAD all the time.
After a lot of research and trying i ended up with a pipeline solution
using System.Addin and System.Addin.Contract.
I use only interfaces and standardclasses for the Views Contract and Adapters like in this example here.
This is my addin containing one methode to write Hello into Acad's Editor and a second methode for drawing a line.
using System.AddIn;
using CADAddinView;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace CADAddIn
{
[AddIn("cadAddIn", Version = "1.0.0.0")]
public class CADAddIn : ICADAddinView
{
public void drawLine()
{
Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
using (DocumentLock acLckDoc = acDoc.LockDocument())
{
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
DBObject blkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
BlockTable acBlkTbl = blkTbl as BlockTable;
BlockTableRecord acBlkTblRec = (BlockTableRecord)acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
Polyline acPoly = new Polyline();
acPoly.SetDatabaseDefaults();
acPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
acPoly.AddVertexAt(0, new Point2d(100, 100), 0, 0, 0);
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);
acTrans.Commit();
}
}
}
public void sayHello()
{
Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("Hello");
}
}
}
this is my HostApplication:
using System.AddIn.Hosting;
using System.Windows.Forms;
using CADHostView;
using System;
using System.Collections.ObjectModel;
using Autodesk.AutoCAD.Runtime;
namespace CADHost
{
public class CADHost
{
[CommandMethod("sayHello")]
public static void sayHello()
{
string addInPath = Environment.CurrentDirectory + "\\Pipeline";
string[] warnings = AddInStore.Update(addInPath);
foreach (string warning in warnings)
{
MessageBox.Show(warning);
}
Collection<AddInToken> tokens = AddInStore.FindAddIns(typeof(ICADHostView), addInPath);
if (tokens.Count == 0)
{
MessageBox.Show("No AddIn found.");
}
else
{
AddInToken cadToken = tokens[0];
ICADHostView cadApp = cadToken.Activate<ICADHostView>(AddInSecurityLevel.Host);
cadApp.sayHello();
}
}
[CommandMethod("drawLine")]
public static void drawLine()
{
string addInPath = Environment.CurrentDirectory + "\\Pipeline";
string[] warnings = AddInStore.Update(addInPath);
foreach (string warning in warnings)
{
MessageBox.Show(warning);
}
Collection<AddInToken> tokens = AddInStore.FindAddIns(typeof(ICADHostView), addInPath);
if (tokens.Count == 0)
{
MessageBox.Show("No AddIn found.");
}
else
{
AddInToken cadToken = tokens[0];
ICADHostView cadApp = cadToken.Activate<ICADHostView>(AddInSecurityLevel.Host);
cadApp.drawLine();
}
}
}
}
Both of the two applications reference to three standard-Dlls from Acad:
accoremgd.dll, acdbmgd.dll, acmgd.dll.
In both projects these dlls have the option local copy false.
If i start then i get an Exception, where the programm cannot find the file "accoremgd.dll" and Acad crashes.
So i tried to set the Option local copy true only for the Addin.
Now it works for the "sayHello"-Methode.
but i get an invalide cast exception when acBlkTbl is initialised.
Would be great if someone has the last steps for me to make this work.
Also great would be a working example must not be made with the Addinsystem
i only want to make this work for not restarting acad all the time^^
Thank you for your help
matthias
I don't believe a separate AppDomain will work, when you call AutoCAD object types it will go to the main AppDomain and get messed up...
As just want to edit your code and don't restart, you'll be better with Edit & Continue feature (available since VC2013 on AutoCAD 2015, I believe).
This is not supported. AutoCAD is a very old and complex program and most of the AutoCAD API objects cannot be used in remote fashion.
Please read:
http://through-the-interface.typepad.com/through_the_interface/2008/09/tired-of-not-be.html
http://forums.autodesk.com/t5/net/netload-is-there-a-net-unload-command/td-p/2404002
https://www.theswamp.org/index.php?topic=38675.0
In the #3, you can see that the AutoCAD development team confirmed that there are some global variables which will prevent working this way.
I gave up my tries to solve this problem. My current "best" solution is to load dlls at the start of AutoCAD. At least i don't have to netload every dll.
If someone has a better solution feel free to tell me^^ Thanks to all that answered. matthias
I am trying to interface C# to R using RDotNet.
The following code is wants R to calculate the sum of two numbers and C# to get the result back and display it in the command window.
using System;
using RDotNet;
namespace rcon
{
class Program
{
static void Main(string[] args)
{
string dllPath = #"C:\Program Files\R\R-3.1.0\bin\i386";
REngine.SetDllDirectory(dllPath);
REngine.CreateInstance("RDotNet");
//REngine engine = REngine.GetInstanceFromID("RDotNet");
using (REngine engine = REngine.GetInstanceFromID("RDotNet"))
{
var x = engine.Evaluate("x <- 1 + 2");
Console.WriteLine(x);
}
}
}
}
but when I try to send the command to R and get back the calue in x I got an error:
"InvalidOperationException was unhandled"
"Operation is not valid due to the current state of the object."
If I explore the object "engine" I see that IsRunning=false.
Can this be the problem? And how can I fix this in order to be able to interface to R?
It looks like you have outdated version of R.NET.
From R.NET project documentation
R.NET 1.5.10 and subsequent versions include significant changes
notably to alleviate two stumbling blocks often dealt with by users:
paths to the R shared library, and preventing multiple engine
initializations.
You can update your R.NET using NuGet manager from Visual Studio. See the same documentation page for detals.
Here is code sample from the same documentatin page - note that initialization of REngine is significantly simpler now (as now Rengine looks at the Registry settings set up by the R installer):
REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it.
REngine engine = REngine.GetInstance();
// A somewhat contrived but customary Hello World:
CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" });
engine.SetSymbol("greetings", charVec);
engine.Evaluate("str(greetings)"); // print out in the console
string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray();
Console.WriteLine("R answered: '{0}'", a[0]);
Console.WriteLine("Press any key to exit the program");
Console.ReadKey();
engine.Dispose();
Unfortunately my knowledge of NANT stuff is very limited but embarked today on updating our build to run some code. We use cruisecontrol.
This works fine - however I need to process two folders so was trying to put common code into a traditional c# method.
<echo message="Ensure only 4 directories in the backup directory"/>
<script language="C#">
<code>
<![CDATA[
public static void ScriptMain(Project project)
{
string path = project.Properties["build.ReleasesShareLocation.BackupParent"];
string [] folders = System.IO.Directory.GetDirectories(path,"*", System.IO.SearchOption.TopDirectoryOnly);
System.Collections.ArrayList dirlist = new System.Collections.ArrayList();
foreach (string folder in folders)
{
dirlist.Add(new System.IO.DirectoryInfo(folder));
}
dirlist.Sort(new DirectoryInfoDateComparer());
dirlist.Reverse();
for (int i = 4; i < dirlist.Count; i++)
{
string foldername = ((System.IO.DirectoryInfo)dirlist[i]).Name;
try
{
((System.IO.DirectoryInfo)dirlist[i]).Delete(true);
project.Log(Level.Info, String.Format("Deleted folder {0}", foldername));
}
catch { project.Log(Level.Warning, String.Format("Unable to delete folder {0}", foldername)); }
}
}
internal class DirectoryInfoDateComparer : System.Collections.IComparer
{
public int Compare(object x, object y)
{
System.IO.DirectoryInfo di1 = (System.IO.DirectoryInfo)x;
System.IO.DirectoryInfo di2 = (System.IO.DirectoryInfo)y;
return di1.CreationTime.CompareTo(di2.CreationTime);
}
}
]]>
</code>
</script>
Rather than repeat all the code - I tried to add a static class with a method to do all the processing so that the main only passes the two paths. But in running the build on the server (is there a way for me to "compile" this locally??) it errored.
This is the code that errored - I'm not sure if I've missed a simple syntax error (I did try to copy and paste the code in visual studio to make sure the brackets and stuff matched up) or if there is a different way I need to do it in NANT build..
<echo message="Ensure only 4 directories in the backup directory"/>
<script language="C#">
<code>
<![CDATA[
public static void ScriptMain(Project project)
{
string path = project.Properties["build.ReleasesShareLocation.BackupParent"];
string path2 = project.Properties["build.DeltaScriptFileShareLocation.BackupParent"];
Processor.ProcessFolder(path);
Processor.ProcessFolder(path2);
}
internal static class Processor
{
public static void ProcessFolder(string path)
{
string [] folders = System.IO.Directory.GetDirectories(path,"*", System.IO.SearchOption.TopDirectoryOnly);
System.Collections.ArrayList dirlist = new System.Collections.ArrayList();
foreach (string folder in folders)
{
dirlist.Add(new System.IO.DirectoryInfo(folder));
}
dirlist.Sort(new DirectoryInfoDateComparer());
dirlist.Reverse();
for (int i = 4; i < dirlist.Count; i++)
{
string foldername = ((System.IO.DirectoryInfo)dirlist[i]).Name;
try
{
((System.IO.DirectoryInfo)dirlist[i]).Delete(true);
project.Log(Level.Info, String.Format("Deleted folder {0}", foldername));
}
catch { project.Log(Level.Warning, String.Format("Unable to delete folder {0}", foldername)); }
}
}
}
internal class DirectoryInfoDateComparer : System.Collections.IComparer
{
public int Compare(object x, object y)
{
System.IO.DirectoryInfo di1 = (System.IO.DirectoryInfo)x;
System.IO.DirectoryInfo di2 = (System.IO.DirectoryInfo)y;
return di1.CreationTime.CompareTo(di2.CreationTime);
}
}
]]>
</code>
</script>
Thanks for any assistance :)
Edit:
I went back through the CC logs and re-read the error message - this time understanding what it was trying to tell me. Turns out I needed to pass my new method the Project parameter. :)
Is there a way to be able to compile the code without having to run a build to find errors like this? I tried pasting it into Visual Studio but as I didn't have the Nant library referenced it wasn't highlighting the error effectively. Or is there something you can download and install on a dev machine to reference appropriate dlls?
Go to command prompt, navigate to the folder where you installed NANT, and type in your NANT build command manually, for example:
nant -f:MyBuildFile.build
That way you'll see the errors, and we can help further.
In re-reading the error logs I found within the wall of red text the answer.
Turns out I needed to pass my new method the Project parameter (as I was referring to Project properties).
So problem solved!
I'm just starting with a new product and I guess I don't understand the PATH variable. My documentation says to update the PATH like this which I do successfully in a little console application:
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff();
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
In the above project, I have a reference to HP.HPTRIM.SDK which exists at:
C:\Program Files\Hewlett-Packard\HP TRIM\HP.HPTRIM.SDK.dll
After the above ran successfully, I tried to permanently change the PATH by using Control Panel:System:Advanced:Environment Variables. I verified the above PATH by examining the registry at HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment. I see the following as the last entry in the PATH value:
;C:\Program Files\Hewlett-Packard\HP TRIM\
I thought this would permanently SET this at the end of the PATH but when I run the above console program with a few lines commented out I get the FileNotFoundException (see below). I am confused about how to get this in the PATH and not have to worry about it anymore.
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
//string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
//string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
//Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff(); // without setting the PATH this fails despite being in REGISTRY...
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
Only newly started processes that don't inherit their environment from their parent will have the updated PATH. You'll have to at least restart the Visual Studio hosting process, close and re-open your solution. To cover all possible corners, log out and log back in so that Windows Explorer (and thus Visual Studio) also start using the updated environment.