Example #1
0
        /// <summary>
        /// Get a list of all hosts filtered by name
        /// </summary>
        /// <param name="hostName">name to filter on, do not use wildcards</param>
        /// <returns>List of all ESXi hosts</returns>
        public List <HostSystem> GetHostSystems(string hostFilterName)
        {
            List <HostSystem> hostSystems = new List <HostSystem>();

            try {
                Datacenter dataCenter = (Datacenter)vSphereClient.FindEntityView(typeof(Datacenter), null, null, null);
                Folder     folder     = (Folder)vSphereClient.GetView(dataCenter.HostFolder, null);
                foreach (VMware.Vim.ManagedObjectReference mObjR in folder.ChildEntity.Where(x => x.Type == "ComputeResource"))
                {
                    ComputeResource computeResource = (ComputeResource)vSphereClient.GetView(mObjR, null);
                    foreach (VMware.Vim.ManagedObjectReference hostRef in computeResource.Host)
                    {
                        HostSystem hostSystem = (HostSystem)vSphereClient.GetView(hostRef, null);
                        if (hostSystem.Name.Contains(hostFilterName) || hostSystem.Name.Equals(hostFilterName))
                        {
                            hostSystems.Add(hostSystem);
                        }
                    }
                }
            }
            catch {
                throw;
            }
            return(hostSystems);
        }
Example #2
0
        private void populateFromCyc()
        {
            TheBot.AddExcuteHandler("cycl", ExecCycQuery);
            TheBot.AddExcuteHandler("subl", EvalSubLHandler);

            int        id = 1;
            FileStream f  = HostSystem.Open("nodes.txt", FileMode.Create);
            TextWriter tw = new StreamWriter(f);

            foreach (var item in cycAccess.converseList("(ask-template '?R '(#$and (#$genls ?R #$Communicating)(#$not (#$isa ?R #$NonVerbalCommunicating))) #$EverythingPSC)"))
            {
                string text = item.ToString();
                string s    =
                    "<Shape ID='" + id++ +
                    "' NameU='Decision' Type='Shape' Master='0'><XForm><PinX>0.984251968503937</PinX><PinY>11.02362204724409</PinY><Width Unit='MM' F='Inh'>0.984251968503937</Width><Height Unit='MM' F='Inh'>0.5905511811023623</Height><LocPinX Unit='MM' F='Inh'>0.4921259842519685</LocPinX><LocPinY Unit='MM' F='Inh'>0.2952755905511811</LocPinY><Angle F='Inh'>0</Angle><FlipX F='Inh'>0</FlipX><FlipY F='Inh'>0</FlipY><ResizeMode F='Inh'>0</ResizeMode></XForm><Event><TheData F='No Formula'>0</TheData><TheText F='No Formula'>0</TheText><EventDblClick F='Inh'>0</EventDblClick><EventXFMod F='No Formula'>0</EventXFMod><EventDrop F='No Formula'>0</EventDrop></Event><vx:Event xmlns:vx='http://schemas.microsoft.com/visio/2006/extension'><vx:EventMultiDrop F='No Formula'>0</vx:EventMultiDrop></vx:Event><LayerMem><LayerMember>0</LayerMember></LayerMem><Text>" +
                    text + "</Text></Shape>";
                tw.WriteLine(s);
            }
            tw.Close();
            try
            {
                f.Close();
            }
            catch (Exception)
            {
            }
            AltBot.writeDebugLine("!NonVerbalCommunicating = " + id);
            //cycAccess.setCyclist("CycAdministrator");
        }
