Ejemplo n.º 1
0
 protected virtual void EstimateAdvice(Data data,
                                       Analysis.AnalysisResult advices, 
                                       Analysis.EstimateOptions options,
                                       data.tmpDS.tradeEstimateDataTable toTbl)
 {
     Analysis.EstimateAdvice(data,advices, options, toTbl);
 }
Ejemplo n.º 2
0
 public void Init(Data data,
                  Analysis.AnalysisResult advices)
 {
     this.myAnalysisData = data;
     this.myTradeAdvices = advices;
     ReLoad();
 }
 public void start(Analysis parent, HttpResponse response, System.Web.SessionState.HttpSessionState session)
 {
     caller = parent;
     Debug.WriteLine("SelectData step of " + caller.getDisplayName() + " started");
     session["stepid"] = 1;
     response.Redirect("~/Default.aspx");
 }
 private void analysisWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     MTConnectAnalyzer.Log.outputTo = MTConnectAnalyzer.Log.OutputMode.LogWriter;
     MTConnectAnalyzer.Log.logwriter = new TextBoxLogWriter(sender as BackgroundWorker);
     analysis = new Analysis(inputPath);
     analysisCompleted = false;
 }
Ejemplo n.º 5
0
        public Analysis Parse(XmlDocument document)
        {
            var analysisObj = new Analysis();
            XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
            ns.AddNamespace("xsuks", "http://schemas.microsoft.com/win/2004/08/events/event");

            var requestUrl = document.SelectSingleNode("failedRequest");
            
            if (requestUrl != null)
            {
                analysisObj.URL = requestUrl.Attributes["url"].Value;
            }

            var bufferNode = requestUrl.SelectSingleNode("xsuks:Event/xsuks:EventData/xsuks:Data[@Name='Buffer']", ns);
            if (bufferNode != null && !string.IsNullOrEmpty(bufferNode.InnerText))
            {
                var text = bufferNode.InnerText.Replace(@"xmlns:ns1=""http:///tempuri.org/""", "")
                    .Replace(@"xmlns:xsi=""http:///www.w3.org/2001/XMLSchema-instance""", "")
                    .Replace(@"xmlns:xsd=""http:///www.w3.org/2001/XMLSchema""", "")
                    .Replace(@"xmlns:soap=""http:///schemas.xmlsoap.org/soap/envelope/""", "");
                var startingPoint = bufferNode.InnerText.IndexOf(":Body");
                startingPoint = startingPoint + 5;
                var endPoint = bufferNode.InnerText.IndexOf(">", bufferNode.InnerText.IndexOf(">", startingPoint) + 1);
                analysisObj.MethodName = bufferNode.InnerText.Substring(startingPoint + 2, endPoint - (startingPoint + 2)).Trim();
                analysisObj.Buffer = bufferNode.InnerText;
            }
            else
            {
                analysisObj.MethodName = "Couldn't Find";
                analysisObj.Buffer = "Couldn't Find";
            }
            return analysisObj;
        }
 public HexerciseControllerService(dynamic parameters)
 {
     var inputParser = new InputParser(parameters);
     _mbid = inputParser.GetMbid();
     _analysis = GetAcousticbrainzAnalysis();
     _colourCalculator = new PredominantPropertyColourCalculator();
     _trackColour = _colourCalculator.From(_analysis);
 }
Ejemplo n.º 7
0
 // constructor
 public BallisticConfig() :
        base()
 {
     analysis = new Analysis();
     //fileLocations = new List<SurvivabilityConfig.FileLocation>();
     criticalComponents = new List<CriticalComponent>();
     ballisticThreats = new List<BallisticThreat>();
 }
 public Color From(Analysis analysis)
 {
     _analysis = analysis;
     var metadataAnalysis = new MetadataAnalysis(analysis);
     _weightedColours.AddList(metadataAnalysis.GetColours(), MetadataWeighting);
     GetAudioAspect();
     var aggregatedColour = ColorHandling.Aggregate(_weightedColours);
     return ColorHandling.ExaggerateColour(3, aggregatedColour);
 }
Ejemplo n.º 9
0
 private IAnalysisSet ObjectSetAttr(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
     if (args.Length >= 3) {
         foreach (var ii in args[0].OfType<InstanceInfo>()) {
             foreach (var key in args[1].GetConstantValueAsString()) {
                 ii.SetMember(node, unit, key, args[2]);
             }
         }
     }
     return AnalysisSet.Empty;
 }
Ejemplo n.º 10
0
 public void Update(Analysis analysis)
 {
     if(analysis != null && !PivotGridSettingsHelper.HasPivotGridSettings(analysis)) {
         IAnalysisControl control = CreateAnalysisControl();
         control.DataSource = new AnalysisDataSource(analysis, new XPCollection<DemoTask>(analysis.Session));
         control.Fields["Priority"].Area = DevExpress.XtraPivotGrid.PivotArea.ColumnArea;
         control.Fields["Subject"].Area = DevExpress.XtraPivotGrid.PivotArea.DataArea;
         control.Fields["AssignedTo.DisplayName"].Area = DevExpress.XtraPivotGrid.PivotArea.RowArea;
         PivotGridSettingsHelper.SavePivotGridSettings(CreatePivotGridSettingsStore(control), analysis);
     }
 }
Ejemplo n.º 11
0
        public void start(Analysis parent, HttpResponse response, System.Web.SessionState.HttpSessionState session)
        {
            ParameterStream stream = ParameterStream.getStream(session);
            String[] features = (String[]) stream.get("selectedFeatures");
            int PCs = (int) stream.get("numberOfPCs");
            Registry.Registry registry = Registry.Registry.getRegistry(session);
            System.Data.DataSet ds = (System.Data.DataSet) registry.GetDataset((string) stream.get("dataSetName"));

            //retrieve dataset table (assume one for now)
            System.Data.DataTable dt = ds.Tables[0];
            
            
            //raw data
            double[,] rawData = new double[dt.Rows.Count, features.Count()];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < features.Count(); j++)
                    rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
            }

            //Create matrix to hold data for PCA
            Matrix X = new Matrix(rawData);

            //Remove mean
            Vector columnVector;
            for (int i = 0; i < X.ColumnCount; i++)
            {
                columnVector = X.GetColumnVector(i);
                X.SetColumnVector(columnVector.Subtract(columnVector.Average()),i);
            }

            Matrix PCmatrix = new Matrix(X.ColumnCount, PCs, 0);
            Vector Weights = new Vector(PCs);

            System.Diagnostics.Stopwatch watch = new Stopwatch();

            //Run algorithm and time it
            watch.Start();
            NIPALS(X, PCs, PCmatrix, Weights);
            watch.Stop();
            stream.set("algRunTime", watch.ElapsedMilliseconds);
            
            /*
            response.Buffer = true;
            response.Write(PCmatrix.ToString() + "\n");
            response.Write(Weights.ToString() + "\n");
            response.Flush();
            */
            Debug.WriteLine("Done with PCA");
            stream.set("PCmatrix", PCmatrix);
            stream.set("Weights", Weights);
            parent.next(response, session);
        }
Ejemplo n.º 12
0
        public Column(Analysis.Shingle.Matrix.Matrix enclosingInstance)
        {
            Rows = new List<Row>();
            Matrix = enclosingInstance;

            lock (Matrix)
            {
                if (Matrix.Columns.Count == 0)
                    IsFirst = true;
            }
            Matrix.Columns.Add(this);
        }
Ejemplo n.º 13
0
 private void UpdateList(List<Analysis> resultList, Analysis objAnalysis, string serverName, string fileName)
 {
     var match = resultList.Find(x => x.Equals(objAnalysis));
     if (match != null)
     {
         match.LogFiles.Add(fileName);
     }
     else
     {
         objAnalysis.LogFiles.Add(fileName);
         resultList.Add(objAnalysis);
     }
 }
 public static Analysis Deserialize(this AcousticbrainzResult analysis)
 {
     var hlObject = new JavaScriptSerializer().Deserialize<Analysis>(analysis.HighLevelJson);
     var llObject = new JavaScriptSerializer().Deserialize<Analysis>(analysis.LowLevelJson);
     var analysisObject = new Analysis
         {
             highlevel = hlObject.highlevel,
             lowlevel = llObject.lowlevel,
             metadata = llObject.metadata,
             rhythm = llObject.rhythm,
             tonal = llObject.tonal
         };
     return analysisObject;
 }
 private static List<Property> AllProperties(Analysis.HighLevel highLevel)
 {
     return new List<Property> {
         new Property(highLevel.danceability),
         new Property(highLevel.gender),
         new Property(highLevel.mood_acoustic),
         new Property(highLevel.mood_aggressive),
         new Property(highLevel.mood_electronic),
         new Property(highLevel.mood_happy),
         new Property(highLevel.mood_party),
         new Property(highLevel.mood_relaxed),
         new Property(highLevel.mood_sad)
     };
 }
