Example #1
0
 public ZipFileSystem(string filePath, string rootPath)
 {
     _filePath = PathInfo.Create(filePath);
     _rootPath = PathInfo.Create(rootPath);
     _file = new ZipFile(filePath);
     _etag = new FileInfo(filePath).LastWriteTimeUtc.Ticks.ToString("X8");
 }
Example #2
0
        public static bool WritePath(Path3D pathInSpace, string pathName, string pathDescription = null, string outputFolderName = null, string ouputFolderPath = null)
        {
            outputFolderName = outputFolderName ?? DefaultFolderName;
            ouputFolderPath = ouputFolderPath ?? DefaultFolderPath;

            var directory = Directory.CreateDirectory(Path.Combine(ouputFolderPath, outputFolderName)); //if it doesn't exist create directory
            string filePath = Path.Combine(ouputFolderPath, outputFolderName, pathName + "." + FileExtension);

            if (string.IsNullOrWhiteSpace(pathName) || File.Exists(filePath))
                return false;

            var pathInfo = new PathInfo()
            {
                PathName = pathName,
                PathDescription = pathDescription ?? DefaultPathDetails,
                Path = pathInSpace.Points
            };

            string obj = JsonConvert.SerializeObject(pathInfo, Formatting.Indented);

            using (StreamWriter writer = new StreamWriter(filePath))
                writer.Write(obj);

            return true;
        }
    void Update()
    {
        //		List<Vector3> pathPos = new List<Vector3>();
        //		for (int n = 0; n < animPath.keyframes.Length; n++){
        //			Vector3 pos = animPath.keyframes[n].position;
        //			pathPos.Add(pos);
        //		}
        //		path = pathPos.ToArray();

        if(path == null || path.Length < 1){ return; }

        Shape sp = new Shape();

        sp.moveTo( path[0] );
        for(int n = 1; n < path.Length-1; n++)
        {
            Vector3 pos = Vector3.Lerp( path[n], path[n+1], 0.5f);
            sp.curveTo( path[n],  pos );
        }

        Vector3 posC = Vector3.Lerp( path[path.Length-2], path[path.Length-1], 0.5f);
        Vector3 posEnd = path[path.Length-1];
        sp.curveTo( posC,  posEnd );

        pathInfo = new PathInfo(sp.commands, sp.data);

        DrawLinePoints();

        //
        Point3D _p3d = pathInfo.lengthToPoint(t_length);
        p3D = new Vector3(_p3d.x, _p3d.y, _p3d.z);
    }
            public static PathInfo EnsurePathInfo(string path)
            {
                PathInfo pathInfo = (PathInfo)pathCache[path];
                if (pathInfo != null)
                {
                    return pathInfo;
                }

                lock (writeLock)
                {
                    pathInfo = (PathInfo)pathCache[path];
                    if (pathInfo != null)
                    {
                        return pathInfo;
                    }

                    if (HostingEnvironment.VirtualPathProvider.FileExists(path))
                    {
                        pathInfo = new PathInfo();
                        pathCache.Add(path, pathInfo);
                        return pathInfo;
                    }
                    else
                    {
                        throw FxTrace.Exception.AsError(new HttpException((int)HttpStatusCode.NotFound, SR.ResourceNotFound));
                    }
                }
            }
	    public ValidTemplateRouteConstraint(ITemplateRepository templateRepository, IFileSystem fileSystem,
			ITerrificNetConfig configuration)
		{
	        _templateRepository = templateRepository;
			_fileSystem = fileSystem;
	        _viewPathInfo = configuration.ViewPath;
		}
 public FileProjectItem(string kind, IFileInfo fileInfo, IFileSystem fileSystem, PathInfo subPath) 
     : base(subPath.ToString(), kind)
 {
     _subPath = subPath;
     _fileSystem = fileSystem;
     FileInfo = fileInfo;
 }
Example #7
0
		private Task Update(object content, PathInfo filePath)
		{
			using (var stream = new StreamWriter(_fileSystem.OpenWrite(filePath)))
			{
				var value = JsonConvert.SerializeObject(content, Formatting.Indented);
				return stream.WriteAsync(value);
			}
		}
		public Stream OpenRead(PathInfo filePath)
		{
			string resourceName;
			if (!_names.TryGetValue(filePath, out resourceName))
				throw new ArgumentException("Invalid file path");

			return _assembly.GetManifestResourceStream(resourceName);
		}
        public Task<bool> Exists(Uri path)
        {
            var pathInfo = new PathInfo(path);
            this.AssertIsValidWabsUri(pathInfo);

            StorageSimulatorItem result = this.GetItem(pathInfo);
            return Task.FromResult(result.IsNotNull());
        }
 public TerrificViewDefinitionRepository(IFileSystem fileSystem, 
     ITerrificNetConfig configuration,
     ITemplateRepository templateRepository,
     IModelTypeProvider typeProvider)
 {
     _fileSystem = fileSystem;
     _templateRepository = templateRepository;
     _typeProvider = typeProvider;
     _viewPathInfo = configuration.ViewPath;
 }
        public Task CreateContainerIfNotExists(string containerName)
        {
            containerName.ArgumentNotNullOrEmpty("containerName");
            var containerUri = new Uri(string.Format("{0}://{1}@{2}", Constants.WabsProtocol, containerName, this.Account.Host));
            var pathInfo = new PathInfo(containerUri);
            this.AssertIsValidWabsUri(pathInfo);
            this.CreateTree(pathInfo);

            return Task.Delay(0);
        }
        private async Task<JSchema> GetSchema(PathInfo path)
        {
            string content = null;
            using (var reader = new StreamReader(_fileSystem.OpenRead(path)))
            {
                content = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            return JsonConvert.DeserializeObject<JSchema>(content);
        }
Example #13
0
	    private async Task<object> GetModelFromPathAsync(PathInfo filePath)
        {
            if (!_fileSystem.FileExists(filePath))
                return null;

            using (var stream = new StreamReader(_fileSystem.OpenRead(filePath)))
            {
                var content = await stream.ReadToEndAsync().ConfigureAwait(false);
                return JsonConvert.DeserializeObject(content);
            }
        }
Example #14
0
		public FileSystem(string basePath)
		{
			if (string.IsNullOrEmpty(basePath))
				basePath = Environment.CurrentDirectory;

			_basePath = PathInfo.Create(basePath);
			_basePathConverted = basePath;

			Initialize();
			InitializeWatcher();
		}
Example #15
0
    public int AddPath(PathInfo newPath)
    {
        // add the struct 
        // get the value added at and then return

        //special case as trees are not walkable so
        if (!Walkable(Map, newPath.End))
            newPath.End = ClosestWalkable(newPath.End);
        Paths.Add(Paths.Count,newPath);
        return Paths.Count - 1;
    }
        private bool TryReadPageDefinition(out IPageViewDefinition viewDefinition, PathInfo fileName)
        {
            using (var reader = new JsonTextReader(new StreamReader(_fileSystem.OpenRead(fileName))))
            {
                viewDefinition = Deserialize(reader);

                if (viewDefinition == null)
                    return false;

                viewDefinition.Id = fileName.ToString();

                return true;
            }
        }
        public void Delete(Uri path)
        {
            var pathInfo = new PathInfo(path);

            if (pathInfo.Path.IsNullOrEmpty())
            {
                throw new InvalidOperationException("An attempt was made to delete a container.  Containers can not be deleted via this API.");
            }
            this.AssertIsValidWabsUri(pathInfo);

            StorageSimulatorItem item = this.GetItem(pathInfo, true);
            if (item.IsNotNull() && item.Items.ContainsKey(pathInfo.PathParts[pathInfo.PathParts.Length - 1]))
            {
                item.Items.Remove(pathInfo.PathParts[pathInfo.PathParts.Length - 1]);
            }
        }
Example #18
0
        public Int32 GetPathID(PathInfo path)
        {
            if (null == path)
                return -1;
            if (null == path.Name) // user password can be null
                return -1;

            String pathName = path.Name.Trim();
            if (pathName.Length == 0)
                return -1;

            String pathPwd = "";
            if (null != path.Password)
                pathPwd = path.Password;

            return mDataAccesser.GetPathID(pathName, pathPwd);
            //return 5;
        }
Example #19
0
    public SearchAStar(SparseGraph<NavGraphNode, GraphEdge> graph
        , int source
        , int target
        , bool isignorewall
        , float strickdistance
        , float hcostpercentage
        , bool drawexplorepath
        , float explorepathremaintime)
    {
        mGraph = graph;
        mPQ = new PriorityQueue<int, float>((int)Mathf.Sqrt(mGraph.NumNodes()));
        mGCosts = new List<float>(graph.NumNodes());
        mFCosts = new List<Pair<int, float>>(graph.NumNodes());
        mShortestPathTree = new List<GraphEdge>(graph.NumNodes());
        mSearchFrontier = new List<GraphEdge>(graph.NumNodes());
        //Init G cost and F cost and Cost value
        for (int i = 0; i < graph.NumNodes(); i++)
        {
            mGCosts.Add(0.0f);
            mFCosts.Add(new Pair<int, float>(i, 0.0f));
            mShortestPathTree.Add(new GraphEdge());
            mSearchFrontier.Add(new GraphEdge());
        }
        mISource = source;
        mITarget = target;
        mOriginalTarget = target;

        Assert.IsTrue(hcostpercentage >= 0);
        mHCostPercentage = hcostpercentage;

        mBDrawExplorePath = drawexplorepath;

        mExplorePathRemainTime = explorepathremaintime;

        mAStarPathInfo = new PathInfo();

        mIsIgnoreWall = isignorewall;

        mStrickDistance = strickdistance;

        //Search(mStrickDistance, mIsIgnoreWall);

        //GeneratePathToTargetInfo();
    }
 public Task<IEnumerable<Uri>> List(Uri path, bool recursive)
 {
     var items = new List<Uri>();
     var queue = new Queue<StorageSimulatorItem>();
     var pathInfo = new PathInfo(path);
     this.AssertIsValidWabsUri(pathInfo);
     StorageSimulatorItem item = this.GetItem(pathInfo, pathInfo.Path.IsNullOrEmpty());
     if (item.IsNotNull())
     {
         queue.Enqueue(item);
         while (queue.Count > 0)
         {
             item = queue.Remove();
             queue.AddRange(item.Items.Values);
             items.Add(item.Path);
         }
     }
     return Task.FromResult((IEnumerable<Uri>)items);
 }
Example #21
0
            public PathParser(string dv)
            {
                // Just parse the string directly.
                curLoc = 0;
                dataValue = dv;
                pathData = new List<PathInfo>();
                while (!atEnd())
                {
                    SegmentType? ft = getSegmentType();
                    if (ft.HasValue)
                    {
                        PathInfo pi = new PathInfo(ft.Value);
                        pathData.Add(pi);
                        switch (ft.Value)
                        {
                            case SegmentType.Move:
                                pi.point = getPoint();
                                break;
                            case SegmentType.Line:
                                pi.point = getPoint();
                                break;
                            case SegmentType.Close:
                                break;
                            case SegmentType.Arc:
                                pi.size = getPoint();
                                eatWhitespace();
                                pi.angle = getDouble();
                                eatWhitespace();
                                pi.isLargeArc = getBoolean();
                                eatWhitespace();
                                eatOneOptionalComma();
                                eatWhitespace();
                                pi.isSweepDirectionClockwise = getBoolean();
                                eatWhitespace();
                                pi.point = getPoint();

                                break;
                            default:
                                break;
                        }
                    }
                }
            }
Example #22
0
        public bool CreateNewPath(PathInfo path, UserInfo user)
        {
            if (null == path || null == user)
                return false;
            if (null == path.Name
                || null == user.Name) // user password can be null
                return false;

            String pathName = path.Name.Trim();
            if (pathName.Length == 0)
                return false;

            String pathPassword = "";
            if(null != path.Password)
                pathPassword = path.Password;

            // Verify the user.

            // Create path

            return mDataAccesser.AddNewPath(pathName, pathPassword, user.Name);
            //return true;
        }
Example #23
0
        private void ParseParameters(Configuration configuration, IFileSystem fileSystem, PathInfo currentFileSystemLocation)
        {
            configuration.FeatureFolder = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.FeatureDirectory);
            configuration.OutputFolder  = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.OutputDirectory);

            if (!string.IsNullOrEmpty(this.TestResultsFormat))
            {
                configuration.TestResultsFormat =
                    (TestResultsFormat)Enum.Parse(typeof(TestResultsFormat), this.TestResultsFormat, true);
            }

            if (!string.IsNullOrEmpty(this.TestResultsFile))
            {
                configuration.AddTestResultFile(fileSystem.FileInfo.FromFileName(this.TestResultsFile));
            }

            configuration.SystemUnderTestName    = this.SystemUnderTestName;
            configuration.SystemUnderTestVersion = this.SystemUnderTestVersion;
            if (!string.IsNullOrEmpty(this.DocumentationFormat))
            {
                configuration.DocumentationFormat = (DocumentationFormat)Enum.Parse(typeof(DocumentationFormat), this.DocumentationFormat, true);
            }

            if (!string.IsNullOrEmpty(this.Language))
            {
                configuration.Language = this.Language;
            }
        }
        } // GetContentReaders

        /// <summary>
        /// Resolves the specified paths to PathInfo objects
        /// </summary>
        ///
        /// <param name="pathsToResolve">
        /// The paths to be resolved. Each path may contain glob characters.
        /// </param>
        ///
        /// <param name="allowNonexistingPaths">
        /// If true, resolves the path even if it doesn't exist.
        /// </param>
        ///
        /// <param name="allowEmptyResult">
        /// If true, allows a wildcard that returns no results.
        /// </param>
        ///
        /// <param name="currentCommandContext">
        /// The context under which the command is running.
        /// </param>
        ///
        /// <returns>
        /// An array of PathInfo objects that are the resolved paths for the
        /// <paramref name="pathsToResolve"/> parameter.
        /// </returns>
        ///
        internal Collection <PathInfo> ResolvePaths(
            string[] pathsToResolve,
            bool allowNonexistingPaths,
            bool allowEmptyResult,
            CmdletProviderContext currentCommandContext)
        {
            Collection <PathInfo> results = new Collection <PathInfo>();

            foreach (string path in pathsToResolve)
            {
                bool pathNotFound   = false;
                bool filtersHidPath = false;

                ErrorRecord pathNotFoundErrorRecord = null;

                try
                {
                    // First resolve each of the paths
                    Collection <PathInfo> pathInfos =
                        SessionState.Path.GetResolvedPSPathFromPSPath(
                            path,
                            currentCommandContext);

                    if (pathInfos.Count == 0)
                    {
                        pathNotFound = true;

                        // If the item simply did not exist,
                        // we would have got an ItemNotFoundException.
                        // If we get here, it's because the filters
                        // excluded the file.
                        if (!currentCommandContext.SuppressWildcardExpansion)
                        {
                            filtersHidPath = true;
                        }
                    }

                    foreach (PathInfo pathInfo in pathInfos)
                    {
                        results.Add(pathInfo);
                    }
                }
                catch (PSNotSupportedException notSupported)
                {
                    WriteError(
                        new ErrorRecord(
                            notSupported.ErrorRecord,
                            notSupported));
                }
                catch (DriveNotFoundException driveNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            driveNotFound.ErrorRecord,
                            driveNotFound));
                }
                catch (ProviderNotFoundException providerNotFound)
                {
                    WriteError(
                        new ErrorRecord(
                            providerNotFound.ErrorRecord,
                            providerNotFound));
                }
                catch (ItemNotFoundException pathNotFoundException)
                {
                    pathNotFound            = true;
                    pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException);
                }

                if (pathNotFound)
                {
                    if (allowNonexistingPaths &&
                        (!filtersHidPath) &&
                        (currentCommandContext.SuppressWildcardExpansion ||
                         (!WildcardPattern.ContainsWildcardCharacters(path))))
                    {
                        ProviderInfo provider       = null;
                        PSDriveInfo  drive          = null;
                        string       unresolvedPath =
                            SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                                path,
                                currentCommandContext,
                                out provider,
                                out drive);

                        PathInfo pathInfo =
                            new PathInfo(
                                drive,
                                provider,
                                unresolvedPath,
                                SessionState);
                        results.Add(pathInfo);
                    }
                    else
                    {
                        if (pathNotFoundErrorRecord == null)
                        {
                            // Detect if the path resolution failed to resolve to a file.
                            String    error = StringUtil.Format(NavigationResources.ItemNotFound, Path);
                            Exception e     = new Exception(error);

                            pathNotFoundErrorRecord = new ErrorRecord(
                                e,
                                "ItemNotFound",
                                ErrorCategory.ObjectNotFound,
                                Path);
                        }

                        WriteError(pathNotFoundErrorRecord);
                    }
                }
            }

            return(results);
        } // ResolvePaths