Example #3
0
        /// <summary>
        /// Sets a new powerstate via the VMware toold and the OS
        /// </summary>
        /// <param name="guestNameFilter">The guest to power on or off via OS</param>
        /// <param name="powerState">True to power on, false to power off</param>
        public void SetVMGuestOSPowerState(String guestNameFilter, bool powerState)
        {
            var filter = new NameValueCollection();

            filter.Add("name", guestNameFilter);
            VirtualMachine vm = null;

            try {
                vm = (VirtualMachine)vSphereClient.FindEntityView(typeof(VirtualMachine), null, filter, null);
            }
            catch (Exception e) {
                lock (m_lock) {
                    WriteLogText(logWriter, e.Message.ToString());
                }
            }
            try {
                if (powerState)
                {
                    HostSystem host = GetHostSystems().FirstOrDefault();
                    if (host != null)
                    {
                        vm.PowerOnVM_Task(host.MoRef);
                    }
                }
                else
                {
                    vm.ShutdownGuest();
                }
            }
            catch (Exception e) {
                lock (m_lock) {
                    WriteLogText(logWriter, e.Message.ToString());
                }
            }
        }
        protected override void initCalculations()
        {
            LayoutSystem.ComputeParams param = new LayoutSystem.ComputeParams();
            float useless = 0;

            param.StepLength = stepLength;
            HostSystem.CalcDescentVector(HostSystem.CurrentStateBuffer, param);             // calc desc vector and energies
            HostSystem.CalcTotalEnergyAndDotProduct(HostSystem.CurrentStateBuffer, HostSystem.CurrentStateBuffer,
                                                    HostSystem.EnergyBuffer, param, out energy, out useless, out checkSum);
        }
        /// <summary>
        /// Loads any custom tag handlers found in the dll referenced in the argument
        /// </summary>
        /// <param name="pathToDLL">the path to the dll containing the custom tag handling code</param>
        static public void loadCustomTagHandlers(string pathToDLL)
        {
            // return;
            string hostSystemResolveToExistingPath = HostSystem.ResolveToExistingPath(pathToDLL);

            if (hostSystemResolveToExistingPath == null)
            {
                throw new FileNotFoundException(pathToDLL);
            }
            Assembly tagDLL      = Assembly.LoadFrom(hostSystemResolveToExistingPath);
            var      tagDLLTypes = tagDLL.GetTypes();

            for (int i = 0; i < tagDLLTypes.Length; i++)
            {
                Type type = tagDLLTypes[i];
                try
                {
                    var typeCustomAttributes = type.GetCustomAttributes(false);
                    if (typeCustomAttributes.Length == 0 && typeof(AIMLTagHandler).IsAssignableFrom(type) &&
                        !type.IsAbstract && !type.IsInterface)
                    {
                        try
                        {
                            AddTagHandler(type);
                        }
                        catch (Exception e)
                        {
                            AltBot.writeException(e);
                        }
                        continue;
                    }
                    for (int j = 0; j < typeCustomAttributes.Length; j++)
                    {
                        if (typeCustomAttributes[j] is CustomTagAttribute)
                        {
                            // We've found a custom tag handling class
                            // so store the assembly and store it away in the Dictionary<,> as a TagHandler class for
                            // later usage
                            try
                            {
                                AddTagHandler(type);
                            }
                            catch (Exception e)
                            {
                                AltBot.writeException(e);
                            }
                        }
                    }
                }
                catch (Exception ee)
                {
                    AltBot.writeException(ee);
                }
            }
        }
Example #6
0
        public static string MakeLex(string lexfileStem)
        {
            string infile  = lexfileStem + ".brill";
            string outfile = lexfileStem + ".dat";

            if (!HostSystem.FileExists(outfile))
            {
                MakeLex(infile, outfile);
            }
            return(outfile);
        }
Example #7
0
        /// <summary>
        /// Fetches all datastores from a VMWare ESXi host
        /// </summary>
        /// <param name="hostName">The host we want to fetch from</param>
        /// <returns>List of all the datastores</returns>
        public List <Datastore> GetHostDatastores(string hostName)
        {
            List <Datastore> datastores = new List <Datastore>();
            HostSystem       theHost    = this.GetHostSystems().Where(host => host.Name == hostName).FirstOrDefault();

            foreach (VMware.Vim.ManagedObjectReference mob in theHost.Datastore)
            {
                Datastore currentDatastore = (Datastore)vSphereClient.GetView(mob, null);
                datastores.Add(currentDatastore);
            }
            return(datastores);
        }
Example #8
0
        private string GetUserDir0(string key)
        {
            string userDir  = HostSystem.Combine(PathToUsersDir, key);
            string luserDir = HostSystem.ToRelativePath(userDir, RuntimeDirectory);

            if (HostSystem.DirExists(luserDir))
            {
                return(luserDir);
            }
            string k1 = key.Replace("_", " ");

            foreach (string fsn in HostSystem.GetDirectories(PathToUsersDir))
            {
                string s = fsn;
                if (fsn.StartsWith(PathToUsersDir))
                {
                    s = s.Substring(PathToUsersDir.Length);
                }
                if (s.StartsWith("/"))
                {
                    s = s.Substring(1);
                }
                if (s.StartsWith("\\"))
                {
                    s = s.Substring(1);
                }
                string s1 = "^" + s.Replace(".", "\\.").Replace("~", ".*").
                            Replace("~", ".*").Replace("_", "\\b").
                            Replace("\\b\\b", "\\b") + "$";

                Regex regex;
                try
                {
                    regex = new Regex(s1);
                }
                catch (Exception e)
                {
                    writeToLog("new Regex '" + s1 + "' " + e);
                    continue;
                }
                if (regex.IsMatch(k1))
                {
                    luserDir = HostSystem.ToRelativePath(fsn, RuntimeDirectory);
                    if (HostSystem.DirExists(luserDir))
                    {
                        return(luserDir);
                    }
                    return(fsn);
                }
            }
            return(luserDir);
        }