Ejemplo n.º 16
0
        static void Main(string[] arguments)
        {
            if (arguments.Length != 2)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("{0} <path to directory containing match files> <path to output file>");
                return;
            }

            string matchesDirectory = arguments[0];
            string outputPath = arguments[1];
            Analysis analysis = new Analysis(matchesDirectory, outputPath, false);
            analysis.Analyse();
            analysis.PrintStatistics();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Checks control state for DAQ continuation, then
        /// If at the end of a cycle
        /// 1) finishes cycle processing (wait for analyzer completion, get results, summarize counts, cycle conditioning steps)
        ///   a) starts the next assay cycle, or
        ///   b) notifies controller of DAQ measurement completion 
        /// </summary>
        /// <param name="activeInstr">instrument object associated with the current DAQ state</param>
        /// <param name="sb">status block object indicating end of a cycle</param>
        internal static void HandleEndOfCycleProcessing(LMInstrument activeInstr, Analysis.StreamStatusBlock sb)
        {
            activeInstr.RDT.PlaceStatusTextOnCurrentCycle(sb);

            bool done = true; // assume done for all instruments

            activeInstr.DAQState = DAQInstrState.Online;

            // tbd RR: need to lock this
            // for each networked instrument
            // check ALL instrument for done so we can set the assay.state to done or repeat
            // only look at active instrs in the listbox list.
            for (int j = 0; j < Instruments.Active.Count; j++) // NEXT: revisit this for mixing of the LM and SR behaviors
            {
                if (Instruments.Active[j].DAQState != DAQInstrState.Online)
                {
                    done = false;
                    break;
                }
            }

            if (done) // all are done
            {
                CurState.State = DAQInstrState.Online;
                gControl.collog.TraceInformation("Assay cycle " + CurState.Measurement.CurrentRepetition + " complete");
                if ((CurState.Measurement.CurrentRepetition < CurState.Measurement.RequestedRepetitions) ||
                    (CurState.Measurement.RequestedRepetitions == 0) && !CurState.IsQuitRequested)
                {
                    // dev note: this method could be spawned in a task because the end processing can be time consuming, delaying the start of next DAQ iteration
                    bool ok = activeInstr.RDT.EndOfCycleProcessing(CurState.Measurement);
                    if (ok)  // start the next cycle
                    {
                        gControl.FireEvent(EventType.ActionInProgress, gControl);
                        gControl.StartLM_SRAssay();
                    }
                    else
                        gControl.MajorOperationCompleted(); // the overall pend handle used by cmd line
                }
                else
                {
                    gControl.collog.TraceInformation("All assay cycles completed");
                    activeInstr.RDT.EndOfCycleProcessing(CurState.Measurement);  // do final processing on the last cycle, then do the last cycle closure processing
                    activeInstr.RDT.EndOfCycleProcessing(CurState.Measurement,  last:true);
                    if (CurState.Action != NCC.NCCAction.HVCalibration)
                        gControl.MajorOperationCompleted(); // the overall pend handle used by cmd line
                }
            }
        }