Example #25
0
        public static GMFile /* errors: different return type? */ ReadFile(string baseDir, JsonData projFile)
        {
            var f = new GMFile();

            // OBJT: depends on SPRT, obj<->id map
            // ROOM: depends on OBJT, BGND
            // SCPT: depends on CODE

            if (projFile.Has("chunkorder") && projFile["chunkorder"].IsArray)
            {
                f.ChunkOrder = DeserializeArray(projFile["chunkorder"], jd => SectionHeadersExtensions.FromChunkName((string)jd));
            }
            else
            {
                Console.Error.WriteLine("Warning: Project file doesn't have a chunk order. You should export with a newer Altar.NET version.");
                f.ChunkOrder = new SectionHeaders[] {
                    SectionHeaders.General,
                    SectionHeaders.Options,
                    SectionHeaders.Language,
                    SectionHeaders.Extensions,
                    SectionHeaders.Sounds,
                    SectionHeaders.AudioGroup,
                    SectionHeaders.Sprites,
                    SectionHeaders.Backgrounds,
                    SectionHeaders.Paths,
                    SectionHeaders.Scripts,
                    SectionHeaders.Globals,
                    SectionHeaders.Shaders,
                    SectionHeaders.Fonts,
                    SectionHeaders.Timelines,
                    SectionHeaders.Objects,
                    SectionHeaders.Rooms,
                    SectionHeaders.DataFiles,
                    SectionHeaders.TexturePage,
                    SectionHeaders.Code,
                    SectionHeaders.Variables,
                    SectionHeaders.Functions,
                    SectionHeaders.Strings,
                    SectionHeaders.Textures,
                    SectionHeaders.Audio,
                    SectionHeaders.EmbedImage,
                };
            }

            if (projFile.Has("general"))
            {
                Console.WriteLine("Loading general...");
                try
                {
                    f.General = DeserializeGeneral(LoadJson(baseDir, (string)(projFile["general"])));
                    if (f.General.Version >= new Version(2, 0))
                    {
                        Console.Error.WriteLine("Warning: GM:S 2.0 support is incomplete!");
                    }
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error loading general");
                    throw;
                }
            }
            if (projFile.Has("options"))
            {
                Console.WriteLine("Loading options...");
                try
                {
                    f.Options = DeserializeOptions(LoadJson(baseDir, (string)(projFile["options"])));
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error loading options");
                    throw;
                }
            }
            if (projFile.Has("strings"))
            {
                Console.WriteLine("Loading strings...");
                try
                {
                    f.Strings = DeserializeArray(LoadJson(baseDir, (string)(projFile["strings"])), jd => (string)jd);
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error loading strings");
                    throw;
                }
            }

            var variables = new ReferenceDef[0];
            var functions = new ReferenceDef[0];

            if (projFile.Has("variables"))
            {
                Console.WriteLine("Loading variables...");
                try
                {
                    var vardata = LoadJson(baseDir, (string)(projFile["variables"]));
                    variables = DeserializeArray(vardata.IsArray ? vardata : vardata["variables"], DeserializeReferenceDef);
                    if (vardata.Has("extra"))
                    {
                        f.VariableExtra = DeserializeArray(vardata["extra"], jd => (uint)jd);
                    }
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error loading variables");
                    throw;
                }
            }
            if (projFile.Has("functions"))
            {
                Console.WriteLine("Loading functions...");
                try
                {
                    var funcdata = LoadJson(baseDir, (string)(projFile["functions"]));
                    functions = DeserializeArray(funcdata.IsArray ? funcdata : funcdata["functions"], DeserializeReferenceDef);
                    if (funcdata.Has("locals"))
                    {
                        f.FunctionLocals = DeserializeArray(funcdata["locals"], DeserializeFuncLocals);
                    }
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error loading functions");
                    throw;
                }
            }
            f.RefData = new RefData {
                Variables = variables, Functions = functions
            };

            if (projFile.Has("textures"))
            {
                Console.WriteLine("Loading textures...");
                var textures = projFile["textures"].ToArray();
                var ts       = new TextureInfo[textures.Length];
                for (int i = 0; i < textures.Length; i++)
                {
                    try
                    {
                        var texinfo = new TextureInfo
                        {
                            PngData = File.ReadAllBytes(Path.Combine(baseDir, (string)(textures[i])))
                        };

                        var bp = new UniquePtr(texinfo.PngData);

                        unsafe
                        {
                            var png = (PngHeader *)bp.BPtr;

                            texinfo.Width  = Utils.SwapEnd32(png->IHDR.Width);
                            texinfo.Height = Utils.SwapEnd32(png->IHDR.Height);
                        }

                        ts[i] = texinfo;
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {textures[i]}");
                        throw;
                    }
                }
                f.Textures = ts;
            }
            if (projFile.Has("tpags"))
            {
                Console.Write("Loading texture pages... ");
                var cl = Console.CursorLeft;
                var ct = Console.CursorTop;

                var tpags = projFile["tpags"].ToArray();
                var tps   = new TexturePageInfo[tpags.Length];
                for (int i = 0; i < tpags.Length; i++)
                {
                    Console.SetCursorPosition(cl, ct);
                    Console.WriteLine(O_PAREN + (i + 1) + SLASH + tpags.Length + C_PAREN);
                    try
                    {
                        tps[i] = DeserializeTPag(LoadJson(baseDir, (string)(tpags[i])));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {tpags[i]}");
                        throw;
                    }
                }
                f.TexturePages = tps;
            }
            if (projFile.Has("audio"))
            {
                Console.WriteLine("Loading audio...");
                var audio = projFile["audio"].ToArray();
                var ais   = new AudioInfo[audio.Length];
                for (int i = 0; i < audio.Length; i++)
                {
                    try
                    {
                        var audioinfo = new AudioInfo
                        {
                            Wave = File.ReadAllBytes(Path.Combine(baseDir, (string)(audio[i])))
                        };
                        ais[i] = audioinfo;
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {audio[i]}");
                        throw;
                    }
                }
                f.Audio = ais;
            }
            if (projFile.Has("sprites"))
            {
                Console.Write("Loading sprites... ");
                var cl = Console.CursorLeft;
                var ct = Console.CursorTop;

                var sprites = projFile["sprites"].ToArray();
                var ss      = new SpriteInfo[sprites.Length];
                for (int i = 0; i < sprites.Length; i++)
                {
                    Console.SetCursorPosition(cl, ct);
                    Console.WriteLine(O_PAREN + (i + 1) + SLASH + sprites.Length + C_PAREN);
                    try
                    {
                        ss[i]      = DeserializeSprite(LoadJson(baseDir, (string)(sprites[i])));
                        ss[i].Name = Path.GetFileNameWithoutExtension((string)(sprites[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {sprites[i]}");
                        throw;
                    }
                }
                f.Sprites = ss;
            }
            if (projFile.Has("objs"))
            {
                Console.Write("Loading objects... ");
                var cl = Console.CursorLeft;
                var ct = Console.CursorTop;

                var objs     = projFile["objs"].ToArray();
                var objNames = objs.Select(o => Path.GetFileNameWithoutExtension((string)o)).ToArray();
                var os       = new ObjectInfo[objs.Length];
                for (int i = 0; i < objs.Length; i++)
                {
                    Console.SetCursorPosition(cl, ct);
                    Console.WriteLine(O_PAREN + (i + 1) + SLASH + objs.Length + C_PAREN);
                    try
                    {
                        os[i] = DeserializeObj(
                            LoadJson(baseDir, (string)(objs[i])),
                            f.Sprites,
                            s => (uint)Array.IndexOf(objNames, s));
                        os[i].Name = objNames[i];
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {objs[i]}");
                        throw;
                    }
                }
                f.Objects = os;
            }
            if (projFile.Has("code"))
            {
                Console.WriteLine("Loading code...");
                var code = projFile["code"].ToArray();
                var cs   = new CodeInfo[code.Length];

                var strings = new StringsListBuilder();
                strings.AddStrings(f.Strings);
                IDictionary <string, uint> objectIndices = new Dictionary <string, uint>(f.Objects.Length);
                for (uint i = 0; i < f.Objects.Length; i++)
                {
                    objectIndices[f.Objects[i].Name] = i;
                }

                for (int i = 0; i < code.Length; i++)
                {
                    Console.WriteLine((string)(code[i]));
                    try
                    {
                        cs[i] = Assembler.DeserializeCodeFromFile(Path.Combine(baseDir, (string)(code[i])), f.General.BytecodeVersion,
                                                                  strings, objectIndices);
                        cs[i].Name          = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension((string)(code[i])));
                        cs[i].ArgumentCount = 1;
                        if (f.FunctionLocals != null)
                        {
                            for (int j = 0; j < f.FunctionLocals.Length; j++)
                            {
                                int fastIndex = (j + i) % f.FunctionLocals.Length;
                                if (f.FunctionLocals[fastIndex].FunctionName == cs[i].Name)
                                {
                                    cs[i].ArgumentCount = f.FunctionLocals[fastIndex].LocalNames.Length;
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {code[i]}");
                        throw;
                    }
                }
                f.Code = cs;

                f.Strings = strings.GetStrings();
            }
            if (projFile.Has("sounds"))
            {
                Console.WriteLine("Loading sounds...");
                var sounds = projFile["sounds"].ToArray();
                var ss     = new SoundInfo[sounds.Length];
                for (int i = 0; i < sounds.Length; i++)
                {
                    try
                    {
                        ss[i]      = DeserializeSound(LoadJson(baseDir, (string)(sounds[i])));
                        ss[i].Name = Path.GetFileNameWithoutExtension((string)(sounds[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {sounds[i]}");
                        throw;
                    }
                }
                f.Sound = ss;
            }
            if (projFile.Has("bg"))
            {
                Console.WriteLine("Loading backgrounds...");
                var bg = projFile["bg"].ToArray();
                var bs = new BackgroundInfo[bg.Length];
                for (int i = 0; i < bg.Length; i++)
                {
                    try
                    {
                        bs[i]      = DeserializeBg(LoadJson(baseDir, (string)(bg[i])));
                        bs[i].Name = Path.GetFileNameWithoutExtension((string)(bg[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {bg[i]}");
                        throw;
                    }
                }
                f.Backgrounds = bs;
            }
            if (projFile.Has("paths"))
            {
                Console.WriteLine("Loading paths...");
                var paths = projFile["paths"].ToArray();
                var ps    = new PathInfo[paths.Length];
                for (int i = 0; i < paths.Length; i++)
                {
                    try
                    {
                        ps[i]      = DeserializePath(LoadJson(baseDir, (string)(paths[i])));
                        ps[i].Name = Path.GetFileNameWithoutExtension((string)(paths[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {paths[i]}");
                        throw;
                    }
                }
                f.Paths = ps;
            }
            if (projFile.Has("scripts"))
            {
                Console.WriteLine("Loading scripts...");
                var scripts = projFile["scripts"].ToArray();
                var ss      = new ScriptInfo[scripts.Length];
                for (int i = 0; i < scripts.Length; i++)
                {
                    try
                    {
                        ss[i]      = DeserializeScript(LoadJson(baseDir, (string)(scripts[i])), f.Code);
                        ss[i].Name = Path.GetFileNameWithoutExtension((string)(scripts[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {scripts[i]}");
                        throw;
                    }
                }
                f.Scripts = ss;
            }
            if (projFile.Has("fonts"))
            {
                Console.WriteLine("Loading fonts...");
                var fonts = projFile["fonts"].ToArray();
                var fs    = new FontInfo[fonts.Length];
                for (int i = 0; i < fonts.Length; i++)
                {
                    try
                    {
                        fs[i]          = DeserializeFont(LoadJson(baseDir, (string)(fonts[i])));
                        fs[i].CodeName = Path.GetFileNameWithoutExtension((string)(fonts[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {fonts[i]}");
                        throw;
                    }
                }
                f.Fonts = fs;
            }
            if (projFile.Has("rooms"))
            {
                Console.Write("Loading rooms... ");
                var cl = Console.CursorLeft;
                var ct = Console.CursorTop;

                var rooms = projFile["rooms"].ToArray();
                var rs    = new RoomInfo[rooms.Length];
                for (int i = 0; i < rooms.Length; i++)
                {
                    Console.SetCursorPosition(cl, ct);
                    Console.WriteLine(O_PAREN + (i + 1) + SLASH + rooms.Length + C_PAREN);
                    try
                    {
                        rs[i]      = DeserializeRoom(LoadJson(baseDir, (string)(rooms[i])), f.Backgrounds, f.Objects);
                        rs[i].Name = Path.GetFileNameWithoutExtension((string)(rooms[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {rooms[i]}");
                        throw;
                    }
                }
                f.Rooms = rs;
            }
            if (projFile.Has("audiogroups"))
            {
                Console.WriteLine("Loading audio groups...");
                try
                {
                    f.AudioGroups = DeserializeArray(LoadJson(baseDir, (string)(projFile["audiogroups"])), jd => (string)jd);
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("Error loading audio groups");
                    throw;
                }
            }
            if (projFile.Has("shaders"))
            {
                Console.WriteLine("Loading shaders...");
                var shaders = projFile["shaders"].ToArray();
                var ss      = new ShaderInfo[shaders.Length];
                for (int i = 0; i < shaders.Length; i++)
                {
                    try
                    {
                        ss[i]      = DeserializeShader(LoadJson(baseDir, (string)(shaders[i])));
                        ss[i].Name = Path.GetFileNameWithoutExtension((string)(shaders[i]));
                    }
                    catch (Exception)
                    {
                        Console.Error.WriteLine($"Error loading {shaders[i]}");
                        throw;
                    }
                }
                f.Shaders = ss;
            }
            return(f);
        }
Example #26
0
 internal PathInfoEx(PathInfo pathInfo)
 {
     _PathInfo = pathInfo;
 }
Example #27
0
 private PathInfo GetTemplateId(PathInfo info)
 {
     return(_fileSystem.Path.Combine(_fileSystem.Path.GetDirectoryName(info), _fileSystem.Path.GetFileNameWithoutExtension(info)));
 }
Example #28
0
        private void FindAndCaculateFromAdvancedStatic(GridSimulationData simData)
        {
            // Instead of using uniform distribution of support between all fixed nodes, calculate non-uniform distribution based on vectors for few closest nodes
            // Use this distribution when setting support weight and transferring mass
            // SupportingWeights: x * support
            // ? TransferMass: x * numStaticBlocksForCurrentDynamicBlock * TransferMass

            int keepLookingDistance = (int)ClosestDistanceThreshold; // How far keep looking when closest static block is found

            simData.Queue.Clear();

            // Set initial distance to max for all dynamic
            foreach (var dyn in simData.DynamicBlocks)
            {
                dyn.Distance = int.MaxValue;
            }

            // Wide search from all static blocks
            foreach (var stat in simData.StaticBlocks)
            {
                stat.Distance = 0;
                var path = new PathInfo()
                {
                    EndNode = stat, StartNode = stat, Distance = 0, DirectionRatio = 1
                };
#if ENHANCED_DEBUG
                path.PathNodes.Add(stat);
#endif
                simData.Queue.Enqueue(path);
            }

            while (simData.Queue.Count > 0)
            {
                var path = simData.Queue.Dequeue();
                foreach (var neighbour in path.EndNode.Neighbours)
                {
                    if (neighbour.IsStatic)
                    {
                        continue;
                    }

                    PathInfo neighbourPath;
                    if (!neighbour.Paths.TryGetValue(path.StartNode, out neighbourPath))
                    {
                        if ((path.Distance - keepLookingDistance) <= neighbour.Distance)
                        {
                            neighbour.Distance = Math.Min(neighbour.Distance, path.Distance);

                            neighbourPath           = new PathInfo();
                            neighbourPath.Distance  = path.Distance + 1;
                            neighbourPath.StartNode = path.StartNode;
                            neighbourPath.EndNode   = neighbour;
#if ENHANCED_DEBUG
                            neighbourPath.PathNodes = path.PathNodes.ToList();
                            neighbourPath.PathNodes.Add(neighbour);
#endif
                            neighbourPath.Parents.Add(path);
                            float t = neighbour.PhysicalMaterial.HorisontalTransmissionMultiplier * path.EndNode.PhysicalMaterial.HorisontalTransmissionMultiplier;

                            float massRatio = MathHelper.Clamp(path.EndNode.Mass / (neighbour.Mass + path.EndNode.Mass), 0, 1);

                            t *= neighbour.Mass * massRatio; //Horisontal transmission is very low on weak objects (floor, roof). Should be correctly get from mount point area
                            float[] horisontalTransmission = new float[] { t, 1, t };

                            int component = ((Vector3D)(neighbour.Pos - path.EndNode.Pos)).AbsMaxComponent();
                            neighbourPath.DirectionRatio = path.DirectionRatio * DirectionRatios[component] * horisontalTransmission[component];
                            neighbour.Paths.Add(path.StartNode, neighbourPath);
                            simData.Queue.Enqueue(neighbourPath);
                            path.StartNode.OwnedPaths.Push(neighbourPath);
                        }
                    }
                    else if (neighbourPath.Distance == path.Distance + 1) // Another path with same length
                    {
                        neighbourPath.Parents.Add(path);
                    }
                }
            }



            // Iterate all dynamic blocks and calculate support ratio for each static
            foreach (var dyn in simData.DynamicBlocks)
            {
                dyn.PathCount = 1;

                if (dyn.Pos == new Vector3I(-6, 6, 0))
                {
                }
                // Uniform distribution
                //foreach (var s in dyn.Paths)
                //{
                //    s.Value.Ratio = 1.0f / dyn.Paths.Count;
                //}
                //continue;

                // Non-uniform distribution
                // Calculate angle between one vector and all other
                // Split weight support based on sum angle ratio
                float totalAngles = 0;
                if (dyn.Paths.Count > 1)
                {
                    foreach (var s in dyn.Paths)
                    {
                        Vector3 localVector1 = (dyn.Pos - s.Value.StartNode.Pos) * m_grid.GridSize;
                        Vector3 worldVector1 = Vector3.TransformNormal(localVector1, m_grid.WorldMatrix);

                        // float sumAngle = 0;
                        float sumAngleReduced = 0;
                        foreach (var s2 in dyn.Paths)
                        {
                            if (s.Key == s2.Key)
                            {
                                continue;
                            }

                            Vector3 localVector2 = (dyn.Pos - s2.Value.StartNode.Pos) * m_grid.GridSize;
                            Vector3 worldVector2 = Vector3.TransformNormal(localVector2, m_grid.WorldMatrix);
                            float   angle        = MyUtils.GetAngleBetweenVectorsAndNormalise(worldVector1, worldVector2);

                            float dot1 = Math.Abs(Vector3.Normalize(worldVector1).Dot(Vector3.Up));
                            float dot2 = Math.Abs(Vector3.Normalize(worldVector2).Dot(Vector3.Up));

                            float lowerBound = 0.1f;
                            dot1 = MathHelper.Lerp(lowerBound, 1, dot1);
                            dot2 = MathHelper.Lerp(lowerBound, 1, dot2);

                            float reducedAngle = angle;

                            if (!MyPetaInputComponent.OLD_SI)
                            {
                                //Reduce dependent on gravity
                                reducedAngle = angle * dot1 * s.Value.DirectionRatio;
                            }

                            //sumAngle += angle;
                            sumAngleReduced += reducedAngle;
                        }
                        s.Value.Ratio = sumAngleReduced;
                        totalAngles  += sumAngleReduced;
                    }

                    foreach (var s in dyn.Paths)
                    {
                        if (totalAngles > 0)
                        {
                            s.Value.Ratio /= totalAngles;
                            if (s.Value.Ratio < 0.000001f)
                            {
                                s.Value.Ratio = 0;
                            }
                        }
                        else
                        {
                            s.Value.Ratio = 1;
                        }
                    }
                }
                else
                {
                    foreach (var s in dyn.Paths)
                    {
                        s.Value.Ratio = 1.0f;
                    }
                }
            }

            // Iterate all static blocks and calculate support mass and mass transfer
            foreach (var staticBlock in simData.StaticBlocks)
            {
                // Initial mass and ratio
                foreach (var path in staticBlock.OwnedPaths)
                {
                    path.EndNode.TransferMass = 0;
                }

                // For each block in path (ordered by distance, furthest first)
                while (staticBlock.OwnedPaths.Count > 0)
                {
                    var pathInfo = staticBlock.OwnedPaths.Pop();
                    var node     = pathInfo.EndNode;

                    Debug.Assert(pathInfo.StartNode == staticBlock, "Wrong path");
                    Debug.Assert(!node.IsStatic, "Static node unexpected");

                    float outgoing = node.TransferMass + node.Mass * pathInfo.Ratio;
                    //float outgoindTotal = 0;
                    //foreach (var p in pathInfo.Parents)
                    //    outgoindTotal += p.DirectionRatio;

                    if (node.Pos == new Vector3I(-1, 1, 0))
                    {
                    }


                    float outgoingPerParent = outgoing / pathInfo.Parents.Count;

                    foreach (var parent in pathInfo.Parents)
                    {
                        var delta = parent.EndNode.Pos - node.Pos; // Node to parent
                        int index, parentIndex;
                        if (delta.X + delta.Y + delta.Z > 0)
                        {
                            index       = delta.Y + delta.Z * 2; // UnitX = 0, UnitY = 1, UnitZ = 2
                            parentIndex = index + 3;
                        }
                        else
                        {
                            index       = -delta.X * 3 - delta.Y * 4 - delta.Z * 5; // // -UnitX = 3, -UnitY = 4, -UnitZ = 5
                            parentIndex = index - 3;
                        }

                        //outgoingPerParent = outgoing * parent.DirectionRatio / outgoindTotal;

#if ENHANCED_DEBUG
                        node.OutgoingNodeswWithWeights[index].Add(new Tuple <Node, float>(parent.EndNode, outgoingPerParent));
#endif
                        if (index == 0 || index == 2 || index == 3 || index == 5)
                        {
                            node.SupportingWeights[index] -= node.PhysicalMaterial.HorisontalFragility * outgoingPerParent;
                        }
                        else
                        {
                            node.SupportingWeights[index] -= outgoingPerParent;
                        }

                        if (parentIndex == 0 || parentIndex == 2 || parentIndex == 3 || parentIndex == 5)
                        {
                            parent.EndNode.SupportingWeights[parentIndex] += parent.EndNode.PhysicalMaterial.HorisontalFragility * outgoingPerParent;
                        }
                        else
                        {
                            parent.EndNode.SupportingWeights[parentIndex] += outgoingPerParent;
                        }
#if ENHANCED_DEBUG
                        parent.EndNode.SupportingNodeswWithWeights[parentIndex].Add(new Tuple <Node, float>(node, outgoingPerParent));
#endif


                        parent.EndNode.TransferMass += outgoingPerParent;
                    }
                    node.TransferMass -= outgoing;
                }
            }


            using (Stats.Timing.Measure("SI - Sum", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag))
            {
                foreach (var node in simData.All)
                {
                    //node.Value.TotalSupportingWeight = 0;
                }

                foreach (var node in simData.All)
                {
                    if (node.Key == new Vector3I(-1, 1, 0))
                    {
                    }

                    float sum = 0;
                    for (int i = 0; i < 6; i++)
                    {
                        float sideWeight = node.Value.SupportingWeights[i];

                        sum += Math.Abs(sideWeight);
                        //sum = Math.Max(sum, Math.Abs(node.Value.SupportingWeights[i]));
                    }

                    if (!(sum == 0 && node.Value.PathCount == 0))
                    {
                        // sum = sum * 2 - 1;
                        node.Value.TotalSupportingWeight += node.Value.IsStatic ? 0 : (sum * 0.5f / node.Value.PathCount);
                    }
                }

                // Idea behind blur:
                // When block is supporting too much weight, it deforms still supports something, but allows neighbour block to support more weight, thus sharing support
                List <Node> supportingNeighbours = new List <Node>();
                foreach (var node in simData.All)
                {
                    supportingNeighbours.Clear();

                    float totalSharedSupport = node.Value.TotalSupportingWeight;
                    float totalMass          = node.Value.Mass;

                    foreach (var neighbour in node.Value.Neighbours)
                    {
                        bool isHorisontalNeighbour = neighbour.Pos.Y == node.Key.Y;
                        bool isVerticallySupported = neighbour.Paths.Any(x => (x.Key.Pos.X == node.Key.X && x.Key.Pos.Z == node.Key.Z));

                        if (isHorisontalNeighbour && isVerticallySupported)
                        {
                            totalSharedSupport += neighbour.TotalSupportingWeight;
                            totalMass          += neighbour.Mass;
                            supportingNeighbours.Add(neighbour);
                        }
                    }

                    if (supportingNeighbours.Count > 0)
                    {
                        float supportPerNode = totalSharedSupport / totalMass;
                        foreach (var neighbour in supportingNeighbours)
                        {
                            neighbour.TotalSupportingWeight = supportPerNode * neighbour.Mass;
                        }
                        node.Value.TotalSupportingWeight = supportPerNode * node.Value.Mass;
                    }
                }

                foreach (var node in simData.All)
                {
                    simData.TotalMax = Math.Max(simData.TotalMax, node.Value.TotalSupportingWeight);
                }

                // var timeMs = (Stopwatch.GetTimestamp() - ts) / (float)Stopwatch.Frequency * 1000.0f;
                //Console.WriteLine(String.Format("Generated structural integrity, time: {0}ms, object name: {1}", timeMs, m_grid.ToString()));
            }
        }
 public Add_AttachmentControl(OOBInfo oobInfo, LocalisationInfo localisationModel, PathInfo pathInfo, string countryCode, List <MilitaryTypeInfo> militaryTypeList)
 {
     InitializeComponent();
     this.oobInfo           = oobInfo;
     this.localisationModel = localisationModel;
     this.pathInfo          = pathInfo;
     this.countryCode       = countryCode;
     this.militaryTypeList  = militaryTypeList;
     Bind();
     BindAttType();
 }
 private PathInfo[] ProcessPaths(System.Type activityType, PathInfo topProperty)
 {
     List<PathInfo> list = new List<PathInfo>();
     if (topProperty == null)
     {
         list.AddRange(this.GetSubPropertiesOnType(activityType, string.Empty));
     }
     else
     {
         list.AddRange(this.GetSubPropertiesOnType(topProperty.PropertyType, topProperty.Path));
     }
     return list.ToArray();
 }
Example #31
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                int    typeId      = int.Parse(context.Request["typeId"]);    //治具种类id
                int    temFixId    = int.Parse(context.Request["temFixId"]);  //临时治具ID
                string fixOrderNum = context.Request["fixOrderNum"];          //治具订单编号
                string name        = context.Request["name"];                 //治具名称//唯一
                string venderName  = context.Request["venderName"];           //厂家名称,默认给"JD"
                string desc        = context.Request["desc"];                 //描述
                string remark      = context.Request["remark"];               //备注
                int    currCount   = int.Parse(context.Request["currCount"]); //当前库存
                int    allCount    = int.Parse(context.Request["allCount"]);  //库存总量
                var    file        = context.Request.Files;                   //文件
                using (FixtureModel model = new FixtureModel())
                {
                    var fx = model.JDJS_WMS_Fixture_System_Table.Where(r => r.Name == name).FirstOrDefault();
                    if (fx != null)
                    {
                        context.Response.Write("该治具名称已存在!");
                        return;
                    }
                    if (file.Count < 1)
                    {
                        context.Response.Write("请输入文件!");
                        return;
                    }
                    int fxNum = 1;
                    fx = model.JDJS_WMS_Fixture_System_Table.Where(r => r.FXNum == fxNum).FirstOrDefault();
                    while (fx != null)
                    {
                        fxNum++;
                        fx = model.JDJS_WMS_Fixture_System_Table.Where(r => r.FXNum == fxNum).FirstOrDefault();
                    }
                    using (System.Data.Entity.DbContextTransaction mytran = model.Database.BeginTransaction())
                    {
                        try
                        {
                            var temfx = model.JDJS_WMS_Fixture_Temporary_Table.Where(r => r.Id == temFixId).FirstOrDefault();
                            if (temfx != null)
                            {
                                model.JDJS_WMS_Fixture_Temporary_Table.Remove(temfx);
                            }
                            JDJS_WMS_Fixture_System_Table jd = new JDJS_WMS_Fixture_System_Table()
                            {
                                AlterTime       = DateTime.Now,
                                CreateTime      = DateTime.Now,
                                Desc            = desc,
                                FileName        = file[0].FileName,
                                FixtureOrderNum = fixOrderNum,
                                FXNum           = fxNum,
                                Name            = name,
                                Remark          = remark,
                                SerialCode      = fxNum.ToString(),
                                StockAllNum     = allCount,
                                StockCurrNum    = currCount,
                                TypeId          = typeId,
                                VenderName      = venderName
                            };
                            model.JDJS_WMS_Fixture_System_Table.Add(jd);
                            model.SaveChanges();
                            mytran.Commit();
                            PathInfo info = new PathInfo();
                            for (int i = 0; i < file.Count; i++)
                            {
                                file[i].SaveAs(System.IO.Path.Combine(info.GetFixtrue_SurfMillFilePath(), file[i].FileName));
                            }
                            string str = "";
                            Fixture_SurfMill.AddChildJIG(name, desc, file[0].FileName, allCount.ToString(), currCount.ToString(), ref str, venderName, fxNum.ToString());

                            using (JDJS_WMS_DB_USEREntities wms = new JDJS_WMS_DB_USEREntities())
                            {
                                JDJS_WMS_Device_Status_Table ststus = new JDJS_WMS_Device_Status_Table()
                                {
                                    explain  = desc,
                                    Status   = name,
                                    SystemId = jd.Id
                                };
                                wms.JDJS_WMS_Device_Status_Table.Add(ststus);
                                wms.SaveChanges();
                            }
                            context.Response.Write(str);
                            return;
                        }
                        catch (Exception ex)
                        {
                            mytran.Rollback();
                            context.Response.Write(ex.Message);
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
                return;
            }
        }
Example #32
0
        private static PathInfo ParsePath(string path)
        {
            var result = new PathInfo();

            if (string.IsNullOrWhiteSpace(path) || path == ".")
            {
                result.Path = string.Empty;
            }
            else if (path.StartsWith("#"))
            {
                var dot = path.IndexOf('.');

                if (dot != -1)
                {
                    result.Path = path.Substring(dot + 1);
                    result.ElementName = path.Substring(1, dot - 1);
                }
                else
                {
                    result.Path = string.Empty;
                    result.ElementName = path.Substring(1);
                }
            }
            else
            {
                result.Path = path;
            }

            return result;
        }
	    public ComponentAssetsController(ITerrificNetConfig config, IFileSystem fileSystem, ServerConfiguration serverConfiguration) 
			: base(fileSystem, serverConfiguration)
	    {
	        _filePath = config.ModulePath;
	    }
Example #34
0
        /// <summary>
        /// Traverses graph from this Vertex to a target Vertex using Breadth-first search like in Dijkstra's algorithm
        /// </summary>
        /// <param name="maxHops">maximum number of hops from this Vertex</param>
        /// <param name="all">find or not find all paths to goal Vertex</param>
        /// <param name="dir">Direction to traverse edges</param>
        /// <param name="toVertex">the goal Vertex. If null, finds all paths</param>
        /// <param name="edgeTypesToTraverse">the type of edges to follow, by default null which means follow all edge types</param>
        /// <param name="includedVertexTypes">the type of vertices's to follow, by default null which means follow all vertex types</param>
        /// <param name="excludedVertexTypes">the type of vertices's not to follow, by default null</param>
        /// <param name="includedVertices">one or more Vertex instances that MUST be in the path for the path to be traversed i.e. if a path does exist
        /// to the specified toVertex, but does not include all the instances in includedVertices set, the Traverse method will exclude that path</param>
        /// <param name="excludedVertices">one or more Vertex instances that MUST NOT be in the path for the path to be traversed i.e. if a path does exist
        /// to the specified toVertex, but does include any of the instances in includedVertices set, the Traverse method will exclude that path</param>
        /// <param name="includedEdges">one or more Edge instances that MUST be in the path for the path to be traversed i.e. if a path does exist
        /// to the specified toVertex, but does not include all the instances in includedEdges set, the Traverse method will exclude that path</param>
        /// <param name="excludedEdges">one or more Edge instances that MUST NOT be in the path for the path to be traversed i.e. if a path does exist
        /// to the specified toVertex, but does include any of the instances in includedEdges set, the Traverse method will exclude that path</param>
        /// <param name="includedVertexProperty">One or more Vertex property types that MUST be in the path for the path to be accepted i.e. if a path does exist
        /// to the specified toVertex, but does not include all of the Vertex properties in the set, the Traverse method will exclude that path</param>
        /// <param name="excludedVertexProperty">One or more Vertex property types that MUST NOT be in the path for the path to be accepted i.e. if a path does exist
        /// to the specified toVertex, but does include any of the Vertex properties in the set, the Traverse method will exclude that path</param>
        /// <param name="includedEdgeProperty">One or more Vertex property types that MUST be in the path for the path to be accepted i.e. if a path does exist
        /// to the specified toVertex, but does not include all of the Vertex properties in the set, the Traverse method will exclude that path</param>
        /// <param name="excludedEdgeProperty">One or more Edge property types that MUST NOT be in the path for the path to be accepted i.e. if a path does exist
        /// to the specified toVertex, but does include any of the Edge properties in the set, the Traverse method will exclude that path</param>
        /// <param name="validateVertex">A function that will be called before accepting a Vertex in path to toVertex. If function returns true then this vertex is accepted in path; otherwise vertex is rejected</param>
        /// <param name="validateEdge">A function that will be called before accepting an Edge in path to toVertex. If function returns true then this Edge is accepted in path; otherwise edge is rejected</param>
        /// <param name="validateEdges">A function that will be called before accepting a candidate Edges list in path to toVertex. If function returns true then this Edge list is accepted in path; otherwise edge list is rejected</param>
        /// <returns>List of paths to goal Vertex</returns>
        public List <List <Edge> > Traverse(int maxHops, bool all = true, Direction dir = Direction.Both, Vertex toVertex = null, ISet <EdgeType> edgeTypesToTraverse = null,
                                            ISet <VertexType> includedVertexTypes    = null, ISet <VertexType> excludedVertexTypes = null, ISet <Vertex> includedVertices        = null, ISet <Vertex> excludedVertices             = null,
                                            ISet <Edge> includedEdges                = null, ISet <Edge> excludedEdges = null, ISet <PropertyType> includedVertexProperty        = null, ISet <PropertyType> excludedVertexProperty = null,
                                            ISet <PropertyType> includedEdgeProperty = null, ISet <PropertyType> excludedEdgeProperty = null, Func <Vertex, bool> validateVertex = null, Func <Edge, bool> validateEdge             = null,
                                            Func <List <Edge>, bool> validateEdges   = null)
        {
            Queue <PathInfo>       q = new Queue <PathInfo>();
            HashSet <PropertyType> vertexPropertyTypesToFind = null;
            HashSet <PropertyType> edgePropertyTypesToFind   = null;
            HashSet <Edge>         edgeSet;
            List <Edge>            path        = new List <Edge>();
            List <List <Edge> >    resultPaths = new List <List <Edge> >();
            var visited = new HashSet <Vertex>();

            if (excludedVertexProperty != null)
            {
                foreach (PropertyType pt in excludedVertexProperty)
                {
                    if (pt.HasPropertyValue(VertexId))
                    {
                        return(resultPaths);
                    }
                    if (pt.HasPropertyValue(toVertex.VertexId))
                    {
                        return(resultPaths);
                    }
                }
            }
            int includedVerticesSize;

            if (includedVertices != null)
            { // these will always be included so remove from list
                includedVertices.Remove(this);
                includedVertices.Remove(toVertex);
                includedVerticesSize = includedVertices.Count;
            }
            else
            {
                includedVerticesSize = 0;
            }
            int includedVertexPropertySize;

            if (includedVertexProperty != null)
            {
                vertexPropertyTypesToFind = new HashSet <PropertyType>(includedVertexProperty);
                foreach (PropertyType pt in vertexPropertyTypesToFind.ToArray())
                {
                    if (pt.HasPropertyValue(VertexId))
                    {
                        vertexPropertyTypesToFind.Remove(pt);
                    }
                    else if (pt.HasPropertyValue(toVertex.VertexId))
                    {
                        vertexPropertyTypesToFind.Remove(pt);
                    }
                }
                includedVertexPropertySize = vertexPropertyTypesToFind.Count;
            }
            else
            {
                includedVertexPropertySize = 0;
            }
            int includedEdgePropertySize;

            if (includedEdgeProperty != null)
            {
                edgePropertyTypesToFind  = new HashSet <PropertyType>(includedEdgeProperty);
                includedEdgePropertySize = edgePropertyTypesToFind.Count;
            }
            else
            {
                includedEdgePropertySize = 0;
            }
            PathInfo pathInfo = new PathInfo(this, path, null);

            if (excludedVertices != null)
            {
                pathInfo.Visited.UnionWith(excludedVertices);
                if (toVertex == null)
                {
                    visited.UnionWith(excludedVertices);
                }
            }
            pathInfo.Visited.Add(this);
            if (toVertex == null)
            {
                visited.Add(this);
            }
            else
            {
                pathInfo.Visited.Add(toVertex);
            }

            q.Enqueue(pathInfo);
            while (q.Count > 0)
            {
                pathInfo = q.Dequeue();
                Dictionary <Vertex, HashSet <Edge> > friends = pathInfo.Node.Traverse(dir, edgeTypesToTraverse);
                if (toVertex != null && friends.TryGetValue(toVertex, out edgeSet))
                {
                    foreach (Edge edge in edgeSet)
                    {
                        if ((excludedEdges == null || excludedEdges.Contains(edge) == false) && (validateEdge == null || validateEdge(edge)))
                        {
                            //Console.WriteLine(this + " and " + toVertex + " have a friendship link");
                            List <Edge> edgePath = pathInfo.EdgePath;
                            edgePath.Add(edge);
                            if (validateEdges == null || validateEdges(edgePath))
                            {
                                bool foundVerticesToInclude = includedVerticesSize == 0;
                                if (includedVerticesSize > 0)
                                {
                                    HashSet <Vertex> verticesToFind = new HashSet <Vertex>(includedVertices);
                                    foreach (Edge edgeInPath in edgePath)
                                    {
                                        if (verticesToFind.Contains(edgeInPath.Tail))
                                        {
                                            verticesToFind.Remove(edgeInPath.Tail);
                                            if (verticesToFind.Count == 0)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                    foundVerticesToInclude = verticesToFind.Count == 0;
                                }
                                bool foundVertexPropertyTypesToInclude = includedVertexPropertySize == 0;
                                if (includedVertexPropertySize > 0)
                                {
                                    var vertexPropertyTypesToFindClone = new HashSet <PropertyType>(vertexPropertyTypesToFind);
                                    foreach (Edge edgeInPath in edgePath)
                                    {
                                        foreach (PropertyType pt in vertexPropertyTypesToFind)
                                        {
                                            if (pt.HasPropertyValue(edgeInPath.Tail.VertexId))
                                            {
                                                vertexPropertyTypesToFindClone.Remove(pt);
                                            }
                                        }
                                        if (vertexPropertyTypesToFindClone.Count == 0)
                                        {
                                            break;
                                        }
                                    }
                                    foundVertexPropertyTypesToInclude = vertexPropertyTypesToFindClone.Count == 0;
                                }
                                bool foundEdgePropertyTypesToInclude = includedEdgePropertySize == 0;
                                if (includedEdgePropertySize > 0)
                                {
                                    var edgePropertyTypesToFindClone = new HashSet <PropertyType>(edgePropertyTypesToFind);
                                    foreach (Edge edgeInPath in edgePath)
                                    {
                                        foreach (PropertyType pt in edgePropertyTypesToFind)
                                        {
                                            if (pt.HasPropertyValue(edgeInPath.EdgeId))
                                            {
                                                edgePropertyTypesToFindClone.Remove(pt);
                                            }
                                        }
                                        if (edgePropertyTypesToFindClone.Count == 0)
                                        {
                                            break;
                                        }
                                    }
                                    foundEdgePropertyTypesToInclude = edgePropertyTypesToFind.Count == 0;
                                }
                                if (foundVerticesToInclude && foundVertexPropertyTypesToInclude && foundEdgePropertyTypesToInclude)
                                {
                                    if (includedEdges == null || includedEdges.IsSubsetOf(edgePath))
                                    {
                                        resultPaths.Add(edgePath);
                                        if (!all)
                                        {
                                            return(resultPaths);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (pathInfo.EdgePath.Count < maxHops || friends.Count == 0)
                {
                    foreach (KeyValuePair <Vertex, HashSet <Edge> > v in friends)
                    {
                        if (pathInfo.Visited.Contains(v.Key) == false && (all || toVertex != null || visited.Contains(v.Key) == false))
                        {
                            foreach (Edge edge in v.Value)
                            {
                                if (excludedEdges == null || excludedEdges.Contains(edge) == false)
                                {
                                    bool doExclude = false;
                                    if (excludedVertexProperty != null)
                                    {
                                        foreach (PropertyType pt in excludedVertexProperty)
                                        {
                                            if (pt.HasPropertyValue(v.Key.VertexId))
                                            {
                                                pathInfo.Visited.Add(v.Key);
                                                if (!all && toVertex == null)
                                                {
                                                    visited.Add(v.Key);
                                                }
                                                doExclude = true;
                                                break;
                                            }
                                        }
                                    }

                                    if (excludedEdgeProperty != null)
                                    {
                                        foreach (PropertyType pt in excludedEdgeProperty)
                                        {
                                            if (pt.HasPropertyValue(edge.EdgeId))
                                            {
                                                doExclude = true;
                                                break;
                                            }
                                        }
                                    }

                                    if (!doExclude)
                                    {
                                        path = new List <Edge>(pathInfo.EdgePath);
                                        path.Add(edge);
                                        PathInfo newPath = new PathInfo(v.Key, path, pathInfo.Visited);
                                        newPath.Visited.Add(v.Key);
                                        if (!all && toVertex == null)
                                        {
                                            visited.Add(v.Key);
                                        }
                                        if (validateEdges == null || validateEdges(path))
                                        {
                                            bool vertexTypeIncluded = includedVertexTypes == null || includedVertexTypes.Contains(v.Key.VertexType);
                                            bool vertexTypeExcluded = excludedVertexTypes != null && excludedVertexTypes.Contains(v.Key.VertexType);
                                            bool validVertex        = validateVertex == null || validateVertex(v.Key);
                                            if (vertexTypeIncluded && validVertex && !vertexTypeExcluded)
                                            {
                                                q.Enqueue(newPath);
                                                if (toVertex == null && newPath.EdgePath.Count <= maxHops)
                                                {
                                                    resultPaths.Add(newPath.EdgePath);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //if (all && resultPaths.Count == 0)
            //  Console.WriteLine(this + " and " + toVertex + " may not be connected by indirect frienship");
            return(resultPaths);
        }
        // ReSharper disable once ExcessiveIndentation
        public static SurroundTopology FromPathTargetInfo(PathTargetInfo pathTargetInfo)
        {
            // We go through the code if only the path belongs to a NVIDIA virtual surround display
            // TODO: Should we try to resolve every target info to be sure?
            if (pathTargetInfo.DisplayTarget.EDIDManufactureCode != "NVS" &&
                pathTargetInfo.DisplayTarget.FriendlyName != "NV Surround")
            {
                return(null);
            }

            try
            {
                // Get parent DisplayConfig PathInfo by checking display targets
                var correspondingWindowsPathInfo =
                    PathInfo.GetActivePaths()
                    .FirstOrDefault(
                        info =>
                        info.TargetsInfo.Any(
                            targetInfo =>
                            targetInfo.DisplayTarget == pathTargetInfo.DisplayTarget));

                if (correspondingWindowsPathInfo != null)
                {
                    // Get corresponding NvAPI PathInfo
                    // If position is same, then the two paths are equal, after all position is whats important in path sources
                    var correspondingNvidiaPathInfo =
                        NvAPIWrapper.Display.PathInfo.GetDisplaysConfig()
                        .FirstOrDefault(
                            info =>
                            info.Position.X == correspondingWindowsPathInfo.Position.X &&
                            info.Position.Y == correspondingWindowsPathInfo.Position.Y &&
                            info.Resolution.Width == correspondingWindowsPathInfo.Resolution.Width &&
                            info.Resolution.Height == correspondingWindowsPathInfo.Resolution.Height);

                    if (correspondingNvidiaPathInfo != null)
                    {
                        // Get corresponding NvAPI PathTargetInfo
                        // We now assume that there is only one target for a NvAPI PathInfo, in an other word, for now, it is not possible to have a cloned surround display
                        var correspondingNvidiaTargetInfo = correspondingNvidiaPathInfo.TargetsInfo.FirstOrDefault();

                        if (correspondingNvidiaTargetInfo != null)
                        {
                            // Get corresponding NvAPI Grid Topology
                            // We also assume that the NVS monitor uses a similar display id to one of real physical monitors
                            var correspondingNvidiaTopology =
                                GridTopology.GetGridTopologies()
                                .FirstOrDefault(
                                    topology => topology.Displays.Any(display =>
                                                                      display.DisplayDevice == correspondingNvidiaTargetInfo.DisplayDevice));

                            if (correspondingNvidiaTopology != null)
                            {
                                return(new SurroundTopology(correspondingNvidiaTopology));
                            }
                        }
                    }
                }
            }
            catch
            {
                // ignored
            }

            return(null);
        }
Example #36
0
        private void FindAndCaculateFromAdvancedStatic()
        {
            // Instead of using uniform distribution of support between all fixed nodes, calculate non-uniform distribution based on vectors for few closest nodes
            // Use this distribution when setting support weight and transferring mass
            // SupportingWeights: x * support
            // ? TransferMass: x * numStaticBlocksForCurrentDynamicBlock * TransferMass

            int keepLookingDistance = (int)ClosestDistanceThreshold; // How far keep looking when closest static block is found
            Queue <PathInfo> queue  = new Queue <PathInfo>();

            // Set initial distance to max for all dynamic
            foreach (var dyn in DynamicBlocks)
            {
                dyn.Distance = int.MaxValue;
            }

            // Wide search from all static blocks
            foreach (var stat in StaticBlocks)
            {
                stat.Distance = 0;
                var path = new PathInfo()
                {
                    EndNode = stat, StartNode = stat, Distance = 0, DirectionRatio = 1
                };
#if ENHANCED_DEBUG
                path.PathNodes.Add(stat);
#endif
                queue.Enqueue(path);
            }

            while (queue.Count > 0)
            {
                var path = queue.Dequeue();
                foreach (var neighbour in path.EndNode.Neighbours)
                {
                    if (neighbour.IsStatic)
                    {
                        continue;
                    }

                    PathInfo neighbourPath;
                    if (!neighbour.Paths.TryGetValue(path.StartNode, out neighbourPath))
                    {
                        if ((path.Distance - keepLookingDistance) <= neighbour.Distance)
                        {
                            neighbour.Distance = Math.Min(neighbour.Distance, path.Distance);

                            neighbourPath           = new PathInfo();
                            neighbourPath.Distance  = path.Distance + 1;
                            neighbourPath.StartNode = path.StartNode;
                            neighbourPath.EndNode   = neighbour;
#if ENHANCED_DEBUG
                            neighbourPath.PathNodes = path.PathNodes.ToList();
                            neighbourPath.PathNodes.Add(neighbour);
#endif
                            neighbourPath.Parents.Add(path);
                            neighbourPath.DirectionRatio = path.DirectionRatio * DirectionRatios[((Vector3D)(neighbour.Pos - path.EndNode.Pos)).AbsMaxComponent()];
                            neighbour.Paths.Add(path.StartNode, neighbourPath);
                            queue.Enqueue(neighbourPath);
                            path.StartNode.OwnedPaths.Push(neighbourPath);
                        }
                    }
                    else if (neighbourPath.Distance == path.Distance + 1) // Another path with same length
                    {
                        neighbourPath.Parents.Add(path);
                    }
                }
            }



            // Iterate all dynamic blocks and calculate support ratio for each static
            foreach (var dyn in DynamicBlocks)
            {
                dyn.PathCount = 1;

                if (dyn.Pos == new Vector3I(-6, 6, 0))
                {
                }
                // Uniform distribution
                //foreach (var s in dyn.Paths)
                //{
                //    s.Value.Ratio = 1.0f / dyn.Paths.Count;
                //}
                //continue;

                // Non-uniform distribution
                // Calculate angle between one vector and all other
                // Split weight support based on sum angle ratio
                float totalAngles = 0;
                if (dyn.Paths.Count > 1)
                {
                    foreach (var s in dyn.Paths)
                    {
                        Vector3 localVector1 = (dyn.Pos - s.Value.StartNode.Pos) * m_grid.GridSize;
                        Vector3 worldVector1 = Vector3.TransformNormal(localVector1, m_grid.WorldMatrix);

                        // float sumAngle = 0;
                        float sumAngleReduced = 0;
                        foreach (var s2 in dyn.Paths)
                        {
                            if (s.Key == s2.Key)
                            {
                                continue;
                            }

                            Vector3 localVector2 = (dyn.Pos - s2.Value.StartNode.Pos) * m_grid.GridSize;
                            Vector3 worldVector2 = Vector3.TransformNormal(localVector2, m_grid.WorldMatrix);
                            float   angle        = MyUtils.GetAngleBetweenVectorsAndNormalise(worldVector1, worldVector2);

                            float dot1 = Math.Abs(Vector3.Normalize(worldVector1).Dot(Vector3.Up));
                            float dot2 = Math.Abs(Vector3.Normalize(worldVector2).Dot(Vector3.Up));

                            float lowerBound = 0.1f;
                            dot1 = MathHelper.Lerp(lowerBound, 1, dot1);
                            dot2 = MathHelper.Lerp(lowerBound, 1, dot2);

                            float reducedAngle = angle;

                            if (!MyPetaInputComponent.OLD_SI)
                            {
                                //Reduce dependent on gravity
                                reducedAngle = angle * dot1 * s.Value.DirectionRatio;
                            }

                            //sumAngle += angle;
                            sumAngleReduced += reducedAngle;
                        }
                        s.Value.Ratio = sumAngleReduced;
                        totalAngles  += sumAngleReduced;
                    }

                    foreach (var s in dyn.Paths)
                    {
                        if (totalAngles > 0)
                        {
                            s.Value.Ratio /= totalAngles;
                        }
                        else
                        {
                            s.Value.Ratio = 1;
                        }
                    }
                }
                else
                {
                    foreach (var s in dyn.Paths)
                    {
                        s.Value.Ratio = 1.0f;
                    }
                }
            }

            // Iterate all static blocks and calculate support mass and mass transfer
            foreach (var staticBlock in StaticBlocks)
            {
                // Initial mass and ratio
                foreach (var path in staticBlock.OwnedPaths)
                {
                    path.EndNode.TransferMass = 0;
                }

                // For each block in path (ordered by distance, furthest first)
                while (staticBlock.OwnedPaths.Count > 0)
                {
                    var pathInfo = staticBlock.OwnedPaths.Pop();
                    var node     = pathInfo.EndNode;

                    Debug.Assert(pathInfo.StartNode == staticBlock, "Wrong path");
                    Debug.Assert(!node.IsStatic, "Static node unexpected");

                    float outgoing = node.TransferMass + node.Mass * pathInfo.Ratio;
                    //float outgoindTotal = 0;
                    //foreach (var p in pathInfo.Parents)
                    //    outgoindTotal += p.DirectionRatio;

                    float outgoingPerParent = outgoing / pathInfo.Parents.Count;

                    foreach (var parent in pathInfo.Parents)
                    {
                        var delta = parent.EndNode.Pos - node.Pos; // Node to parent
                        int index, parentIndex;
                        if (delta.X + delta.Y + delta.Z > 0)
                        {
                            index       = delta.Y + delta.Z * 2; // UnitX = 0, UnitY = 1, UnitZ = 2
                            parentIndex = index + 3;
                        }
                        else
                        {
                            index       = -delta.X * 3 - delta.Y * 4 - delta.Z * 5; // // -UnitX = 3, -UnitY = 4, -UnitZ = 5
                            parentIndex = index - 3;
                        }

                        //outgoingPerParent = outgoing * parent.DirectionRatio / outgoindTotal;

#if ENHANCED_DEBUG
                        node.OutgoingNodeswWithWeights[index].Add(new Tuple <Node, float>(parent.EndNode, outgoingPerParent));
#endif
                        node.SupportingWeights[index] -= outgoingPerParent;


                        parent.EndNode.SupportingWeights[parentIndex] += outgoingPerParent;
#if ENHANCED_DEBUG
                        parent.EndNode.SupportingNodeswWithWeights[parentIndex].Add(new Tuple <Node, float>(node, outgoingPerParent));
#endif


                        parent.EndNode.TransferMass += outgoingPerParent;
                    }
                    node.TransferMass -= outgoing;
                }
            }
        }
Example #37
0
 /// <summary>
 /// Replaces the context path of the storage, dispose of the returned IDisposable
 /// to restore the Storage's previous ContextPath.
 /// </summary>
 /// <param name="contextPath">The full context path to change to</param>
 /// <returns>Context can be disposed to restore the previous state</returns>
 public IDisposable SetContext(string contextPath)
 {
     return(PathInfo.SetPath(this, contextPath));
 }
Example #38
0
		public JsonLabelService(IFileSystem fileSystem)
		{
			_fileSystem = fileSystem;
			_fileName = PathInfo.Create("labels.json");
		}
Example #39
0
 /// <summary>
 /// Constructs a storage wrapper for the given name/value store and sets the initial
 /// path to the provided value.
 /// </summary>
 /// <param name="store">The storage container to use</param>
 /// <param name="contextPath">The full context of the storage item, delimit with '/' or '\'</param>
 public Storage(INameValueStore store, string contextPath)
 {
     _store = Check.NotNull(store);
     PathInfo.SetPath(this, contextPath);
 }
Example #40
0
 public static void AssertValidStoragePathInfo(PathInfo pathInfo)
 {
     Assert.IsNotNull(pathInfo.ETag);
     Assert.IsNotNull(pathInfo.LastModified);
 }
        public TestContext BuildContext(PathInfo file, TestOptions options)
        {
            if (file == null)
            {
                throw new ArgumentNullException("testFilePathInfo");
            }


            ChutzpahTracer.TraceInformation("Building test context for '{0}'", file.FullPath);

            PathType testFileKind = file.Type;
            string   testFilePath = file.FullPath;

            if (!IsValidTestPathType(testFileKind))
            {
                throw new ArgumentException("Expecting a .js, .ts, .coffee or .html file or a url");
            }

            if (testFilePath == null)
            {
                throw new FileNotFoundException("Unable to find file: " + file.Path);
            }

            var testFileDirectory    = Path.GetDirectoryName(testFilePath);
            var chutzpahTestSettings = settingsService.FindSettingsFile(testFileDirectory);

            if (!IsTestPathIncluded(testFilePath, chutzpahTestSettings))
            {
                ChutzpahTracer.TraceInformation("Excluded test file '{0}' given chutzpah.json settings", testFilePath);
                return(null);
            }

            string testFileText;

            if (testFileKind == PathType.Url)
            {
                testFileText = httpClient.GetContent(testFilePath);
            }
            else
            {
                testFileText = fileSystem.GetText(testFilePath);
            }

            IFrameworkDefinition definition;

            if (TryDetectFramework(testFileText, testFileKind, chutzpahTestSettings, out definition))
            {
                // For HTML test files we don't need to create a test harness to just return this file
                if (testFileKind == PathType.Html || testFileKind == PathType.Url)
                {
                    ChutzpahTracer.TraceInformation("Test kind is {0} so we are trusting the supplied test harness and not building our own", testFileKind);

                    return(new TestContext
                    {
                        InputTestFile = testFilePath,
                        TestHarnessPath = testFilePath,
                        IsRemoteHarness = testFileKind == PathType.Url,
                        TestRunner = definition.GetTestRunner(chutzpahTestSettings),
                    });
                }

                var referencedFiles = new List <ReferencedFile>();
                var temporaryFiles  = new List <string>();


                string inputTestFileDir     = Path.GetDirectoryName(testFilePath);
                var    testHarnessDirectory = GetTestHarnessDirectory(chutzpahTestSettings, inputTestFileDir);
                var    fileUnderTest        = GetFileUnderTest(testFilePath, chutzpahTestSettings);
                referencedFiles.Add(fileUnderTest);
                definition.Process(fileUnderTest, testFileText, chutzpahTestSettings);


                referenceProcessor.GetReferencedFiles(referencedFiles, definition, testFileText, testFilePath, chutzpahTestSettings);

                // This is the legacy way Chutzpah compiled files that are TypeScript or CoffeeScript
                // Remaining but will eventually be deprecated and removed
                ProcessForFilesGeneration(referencedFiles, temporaryFiles, chutzpahTestSettings);


                IEnumerable <string> deps = definition.GetFileDependencies(chutzpahTestSettings);

                var coverageEngine = SetupCodeCoverageEngine(options, chutzpahTestSettings, definition, referencedFiles);

                AddTestFrameworkDependencies(deps, referencedFiles);


                return(new TestContext
                {
                    FrameworkDefinition = definition,
                    CoverageEngine = coverageEngine,
                    InputTestFile = testFilePath,
                    TestHarnessDirectory = testHarnessDirectory,
                    ReferencedFiles = referencedFiles,
                    TestRunner = definition.GetTestRunner(chutzpahTestSettings),
                    TemporaryFiles = temporaryFiles,
                    TestFileSettings = chutzpahTestSettings
                });
            }
            else
            {
                ChutzpahTracer.TraceWarning("Failed to detect test framework for '{0}'", testFilePath);
            }

            return(null);
        }
Example #42
0
 public bool TryBuildContext(PathInfo file, TestOptions options, out TestContext context)
 {
     context = BuildContext(file, options);
     return(context != null);
 }
Example #43
0
        static void Path(PathInfo info, Expression expr, Expression path)
        {
#if DEBUG
            _callCounter1++;
#endif

            if (expr == null)
            {
                return;
            }

            switch (expr.NodeType)
            {
            case ExpressionType.Add:
            case ExpressionType.AddChecked:
            case ExpressionType.And:
            case ExpressionType.AndAlso:
            case ExpressionType.ArrayIndex:
            case ExpressionType.Assign:
            case ExpressionType.Coalesce:
            case ExpressionType.Divide:
            case ExpressionType.Equal:
            case ExpressionType.ExclusiveOr:
            case ExpressionType.GreaterThan:
            case ExpressionType.GreaterThanOrEqual:
            case ExpressionType.LeftShift:
            case ExpressionType.LessThan:
            case ExpressionType.LessThanOrEqual:
            case ExpressionType.Modulo:
            case ExpressionType.Multiply:
            case ExpressionType.MultiplyChecked:
            case ExpressionType.NotEqual:
            case ExpressionType.Or:
            case ExpressionType.OrElse:
            case ExpressionType.Power:
            case ExpressionType.RightShift:
            case ExpressionType.Subtract:
            case ExpressionType.SubtractChecked:
            {
                path = ConvertTo(path, typeof(BinaryExpression));

                Path(info, ((BinaryExpression)expr).Conversion, Expression.Property(path, ReflectionHelper.Binary.Conversion));
                Path(info, ((BinaryExpression)expr).Left, Expression.Property(path, ReflectionHelper.Binary.Left));
                Path(info, ((BinaryExpression)expr).Right, Expression.Property(path, ReflectionHelper.Binary.Right));

                break;
            }

            case ExpressionType.ArrayLength:
            case ExpressionType.Convert:
            case ExpressionType.ConvertChecked:
            case ExpressionType.Negate:
            case ExpressionType.NegateChecked:
            case ExpressionType.Not:
            case ExpressionType.Quote:
            case ExpressionType.TypeAs:
            case ExpressionType.UnaryPlus:
                Path(
                    info,
                    ((UnaryExpression)expr).Operand,
                    path = ConvertTo(path, typeof(UnaryExpression)),
                    ReflectionHelper.Unary.Operand);
                break;

            case ExpressionType.Call:
            {
                path = ConvertTo(path, typeof(MethodCallExpression));

                Path(info, ((MethodCallExpression)expr).Object, path, ReflectionHelper.MethodCall.Object);
                Path(info, ((MethodCallExpression)expr).Arguments, path, ReflectionHelper.MethodCall.Arguments);

                break;
            }

            case ExpressionType.Conditional:
            {
                path = ConvertTo(path, typeof(ConditionalExpression));

                Path(info, ((ConditionalExpression)expr).Test, path, ReflectionHelper.Conditional.Test);
                Path(info, ((ConditionalExpression)expr).IfTrue, path, ReflectionHelper.Conditional.IfTrue);
                Path(info, ((ConditionalExpression)expr).IfFalse, path, ReflectionHelper.Conditional.IfFalse);

                break;
            }

            case ExpressionType.Invoke:
            {
                path = ConvertTo(path, typeof(InvocationExpression));

                Path(info, ((InvocationExpression)expr).Expression, path, ReflectionHelper.Invocation.Expression);
                Path(info, ((InvocationExpression)expr).Arguments, path, ReflectionHelper.Invocation.Arguments);

                break;
            }

            case ExpressionType.Lambda:
            {
                path = ConvertTo(path, typeof(LambdaExpression));

                Path(info, ((LambdaExpression)expr).Body, path, ReflectionHelper.LambdaExpr.Body);
                Path(info, ((LambdaExpression)expr).Parameters, path, ReflectionHelper.LambdaExpr.Parameters);

                break;
            }

            case ExpressionType.ListInit:
            {
                path = ConvertTo(path, typeof(ListInitExpression));

                Path(info, ((ListInitExpression)expr).NewExpression, path, ReflectionHelper.ListInit.NewExpression);
                Path(((ListInitExpression)expr).Initializers, path, ReflectionHelper.ListInit.Initializers,
                     (ex, p) => Path(info, ex.Arguments, p, ReflectionHelper.ElementInit.Arguments));

                break;
            }

            case ExpressionType.MemberAccess:
                Path(
                    info,
                    ((MemberExpression)expr).Expression,
                    path = ConvertTo(path, typeof(MemberExpression)),
                    ReflectionHelper.Member.Expression);
                break;

            case ExpressionType.MemberInit:
            {
                void Modify(MemberBinding b, Expression pinf)
                {
                    switch (b.BindingType)
                    {
                    case MemberBindingType.Assignment:
                        Path(
                            info,
                            ((MemberAssignment)b).Expression,
                            ConvertTo(pinf, typeof(MemberAssignment)),
                            ReflectionHelper.MemberAssignmentBind.Expression);
                        break;

                    case MemberBindingType.ListBinding:
                        Path(
                            ((MemberListBinding)b).Initializers,
                            ConvertTo(pinf, typeof(MemberListBinding)),
                            ReflectionHelper.MemberListBind.Initializers,
                            (p, psi) => Path(info, p.Arguments, psi, ReflectionHelper.ElementInit.Arguments));
                        break;

                    case MemberBindingType.MemberBinding:
                        Path(
                            ((MemberMemberBinding)b).Bindings,
                            ConvertTo(pinf, typeof(MemberMemberBinding)),
                            ReflectionHelper.MemberMemberBind.Bindings,
                            Modify);
                        break;
                    }
                }

                path = ConvertTo(path, typeof(MemberInitExpression));

                Path(info, ((MemberInitExpression)expr).NewExpression, path, ReflectionHelper.MemberInit.NewExpression);
                Path(((MemberInitExpression)expr).Bindings, path, ReflectionHelper.MemberInit.Bindings, Modify);

                break;
            }

            case ExpressionType.New:
                Path(
                    info,
                    ((NewExpression)expr).Arguments,
                    path = ConvertTo(path, typeof(NewExpression)),
                    ReflectionHelper.New.Arguments);
                break;

            case ExpressionType.NewArrayBounds:
                Path(
                    info,
                    ((NewArrayExpression)expr).Expressions,
                    path = ConvertTo(path, typeof(NewArrayExpression)),
                    ReflectionHelper.NewArray.Expressions);
                break;

            case ExpressionType.NewArrayInit:
                Path(
                    info,
                    ((NewArrayExpression)expr).Expressions,
                    path = ConvertTo(path, typeof(NewArrayExpression)),
                    ReflectionHelper.NewArray.Expressions);
                break;

            case ExpressionType.TypeIs:
                Path(
                    info,
                    ((TypeBinaryExpression)expr).Expression,
                    path = ConvertTo(path, typeof(TypeBinaryExpression)),
                    ReflectionHelper.TypeBinary.Expression);
                break;

            case ExpressionType.Block:
            {
                path = ConvertTo(path, typeof(BlockExpression));

                Path(info, ((BlockExpression)expr).Expressions, path, ReflectionHelper.Block.Expressions);
                Path(info, ((BlockExpression)expr).Variables, path, ReflectionHelper.Block.Variables);                                  // ?

                break;
            }

            case ExpressionType.Constant:
            {
                path = ConvertTo(path, typeof(ConstantExpression));

                if (((ConstantExpression)expr).Value is IQueryable iq && !info.Visited.Contains(iq.Expression))
                {
                    info.Visited.Add(iq.Expression);

                    Expression p = Expression.Property(path, ReflectionHelper.Constant.Value);
                    p = ConvertTo(p, typeof(IQueryable));
                    Path(info, iq.Expression, p, ReflectionHelper.QueryableInt.Expression);
                }

                break;
            }

            case ExpressionType.Parameter: path = ConvertTo(path, typeof(ParameterExpression)); break;

            case ExpressionType.Extension:
            {
                if (expr.CanReduce)
                {
                    expr = expr.Reduce();
                    Path(info, expr, path);
                }
                break;
            }
            }

            info.Func(expr, path);
        }
        public void ProcessRequest(HttpContext context)
        {
            var      files    = context.Request.Files;
            PathInfo pathInfo = new PathInfo();
            var      fileName = files[0].FileName;
            var      path     = Path.Combine(pathInfo.upLoadPath(), fileName);

            if (File.Exists(path))
            {
                File.Delete(path);
            }



            files[0].SaveAs(path);
            string FilePath = path;

            List <QualityInfo> qualities = new List <QualityInfo>();

            string fileSuffix = System.IO.Path.GetExtension(FilePath);

            if (fileSuffix == ".xls")
            {
                #region
                {
                    DataTable dt = getData(FilePath).Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        using (JDJS_WMS_DB_USEREntities CIE = new JDJS_WMS_DB_USEREntities())
                        {
                            string a1    = dt.Rows[i]["订单单号"].ToString();
                            var    order = CIE.JDJS_WMS_Order_Entry_Table.Where(r => r.Order_Number == a1);
                            if (order.Count() > 0)
                            {
                                QualityInfo quality = new QualityInfo();
                                quality.OrderNum          = Convert.ToInt32(order.First().Order_ID);
                                quality.WorkpieceNumber   = Convert.ToInt32(dt.Rows[i]["工件序号"].ToString());
                                quality.SizeNumber        = Convert.ToInt32(dt.Rows[i]["尺寸序号"].ToString());
                                quality.SizeName          = dt.Rows[i]["尺寸名称"].ToString();;
                                quality.StandardValue     = Convert.ToDouble(dt.Rows[i]["尺寸理论值"].ToString());
                                quality.ToleranceRangeMin = Convert.ToDouble(dt.Rows[i]["合理误差范围下公差"].ToString());
                                quality.ToleranceRangeMax = Convert.ToDouble(dt.Rows[i]["合理误差范围上公差"].ToString());
                                quality.Measurements      = Convert.ToDouble(dt.Rows[i]["尺寸实测值"].ToString());
                                if (dt.Rows[i]["是否超差"].ToString() == "是")
                                {
                                    quality.OutOfTolerance = 1;
                                }
                                else if (dt.Rows[i]["是否超差"].ToString() == "否")
                                {
                                    quality.OutOfTolerance = 0;
                                }
                                else
                                {
                                    quality.OutOfTolerance = 2;
                                }
                                qualities.Add(quality);
                            }
                        }
                    }
                }
                #endregion
            }
            else if (fileSuffix == ".csv")
            {
                //List<QualityInfo> qualities = new List<QualityInfo>();
                //using (FileStream file = new FileStream(FilePath, FileMode.Append))
                //{

                using (StreamReader read = new StreamReader(FilePath, Encoding.Default))
                {
                    string str = read.ReadLine();
                    str = read.ReadLine();
                    while (str != null)
                    {
                        if (str != null && str != ",,,,,,,")
                        {
                            string[] info = str.Split(',');
                            using (JDJS_WMS_DB_USEREntities CIE = new JDJS_WMS_DB_USEREntities())
                            {
                                string ordernum = info[0];
                                var    order    = CIE.JDJS_WMS_Order_Entry_Table.Where(r => r.Order_Number == ordernum);
                                if (order.Count() > 0)
                                {
                                    QualityInfo quality = new QualityInfo();
                                    quality.OrderNum          = Convert.ToInt32(order.First().Order_ID);
                                    quality.WorkpieceNumber   = Convert.ToInt32(info[1]);
                                    quality.SizeNumber        = Convert.ToInt32(info[2]);
                                    quality.SizeName          = info[3];
                                    quality.StandardValue     = Convert.ToDouble(info[4]);
                                    quality.ToleranceRangeMin = Convert.ToDouble(info[5]);
                                    quality.ToleranceRangeMax = Convert.ToDouble(info[6]);
                                    quality.Measurements      = Convert.ToDouble(info[7]);
                                    if (info[8] == "是")
                                    {
                                        quality.OutOfTolerance = 1;
                                    }
                                    else if (info[8] == "否")
                                    {
                                        quality.OutOfTolerance = 0;
                                    }
                                    else
                                    {
                                        quality.OutOfTolerance = 2;
                                    }
                                    qualities.Add(quality);
                                }
                            }
                        }
                        str = read.ReadLine();
                    }
                }
                //}
            }
            else
            {
                context.Response.Write("请输入格式为csv或xls的文件");
                return;
            }



            using (JDJS_WMS_DB_USEREntities CIE = new JDJS_WMS_DB_USEREntities())
            {
                using (System.Data.Entity.DbContextTransaction mytran = CIE.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (var item in qualities)
                        {
                            JDJS_WMS_Quality_ManualInput_Measurement_Table ma = new JDJS_WMS_Quality_ManualInput_Measurement_Table()
                            {
                                OrderID           = item.OrderNum,
                                WorkpieceNumber   = item.WorkpieceNumber,
                                SizeNumber        = item.SizeNumber,
                                SizeName          = item.SizeName,
                                StandardValue     = item.StandardValue,
                                ToleranceRangeMin = item.ToleranceRangeMin,
                                ToleranceRangeMax = item.ToleranceRangeMax,
                                Measurements      = item.Measurements,
                                OutOfTolerance    = item.OutOfTolerance
                            };
                            CIE.JDJS_WMS_Quality_ManualInput_Measurement_Table.Add(ma);
                        }
                        CIE.SaveChanges();
                        mytran.Commit();
                    }
                    catch
                    {
                        mytran.Rollback();
                    }
                }
            }



            context.Response.Write("ok");
        }
Example #45
0
 public TestContext BuildContext(PathInfo file, TestOptions options)
 {
     return(BuildContext(new List <PathInfo> {
         file
     }, options));
 }
Example #46
0
        private void ParseParameters(IConfiguration configuration, IFileSystem fileSystem, PathInfo currentFileSystemLocation)
        {
            configuration.FeatureFolder = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.FeatureDirectory);
            configuration.OutputFolder  = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.OutputDirectory);

            if (!string.IsNullOrEmpty(this.TestResultsFormat))
            {
                configuration.TestResultsFormat =
                    (TestResultsFormat)Enum.Parse(typeof(TestResultsFormat), this.TestResultsFormat, true);
            }

            if (!string.IsNullOrEmpty(this.TestResultsFile))
            {
                configuration.AddTestResultFiles(
                    PathExtensions.GetAllFilesFromPathAndFileNameWithOptionalSemicolonsAndWildCards(this.TestResultsFile, fileSystem));
            }

            configuration.SystemUnderTestName    = this.SystemUnderTestName;
            configuration.SystemUnderTestVersion = this.SystemUnderTestVersion;
            if (!string.IsNullOrEmpty(this.DocumentationFormat))
            {
                configuration.DocumentationFormat = (DocumentationFormat)Enum.Parse(typeof(DocumentationFormat), this.DocumentationFormat, true);
            }

            if (!string.IsNullOrEmpty(this.Language))
            {
                configuration.Language = this.Language;
            }

            if (this.IncludeExperimentalFeatures.IsPresent)
            {
                configuration.EnableExperimentalFeatures();
            }

            if (this.IncludeExperimentalFeatures.IsPresent)
            {
                configuration.EnableExperimentalFeatures();
            }

            if (!string.IsNullOrEmpty(this.ExcludeTags))
            {
                configuration.ExcludeTags = this.ExcludeTags;
            }

            bool shouldEnableComments;

            if (bool.TryParse(this.EnableComments, out shouldEnableComments))
            {
                if (!shouldEnableComments)
                {
                    configuration.DisableComments();
                }
            }
        }
 /// <summary>
 /// Constructs a content cache item.
 /// </summary>
 ///
 /// <param name="pathInfo">
 /// The path information for which the cache will be bound.
 /// </param>
 ///
 public ContentPathsCache(PathInfo pathInfo)
 {
     PathInfo = pathInfo;
 }
    Position firstPoint = null;//第一个点的位置 自动移动进度条到该点

    /// <summary>
    /// 显示某个标签的历史数据
    /// </summary>
    /// <param name="code"></param>
    public void ShowHistoryData()
    {
        if (isLoadDataSuccessed)
        {
            return;
        }
        //LocationManager.Instance.ClearHistoryPaths();
        //string code = "0002";

        List <HistoryPersonUIItem> historyPersonUIItems = personsGrid.GetComponentsInChildren <HistoryPersonUIItem>().ToList();

        DateTime end   = GetEndTime();
        DateTime start = GetStartTime();
        List <List <Position> > psList = new List <List <Position> >();

        personnel_Points = new Dictionary <Personnel, List <Position> >();
        //List<Position> ps = new List<Position>();
        List <LocationHistoryPath_M> paths = new List <LocationHistoryPath_M>();

        progressbarLoadValue = 0;

        List <int> topoNodeIds = RoomFactory.Instance.GetCurrentDepNodeChildNodeIds(SceneEvents.DepNode);

        Loom.StartSingleThread(() =>
        {
            firstPoint = null;
            foreach (Personnel p in currentPersonnels)
            {
                List <Position> ps = GetHistoryData(p.Id, topoNodeIds, start, end, 1440f);
                psList.Add(ps);
                if (personnel_Points.ContainsKey(p))
                {
                    personnel_Points[p] = ps;
                }
                else
                {
                    personnel_Points.Add(p, ps);
                }
                if (ps != null && ps.Count > 0)
                {
                    Position fps = ps[0];
                    if (firstPoint == null)
                    {
                        firstPoint = fps;
                    }
                    else
                    {
                        if (fps.Time < firstPoint.Time)
                        {
                            firstPoint = fps;
                        }
                    }
                }
            }
            Debug.Log("StartSingleThread1");
            Loom.DispatchToMainThread(() =>
            {
                ProgressbarLoad.Instance.Show(1);
                ProgressbarLoad.Instance.Hide();
                int k = 0;
                foreach (Personnel p in personnel_Points.Keys)
                {
                    List <Position> ps = personnel_Points[p];
                    Debug.LogError("点数:" + ps.Count);
                    if (ps.Count < 2)
                    {
                        continue;
                    }
                    var posInfoList = new PositionInfoList();
                    for (int i = 0; i < ps.Count; i++)
                    {
                        var posInfo = new PositionInfo(ps[i], start);
                        posInfoList.Add(posInfo);
                    }

                    Color colorT             = colors[k % colors.Count];
                    HistoryPersonUIItem item = historyPersonUIItems.Find((i) => i.personnel.Id == p.Id);
                    if (item != null)
                    {
                        colorT = item.color;
                    }

                    PathInfo pathInfo   = new PathInfo();
                    pathInfo.personnelT = p;
                    pathInfo.color      = colorT;
                    pathInfo.posList    = posInfoList;
                    pathInfo.timeLength = timeLength;

                    LocationHistoryPath_M histoyObj = LocationHistoryManager.Instance.ShowLocationHistoryPath_M(pathInfo);
                    //histoyObj.InitData(timeLength, timelist);
                    HistoryManController historyManController = histoyObj.gameObject.AddComponent <HistoryManController>();
                    histoyObj.historyManController            = historyManController;
                    historyManController.Init(colorT, histoyObj);
                    PersonAnimationController personAnimationController = histoyObj.gameObject.GetComponent <PersonAnimationController>();
                    personAnimationController.DoMove();
                    Debug.Log("StartSingleThread2");
                    k++;
                }
            });

            //Debug.Log("StartSingleThread3");
            Loom.DispatchToMainThread(() =>
            {
                isLoadDataSuccessed = true;
                //timeStart = Time.time;
                timeSum = 0;
                Debug.Log("StartSingleThread3");
                if (firstPoint != null)
                {
                    DateTime t = LocationManager.GetTimestampToDateTime(firstPoint.Time);
                    Debug.Log(firstPoint.Time);
                    timeSum = t.Hour * 3600 + t.Minute * 60 + t.Second - slider.ValueMin * 3600;
                    Debug.Log(timeSum);
                }
            });
        });
    }
        /// <summary>
        /// Wraps the content into a PSObject and adds context information as notes
        /// </summary>
        ///
        /// <param name="content">
        /// The content being written out.
        /// </param>
        ///
        /// <param name="readCount">
        /// The number of blocks that have been read so far.
        /// </param>
        ///
        /// <param name="pathInfo">
        /// The context the content was retrieved from.
        /// </param>
        ///
        /// <param name="context">
        /// The context the command is being run under.
        /// </param>
        ///
        internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context)
        {
            Dbg.Diagnostics.Assert(
                content != null,
                "The caller should verify the content.");

            Dbg.Diagnostics.Assert(
                pathInfo != null,
                "The caller should verify the pathInfo.");

            Dbg.Diagnostics.Assert(
                context != null,
                "The caller should verify the context.");

            PSObject result = PSObject.AsPSObject(content);

            Dbg.Diagnostics.Assert(
                result != null,
                "A PSObject should always be constructed.");

            // Use the cached notes if the cache exists and the path is still the same
            PSNoteProperty note;

            if (_currentContentItem != null &&
                ((_currentContentItem.PathInfo == pathInfo) ||
                 (
                     String.Compare(
                         pathInfo.Path,
                         _currentContentItem.PathInfo.Path,
                         StringComparison.OrdinalIgnoreCase) == 0)
                )
                )
            {
                result = _currentContentItem.AttachNotes(result);
            }
            else
            {
                // Generate a new cache item and cache the notes

                _currentContentItem = new ContentPathsCache(pathInfo);

                // Construct a provider qualified path as the Path note
                string psPath = pathInfo.Path;
                note = new PSNoteProperty("PSPath", psPath);
                result.Properties.Add(note, true);
                tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath);
                _currentContentItem.PSPath = psPath;

                try
                {
                    // Now get the parent path and child name

                    string parentPath = null;

                    if (pathInfo.Drive != null)
                    {
                        parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context);
                    }
                    else
                    {
                        parentPath = SessionState.Path.ParseParent(pathInfo.Path, String.Empty, context);
                    }
                    note = new PSNoteProperty("PSParentPath", parentPath);
                    result.Properties.Add(note, true);
                    tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath);
                    _currentContentItem.ParentPath = parentPath;

                    // Get the child name

                    string childName = SessionState.Path.ParseChildName(pathInfo.Path, context);
                    note = new PSNoteProperty("PSChildName", childName);
                    result.Properties.Add(note, true);
                    tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName);
                    _currentContentItem.ChildName = childName;
                }
                catch (NotSupportedException)
                {
                    // Ignore. The object just won't have ParentPath or ChildName set.
                }

                // PSDriveInfo

                if (pathInfo.Drive != null)
                {
                    PSDriveInfo drive = pathInfo.Drive;
                    note = new PSNoteProperty("PSDrive", drive);
                    result.Properties.Add(note, true);
                    tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive);
                    _currentContentItem.Drive = drive;
                }

                // ProviderInfo

                ProviderInfo provider = pathInfo.Provider;
                note = new PSNoteProperty("PSProvider", provider);
                result.Properties.Add(note, true);
                tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider);
                _currentContentItem.Provider = provider;
            }

            // Add the ReadCount note
            note = new PSNoteProperty("ReadCount", readCount);
            result.Properties.Add(note, true);

            WriteObject(result);
        } // WriteContentObject
Example #50
0
        public WizardPageImportPreparationViewModel(Window owner, object view, TaskContext taskContext,
                                                    FileTypeSupport.SDLXLIFF.SegmentBuilder segmentBuilder, PathInfo pathInfo) : base(owner, view, taskContext)
        {
            _segmentBuilder = segmentBuilder;
            _pathInfo       = pathInfo;

            IsValid = true;
            InitializeJobProcessList();

            LoadPage  += OnLoadPage;
            LeavePage += OnLeavePage;
        }
        private void DebugDrawPath(PathInfo pathInfo, float offset, int index)
        {
#if ENHANCED_DEBUG
            for (int i = 0; i < pathInfo.PathNodes.Count - 1; i++)
            {
                var startNode = pathInfo.PathNodes[i];
                var endNode = pathInfo.PathNodes[i + 1];

                var startPosition = Vector3D.Transform(startNode.Pos * m_grid.GridSize, m_grid.WorldMatrix);
                var endPosition = Vector3D.Transform(endNode.Pos * m_grid.GridSize, m_grid.WorldMatrix);

                var offsetVector = new Vector3(offset);
                //MyRenderProxy.DebugDrawLine3D(startPosition + offsetVector, endPosition + offsetVector, Color.Red, Color.Red, false);
                DrawSlidingLine(endPosition + offsetVector, startPosition + offsetVector, Color.White, Color.Red);

                if (startNode.IsStatic)
                    MyRenderProxy.DebugDrawSphere(startPosition + offsetVector, 0.5f, Color.Gray, 1, false);

                if (i == pathInfo.PathNodes.Count - 2)
                {
                    MyRenderProxy.DebugDrawText3D(endPosition + offsetVector, index.ToString() + " (" + pathInfo.Ratio + ")", Color.White, 0.5f, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER);
                }
            }
#endif
        }
Example #52
0
 public override void Initialize()
 {
     Enabled           = true;
     _pathInfo         = new PathInfo();
     _languageProvider = new LanguageProvider(_pathInfo);
 }
        public void ProcessRequest(HttpContext context)
        {
            var form                 = context.Request.Form;
            var files                = context.Request.Files;
            var orderNumberId        = int.Parse(form["orderId"]);    //订单id
            var workNumber           = int.Parse(form["workNumber"]); //工序号
            var number               = int.Parse(form["number"]);     //系数
            var blankType            = form["blankType"];             //毛坯种类  判断null
            var blankSpecification   = form["blankSpecification"];    //毛坯类型   判断null
            var blankNumber          = form["blankNumber"];           //毛坯数量  判断null
            var fixtureType          = form["fixtureType"];           //治具种类
            var fixtureSpecification = form["fixtureSpecification"];  //治具规格
            var cncType              = form["cncType"];               //机床型号


            //var fileBlank = context.Request.Files["fileBlank"];//毛坯图纸 判断null
            //var fileFixture = context.Request.Files["fileFixture"];//治具图纸 判断null
            var allFiles = context.Request.Files;

            if (cncType == null)
            {
                context.Response.Write("请输入机床类型");
                return;
            }
            double   ToolTime    = 0.1666666666;   //换刀时间
            double   ProcessTime = 0;              //工序时间
            double   OnMachMea   = 0.033333333333; //探测时间
            int      toolNum     = 0;              //换刀次数
            string   ToolNo      = "0";
            int      toolFlag    = 1;
            PathInfo pathInfo    = new PathInfo();

            using (JDJS_WMS_DB_USEREntities entities = new JDJS_WMS_DB_USEREntities())
            {
                using (System.Data.Entity.DbContextTransaction mytran = entities.Database.BeginTransaction())
                {
                    try
                    {
                        if (entities.JDJS_WMS_Order_Process_Info_Table.Where(r => r.OrderID == orderNumberId & r.ProcessID == workNumber & r.sign == -1).Count() > 0)
                        {
                            context.Response.Write("该订单下工序已存在");
                            return;
                        }
                        foreach (var item in entities.JDJS_WMS_Order_Process_Info_Table.Where(r => r.OrderID == orderNumberId && r.sign != 0))
                        {
                            item.sign = -1;
                            item.program_audit_sign = -1;
                        }
                        var    orderNumber        = entities.JDJS_WMS_Order_Entry_Table.Where(r => r.Order_ID == orderNumberId).First().Order_Number;
                        int    BlankNumber        = 0;
                        int    BlankType          = 0;
                        string BlankSpecification = "";
                        string JigSpecification   = "";
                        int    FixtureType        = 0;
                        FixtureType = Convert.ToInt32(fixtureType);
                        for (int i = 0; i < allFiles.Count; i++)
                        {
                            if (context.Request.Files["fileBlank" + i] != null)
                            {
                                var           pathblank      = Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "毛坯", context.Request.Files["fileBlank" + i].FileName);
                                DirectoryInfo directoryBlank = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "毛坯"));
                                if (!directoryBlank.Exists)
                                {
                                    directoryBlank.Create();
                                }
                                context.Request.Files["fileBlank" + i].SaveAs(pathblank);
                            }
                            if (context.Request.Files["fileFixture" + i] != null)
                            {
                                var           path             = Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "治具", context.Request.Files["fileFixture" + i].FileName);
                                DirectoryInfo directoryFixture = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "治具"));
                                if (!directoryFixture.Exists)
                                {
                                    directoryFixture.Create();
                                }
                                context.Request.Files["fileFixture" + i].SaveAs(path);
                            }
                            if (context.Request.Files["technologyFile" + i] != null)
                            {
                                var           path             = Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "工艺文件", context.Request.Files["technologyFile" + i].FileName);
                                DirectoryInfo directoryFixture = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "工艺文件"));
                                if (!directoryFixture.Exists)
                                {
                                    directoryFixture.Create();
                                }
                                context.Request.Files["technologyFile" + i].SaveAs(path);
                            }//
                        }
                        //if (fileFixture != null)
                        //{
                        //    FileInfo fileInfo = new FileInfo(fileFixture.FileName);
                        //    var pathblank = Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "治具", fileInfo.Name);
                        //    DirectoryInfo directoryBlank = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(),"治具"));
                        //    if (!directoryBlank.Exists)
                        //    {
                        //        directoryBlank.Create();
                        //    }
                        //    fileFixture.SaveAs(pathblank);
                        //}
                        //if (fileBlank != null)
                        //{
                        //    FileInfo fileInfo = new FileInfo(fileBlank.FileName);
                        //    var pathblank = Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(), "毛坯", fileInfo.Name);
                        //    DirectoryInfo directoryBlank = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "工序" + workNumber.ToString(),"毛坯"));
                        //    if (!directoryBlank.Exists)
                        //    {
                        //        directoryBlank.Create();
                        //    }
                        //    fileBlank.SaveAs(pathblank);
                        //}
                        if (fixtureSpecification == null)
                        {
                        }
                        else
                        {
                            JigSpecification = fixtureSpecification;
                        }
                        if (workNumber == 1)
                        {
                            if (blankNumber == null)
                            {
                                context.Response.Write("请输入毛坯数量");
                                return;
                            }
                            BlankNumber = Convert.ToInt32(blankNumber);
                            if (blankType == null)
                            {
                                context.Response.Write("请输入毛坯种类");
                                return;
                            }
                            BlankType = Convert.ToInt32(blankType);
                            if (BlankSpecification == null)
                            {
                            }
                            else
                            {
                                BlankSpecification = blankSpecification + "#1#";
                            }
                        }
                        else
                        {
                            var process1 = entities.JDJS_WMS_Order_Blank_Table.Where(r => r.OrderID == orderNumberId).FirstOrDefault();
                            if (process1 != null)
                            {
                                BlankNumber        = Convert.ToInt32(process1.BlackNumber);
                                BlankType          = Convert.ToInt32(process1.BlankType);
                                BlankSpecification = process1.BlankSpecification;
                            }
                            else
                            {
                                context.Response.Write("请先输入毛坯信息");
                                return;
                            }
                        }

                        var judge = entities.JDJS_WMS_Order_Blank_Table.Where(r => r.OrderID == orderNumberId);
                        if (judge.Count() == 0)
                        {
                            var newRow = new JDJS_WMS_Order_Blank_Table
                            {
                                OrderID                  = orderNumberId,
                                BlankType                = BlankType,
                                BlankSpecification       = BlankSpecification,
                                BlackNumber              = BlankNumber,
                                BlankState               = "待备料",
                                BlanktotalPreparedNumber = 0,
                                BlankAddition            = 0
                            };
                            entities.JDJS_WMS_Order_Blank_Table.Add(newRow);
                        }
                        else
                        {
                            BlankSpecification = judge.First().BlankSpecification;
                            BlankType          = Convert.ToInt32(judge.First().BlankType);
                        }

                        //var name0 = files[0].FileName;
                        //var name1 = files[1].FileName;
                        //string last0 = Path.GetExtension(name0);
                        //string last1 = Path.GetExtension(name1);
                        //var program = orderNumber + "-P" + workNumber + last0;
                        //var toolChartName = "T-" + orderNumber + "-P" + workNumber + last1;


                        //var path0 = Path.Combine(pathInfo.upLoadPath(), orderNumber, "加工文件", program);
                        //DirectoryInfo directoryP = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "加工文件"));
                        //if (!directoryP.Exists)
                        //{
                        //    directoryP.Create();
                        //}
                        //files[0].SaveAs(path0);
                        //var path1 = Path.Combine(pathInfo.upLoadPath(), orderNumber, "刀具表", toolChartName);
                        //DirectoryInfo directoryT = new DirectoryInfo(Path.Combine(pathInfo.upLoadPath(), orderNumber, "刀具表"));
                        //if (!directoryT.Exists)
                        //{
                        //    directoryT.Create();
                        //}
                        //files[1].SaveAs(path1);


                        {
                            //string FilePath = path1;
                            //string path = Path.GetFileNameWithoutExtension(FilePath);
                            int ProcessID = 0;
                            //string[] str = path.Split('-');
                            string OrderNum = orderNumber;
                            string Process  = workNumber.ToString();
                            //List<int> ToolNum = new List<int>();
                            //List<ToolInfo> toolInfos = new List<ToolInfo>();
                            //string fileSuffix = System.IO.Path.GetExtension(FilePath);

                            //if (fileSuffix == ".xls")
                            //{
                            //    #region
                            //    {
                            //        DataTable dt = getData(FilePath).Tables[0];
                            //        dt.Columns[0].ColumnName = "序号";
                            //        dt.Columns[1].ColumnName = "路径名";
                            //        dt.Columns[2].ColumnName = "刀号";
                            //        dt.Columns[3].ColumnName = "刀具";
                            //        dt.Columns[4].ColumnName = "刀柄";
                            //        dt.Columns[5].ColumnName = "刀具伸出长度";
                            //        dt.Columns[6].ColumnName = "直径";
                            //        dt.Columns[7].ColumnName = "加工时间";
                            //        for (int i = 0; i < dt.Rows.Count; i++)
                            //        {
                            //            if (i == 0 || i == 1 || i == 2 || i == 3 || i == 4 || i == 5 || i == 6 || i == 8)
                            //            {
                            //                //dt.Rows.Remove(dt.Rows[0]);
                            //            }
                            //            else if (i == 7)
                            //            {

                            //                ProcessTime = 0;
                            //            }
                            //            else
                            //            {


                            //                string toolnum = dt.Rows[i]["刀号"].ToString();
                            //                double _toolnum = 0;
                            //                if (isNumberic(toolnum, out _toolnum))
                            //                {
                            //                    if (toolnum != ToolNo)
                            //                    {
                            //                        toolNum++;
                            //                        ToolNo = toolnum;
                            //                    }

                            //                    if (dt.Rows[i]["加工时间"].ToString() != "" && dt.Rows[i]["加工时间"] != null)
                            //                    {
                            //                        if (dt.Rows[i]["加工时间"].ToString().Contains(':'))
                            //                        {
                            //                            var timeInfo = dt.Rows[i]["加工时间"].ToString().Split(':');
                            //                            int hT = Convert.ToInt32(timeInfo[0]);
                            //                            int minT = Convert.ToInt32(timeInfo[1]);
                            //                            int secT = Convert.ToInt32(timeInfo[2]);
                            //                            ProcessTime += (hT * 60 + minT + ((float)secT / 60));
                            //                        }
                            //                        else
                            //                        {
                            //                            ProcessTime += (Convert.ToDouble(dt.Rows[i]["加工时间"].ToString()) * 1440);
                            //                        }
                            //                    }

                            //                    if (!ToolNum.Contains(Convert.ToInt32(dt.Rows[i]["刀号"].ToString())))
                            //                    {
                            //                        ToolNum.Add(Convert.ToInt32(dt.Rows[i]["刀号"].ToString()));
                            //                        ToolInfo tool = new ToolInfo();
                            //                        tool.PathName = dt.Rows[i]["路径名"].ToString();
                            //                        string toolno = dt.Rows[i]["刀号"].ToString();
                            //                        double _toolno = 0;
                            //                        if (isNumberic(toolno, out _toolno))
                            //                        {
                            //                            tool.ToolNO = Convert.ToInt32(dt.Rows[i]["刀号"].ToString());
                            //                        }
                            //                        tool.ToolName = dt.Rows[i]["刀具"].ToString();
                            //                        string tooll = dt.Rows[i]["刀具伸出长度"].ToString();
                            //                        double _tooll = 0;
                            //                        if (isNumberic(tooll, out _tooll))
                            //                        {
                            //                            tool.ToolLength = Convert.ToDouble(dt.Rows[i]["刀具伸出长度"].ToString());
                            //                        }
                            //                        string ToolD = dt.Rows[i]["直径"].ToString();
                            //                        double _ToolD = 0;
                            //                        if (isNumberic(ToolD, out _ToolD))
                            //                        {
                            //                            tool.ToolDiameter = Convert.ToDouble(dt.Rows[i]["直径"].ToString());
                            //                        }

                            //                        tool.Shank = dt.Rows[i]["刀柄"].ToString();
                            //                        toolInfos.Add(tool);
                            //                    }
                            //                }
                            //            }

                            //        }
                            //    }
                            //    #endregion
                            //}
                            //else
                            //{
                            //    mytran.Rollback();
                            //    context.Response.Write("刀具表请输入xls格式文件");
                            //    return;

                            //}
                            //var toolStand = entities.JDJS_WMS_Tool_Standard_Table.ToList();
                            //var CETOU = toolStand.Where(r => r.Name == "测头");
                            //int cetouID = -1;
                            //if (CETOU.Count() > 0)
                            //{
                            //    cetouID = Convert.ToInt32(CETOU.First().ToolID.Substring(1));
                            //}
                            //List<string> toolStandNo = new List<string>();
                            //foreach (var real in toolStand)
                            //{
                            //    string strT = real.ToolID;
                            //    toolStandNo.Add(strT);
                            //}
                            //foreach (var item in toolInfos)
                            //{
                            //    //判断是否有特殊刀具,判断刀具是否在刀具标准表是否存在

                            //    if (!toolStandNo.Contains("T" + item.ToolNO.ToString()))
                            //    {
                            //        toolFlag = 0;
                            //        break;
                            //    }
                            //}
                            //double times = Math.Ceiling(OnMachMea * time + ToolTime * toolNum + ProcessTime);
                            var row = new JDJS_WMS_Order_Process_Info_Table
                            {
                                OrderID   = orderNumberId,
                                ProcessID = workNumber,
                                //ProcessTime = times,
                                DeviceType         = Convert.ToInt32(cncType),
                                BlankType          = BlankType,
                                BlankSpecification = BlankSpecification,
                                JigSpecification   = JigSpecification + "#1#",
                                //programName = program,
                                //toolChartName = toolChartName,
                                sign            = -1,
                                BlankNumber     = BlankNumber,
                                toolPreparation = toolFlag,
                                JigType         = FixtureType,
                                Modulus         = number
                            };
                            entities.JDJS_WMS_Order_Process_Info_Table.Add(row);
                            entities.SaveChanges();

                            var order = entities.JDJS_WMS_Order_Entry_Table.Where(r => r.Order_Number == OrderNum);
                            if (order.Count() > 0)
                            {
                                int    orderid = order.First().Order_ID;
                                double pros    = 0;
                                if (isNumberic(Process, out pros))
                                {
                                    int prose = Convert.ToInt32(Process);
                                    var pro   = entities.JDJS_WMS_Order_Process_Info_Table.Where(r => r.OrderID == orderid && r.ProcessID == prose & r.sign == -1);
                                    if (pro.Count() > 0)
                                    {
                                        ProcessID = pro.First().ID;
                                    }
                                }
                            }
                            //foreach (var item in toolInfos)
                            //{

                            //    if (item.ToolNO != cetouID)
                            //    {
                            //        JDJS_WMS_Order_Process_Tool_Info_Table tool = new JDJS_WMS_Order_Process_Tool_Info_Table()
                            //        {
                            //            ProcessID = ProcessID,
                            //            PathName = item.PathName,
                            //            ToolNO = item.ToolNO,
                            //            ToolName = item.ToolName,
                            //            ToolLength = item.ToolLength,
                            //            ToolDiameter = item.ToolDiameter,
                            //            //ToolAroidance = item.ToolAroidance,
                            //            Shank = item.Shank
                            //        };
                            //        entities.JDJS_WMS_Order_Process_Tool_Info_Table.Add(tool);
                            //    }
                            //}
                            var processinfo = entities.JDJS_WMS_Order_Process_Info_Table.Where(r => r.ProcessID == ProcessID & r.OrderID == orderNumberId & r.sign != 0);
                            int id          = ProcessID;
                            var orderNum    = entities.JDJS_WMS_Order_Entry_Table.Where(r => r.Order_ID == orderNumberId);
                            int output      = orderNum.FirstOrDefault().Product_Output;
                            JDJS_WMS_Order_Fixture_Manager_Table fix = new JDJS_WMS_Order_Fixture_Manager_Table()
                            {
                                ProcessID     = id,
                                FixtureNumber = 0,
                                FixtureFinishPerpareNumber = 0,
                                FixtureAdditionNumber      = 0
                            };

                            JDJS_WMS_Warehouse_InOut_History_Table jd = new JDJS_WMS_Warehouse_InOut_History_Table()
                            {
                                InNum     = 0,
                                OutNum    = 0,
                                ProcessId = id
                            };
                            entities.JDJS_WMS_Warehouse_InOut_History_Table.Add(jd);
                            entities.JDJS_WMS_Order_Fixture_Manager_Table.Add(fix);
                            entities.SaveChanges();
                        }


                        //var path0 = Path.Combine(@"D:\服务器文件勿动", orderNumber, program);

                        entities.SaveChanges();
                        mytran.Commit();
                    }
                    catch (Exception ex)
                    {
                        mytran.Rollback();
                        context.Response.Write(ex.Message);
                        return;
                    }
                }
            }
            context.Response.Write("ok");
        }
Example #54
0
        /// <summary>
        /// Initializes/ loads info about XCOM resources.
        /// </summary>
        /// <param name="pathConfig"></param>
        public static void InitializeResources(PathInfo pathConfig)
        {
//			XConsole.Init(20);

            TileGroupInfo = new TileGroupManager(new TilesetManager(pathConfig.Fullpath));
        }
Example #55
0
        private void ValidateState(PathInfo pathInfo)
        {
            if (pathInfo.ElementName != null && ElementName != null)
            {
                throw new InvalidOperationException(
                    "ElementName property cannot be set when an #elementName path is provided.");
            }

            if ((pathInfo.ElementName != null || ElementName != null) &&
                RelativeSource != null)
            {
                throw new InvalidOperationException(
                    "ElementName property cannot be set with a RelativeSource.");
            }
        }
Example #56
0
        private void openProjectFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PathInfo p = new PathInfo();

            Process.Start(p.Projects);
        }
 private List<PathInfo> PopulateAutoCompleteList(Activity activity, PathInfo path)
 {
     List<PathInfo> list = new List<PathInfo>();
     System.Type activityType = this.GetActivityType(activity);
     PathInfo[] collection = (activityType != null) ? this.ProcessPaths(activityType, path) : null;
     if (collection != null)
     {
         list.AddRange(collection);
     }
     return list;
 }
Example #58
0
 public DelegateReturnHelperDescriptor(PathInfo name, HandlebarsReturnHelper helper) : base(name)
     => _helper = helper;
 private void SelectedActivityChanged(Activity activity, PathInfo memberPathInfo, string path)
 {
     string str = string.Empty;
     string simpleTypeFullName = this.GetSimpleTypeFullName(this.boundType);
     if (memberPathInfo != null)
     {
         if ((path == null) || (path.Length == 0))
         {
             str = string.Format(CultureInfo.CurrentCulture, this.PleaseSelectActivityProperty, new object[] { simpleTypeFullName });
         }
         else
         {
             MemberActivityBindTreeNode.MemberName(memberPathInfo.Path);
             string str3 = this.GetSimpleTypeFullName(memberPathInfo.PropertyType);
             string memberDescription = this.GetMemberDescription(memberPathInfo.MemberInfo);
             if (TypeProvider.IsAssignable(this.boundType, memberPathInfo.PropertyType))
             {
                 str = string.Format(CultureInfo.CurrentCulture, this.PropertyAssignableFormat, new object[] { str3, simpleTypeFullName }) + ((memberDescription.Length > 0) ? string.Format(CultureInfo.CurrentCulture, this.DescriptionFormat, new object[] { memberDescription }) : string.Empty);
             }
             else
             {
                 str = string.Format(CultureInfo.CurrentCulture, this.PleaseSelectCorrectActivityProperty, new object[] { simpleTypeFullName, str3 });
             }
             str = str + ((MemberActivityBindTreeNode.MemberName(path).IndexOfAny(new char[] { '[', ']' }) != -1) ? this.EditIndex : string.Empty);
         }
     }
     else
     {
         str = string.Format(CultureInfo.CurrentCulture, this.PleaseSelectActivityProperty, new object[] { simpleTypeFullName });
     }
     this.helpTextBox.Lines = str.Split(new char[] { '\n' });
 }
 protected ReturnBlockHelperDescriptor(PathInfo name) : base(name)
 {
 }