Example #9
0
        public string GetPathSetting(string namePath, string defaultVal)
        {
            string retP = SettingPath0(namePath, defaultVal);

            if (retP == null)
            {
                return(defaultVal);
            }
            string ret  = HostSystem.ToRelativePath(retP, RuntimeDirectory);
            string retA = HostSystem.GetAbsolutePath(retP);

            return(ret);
        }
Example #10
0
        /// <summary>
        /// This function performs the first iteration of calculations
        /// </summary>
        protected override void initCalculations()
        {
            LayoutSystem.ComputeParams param = new LayoutSystem.ComputeParams();
            param.StepLength = stepLength;
            HostSystem.CalcDescentVector(HostSystem.CurrentStateBuffer, param);             // calc desc vector and energies
            HostSystem.CalcTotalEnergyAndDotProduct(HostSystem.CurrentStateBuffer, HostSystem.CurrentStateBuffer,
                                                    HostSystem.EnergyBuffer, param, out energy, out pGradE, out checkSum);
            initialEnergy    = energy;
            deltaEnergyBound = energy;


//			energyEstim = estimEnergy();
        }
Example #11
0
        public string GetUserDir(string key)
        {
            string sk = "";

            foreach (char s in key)
            {
                if (IsOkForNameChar(s))
                {
                    sk += s;
                }
            }
            lock (ListUserDirs)
                return(UserOper("GetUserDir " + key, () => HostSystem.Slashify(GetUserDir0(key)), QuietLogger));
        }
 internal static void InitTagHandlers()
 {
     CustomTags = new Dictionary <string, TagHandler>();
     //this.GraphMaster = new GraphMaster();
     //this.HeardSelfSayGraph = new GraphMaster();
     if (HostSystem.FileExists("AIMLbot.dll"))
     {
         loadCustomTagHandlers("AIMLbot.dll");
     }
     if (HostSystem.FileExists("AIMLbot.exe"))
     {
         loadCustomTagHandlers("AIMLbot.exe");
     }
 }
Example #13
0
        /// <summary>
        /// Fetches a specified datastore from a VMWare ESXi host
        /// </summary>
        /// <param name="hostName">The host we want to fetch from</param>
        /// <param name="dataStoreName">The datastore we want to fetch of type: [datastore] /folder/file</param>
        /// <returns>The datastore we want</returns>
        public Datastore GetHostDatastore(string hostName, string dataStoreName)
        {
            HostSystem theHost = this.GetHostSystems().Where(host => host.Name == hostName).FirstOrDefault();

            foreach (VMware.Vim.ManagedObjectReference mob in theHost.Datastore)
            {
                Datastore currentDatastore = (Datastore)vSphereClient.GetView(mob, null);
                if (currentDatastore.Name.ToLower() == dataStoreName.ToLower())
                {
                    return(currentDatastore);
                }
            }
            return(null);
        }
Example #14
0
        private string ToPath(string path, out string prefix)
        {
            if (path == null)
            {
                prefix = null;
                return(null);
            }
            string realPath = HostSystem.FirstExisting(path, RuntimeDirectories, out prefix);

            if (realPath != null)
            {
                return(realPath);
            }
            return(HostSystem.Combine(prefix, path));
        }
Example #15
0
        /// <summary>
        /// Check if a host has a access right assigned for the current session
        /// NB! Function fails with: The operation is not supported on the object
        /// </summary>
        /// <param name="host">HostSystem</param>
        /// <param name="privilegeID">new string[] { "VirtualMachine.Interact.ConsoleInteract" }</param>
        /// <returns>Success state</returns>
        public bool CheckAccessRightOnHost(HostSystem host, string[] privilegeID)
        {
            bool status = true;
            AuthorizationManager authManager = GetAuthorizationManager();

            try {
                foreach (bool x in authManager.HasPrivilegeOnEntity(host.MoRef, thisSession.Key, privilegeID).ToList())
                {
                    status = (x == false ? false : status);
                }
            }
            catch {
                throw;
            }
            return(status);
        }