Ejemplo n.º 18
0
 private IAnalysisSet ObjectNew(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
     if (args.Length >= 1) {
         var instance = AnalysisSet.Empty;
         foreach (var n in args[0]) {
             var bci = n as BuiltinClassInfo;
             var ci = n as ClassInfo;
             if (bci != null) {
                 instance = instance.Union(bci.Instance);
             } else if (ci != null) {
                 instance = instance.Union(ci.Instance);
             }
         }
         return instance;
     }
     return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance;
 }
        public ActionResult AnalysisByMonth(FormCollection collection)
        {
            using (var session = new SessionFactory().OpenSession())
            {
                var year = (collection["year"] + string.Empty).Trim().TryToInt();
                if (!year.HasValue)
                {
                    FlashWarn("年份有误,请选择年份!");
                    return Close();
                }
                var contractList = session.Find<Contract>();
                var dossierList = session.Find<Dossier>();
                var punishmentDossierList = session.Find<PunishmentDossier>();
                var recordList = session.Find<Record>();

                var list = new List<Analysis>();
                for (int i = 1; i < 13; i++)
                {
                    var item = new Analysis
                    {
                        Month = i + "月",
                        ContractNo = contractList.Count(m => m.Time.Year == year && m.Time.Month == i),
                        DossierNo = dossierList.Count(m => m.Time.Year == year && m.Time.Month == i),
                        PunishmentDossier = punishmentDossierList.Count(m => m.Time.Year == year && m.Time.Month == i),
                        RecordNo = recordList.Count(m => m.Time.Year == year && m.Time.Month == i)
                    };
                    list.Add(item);
                }
                var total =
                    new Analysis
                    {
                        Month = "合计",
                        ContractNo = contractList.Count(m => m.Time.Year == year),
                        DossierNo = dossierList.Count(m => m.Time.Year == year),
                        PunishmentDossier = punishmentDossierList.Count(m => m.Time.Year == year),
                        RecordNo = recordList.Count(m => m.Time.Year == year)

                    };
                list.Add(total);

                return View(list);
            }
        }
 public void Should_handle_special_characters_correctly()
 {
     var analysis = new Analysis
         {
             metadata = new Analysis.Metadata
                 {
                     tags = new Analysis.Metadata.Tags
                         {
                             artist = new []{"  p!nk/ke$ha  "},
                             album = new []{"Iron&Wine>cheese\\   ham~eggs"},
                             title = new []{"fight-for(your)[right]to.progr@m!"}
                         }
                 }
         };
     var actual =new MetadataAnalysis(analysis).Aggregate();
     var expected = new List<string>{ "pink", "kesha", "iron", "wine", "cheese",
         "ham", "eggs", "fight", "for", "your", "right", "to", "program"};
     foreach (var word in actual)
     {
         Console.WriteLine(word);
         Assert.That(expected.Contains(word), "Actual contained the unexpected word: " + word);
     }
     Assert.That(actual.Count, Is.EqualTo(expected.Count));
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Sends every chunk of the .fcs file and sends an sms to the user
        /// </summary>
        /// <param name="model"></param>
        /// <param name="blockBlob"></param>
        /// <returns></returns>
        private async Task<ActionResult> CommitAllChunks(CloudFile model, CloudBlockBlob blockBlob)
        {
            model.IsUploadCompleted = true;

            var errorInOperation = false;

            try
            {
                var blockList = Enumerable.Range(1, (int)model.BlockCount).ToList().Select(rangeElement =>
                               Convert.ToBase64String(Encoding.UTF8.GetBytes(
                               string.Format(CultureInfo.InvariantCulture, "{0:D4}", rangeElement))));

                //model.BlockBlob.PutBlockListAsync(blockList);
                await blockBlob.PutBlockListAsync(blockList);

                var duration = DateTime.Now - model.StartTime;

                float fileSizeInKb = model.Size / 1024;

                var fileSizeMessage = fileSizeInKb > 1024 ?
                    string.Concat((fileSizeInKb / 1024).ToString(CultureInfo.CurrentCulture), " MB") :
                    string.Concat(fileSizeInKb.ToString(CultureInfo.CurrentCulture), " KB");

                var message = string.Format(CultureInfo.CurrentCulture,
                    "File uploaded successfully. {0} took {1} seconds to upload\n",
                    fileSizeMessage, duration.TotalSeconds);

                //Get the user
                var user = GetUser();
                //var fcsPath = user.LastName.ToLower() + "-" + user.FirstName.ToLower() + "-" + user.Id + "/" + model.FileName;
                var fcsPath = user.LastName.ToLower() + "-" + user.FirstName.ToLower() + "/" + model.FileName;

                var storedPatient = _context.Patients.First(x => x.Id == model.Patient);

                var analysis = new Analysis
                {
                    Date = DateTime.Now.Date,
                    FcsFilePath = fcsPath,
                    FcsUploadDate = DateTime.Now.Date.ToString("MM-dd-yyyy-hh-mm"),
                    ResultFilePath = "",
                    ResultDate = DateTime.Now.Date,
                    Delta = 0.00
                };

                storedPatient.Analyses.Add(analysis);
                user.Analyses.Add(analysis);
                _context.SaveChanges();

                if (!string.IsNullOrWhiteSpace(user.Phone))
                {
                    //send message to the user
                    _smsSender.SendSms(new AuthMessageSender.Message
                    {
                        Body = "Greetings" + "\nStatus on: " + model.OriginalFileName + "\n" + message
                    }, _sid, _authToken, _number, user.Phone);
                }

                model.UploadStatusMessage = message;
            }
            catch (StorageException e)
            {
                model.UploadStatusMessage = "Failed to Upload file. Exception - " + e.Message;
                errorInOperation = true;
            }
            finally
            {
                HttpContext.Session.Remove("CurrentFile");
            }
            return Json(new
            {
                error = errorInOperation,
                isLastBlock = model.IsUploadCompleted,
                message = model.UploadStatusMessage
            });
        }
Ejemplo n.º 22
0
 public Task WaitAsync(CancellationToken cancellationToken)
 {
     Analysis.IgnoreArgument(cancellationToken);
     return(Unit.VoidTask);
 }
Ejemplo n.º 23
0
        public static bool GetBestSolution(PackableBrick packableProperties, BoxProperties caseProperties, InterlayerProperties interlayer
                                           , ConstraintSetBoxCase constraintSet, bool allowMultipleLayerOrientations
                                           , Vector3D cameraPosition, bool showCotations, float fontSizeRatio, Size sz
                                           , ref int layerCount, ref int caseCount, ref int interlayerCount
                                           , ref double weightTotal, ref double weightLoad, ref double?weightNet
                                           , ref Vector3D bbLoad, ref Vector3D bbGlob
                                           , ref double volumeEfficency, ref double?weightEfficiency
                                           , ref byte[] imageBytes
                                           , ref string[] errors
                                           )
        {
            List <string> lErrors = new List <string>();

            if (!packableProperties.FitsIn(caseProperties, constraintSet))
            {
                lErrors.Add($"{packableProperties.Name} does not fit in {caseProperties.Name} with given constraint set!");
                return(false);
            }
            try
            {
                SolverBoxCase   solver   = new SolverBoxCase(packableProperties, caseProperties);
                List <Analysis> analyses = solver.BuildAnalyses(constraintSet, allowMultipleLayerOrientations);
                if (analyses.Count > 0)
                {
                    Analysis analysis = analyses[0];
                    layerCount      = analysis.Solution.LayerCount;
                    caseCount       = analysis.Solution.ItemCount;
                    interlayerCount = analysis.Solution.LayerCount;

                    weightLoad  = analysis.Solution.LoadWeight;
                    weightTotal = analysis.Solution.Weight;

                    OptDouble optNetWeight = analysis.Solution.NetWeight;
                    weightNet        = optNetWeight.Activated ? optNetWeight.Value : (double?)null;
                    bbGlob           = analysis.Solution.BBoxGlobal.DimensionsVec;
                    bbLoad           = analysis.Solution.BBoxLoad.DimensionsVec;
                    volumeEfficency  = analysis.Solution.VolumeEfficiency;
                    weightEfficiency = null;
                    if (analysis.Solution.WeightEfficiency.Activated)
                    {
                        weightEfficiency = analysis.Solution.WeightEfficiency.Value;
                    }

                    // generate image path
                    Graphics3DImage graphics = new Graphics3DImage(sz)
                    {
                        FontSizeRatio  = fontSizeRatio,
                        CameraPosition = cameraPosition,
                        ShowDimensions = showCotations
                    };
                    ViewerSolution sv = new ViewerSolution(analysis.Solution);
                    sv.Draw(graphics, Transform3D.Identity);
                    graphics.Flush();
                    Bitmap         bmp       = graphics.Bitmap;
                    ImageConverter converter = new ImageConverter();
                    imageBytes = (byte[])converter.ConvertTo(bmp, typeof(byte[]));
                }
                else
                {
                    lErrors.Add("No solution found!");
                }
            }
            catch (Exception ex)
            {
                lErrors.Add(ex.Message);
            }
            errors = lErrors.ToArray();
            return(0 == lErrors.Count);
        }
Ejemplo n.º 24
0
        private bool PersistFullBuild(IConfiguration configuration, PathTable pathTable, CancellationToken cancellationToken)
        {
            var snapshotFile = m_snapshotFile.ToString(pathTable);
            var mountFolder  = snapshotFile + ".tmpdir";

            try
            {
                // Find a drive to mount the VHD as for this process. The VHD will be mapped to a particular NTFS folder
                // and then mounted as a drive using the drive mapping functionality. This is done to avoid issues with MAX_PATH
                // issues since many codebases have paths nearing MAX_PATH which would go over if rooted in a subdirectory
                // of even a reasonably short path length.
                char unusedDrive       = char.MinValue;
                var  systemDriveLetter = SpecialFolderUtilities.SystemDirectory[0];
                for (char drive = 'A'; drive <= 'Z'; drive++)
                {
                    if (drive == systemDriveLetter || drive == 'C')
                    {
                        continue;
                    }

                    if (!AbsolutePath.TryGet(pathTable, new StringSegment(drive + @":\"), out _))
                    {
                        unusedDrive = drive;
                    }
                }

                if (unusedDrive == char.MinValue)
                {
                    Tracing.Logger.Log.GenericSnapshotError(m_loggingContext, "Snapshot error: Could not find unused drive to use for snapshot destination");
                    return(false);
                }

                bool mounted = VhdUtilities.Mount(snapshotFile, sizeMb: 1 << 20 /* 1 TB */, mountFolder: mountFolder);
                if (!mounted)
                {
                    Tracing.Logger.Log.GenericSnapshotError(
                        m_loggingContext,
                        I($"Snapshot error: Could not create VHD '{unusedDrive}' and mount at '{mountFolder}'"));
                    return(false);
                }

                // Map drive for mounted vhd in order to minimize chance of MAX_PATH issues copying files to VHD.
                bool mappingApplied =
                    ProcessNativeMethods.ApplyDriveMappings(new[] { new PathMapping(unusedDrive, Path.GetFullPath(mountFolder)) });
                if (!mappingApplied)
                {
                    Tracing.Logger.Log.GenericSnapshotError(
                        m_loggingContext,
                        I($"Snapshot error: Drive mapping could not be applied from '{unusedDrive}' to '{mountFolder}'"));
                    return(false);
                }

                var mountDriveRoot       = unusedDrive + @":\";
                var buildEvaluationFiles = new HashSet <AbsolutePath>(m_files);

                if (configuration.Cache.CacheConfigFile.IsValid)
                {
                    buildEvaluationFiles.Add(configuration.Cache.CacheConfigFile);
                }

                // Track used roots so mappings can be added for inputs and outputs when running BuildXL on snap
                ConcurrentDictionary <AbsolutePath, Unit> usedRoots = new ConcurrentDictionary <AbsolutePath, Unit>();

                int capturedFileCount = 0;
                int totalFileCount    = buildEvaluationFiles.Count + m_pipGraph.FileCount;

                Action updateStatus = () => { Console.WriteLine("Snapshot: {0} of {1} files captured", capturedFileCount, totalFileCount); };

                updateStatus();
                var t = new StoppableTimer(updateStatus, 5000, 5000);

                // Copy the build evaluation files
                Parallel.ForEach(
                    buildEvaluationFiles.ToArray(),
                    new ParallelOptions()
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = cancellationToken
                },
                    buildEvaluationFile =>
                {
                    usedRoots[buildEvaluationFile.GetRoot(pathTable)] = Unit.Void;
                    CopyPath(pathTable, buildEvaluationFile, mountDriveRoot);
                    Interlocked.Increment(ref capturedFileCount);
                });

                if (m_pipGraph != null)
                {
                    // Copy all source files
                    Parallel.ForEach(
                        m_pipGraph.AllFiles.ToArray(),
                        new ParallelOptions {
                        MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = cancellationToken
                    },
                        pipFile =>
                    {
                        try
                        {
                            usedRoots[pipFile.Path.GetRoot(pathTable)] = Unit.Void;
                            if (pipFile.IsOutputFile)
                            {
                                return;
                            }

                            if (!buildEvaluationFiles.Contains(pipFile.Path))
                            {
                                CopyPath(pathTable, pipFile.Path, mountDriveRoot);
                            }
                        }
                        finally
                        {
                            Interlocked.Increment(ref capturedFileCount);
                        }
                    });
                }

                // kill and wait for the status timer to die...
                t.Dispose();

                using (var writer = new StreamWriter(File.OpenWrite(Path.Combine(mountDriveRoot, "notes.txt"))))
                {
                    writer.WriteLine("Full Build Snapshot Info");
                    writer.WriteLine();
                    WriteNotes(configuration, pathTable, writer, path => path.ToString(pathTable));
                }

                using (var writer = new StreamWriter(File.OpenWrite(Path.Combine(mountDriveRoot, "runbxl.cmd"))))
                {
                    writer.Write("%BUILDXL_EXE_PATH% \"@%~dp0\\buildxl.rsp\" %*");
                    foreach (var usedRoot in usedRoots.Keys)
                    {
                        var usedRootLetter = usedRoot.ToString(pathTable)[0];
                        if (usedRootLetter.ToUpperInvariantFast() == 'C')
                        {
                            continue;
                        }

                        Directory.CreateDirectory(Path.Combine(mountDriveRoot, usedRootLetter.ToString()));
                        writer.Write(" /rootMap:{0}=\"%~dp0\\{0}\"", usedRootLetter);
                    }
                }

                using (var writer = new StreamWriter(File.OpenWrite(Path.Combine(mountDriveRoot, "buildxl.rsp"))))
                {
                    foreach (var argument in m_commandLineArguments)
                    {
                        writer.WriteLine(argument);
                    }

                    // Disable snapshot when running from snapshot
                    writer.WriteLine("/snapshotMode:None");

                    foreach (var envVar in m_environmentVariables)
                    {
                        writer.WriteLine("/envVar:{0}={1}", envVar.Key, envVar.Value ?? string.Empty);
                    }
                }
            }
            finally
            {
                Analysis.IgnoreResult(VhdUtilities.Dismount(snapshotFile, mountFolder));

                // TODO: Report error.
            }

            return(true);
        }
        private void FillGrid()
        {
            try
            {
                // remove all existing rows
                gridSolutions.Rows.Clear();
                // *** IViews
                // captionHeader
                SourceGrid.Cells.Views.RowHeader        captionHeader   = new SourceGrid.Cells.Views.RowHeader();
                DevAge.Drawing.VisualElements.RowHeader veHeaderCaption = new DevAge.Drawing.VisualElements.RowHeader();
                veHeaderCaption.BackColor   = Color.SteelBlue;
                veHeaderCaption.Border      = DevAge.Drawing.RectangleBorder.NoBorder;
                captionHeader.Background    = veHeaderCaption;
                captionHeader.ForeColor     = Color.Black;
                captionHeader.Font          = new Font("Arial", GridFontSize, FontStyle.Bold);
                captionHeader.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
                // viewRowHeader
                SourceGrid.Cells.Views.ColumnHeader        viewColumnHeader = new SourceGrid.Cells.Views.ColumnHeader();
                DevAge.Drawing.VisualElements.ColumnHeader backHeader       = new DevAge.Drawing.VisualElements.ColumnHeader();
                backHeader.BackColor                   = Color.LightGray;
                backHeader.Border                      = DevAge.Drawing.RectangleBorder.NoBorder;
                viewColumnHeader.Background            = backHeader;
                viewColumnHeader.ForeColor             = Color.Black;
                viewColumnHeader.Font                  = new Font("Arial", GridFontSize, FontStyle.Regular);
                viewColumnHeader.ElementSort.SortStyle = DevAge.Drawing.HeaderSortStyle.None;
                // viewNormal
                CellBackColorAlternate viewNormal = new CellBackColorAlternate(Color.LightBlue, Color.White);
                // ***
                // set first row
                gridSolutions.BorderStyle  = BorderStyle.FixedSingle;
                gridSolutions.ColumnsCount = 7;
                gridSolutions.FixedRows    = 1;
                gridSolutions.Rows.Insert(0);
                // header
                int iCol = 0;
                SourceGrid.Cells.ColumnHeader columnHeader;
                // A1xA2xA3
                columnHeader = new SourceGrid.Cells.ColumnHeader("A1 x A2 x A3");
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;
                // dimensions
                columnHeader = new SourceGrid.Cells.ColumnHeader(
                    string.Format(Properties.Resources.ID_DIMENSIONS, UnitsManager.LengthUnitString));
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;
                // weight
                columnHeader = new SourceGrid.Cells.ColumnHeader(string.Format(Properties.Resources.ID_WEIGHT_WU, UnitsManager.MassUnitString));
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;
                // #packs
                columnHeader = new SourceGrid.Cells.ColumnHeader("#");
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;
                // weight
                columnHeader = new SourceGrid.Cells.ColumnHeader(string.Format(Properties.Resources.ID_PALLETWEIGHT, UnitsManager.MassUnitString));
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;
                // efficiency
                columnHeader = new SourceGrid.Cells.ColumnHeader(Properties.Resources.ID_EFFICIENCYPERCENTAGE);
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;
                // maximum space
                columnHeader = new SourceGrid.Cells.ColumnHeader(string.Format(Properties.Resources.ID_MAXIMUMSPACE, UnitsManager.LengthUnitString));
                columnHeader.AutomaticSortEnabled = false;
                columnHeader.View        = viewColumnHeader;
                gridSolutions[0, iCol++] = columnHeader;

                int iRow = 0;
                foreach (Analysis analysis in _analyses)
                {
                    AnalysisCasePallet analysisCasePallet = analysis as AnalysisCasePallet;
                    PackProperties     pack = analysisCasePallet.Content as PackProperties;
                    int layerCount          = analysisCasePallet.Solution.Layers.Count;
                    if (layerCount < 1)
                    {
                        continue;
                    }
                    int    packPerLayerCount = analysisCasePallet.Solution.Layers[0].BoxCount;
                    int    itemCount         = analysisCasePallet.Solution.ItemCount;
                    double palletWeight      = analysisCasePallet.Solution.Weight;
                    double volumeEfficiency  = analysisCasePallet.Solution.VolumeEfficiency;
                    double maximumSpace      = analysisCasePallet.Solution.LayerCount > 0 ? analysisCasePallet.Solution.LayerMaximumSpace(0) : 0;


                    gridSolutions.Rows.Insert(++iRow);
                    iCol = 0;
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0} x {1} x {2}",
                                                                                          pack.Arrangement.Length, pack.Arrangement.Width, pack.Arrangement.Height));
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0:0.#} x {1:0.#} x {2:0.#}",
                                                                                          pack.OuterDimensions.X, pack.OuterDimensions.Y, pack.OuterDimensions.Z));
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0:0.###}",
                                                                                          pack.Weight));
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0} = {1} x {2}", itemCount, packPerLayerCount, layerCount));
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0:0.###}", palletWeight));
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0:0.#}", volumeEfficiency));
                    gridSolutions[iRow, iCol++] = new SourceGrid.Cells.Cell(string.Format("{0:0.#}", maximumSpace));
                }

                gridSolutions.AutoStretchColumnsToFitWidth = true;
                gridSolutions.AutoSizeCells();
                gridSolutions.Columns.StretchToFit();

                // select first solution
                if (gridSolutions.RowsCount > 1)
                {
                    gridSolutions.Selection.SelectRow(1, true);
                }
                else
                {
                    // grid empty -> clear drawing
                    _selectedAnalysis = null;
                    graphCtrlPack.Invalidate();
                    graphCtrlSolution.Invalidate();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }
Ejemplo n.º 26
0
 public override void Analyze(Analysis Mna)
 {
 }
Ejemplo n.º 27
0
        /// <inheritdoc />
        public async Task <Possible <ICache, Failure> > InitializeCacheAsync(ICacheConfigData cacheData, Guid activityId)
        {
            Contract.Requires(cacheData != null);

            using (var eventing = new InitializeCacheActivity(VerticalCacheAggregator.EventSource, activityId, typeof(VerticalCacheAggregator).FullName))
            {
                eventing.Start(cacheData);

                var possibleCacheConfig = cacheData.Create <Config>();

                if (!possibleCacheConfig.Succeeded)
                {
                    return(eventing.StopFailure(possibleCacheConfig.Failure));
                }

                Config cacheAggregatorConfig = possibleCacheConfig.Result;

                // temporary
                if (cacheAggregatorConfig.PreFetchCasData == true)
                {
                    throw new NotImplementedException();
                }

                // initialize local cache
                var maybeCache = await CacheFactory.InitializeCacheAsync(cacheAggregatorConfig.LocalCache, activityId);

                if (!maybeCache.Succeeded)
                {
                    return(eventing.StopFailure(maybeCache.Failure));
                }

                ICache local = maybeCache.Result;

                if (local.IsReadOnly)
                {
                    Analysis.IgnoreResult(await local.ShutdownAsync(), justification: "Okay to ignore shutdown status");
                    return(eventing.StopFailure(new VerticalCacheAggregatorNeedsWriteableLocalFailure(local.CacheId)));
                }

                if (cacheAggregatorConfig.UseLocalOnly)
                {
                    return(eventing.Returns(Possible.Create(local)));
                }

                maybeCache = await ConstructRemoteCacheAsync(activityId, cacheAggregatorConfig);

                if (!maybeCache.Succeeded)
                {
                    eventing.Write(CacheActivity.CriticalDataOptions, new { RemoteCacheFailed = maybeCache.Failure });

                    if (cacheAggregatorConfig.FailIfRemoteFails)
                    {
                        Analysis.IgnoreResult(await local.ShutdownAsync(), justification: "Okay to ignore shutdown status");
                        return(eventing.StopFailure(maybeCache.Failure));
                    }

                    // If the remote cache does not construct, we fall back to just the local.
                    // This is basically like a disconnected state only we are starting disconnnected
                    // and thus are just the local cache now.  We can just return the local and
                    // not add the overhead of the aggregator.
                    string failureMessage = string.Format(
                        System.Globalization.CultureInfo.InvariantCulture,
                        RemoteConstructionFailureWarning,
                        local.CacheId);

                    // Note: Compiler is confused and needs help converting ICache to Possible here but not a few lines below.
                    return(eventing.Returns(new MessageForwardingCache(new Failure[] { maybeCache.Failure.Annotate(failureMessage) }, local)));
                }

                ICache remote = maybeCache.Result;

                bool readOnlyRemote = remote.IsReadOnly || cacheAggregatorConfig.RemoteIsReadOnly;

                try
                {
                    // instantiate new VerticalCacheAggregator
                    return(eventing.Returns(new VerticalCacheAggregator(
                                                local,
                                                remote,
                                                readOnlyRemote,
                                                cacheAggregatorConfig.WriteThroughCasData,
                                                cacheAggregatorConfig.RemoteContentIsReadOnly)));
                }
                catch (Exception e)
                {
                    string cacheId = local.CacheId + "_" + remote.CacheId;
                    Analysis.IgnoreResult(await local.ShutdownAsync(), justification: "Okay to ignore shutdown status");
                    Analysis.IgnoreResult(await remote.ShutdownAsync(), justification: "Okay to ignore shutdown status");
                    return(eventing.StopFailure(new CacheConstructionFailure(cacheId, e)));
                }
            }
        }