Example #16
0
        internal long LoadFileByLines0(string filename, WordExpander expandWithWordNet)
        {
            checkDbLock();
            long   totals = 0;
            string line;
            long   linecount = 0;

            if (HostSystem.FileExists(filename))
            {
                string absoluteFileName                   = HostSystem.GetAbsolutePath(filename);
                System.IO.TextReader       tr             = new StreamReader(absoluteFileName);
                Dictionary <ulong, string> contentIdPairs = new Dictionary <ulong, string>();

                while ((linecount < 80000) && ((line = tr.ReadLine()) != null))
                {
                    linecount++;
                    if (linecount % 1000 == 0)
                    {
                        // batch a 1000
                        writeToLog("Lucene learn {0}", linecount);
                        int numIndexedb = Index(contentIdPairs, expandWithWordNet);
                        writeToLog("Indexed {0} lines.", numIndexedb);
                        totals += linecount;

                        contentIdPairs = new Dictionary <ulong, string>();
                    }
                    line = line.Trim();
                    if (line.Length != 0 && line[0] != '#')
                    {
                        contentIdPairs.Add(IncDocId(), line);
                    }
                }
                tr.Close();
                // Indexing:
                int numIndexed = Index(contentIdPairs, expandWithWordNet);
                writeToLog("Indexed {0} lines.", numIndexed);


                writeToLog("Last Line Mlearn {0}", linecount);
            }
            else
            {
                writeToLog(" LoadFileByLines cannot find file '{0}'", filename);
            }
            return(totals);
        }
        internal int Connect()
        {
            int result = 0;

            // make session ID equal to latest query id added, mostly for progress tracking purposes
            SessionID = Queries[Queries.Count - 1].Id;

            if (this.Error.Length > 0) // don't run if we experienced errors before
            {
                Completed = true; result = -1; return(result);
            }

            if (!Connected)
            {
                Error = ""; // clear session error details
                // try seeing if port is accessible
                Error = CNetwork.CheckPortStatus(Server.IP, HviClient.DefaultPort);

                if (Error.Length == 0)
                {
                    HVClient = new HviClient();
                    if (Server.UserName == Environment.UserDomainName + "\\" + Environment.UserName)
                    {
                        HVSession = HVClient.LoginWithCurrentCredentials(this);
                    }
                    else
                    {
                        HVSession = HVClient.Login(this);
                    }                                          // otherwise use username and password
                    if (HVSession != null)
                    {
                        if (HVSession.LoginTime != null)
                        {
                            Server.Name = HVClient.Name; Server.Version = HVSession.Version + " (" + HVSession.Build + ")"; Connected = true; result = 0;
                        }
                    }
                    else
                    {
                        Completed = true; result = -1;
                    }
                }
            }
            return(result);
        }
Example #18
0
        protected override void update(int userCommand)
        {
            var graphSys = HostSystem.Environment.GetService <GraphSystem>();

            LayoutSystem.ComputeParams param = new LayoutSystem.ComputeParams();

            // manual step change:
            if (userCommand > 0)
            {
                stepLength = increaseStep(stepLength);
            }
            if (userCommand < 0)
            {
                stepLength = decreaseStep(stepLength);
            }

            if (HostSystem.CurrentStateBuffer != null)
            {
                param.StepLength = stepLength;

                if (HostSystem.RunPause == LayoutSystem.State.RUN)
                {
                    for (int i = 0; i < graphSys.Config.IterationsPerFrame; ++i)
                    {
                        HostSystem.CalcDescentVector(HostSystem.CurrentStateBuffer, param);                             // calculate current descent vectors

                        HostSystem.MoveVertices(HostSystem.CurrentStateBuffer,
                                                HostSystem.NextStateBuffer, param);             // move vertices in the descent direction

                        // swap buffers: --------------------------------------------------------------------
                        HostSystem.SwapBuffers();
                        ++numIterations;
                    }
                }
            }

            var debStr = HostSystem.Environment.GetService <DebugStrings>();

//			debStr.Add(Color.Black, "FIXED MODE");
//			debStr.Add(Color.Aqua, "Step factor  = " + stepLength);
//			debStr.Add(Color.Aqua, "Iteration      = " + numIterations);
        }
Example #19
0
 public static void MakeLex(string infile, string outfile)
 {
     try
     {
         Hashtable hash = new Hashtable();
         //int count = 0;
         StreamReader reader = HostSystem.GetStreamReader(infile);
         string       line;
         do
         {
             line = reader.ReadLine();
             if (line == null)
             {
                 break;
             }
             int index = line.IndexOf(" ");
             //Console.WriteLine("line: " + line + " index: " + index);
             string word = line.Substring(0, index).Trim();
             string tags = line.Substring(index).Trim();
             //Console.WriteLine("word: " + word + ", tags: " + tags);
             //count++;
             if (hash[word] == null)
             {
                 hash.Add(word, tags);
             }
             // ReSharper disable ConditionIsAlwaysTrueOrFalse
         } while (line != null);
         // ReSharper restore ConditionIsAlwaysTrueOrFalse
         reader.Close();
         Stream     file      = HostSystem.Open(outfile, FileMode.Create);
         IFormatter formatter = (IFormatter) new BinaryFormatter();
         // Serialize the object hashto stream
         formatter.Serialize(file, hash);
         file.Close();
     }
     catch (Exception e2)
     {
         DLRConsole.DebugWriteLine("Error: " + e2);
     }
 }
Example #20
0
 public void SuggestPath(string path)
 {
     if (NullOrStar(path))
     {
         return;
     }
     if (NullOrStar(CurrentlyLoadingFrom))
     {
         CurrentlyLoadingFrom = path;
     }
     if (NullOrStar(CurrentFilename))
     {
         CurrentFilename = path;
     }
     else
     {
         if (HostSystem.FileExists(path))
         {
             CurrentFilename = path;
         }
     }
 }
Example #21
0
        internal int LoadUsers0(string key, string from)
        {
            Regex  regex = new Regex(key, RegexOptions.IgnoreCase);
            int    users = 0;
            string k1    = key.Replace("_", " ");

            foreach (string fsn in HostSystem.GetDirectories(from))
            {
                var files = HostSystem.GetFiles(fsn, "*.xml");
                if (files == null || files.Length == 0)
                {
                    continue;
                }

                string s = fsn;
                if (fsn.StartsWith(from))
                {
                    s = s.Substring(from.Length);
                }
                if (s.StartsWith("/"))
                {
                    s = s.Substring(1);
                }
                if (s.StartsWith("\\"))
                {
                    s = s.Substring(1);
                }
                if (regex.IsMatch(s))
                {
                    string     name = s.Replace("_", " ").Replace("~", " ").Replace("  ", " ");
                    MasterUser user = (MasterUser)FindOrCreateUser(name);
                    user.UserDirectory = user.UserDirectory ?? fsn;
                    users++;
                }
            }
            return(users);
        }
Example #22
0
 protected override Unifiable ProcessChangeU()
 {
     if (CheckNode("dbload"))
     {
         // Simply push the filled in tag contents onto the stack
         try
         {
             // Find and Replace
             Unifiable templateNodeInnerValue = Recurse();
             string    path = (string)templateNodeInnerValue;
             path = path.Trim();
             string[] files = HostSystem.GetFiles(path);
             if (files != null && files.Length > 0)
             {
                 AddSideEffect("DBLOAD " + path, () =>
                 {
                     foreach (string file in files)
                     {
                         TargetBot.LuceneIndexer.LoadDocuments(file,
                                                               templateNode);
                     }
                 });
                 return("@echo DBLOAD " + path);
             }
             else
             {
                 Console.WriteLine("WARNING: dbload cannot find file :{0}", path);
             }
         }
         catch (Exception e)
         {
             writeToLog("ERROR: {0}", e);
         }
     }
     return(Unifiable.Empty);
 }
Example #23
0
        static void initNatLangDb()
        {
            if (lexHash != null)
            {
                if (lexHash.Contains("OK"))
                {
                    var typef = lexHash["OK"];
                }
                return; // singleton pattern
            }

            try
            {
                StringCachePOSWORD["hello"]  =
                    StringCachePOSWORD["hi"] = " # Interjection-SpeechPart # Hi-TheWord # Hello-TheWord ";
                lexHash = new Hashtable();

                string outfile = MakeLex(LEXICON);
                Stream file    = HostSystem.Open(outfile, FileMode.Open);
                try
                {
                    var formatter = (IFormatter) new BinaryFormatter();
                    lexHash = formatter.Deserialize(file) as Hashtable;
                }
                finally
                {
                    file.Close();
                }
                DLRConsole.DebugWriteLine("Initialized lexHash from serialized data.");
            }
            catch (Exception exception)
            {
                DLRConsole.DebugWriteLine("ERROR: " + exception);
            }
            NLPLibTest();
        }
Example #24
0
 public EsxHostSystem(VSphereManagedObject vSphereManagedObject, string hostName)
     : base(vSphereManagedObject)
 {
     _hostSystem = GetHostSystem(hostName);
 }