Ejemplo n.º 28
0
 public Painter(Analysis analysis, LandmarkFinder finder)
 {
     Analysis = analysis;
     Finder   = finder;
 }
Ejemplo n.º 29
0
        //[SecurityFilter ("quality__allow_update")]
        public async Task <IActionResult> Put([FromQuery] int productionOrderId, [FromQuery] int furnaceQuantity, [FromBody] Analysis analysis)
        {
            try {
                if (ModelState.IsValid)
                {
                    var returnCalculate = await _calculateAnalysisService.Calculates(productionOrderId, furnaceQuantity, analysis, false);

                    return(Ok(returnCalculate));
                }
                return(BadRequest(ModelState));
            } catch (Exception ex) {
                return(StatusCode(500, ex.Message));
            }
        }
Ejemplo n.º 30
0
        private void GenerateResult(
            string name, string description
            , double length, double width, double height
            , double?weight
            , PalletProperties palletProperties
            , ref int stackCount, ref double loadWeight, ref double totalWeight
            , ref double stackEfficiency
            , ref string stackImagePath)
        {
            stackCount     = 0;
            totalWeight    = 0.0;
            stackImagePath = string.Empty;

            // generate case
            BoxProperties bProperties = new BoxProperties(null, length, width, height);

            bProperties.ID.SetNameDesc(name, description);
            if (weight.HasValue)
            {
                bProperties.SetWeight(weight.Value);
            }
            bProperties.SetColor(Color.Chocolate);
            bProperties.TapeWidth = new OptDouble(true, Math.Min(50.0, 0.5 * width));
            bProperties.TapeColor = Color.Beige;

            Graphics3DImage graphics = null;

            if (GenerateImage || GenerateImageInFolder)
            {
                // generate image path
                stackImagePath = Path.Combine(Path.ChangeExtension(Path.GetTempFileName(), "png"));

                if (GenerateImageInFolder)
                {
                    stackImagePath = Path.ChangeExtension(Path.Combine(Path.Combine(DirectoryPathImages, name)), "png");
                }

                graphics = new Graphics3DImage(new Size(ImageSize, ImageSize))
                {
                    FontSizeRatio  = 0.01f,
                    CameraPosition = Graphics3D.Corner_0
                };
            }

            // compute analysis
            ConstraintSetCasePallet constraintSet = new ConstraintSetCasePallet();

            constraintSet.SetAllowedOrientations(new bool[] { !AllowOnlyZOrientation, !AllowOnlyZOrientation, true });
            constraintSet.SetMaxHeight(new OptDouble(true, PalletMaximumHeight));
            constraintSet.Overhang = Overhang;

            SolverCasePallet solver   = new SolverCasePallet(bProperties, palletProperties);
            List <Analysis>  analyses = solver.BuildAnalyses(constraintSet, false);

            if (analyses.Count > 0)
            {
                Analysis analysis = analyses[0];
                stackCount      = analysis.Solution.ItemCount;
                loadWeight      = analysis.Solution.LoadWeight;
                totalWeight     = analysis.Solution.Weight;
                stackEfficiency = analysis.Solution.VolumeEfficiency;

                if (stackCount <= StackCountMax)
                {
                    if (GenerateImage || GenerateImageInFolder)
                    {
                        ViewerSolution sv = new ViewerSolution(analysis.Solution);
                        sv.Draw(graphics, Transform3D.Identity);
                        graphics.Flush();
                    }
                    if (GenerateReport)
                    {
                        ReportData inputData      = new ReportData(analysis);
                        string     outputFilePath = Path.ChangeExtension(Path.Combine(DirectoryPathReports, string.Format("Report_{0}_on_{1}", analysis.Content.Name, analysis.Container.Name)), "doc");

                        ReportNode rnRoot   = null;
                        Margins    margins  = new Margins();
                        Reporter   reporter = new ReporterMSWord(inputData, ref rnRoot, Reporter.TemplatePath, outputFilePath, margins);
                    }
                }
            }
            if (GenerateImage)
            {
                Bitmap bmp = graphics.Bitmap;
                bmp.Save(stackImagePath, System.Drawing.Imaging.ImageFormat.Png);
            }
        }
Ejemplo n.º 31
0
        public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "processimage")]
                                     HttpRequestMessage req, TraceWriter log)
        {
            Startup.Init();

            ImageAnalysisTableAdapter imageAnalysisTableAdapter = new ImageAnalysisTableAdapter();

            imageAnalysisTableAdapter.Init();

            const string imageUrl = "https://tumblrpics.blob.core.windows.net/orig-66/c48440825ac6eab1af6c4de39bbc59d6_ph8zkhbeVA1tf8706_1280.jpg";

            using (HttpClient httpClient = new HttpClient())
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                string apiKey = ConfigurationManager.AppSettings["GoogleApiKey"];

                string url = "https://vision.googleapis.com/v1/images:annotate?key=" + apiKey;

                VisionApiRequest request = VisionApiRequest.CreateFromImageUris(imageUrl);

                string requestJson = JsonConvert.SerializeObject(request, JsonUtils.GoogleSerializerSettings);

                StringContent stringContent = new StringContent(requestJson, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await httpClient.PostAsync(url, stringContent);

                HttpContent responseContent            = response.Content;
                string      googleVisionResponseString = await responseContent.ReadAsStringAsync();

                VisionApiResponse visionApiResponse =
                    JsonConvert.DeserializeObject <VisionApiResponse>(googleVisionResponseString, JsonUtils.GoogleSerializerSettings);

                string faceApiKey = ConfigurationManager.AppSettings["FaceApiKey"];
                httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", faceApiKey);
                stringContent = new StringContent($"{{\"url\":\"{imageUrl}\"}}", Encoding.UTF8, "application/json");
                response      = await httpClient.PostAsync(
                    "https://northeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=" +
                    "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
                    stringContent);

                responseContent = response.Content;

                string msDetectResponseString = await responseContent.ReadAsStringAsync();

                List <Face> msFaces = JsonConvert.DeserializeObject <List <Face> >(msDetectResponseString);

                string visionApiKey = ConfigurationManager.AppSettings["ComputerVisionApiKey"];
                httpClient.DefaultRequestHeaders.Remove("Ocp-Apim-Subscription-Key");
                httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", visionApiKey);
                stringContent = new StringContent($"{{\"url\":\"{imageUrl}\"}}", Encoding.UTF8, "application/json");
                response      = await httpClient.PostAsync(
                    "https://northeurope.api.cognitive.microsoft.com/vision/v2.0/analyze?visualFeatures=Description,ImageType,Adult,Categories,Tags,Objects,Color&language=en",
                    stringContent);

                responseContent = response.Content;

                string msAnalyzeResponseString = await responseContent.ReadAsStringAsync();

                Analysis msAnalysis = JsonConvert.DeserializeObject <Analysis>(msAnalyzeResponseString);

                if (visionApiResponse.Responses.Count == 1 && msFaces.Count > 0 && msAnalysis != null)
                {
                    ImageAnalysis canonicalImageAnalysis = new ImageAnalysis(visionApiResponse.Responses[0], msAnalysis, msFaces);
                }
            }
        }
        public Color From(Analysis analysis)
        {
            var metadataAnalysis = new MetadataAnalysis(analysis);
            _weightedColours.AddList(metadataAnalysis.GetColours(), MetadataWeighting);

            var audioAnalysis = new AudioAnalysis(analysis);
            _weightedColours.AddList(audioAnalysis.GetPredominantColours(), AudioWeighting);

            var aggregatedColour = ColorHandling.Aggregate(_weightedColours);
            return ColorHandling.ExaggerateColour(1,aggregatedColour);
        }