Example #25
0
        /// <summary>
        /// This is the main function to call at each iteration
        /// </summary>
        /// <param name="userCommand"></param>
        protected override void update(int userCommand)
        {
            var graphSys = HostSystem.Environment.GetService <GraphSystem>();

            LayoutSystem.ComputeParams param = new LayoutSystem.ComputeParams();

            bool  cond1           = false;
            bool  cond2           = false;
            float energyThreshold = (float)HostSystem.ParticleCount / 10000.0f;
//			float energyThreshold = (float)HostSystem.ParticleCount / 5000000.0f;
            float chosenStepLength = stepLength;

            // Wolfe constants:
            //		float C1 = 0.1f;
            //		float C2 = 0.99f;

            //float C1 = 0.3f;
            //float C2 = 0.99f;
            var   graphSystem = HostSystem.Environment.GetService <GraphSystem>();
            float C1          = graphSystem.Config.C1;
            float C2          = graphSystem.Config.C2;

            // Algorithm outline:
            //
            //  1. Calc descent vector pk
            //  2. calc pk * grad(Ek)
            //  3. calc Ek
            //  4. try move with some step factor
            //  5. calc pk * grad(Ek+1)
            //  6. calc Ek+1
            //  7. check Wolfe conditions
            //  8. if both are OK GOTO 11
            //  9. modify step factor
            // 10. GOTO 4
            // 11. swap try buffer with current buffer
            // 12. GOTO 1
            //


            // manual step change:
            if (userCommand > 0)
            {
                stepLength += 0.01f;
            }
            if (userCommand < 0)
            {
                stepLength -= 0.01f;
            }


            if (HostSystem.CurrentStateBuffer != null)
            {
                if (HostSystem.RunPause == LayoutSystem.State.RUN)
                {
                    //		StreamWriter sw = File.AppendText( "stepsize.csv" );
                    for (int i = 0; i < graphSys.Config.IterationsPerFrame; ++i)
                    {
                        float Ek  = energy;                             // current energy
                        float Ek1 = 0;                                  // next energy

                        float pkGradEk  = 1;                            // current dot prodct
                        float pkGradEk1 = 1;                            // next dot prodct

                        cond1 = false;
                        cond2 = false;

                        int tries = 0;

                        param.StepLength = stepLength;
                        if (!FixedStep)
                        {
                            HostSystem.CalcTotalEnergyAndDotProduct(
                                HostSystem.CurrentStateBuffer,
                                HostSystem.CurrentStateBuffer,
                                HostSystem.EnergyBuffer,
                                param, out Ek, out pkGradEk, out checkSum);
                        }

                        while (!(cond1 && cond2))
                        {
                            if (FixedStep)
                            {
                                cond1 = true;
                                cond2 = true;
                            }

                            param.StepLength = stepLength;

                            HostSystem.MoveVertices(
                                HostSystem.CurrentStateBuffer,
                                HostSystem.NextStateBuffer,
                                param);                                 // move vertices in descent direction

                            HostSystem.CalcDescentVector(
                                HostSystem.NextStateBuffer,
                                param);                                 // calculate energies and next descent vectors

                            if (!FixedStep)
                            {
                                HostSystem.CalcTotalEnergyAndDotProduct(
                                    HostSystem.CurrentStateBuffer,
                                    HostSystem.NextStateBuffer,
                                    HostSystem.EnergyBuffer,
                                    param, out Ek1, out pkGradEk1, out checkSum);


                                // check Wolfe conditions:
                                cond1 = (Ek1 - Ek <= stepLength * C1 * pkGradEk);
                                cond2 = (pkGradEk1 >= C2 * pkGradEk);

                                //// if we are very close to minimum, do not check conditions (it leads to infinite cycles)
                                //if (Math.Abs(Ek1 - Ek) < energyThreshold)
                                //{
                                //	cond1 = cond2 = true;
                                //}

                                //// Debug output:
                                //if (tries > 4)
                                //{
                                //	Console.WriteLine("step = " + stepLength + " " +
                                //		"cond#1 = " + (cond1 ? "TRUE" : "FALSE") + " " +
                                //		"cond#2 = " + (cond2 ? "TRUE" : "FALSE") + " " +
                                //		"deltaE = " + (Ek1 - Ek)
                                //		);
                                //}

                                // change step length:
                                if (cond1 && !cond2)
                                {
                                    stepLength = increaseStep(stepLength);
                                }
                                if (!cond1 && !cond2)
                                {
                                    stepLength = increaseStep(stepLength);
                                }

                                if (!cond1 && cond2)
                                {
                                    stepLength = decreaseStep(stepLength);
                                }
                            }
                            ++tries;
                            ++numIterations;

                            // To prevent freeze:
                            if (tries >= graphSys.Config.SearchIterations)
                            {
                                break;
                            }
                        }
                        // swap buffers: --------------------------------------------------------------------
                        HostSystem.SwapBuffers();

                        if (stepLength == chosenStepLength)                         // if the new step length is the same as before
                        {
                            ++stepStability;
                        }
                        else
                        {
                            stepStability = 0;
                        }
                        chosenStepLength = stepLength;


                        energy      = Ek1;
                        deltaEnergy = Ek1 - Ek;
                        // update bound deltaE:
                        if (Math.Abs(deltaEnergy) < Math.Abs(deltaEnergyBound))
                        {
                            deltaEnergyBound = deltaEnergy;
                        }
                        pGradE = pkGradEk1;

                        // write to file:
                        //			sw.WriteLine(numIterations + "," + stepLength + "," + (float)Math.Sqrt(Math.Abs(deltaEnergyBound) / initialEnergy)
                        //				+ "," + getChangeRate());

                        if (!FixedStep &&
                            stepStability >= graphSys.Config.SwitchToManualAfter)                             // if stable step length found, switch to fixed step
                        {
                            FixedStep = true;
                            //						Console.WriteLine("Step fixed at iteration #" + numIterations);
                        }

                        //if (Math.Abs(deltaEnergy) < energyThreshold) // if deltaE is low enough, switch to fixed step
                        //{
                        //	FixedStep = true;
                        //	HostSystem.RunPause = LayoutSystem.State.PAUSE;
                        //	Console.WriteLine( energyThreshold + "  " + deltaEnergy );
                        //
                        //}
                    }
                    //			sw.Close();
                }
            }

            var debStr = HostSystem.Environment.GetService <DebugStrings>();

            debStr.Add(Color.Black, "AUTO MODE");
//			debStr.Add(Color.Black,		"C1 = " + C1);
//			debStr.Add(Color.Black,		"C2 = " + C2);
            debStr.Add(Color.Aqua, "Step factor   = " + chosenStepLength);
//			debStr.Add(Color.Aqua,		"Energy        = " + energy);
            debStr.Add(Color.Aqua, "DeltaE        = " + deltaEnergy);
//			debStr.Add(Color.Aqua,		"pTp           = " + pGradE);
            debStr.Add(Color.Aqua, "Iteration     = " + numIterations);
            debStr.Add(Color.RoyalBlue, "Mode:   " + (FixedStep ? "FIXED" : "SEARCH"));
            debStr.Add(Color.Aqua, "Stability     = " + stepStability);
//			debStr.Add(Color.Aqua,		"E/E0          = " + (energy/initialEnergy));
            debStr.Add(Color.Aqua, "Change        = " + getChangeRate());
//			debStr.Add(Color.Orchid,	"Check sum     = " + checkSum);

//			debStr.Add(Color.Black, "E0/N          = " + (initialEnergy / (float)HostSystem.ParticleCount));
//			debStr.Add(Color.Black,	"nodes/edges   = " + ((float)HostSystem.ParticleCount / (float)HostSystem.LinkCount ));
//			debStr.Add(Color.Black, "ESTIM   = " + energyEstim);
//			debStr.Add(Color.Black, "REAL/ESTIM      = " + (initialEnergy / energyEstim));
        }
        protected override void update(int userCommand)
        {
            var graphSys = HostSystem.Environment.GetService <GraphSystem>();

            LayoutSystem.ComputeParams param = new LayoutSystem.ComputeParams();
            param.StepLength = stepLength;
            float nextEnergy = 0;
            float useless    = 0;

            if (HostSystem.CurrentStateBuffer != null)
            {
                if (HostSystem.RunPause == LayoutSystem.State.RUN)
                {
                    for (int i = 0; i < graphSys.Config.IterationsPerFrame; ++i)
                    {
                        HostSystem.MoveVertices(
                            HostSystem.CurrentStateBuffer,
                            HostSystem.NextStateBuffer,
                            param
                            );

                        HostSystem.CalcDescentVector(
                            HostSystem.NextStateBuffer,
                            param
                            );

                        HostSystem.CalcTotalEnergyAndDotProduct(
                            HostSystem.NextStateBuffer,
                            HostSystem.NextStateBuffer,
                            HostSystem.EnergyBuffer,
                            param,
                            out nextEnergy,
                            out useless,
                            out checkSum
                            );

                        HostSystem.SwapBuffers();

                        if (nextEnergy < energy)
                        {
                            ++progress;
                        }
                        else
                        {
                            progress   = 0;
                            stepLength = decreaseStep(stepLength);
                        }

                        if (progress > maxProgress)
                        {
                            progress   = 0;
                            stepLength = increaseStep(stepLength);
                        }
                        deltaEnergy = nextEnergy - energy;
                        energy      = nextEnergy;
                        ++numIterations;
                    }
                }
            }

            var debStr = HostSystem.Environment.GetService <DebugStrings>();

            debStr.Add(Color.Black, "WOLFRAM MODE");
            debStr.Add(Color.Aqua, "Step factor  = " + stepLength);
            debStr.Add(Color.Aqua, "Energy       = " + energy);
            debStr.Add(Color.Aqua, "deltaEnergy  = " + deltaEnergy);
            debStr.Add(Color.Aqua, "Iteration      = " + numIterations);
        }
Example #27
0
 public EsxHostSystem(VSphereManagedObject vSphereManagedObject, string hostName)
     : base(vSphereManagedObject)
 {
     _hostSystem = GetHostSystem(hostName);
 }
Example #28
0
 internal EsxHostSystem(VSphereManagedObject vSphereManagedObject, HostSystem hostSystem)
     : base(vSphereManagedObject)
 {
     _hostSystem = hostSystem;
 }
Example #29
0
 internal EsxHostSystem(VSphereManagedObject vSphereManagedObject, HostSystem hostSystem)
     : base(vSphereManagedObject)
 {
     _hostSystem = hostSystem;
 }
Example #30
0
        private static void Run()
        {
            try
            {
                VimClient client = new VimClientImpl();
                // connect to vSphere web service

                client.Connect(serviceUrl);
                // Login using username/password credentials
                client.Login(userName, password);
                // Get DiagnosticManager

                var vmList = client.FindEntityViews(typeof(VirtualMachine), null, null, null);
                foreach (VirtualMachine vm in vmList)
                {
                    Console.WriteLine(vm.Name);

                    HostSystem host = (HostSystem)client.GetView(vm.Runtime.Host, null);



                    // Datastores
                    foreach (ManagedObjectReference mor in vm.Datastore)
                    {
                        Datastore datastore = (Datastore)client.GetView(mor, null);
                        var       vmfsInfo  = datastore.Info as VmfsDatastoreInfo;

                        Console.WriteLine($"Name: {vmfsInfo.Name}");
                        Console.WriteLine($"Type: {vmfsInfo.Vmfs.Type}");
                        Console.WriteLine($"Location: {vmfsInfo.Url}");
                        Console.WriteLine($"UUID: {vmfsInfo.Vmfs.Uuid}");
                        Console.WriteLine($"SSD: {vmfsInfo.Vmfs.Ssd}");

                        Console.WriteLine("Memory");
                        Console.WriteLine($"FreeSpace: {FormatBytes(datastore.Info.FreeSpace)}");
                        Console.WriteLine($"Capacity: {FormatBytes(vmfsInfo.Vmfs.Capacity)}");

                        foreach (HostScsiDiskPartition partition in vmfsInfo.Vmfs.Extent)
                        {
                            Console.WriteLine($"Disk name: {partition.DiskName} Partition: {partition.Partition}");
                            //datastore.Host
                        }
                        //Console.WriteLine($"Capacity: {ConvertToMb(vmfsInfo.Vmfs.Capacity)}");
                    }
                }

                //var hostlist = client.FindEntityViews(typeof(HostVStorageObjectManager), null, null, null);

                //Populate the Host names into the Host ListBox
                //foreach (HostSystem vmhost in hostlist)
                //{
                //    Console.WriteLine(vmhost.Name);

                //    foreach (Datastore store in (Datastore)vmhost.Datastore)
                //    {

                //    }
                //}

                // DataCenters
                IList dcList = client.FindEntityViews(typeof(Datacenter), null, null, null);
                foreach (Datacenter dc in dcList)
                {
                }

                Console.WriteLine("//--------------------------------------//");

                //DiagnosticManager diagMgr = (DiagnosticManager)client.GetView(client.ServiceContent.DiagnosticManager, null);
                //// Obtain the last line of the logfile by setting an arbitrarily large
                //// line number as the starting point
                //DiagnosticManagerLogHeader log = diagMgr.BrowseDiagnosticLog(null, "hostd", 999999999, null);
                //int lineEnd = log.LineEnd;
                //// Get the last 5 lines of the log first
                //int start = lineEnd - 5;
                //log = diagMgr.BrowseDiagnosticLog(null, "hostd", start, null);
                //foreach (string line in log.LineText)
                //{
                //    Console.WriteLine(line);
                //}
                // Logout from the vSphere server
                client.Disconnect();
            }
            catch (Exception)
            {
                throw;
            }
        }