Ejemplo n.º 33
0
        public void Start()
        {
            Contract.Assume(!m_processStarted);

            Encoding        reportEncoding  = Encoding.Unicode;
            SafeFileHandle  childHandle     = null;
            DetouredProcess detouredProcess = m_detouredProcess;

            using (m_reportReaderSemaphore.AcquireSemaphore())
            {
                SafeFileHandle reportHandle;
                try
                {
                    Pipes.CreateInheritablePipe(
                        Pipes.PipeInheritance.InheritWrite,
                        Pipes.PipeFlags.ReadSideAsync,
                        readHandle: out reportHandle,
                        writeHandle: out childHandle);

                    var setup =
                        new FileAccessSetup
                    {
                        ReportPath = "#" + childHandle.DangerousGetHandle().ToInt64(),
                        DllNameX64 = s_binaryPaths.DllNameX64,
                        DllNameX86 = s_binaryPaths.DllNameX86,
                    };

                    bool debugFlagsMatch = true;
                    ArraySegment <byte> manifestBytes = new ArraySegment <byte>();
                    if (m_fileAccessManifest != null)
                    {
                        manifestBytes = m_fileAccessManifest.GetPayloadBytes(setup, FileAccessManifestStream, m_timeoutMins, ref debugFlagsMatch);
                    }

                    if (!debugFlagsMatch)
                    {
                        throw new BuildXLException("Mismatching build type for BuildXL and DetoursServices.dll.");
                    }

                    m_standardInputTcs = TaskSourceSlim.Create <bool>();
                    detouredProcess.Start(
                        s_payloadGuid,
                        manifestBytes,
                        childHandle,
                        s_binaryPaths.DllNameX64,
                        s_binaryPaths.DllNameX86);

                    // At this point, we believe calling 'kill' will result in an eventual callback for job teardown.
                    // This knowledge is significant for ensuring correct cleanup if we did vs. did not start a process;
                    // if started, we expect teardown to happen eventually and clean everything up.
                    m_processStarted = true;

                    ProcessId = detouredProcess.GetProcessId();
                }
                finally
                {
                    // release memory
                    m_fileAccessManifest = null;

                    // Note that in the success path, childHandle should already be closed (by Start).
                    if (childHandle != null && !childHandle.IsInvalid)
                    {
                        childHandle.Dispose();
                    }
                }

                var reportFile = AsyncFileFactory.CreateAsyncFile(
                    reportHandle,
                    FileDesiredAccess.GenericRead,
                    ownsHandle: true,
                    kind: FileKind.Pipe);
                StreamDataReceived reportLineReceivedCallback = m_reports == null ? (StreamDataReceived)null : ReportLineReceived;
                m_reportReader = new AsyncPipeReader(reportFile, reportLineReceivedCallback, reportEncoding, m_bufferSize);
                m_reportReader.BeginReadLine();
            }

            // don't wait, we want feeding in of standard input to happen asynchronously
            Analysis.IgnoreResult(FeedStandardInputAsync(detouredProcess, m_standardInputReader, m_standardInputTcs));
        }
Ejemplo n.º 34
0
 public RunWindow(Analysis analysis)
 {
     InitializeComponent();
     compile(analysis);
 }
Ejemplo n.º 35
0
        public static bool TryDumpProcess(IntPtr processHandle, int processId, string dumpPath, out Exception dumpCreationException, bool compress = false)
        {
            if (OperatingSystemHelper.IsUnixOS)
            {
                dumpCreationException = new PlatformNotSupportedException();
                return(false);
            }

            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(dumpPath));

                FileUtilities.DeleteFile(dumpPath);
                var uncompressedDumpPath = dumpPath;

                if (compress)
                {
                    uncompressedDumpPath = dumpPath + ".dmp.tmp";
                    Analysis.IgnoreResult(FileUtilities.TryDeleteFile(uncompressedDumpPath));
                }

                using (FileStream fs = new FileStream(uncompressedDumpPath, FileMode.Create))
                {
                    lock (s_dumpProcessLock)
                    {
                        bool dumpSuccess = ProcessUtilitiesWin.MiniDumpWriteDump(
                            hProcess: processHandle,
                            processId: (uint)processId,
                            hFile: fs.SafeFileHandle,
                            dumpType: (uint)ProcessUtilitiesWin.MINIDUMP_TYPE.MiniDumpWithFullMemory,
                            expParam: IntPtr.Zero,
                            userStreamParam: IntPtr.Zero,
                            callbackParam: IntPtr.Zero);

                        if (!dumpSuccess)
                        {
                            var code    = Marshal.GetLastWin32Error();
                            var message = new Win32Exception(code).Message;

                            throw new BuildXLException($"Failed to create process dump. Native error: ({code:x}) {message}, dump-path={dumpPath}");
                        }
                    }
                }

                if (compress)
                {
                    using (FileStream compressedDumpStream = new FileStream(dumpPath, FileMode.Create))
                        using (var archive = new ZipArchive(compressedDumpStream, ZipArchiveMode.Create))
                        {
                            var entry = archive.CreateEntry(Path.GetFileNameWithoutExtension(dumpPath) + ".dmp", CompressionLevel.Fastest);

                            using (FileStream uncompressedDumpStream = File.Open(uncompressedDumpPath, FileMode.Open))
                                using (var entryStream = entry.Open())
                                {
                                    uncompressedDumpStream.CopyTo(entryStream);
                                }
                        }

                    FileUtilities.DeleteFile(uncompressedDumpPath);
                }

                dumpCreationException = null;
                return(true);
            }
            catch (Exception ex)
            {
                dumpCreationException = ex;
                return(false);
            }
        }
Ejemplo n.º 36
0
        private IAnalysisSet DictionaryUpdate(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
            if (args.Length >= 1) {
                foreach (var otherDict in args[0].OfType<DictionaryInfo>()) {
                    if (!Object.ReferenceEquals(otherDict, this)) {
                        _keysAndValues.CopyFrom(otherDict._keysAndValues);
                    }
                }
            }
            // TODO: Process keyword args and add those values to our dictionary, plus a string key

            return AnalysisSet.Empty;
        }
Ejemplo n.º 37
0
        public virtual void UpdateGrid()
        {
            try
            {
                // sanity check
                if (gridSolutions.ColumnsCount < 2)
                {
                    return;
                }
                // remove all existing rows
                gridSolutions.Rows.Clear();
                // *** IViews
                // caption header
                DevAge.Drawing.VisualElements.RowHeader veHeaderCaption = new DevAge.Drawing.VisualElements.RowHeader()
                {
                    BackColor = Color.SteelBlue,
                    Border    = DevAge.Drawing.RectangleBorder.NoBorder
                };
                SourceGrid.Cells.Views.RowHeader captionHeader = new SourceGrid.Cells.Views.RowHeader
                {
                    Background    = veHeaderCaption,
                    ForeColor     = Color.Black,
                    Font          = new Font("Arial", GridFontSize + 2, FontStyle.Bold),
                    TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter
                };
                SourceGrid.Cells.Views.RowHeader captionHeader2 = new SourceGrid.Cells.Views.RowHeader
                {
                    Background    = veHeaderCaption,
                    ForeColor     = Color.Black,
                    Font          = new Font("Arial", GridFontSize, FontStyle.Regular),
                    TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter
                };
                // viewRowHeader
                DevAge.Drawing.VisualElements.RowHeader backHeader = new DevAge.Drawing.VisualElements.RowHeader()
                {
                    BackColor = Color.LightGray,
                    Border    = DevAge.Drawing.RectangleBorder.NoBorder
                };
                SourceGrid.Cells.Views.RowHeader viewRowHeader = new SourceGrid.Cells.Views.RowHeader
                {
                    Background = backHeader,
                    ForeColor  = Color.Black,
                    Font       = new Font("Arial", GridFontSize, FontStyle.Regular)
                };
                // viewNormal
                CellBackColorAlternate viewNormal = new CellBackColorAlternate(Color.LightBlue, Color.White);
                // ***

                int iRow = -1;
                // ### sol items : begin
                int solItemIndex = 0;
                foreach (var solItem in Solution.SolItems)
                {
                    gridSolutions.Rows.Insert(++iRow);
                    var rowHeader = new SourceGrid.Cells.RowHeader(string.Format(Resources.ID_PALLET_NUMBER, solItemIndex))
                    {
                        ColumnSpan = 2,
                        View       = captionHeader
                    };
                    gridSolutions[iRow, 0] = rowHeader;

                    gridSolutions.Rows.Insert(++iRow);
                    rowHeader = new SourceGrid.Cells.RowHeader(Resources.ID_ITEMS)
                    {
                        ColumnSpan = 2,
                        View       = captionHeader2
                    };
                    gridSolutions[iRow, 0] = rowHeader;

                    var dictNameCount = solItem.SolutionItems;
                    foreach (int containedItemIndex in dictNameCount.Keys)
                    {
                        // name
                        string name = string.Empty;
                        if (Analysis.ContentTypeByIndex(containedItemIndex) is Packable packable)
                        {
                            name = packable.Name;
                        }
                        // count
                        int count = dictNameCount[containedItemIndex];

                        if (count > 0)
                        {
                            gridSolutions.Rows.Insert(++iRow);
                            var itemHeader = new SourceGrid.Cells.RowHeader(name)
                            {
                                View = viewRowHeader
                            };
                            gridSolutions[iRow, 0] = itemHeader;
                            gridSolutions[iRow, 1] = new SourceGrid.Cells.Cell(string.Format("{0}", count));
                        }
                    }

                    // pallet data header
                    gridSolutions.Rows.Insert(++iRow);
                    rowHeader = new SourceGrid.Cells.RowHeader(Resources.ID_PALLETDATA)
                    {
                        ColumnSpan = 2,
                        View       = captionHeader2
                    };
                    gridSolutions[iRow, 0] = rowHeader;
                    // ***
                    // outer dimensions
                    BBox3D bboxGlobal = Solution.BBoxGlobal(solItemIndex);
                    // ---
                    gridSolutions.Rows.Insert(++iRow);
                    rowHeader = new SourceGrid.Cells.RowHeader(
                        string.Format(Resources.ID_OUTERDIMENSIONS, UnitsManager.LengthUnitString))
                    {
                        View = viewRowHeader
                    };
                    gridSolutions[iRow, 0] = rowHeader;
                    gridSolutions[iRow, 1] = new SourceGrid.Cells.Cell(
                        string.Format(CultureInfo.InvariantCulture
                                      , "{0:0.#} x {1:0.#} x {2:0.#}"
                                      , bboxGlobal.Length, bboxGlobal.Width, bboxGlobal.Height));
                    // load dimensions
                    BBox3D bboxLoad = Solution.BBoxLoad(solItemIndex);
                    gridSolutions.Rows.Insert(++iRow);
                    rowHeader = new SourceGrid.Cells.RowHeader(
                        string.Format(Resources.ID_LOADDIMENSIONS, UnitsManager.LengthUnitString))
                    {
                        View = viewRowHeader
                    };
                    gridSolutions[iRow, 0] = rowHeader;
                    gridSolutions[iRow, 1] = new SourceGrid.Cells.Cell(
                        string.Format(CultureInfo.InvariantCulture
                                      , "{0:0.#} x {1:0.#} x {2:0.#}"
                                      , bboxLoad.Length, bboxLoad.Width, bboxLoad.Height));
                    // ***
                    // ***
                    // load weight
                    gridSolutions.Rows.Insert(++iRow);
                    rowHeader = new SourceGrid.Cells.RowHeader(
                        string.Format(Resources.ID_LOADWEIGHT_WU, UnitsManager.MassUnitString))
                    {
                        View = viewRowHeader
                    };
                    gridSolutions[iRow, 0] = rowHeader;
                    gridSolutions[iRow, 1] = new SourceGrid.Cells.Cell(
                        string.Format(CultureInfo.InvariantCulture, "{0:0.#}", Solution.LoadWeight(solItemIndex)));

                    // total weight
                    gridSolutions.Rows.Insert(++iRow);
                    rowHeader = new SourceGrid.Cells.RowHeader(
                        string.Format(Resources.ID_PALLETWEIGHT_WU, UnitsManager.MassUnitString))
                    {
                        View = viewRowHeader
                    };
                    gridSolutions[iRow, 0] = rowHeader;
                    gridSolutions[iRow, 1] = new SourceGrid.Cells.Cell(
                        string.Format(CultureInfo.InvariantCulture
                                      , "{0:0.#}"
                                      , Solution.Weight(solItemIndex)));
                    // ***
                    // increment sol item index
                    ++solItemIndex;
                }
                // ### sol items : end
                gridSolutions.AutoSizeCells();
                gridSolutions.AutoStretchColumnsToFitWidth = true;
                gridSolutions.Invalidate();
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
Ejemplo n.º 38
0
        private IAnalysisSet DictionaryValues(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
            _keysAndValues.AddDependency(unit);

            if (_valuesList == null) {
                _valuesList = new ListInfo(
                    new[] { ValuesVariable },
                    unit.ProjectState.ClassInfos[BuiltinTypeId.List],
                    node,
                    unit.ProjectEntry
                );
            }
            return _valuesList;
        }
Ejemplo n.º 39
0
        public void BadResponseFile()
        {
            string tempPath = Path.Combine(TestOutputDirectory, "BadResponseFile");

            Assert.Throws <InvalidArgumentException>(() => Analysis.IgnoreResult(new CommandLineUtilities(new[] { "@\"" + tempPath + "\"" })));
        }
Ejemplo n.º 40
0
        private IAnalysisSet DictionaryGet(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
            _keysAndValues.AddDependency(unit);

            if (args.Length == 1) {
                return _keysAndValues.GetValueType(args[0]);
            } else if (args.Length >= 2) {
                return _keysAndValues.GetValueType(args[0]).Union(args[1]);
            }

            return AnalysisSet.Empty;
        }
Ejemplo n.º 41
0
        private void OnCompute(object sender, EventArgs e)
        {
            try
            {
                Excel.Worksheet xlSheet = Globals.StackBuilderAddIn.Application.ActiveSheet as Excel.Worksheet;
                if (null != xlSheet)
                {
                    Console.WriteLine(string.Format("Sheet name = {0}", xlSheet.Name));

                    double caseLength = ReadDouble(xlSheet, Settings.Default.CellCaseLength, Resources.ID_CASE_LENGTH);
                    double caseWidth  = ReadDouble(xlSheet, Settings.Default.CellCaseWidth, Resources.ID_CASE_WIDTH);
                    double caseHeight = ReadDouble(xlSheet, Settings.Default.CellCaseHeight, Resources.ID_CASE_HEIGHT);
                    double caseWeight = ReadDouble(xlSheet, Settings.Default.CellCaseWeight, Resources.ID_CASE_WEIGHT);

                    double palletLength = ReadDouble(xlSheet, Settings.Default.CellPalletLength, Resources.ID_PALLET_LENGTH);
                    double palletWidth  = ReadDouble(xlSheet, Settings.Default.CellPalletWidth, Resources.ID_PALLET_WIDTH);
                    double palletHeight = ReadDouble(xlSheet, Settings.Default.CellPalletHeight, Resources.ID_PALLET_HEIGHT);
                    double palletWeight = ReadDouble(xlSheet, Settings.Default.CellPalletWeight, Resources.ID_PALLET_WEIGHT);

                    double palletMaximumHeight = ReadDouble(xlSheet, Settings.Default.CellMaxPalletHeight, Resources.ID_CONSTRAINTS_PALLETMAXIHEIGHT);
                    double palletMaximumWeight = ReadDouble(xlSheet, Settings.Default.CellMaxPalletWeight, Resources.ID_CONSTRAINTS_PALLETMAXIWEIGHT);

                    // ### actually compute result ###
                    // build a case
                    BoxProperties bProperties = new BoxProperties(null, caseLength, caseWidth, caseHeight);
                    bProperties.SetWeight(caseWeight);
                    bProperties.SetColor(Color.Chocolate);
                    bProperties.TapeWidth = new OptDouble(true, 5);
                    bProperties.TapeColor = Color.Beige;

                    // build a pallet
                    PalletProperties palletProperties = new PalletProperties(null, PalletTypeName, palletLength, palletWidth, palletHeight);
                    palletProperties.Weight = palletWeight;
                    palletProperties.Color  = Color.Yellow;

                    // build a constraint set
                    ConstraintSetCasePallet constraintSet = new ConstraintSetCasePallet();
                    constraintSet.SetAllowedOrientations(new bool[] { false, false, true });
                    constraintSet.SetMaxHeight(new OptDouble(true, palletMaximumHeight));
                    constraintSet.OptMaxWeight = new OptDouble(true, palletMaximumWeight);

                    // use a solver and get a list of sorted analyses + select the best one
                    SolverCasePallet solver   = new SolverCasePallet(bProperties, palletProperties);
                    List <Analysis>  analyses = solver.BuildAnalyses(constraintSet);
                    if (analyses.Count > 0)
                    {
                        Analysis analysis    = analyses[0];
                        int      caseCount   = analysis.Solution.ItemCount; // <- your case count
                        double   loadWeight  = analysis.Solution.LoadWeight;
                        double   totalWeight = analysis.Solution.Weight;    // <- your pallet weight

                        Graphics3DImage graphics = null;
                        // generate image path
                        string stackImagePath = Path.Combine(Path.ChangeExtension(Path.GetTempFileName(), "png"));
                        graphics = new Graphics3DImage(new Size(Settings.Default.ImageDef, Settings.Default.ImageDef));
                        graphics.FontSizeRatio  = 0.01f;
                        graphics.CameraPosition = Graphics3D.Corner_0;
                        ViewerSolution sv = new ViewerSolution(analysis.Solution);
                        sv.Draw(graphics, Transform3D.Identity);
                        graphics.Flush();
                        Bitmap bmp = graphics.Bitmap;
                        bmp.Save(stackImagePath);


                        WriteInt(xlSheet, Settings.Default.CellNoCases, Resources.ID_RESULT_NOCASES, caseCount);
                        WriteDouble(xlSheet, Settings.Default.CellLoadWeight, Resources.ID_RESULT_LOADWEIGHT, loadWeight);
                        WriteDouble(xlSheet, Settings.Default.CellTotalPalletWeight, Resources.ID_RESULT_TOTALPALLETWEIGHT, totalWeight);

                        string filePath = string.Empty;

                        Globals.StackBuilderAddIn.Application.ActiveSheet.Shapes.AddPicture(
                            stackImagePath,
                            Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoCTrue,
                            Settings.Default.ImageLeft / 0.035, Settings.Default.ImageTop / 0.035,
                            Settings.Default.ImageWidth / 0.035, Settings.Default.ImageHeight / 0.035);
                    }
                    // ###
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Ejemplo n.º 42
0
 public ImageInst(Analysis analysis, Vector3D dims, BoxPosition boxPosition)
 {
     _analysis = analysis; _dims = dims; _boxPosition = boxPosition;
 }
Ejemplo n.º 43
0
 public void CleanBeforeTesting()
 {
     analysis = new Analysis(streamL);
     analysis.ExtractMetaData();
 }
Ejemplo n.º 44
0
 private void ContinuouslyPostAccessReports(SandboxedProcessUnix process, List <ReportInstruction> instructions)
 {
     Analysis.IgnoreResult(GetContinuouslyPostAccessReportsTask(process, instructions), "fire and forget");
 }
Ejemplo n.º 45
0
 public ImageCached(Analysis analysis, HalfAxis.HAxis axisLength, HalfAxis.HAxis axisWidth)
 {
     _analysis = analysis; _axisLength = axisLength; _axisWidth = axisWidth;
 }
Ejemplo n.º 46
0
 public void OnAnalysisUpdated(Document doc, Analysis analysis)
 {
     _log.Info(string.Format("Analysis {0} updated", analysis.Name));
 }
Ejemplo n.º 47
0
 public void Analyse(Analysis.Context context)
 {
     context.AddProgramToAnalysis (this.program);
 }
Ejemplo n.º 48
0
 public void OnNewAnalysisCreated(Document doc, Analysis analysis)
 {
     _log.Info(string.Format("Analysis created : {0}", analysis.Name));
 }
Ejemplo n.º 49
0
 protected abstract bool MatchesAnalysisType(Analysis analysis);
Ejemplo n.º 50
0
 protected override bool MatchesAnalysisType(Analysis analysis)
 {
     return(analysis is AnalysisCylinderCase);
 }
 public AudioAnalysis(Analysis analysis)
 {
     _analysis = analysis;
 }
Ejemplo n.º 52
0
 protected abstract void ExportAnalysisSpecific(Analysis analysis);
Ejemplo n.º 53
0
 public static Analysis Analyze(BoundNode node, MethodSymbol method)
 {
     var analysis = new Analysis(method);
     analysis.Analyze(node);
     return analysis;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AnalysisFunctionFunc"/> class.
 /// </summary>
 /// <param name="function">Function</param>
 /// <param name="argument">Argument</param>
 /// <param name="analysis">Analysis</param>
 public AnalysisFunctionFunc(AnalysisFunction function, AnalysisValueFunction argument, Analysis analysis)
     : base(analysis)
 {
     this.ArgumentFunction = argument;
     this.AnalysisFunction = function;
 }
Ejemplo n.º 55
0
        private IAnalysisSet DictionaryPop(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
            _keysAndValues.AddDependency(unit);

            return _keysAndValues.AllValueTypes;
        }
Ejemplo n.º 56
0
 public ExceptionUnexpectedAnalysisType(Analysis analysis)
 {
     InputAnalysis = analysis;
 }
Ejemplo n.º 57
0
        private IAnalysisSet DictionaryIterValues(Node node, Analysis.AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
            _keysAndValues.AddDependency(unit);

            if (_valuesIter == null) {
                _valuesIter = new IteratorInfo(
                    new[] { ValuesVariable },
                    unit.ProjectState.ClassInfos[BuiltinTypeId.DictValues],
                    node
                );
            }
            return _valuesIter;
        }
        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            lock (lockObject)
            {
                if (IsMeasuring)
                {
                    return;
                }
            }

            if (!IsHardwareValid)
            {
                RunningStatus = "硬件无效";
                return;
            }

            RunningStatus = "运行中";

            //复位示波器设置
            Scope.Disconnect();
            Scope.Connect();
            Scope.CHAScale      = SystemParamManager.SystemParam.GlobalParam.Scale;
            Scope.SampleRate    = SystemParamManager.SystemParam.GlobalParam.SampleRate;
            Scope.CHAVoltageDIV = SystemParamManager.SystemParam.GlobalParam.VoltageDIV;

            //设置电源模块直通
            PLC.PWMSwitch  = false;
            PLC.FlowSwitch = true;

            OnMeasurementStarted();

            measureThread = new Thread(() =>
            {
                lock (lockObject)
                {
                    IsMeasuring = true;
                }

                //设置频率
                PWM.Frequency = 0;
                PWM.DutyRatio = SystemParamManager.SystemParam.FrequencyMeasureParams.DutyRatio;

                //使能Power输出
                Power.Voltage        = SystemParamManager.SystemParam.FrequencyMeasureParams.OutputVoltage;
                Power.IsEnableOutput = true;
                Thread.Sleep(SystemParamManager.SystemParam.GlobalParam.PowerCommonDelay);

                //设置Scope采集时长
                Scope.SampleTime = SampleTime;

                //读取Scope数据
                double[] originalData;
                Scope.ReadDataBlock(0, out originalData);

                if ((originalData == null) || (originalData.Length == 0))
                {
                    //测试失败
                    OnMessageRaised(MessageLevel.Warning, $"F: ReadDataBlock Fail");
                    OnMeasurementCompleted(new ThroughputMeasurementCompletedEventArgs());
                    return;
                }

                //数据滤波
                double[] filterData;
                Analysis.MeanFilter(originalData, 7, out filterData);

                //电压转流量
                double[] pressureData = filterData.ToList().ConvertAll(x => VoltageToFlow(x)).ToArray();

                //获取平均值
                Flow = Analysis.Mean(pressureData);

                //显示结果
                ShowEdgeData(pressureData);

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                //测试成功
                OnMeasurementCompleted(new ThroughputMeasurementCompletedEventArgs(true, Flow));

                stopwatch.Stop();
            });

            measureThread.Start();
        }
Ejemplo n.º 59
0
 /// <summary>
 /// By calling this method a client can ensure that the sideband file will be created even
 /// if 0 paths are recorded for it.  If this method is not explicitly called, the sideband
 /// file will only be created if at least one write is recorded to it.
 /// </summary>
 public void EnsureHeaderWritten()
 {
     Analysis.IgnoreResult(m_lazyBxlWriter.Value);
 }
 public static AnalysisModelBase CreateAnalysisModel(Analysis analysis)
 {
     return(CreateAnalysisModel(analysis.Script.ScriptFileName, analysis.Dataset));
 }