Example #1
1
        /// <summary>
        /// Locates the changes between the prior and post state of the modules..
        /// </summary>
        /// <param name="modules_prior">List of the available modules prior to the update.</param>
        /// <param name="modules_post">List of the available modules after the update.</param>
        private void PrintChanges(List<CkanModule> modules_prior, List<CkanModule> modules_post)
        {
            var prior = new HashSet<CkanModule>(modules_prior, new NameComparer());
            var post = new HashSet<CkanModule>(modules_post, new NameComparer());


            var added = new HashSet<CkanModule>(post.Except(prior, new NameComparer()));
            var removed = new HashSet<CkanModule>(prior.Except(post, new NameComparer()));


            var unchanged = post.Intersect(prior);//Default compare includes versions
            var updated = post.Except(unchanged).Except(added).Except(removed).ToList();

            // Print the changes.
            user.RaiseMessage("Found {0} new modules, {1} removed modules and {2} updated modules.", added.Count(), removed.Count(), updated.Count());

            if (added.Count > 0)
            {
                PrintModules("New modules [Name (CKAN identifier)]:", added);
            }

            if (removed.Count > 0)
            {
                PrintModules("Removed modules [Name (CKAN identifier)]:", removed);
            }

            if (updated.Count > 0)
            {
                PrintModules("Updated modules [Name (CKAN identifier)]:", updated);
            }
        }
Example #2
0
        public bool run()
        {
            var triangleNumbers = new HashSet<long>();
            var pentagonalNumbers = new HashSet<long>();
            var hexagonalNumbers = new HashSet<long>();
            for (var n = 1L; ; n++)
            {
                long v1 = n * (n + 1) / 2;
                long v2 = n * (3 * n - 1) / 2;
                long v3 = n * (2 * n - 1);
                triangleNumbers.Add(v1);
                pentagonalNumbers.Add(v2);
                hexagonalNumbers.Add(v3);

                if ((pentagonalNumbers.Contains(v1) && hexagonalNumbers.Contains(v1)) ||
                    (triangleNumbers.Contains(v2) && hexagonalNumbers.Contains(v2)) ||
                    (triangleNumbers.Contains(v3) && pentagonalNumbers.Contains(v3)))
                {
                    {
                        if (triangleNumbers.Intersect(pentagonalNumbers)
                                .Intersect(hexagonalNumbers).Count() == 3)
                        {
                            break;
                        }
                    }
                }
            }

            var result =
                triangleNumbers.Intersect(pentagonalNumbers)
                    .Intersect(hexagonalNumbers).OrderBy(v => v).Last();

            return result == 1533776805;
        }
Example #3
0
    static void Main(string[] args)
    {
        int[] input = Console.ReadLine().Split(' ')
            .Select(int.Parse).ToArray();

        int firstSetCount = input.First();
        int secondSetCount = input.Last();

        HashSet<int> firstSet = new HashSet<int>();
        HashSet<int> secondSet = new HashSet<int>();

        for (int i = 0; i < firstSetCount; i++)
        {
            firstSet.Add(int.Parse(Console.ReadLine()));
        }

        for (int i = 0; i < secondSetCount; i++)
        {
            secondSet.Add(int.Parse(Console.ReadLine()));
        }

        List<int> intersect = firstSet.Intersect(secondSet).ToList();

        intersect.ForEach(a => Console.Write(a + " "));
    }
Example #4
0
        public static void Main(string[] args)
        {
            var setSizes =
                Console.ReadLine()
                    .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(int.Parse)
                    .ToArray();

            var firstSet = new HashSet<int>();
            var secondSet = new HashSet<int>();

            for (int i = 0; i < setSizes[0]; i++)
            {
                firstSet.Add(int.Parse(Console.ReadLine()));
            }

            for (int i = 0; i < setSizes[1]; i++)
            {
                secondSet.Add(int.Parse(Console.ReadLine()));
            }

            var resultSet = firstSet.Intersect(secondSet);

            Console.WriteLine(string.Join(" ", resultSet));
        }
		public void UpdateReservedWordsInDialect()
		{
			var reservedDb = new HashSet<string>();
			var configuration = TestConfigurationHelper.GetDefaultConfiguration();
			var dialect = Dialect.Dialect.GetDialect(configuration.Properties);
			var connectionHelper = new ManagedProviderConnectionHelper(configuration.Properties);
			connectionHelper.Prepare();
			try
			{
				var metaData = dialect.GetDataBaseSchema(connectionHelper.Connection);
				foreach (var rw in metaData.GetReservedWords())
				{
					reservedDb.Add(rw.ToLowerInvariant());
				}
			}
			finally
			{
				connectionHelper.Release();
			}

			var sf = (ISessionFactoryImplementor) configuration.BuildSessionFactory();
			SchemaMetadataUpdater.Update(sf);
			var match = reservedDb.Intersect(sf.Dialect.Keywords);
			Assert.That(match, Is.EquivalentTo(reservedDb));
		}
Example #6
0
        public static void Main()
        {
            HashSet<int> mySet = new HashSet<int>();
            mySet.Add(10);
            mySet.Add(11);
            mySet.Add(12);
            mySet.Add(13);
            mySet.Add(19);
            mySet.Add(14);
            mySet.Add(15);

            HashSet<int> myOtherSet = new HashSet<int>();
            myOtherSet.Add(10);
            myOtherSet.Add(11);
            myOtherSet.Add(12);
            myOtherSet.Add(13);
            myOtherSet.Add(14);
            myOtherSet.Add(15);
            myOtherSet.Add(16);

            //var union = mySet.Union(myOtherSet);

            //foreach (var item in union)
            //{
            //    Console.WriteLine(item);
            //}

            var intersect = mySet.Intersect(myOtherSet);

            foreach (var item in intersect)
            {
                Console.WriteLine(item);
            }
        }
Example #7
0
        public static double simularity(HashSet<string> setA, HashSet<string> setB)
        {
            double interCount = setA.Intersect(setB).Count();
            if (interCount == 0) return 0;

            double unionCount = setA.Union(setB).Count();
            return interCount / unionCount;
        }
Example #8
0
        /// <summary>
        /// Does intersect using hash sets.
        /// </summary>
        /// <param name="list1"></param>
        /// <param name="list2"></param>
        /// <param name="toLower"></param>
        /// <param name="factor"></param>
        /// <returns></returns>
        public static bool HashSetIntersects(IEnumerable<string> list1, IEnumerable<string> list2, bool toLower, int factor)
        {
            var set1 = new HashSet<string>(list1);
            var set2 = new HashSet<string>(list2);

            if (toLower)
            {
                return set1.Select(x => x.ToLower()).Intersect(set2.Select(x => x.ToLower())).Count() >= factor;
            }

            return set1.Intersect(set2).Count() >= factor;
        }
        public void TestRecognizeSpirals()
        {
            Bitmap b = MakeBitmap(100, 100, (Graphics g) =>
                {
                    int top = 20;
                    int bottom = 75;

                    for (int i = 20; i <= 60; i += 10 )
                    {
                        g.DrawLine(Pens.Black, i, top, i, bottom);

                        if (i != 80) {
                            if ((i / 10) % 2 == 0) {
                                top += 10;
                                g.DrawLine(Pens.Black, i, bottom, i + 10, bottom);
                            }
                            else {
                                bottom -= 10;
                                g.DrawLine(Pens.Black, i, top, i + 10, top);
                            }
                        }
                    }

                    g.FillPolygon(Brushes.Black, new Point[] {
                        new Point(30, 20),
                        new Point(80, 20),
                        new Point(80, 45) });
                    g.DrawPolygon(Pens.Black, new Point[] {  //Make sure that we draw the borders too
                        new Point(30, 20),
                        new Point(80, 20),
                        new Point(80, 45) });

                    g.FillPolygon(Brushes.Black, new Point[] {
                        new Point(30, 80),
                        new Point(80, 80),
                        new Point(80, 55) });
                    g.DrawPolygon(Pens.Black, new Point[] {
                        new Point(30, 80),
                        new Point(80, 80),
                        new Point(80, 55) });
                });

            HashSet<Rectangle> expected = new HashSet<Rectangle>();
            HashSet<Rectangle> blobs = new HashSet<Rectangle>(from blob in MangaParser.Graphics.Raster.Graphics.IdentifyBlobs(b)
                                                              select blob.BoundingBox);

            expected.Add(new Rectangle(20, 20, 51, 56));
            expected.Add(new Rectangle(30, 20, 51, 26));
            expected.Add(new Rectangle(30, 55, 51, 26));

            Assert.AreEqual(expected.Count, blobs.Intersect(expected).Count());
        }
        public static void Main(string[] args)
        {
            HashSet<int> first = new HashSet<int>();
            first.Add(1);
            first.Add(2);
            first.Add(3);

            Console.Write("First set: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            HashSet<int> second = new HashSet<int>();
            second.Add(4);
            second.Add(1);
            second.Remove(1);

            Console.Write("Second set: ");
            foreach (var item in second)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            first.Union(second);

            Console.Write("Sets union: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            //second.Add(1);

            first.Intersect(second);

            Console.Write("Sets intersection: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();
        }
    public IEnumerable<Person> GetMatchesByKeysAndTown(string[] param)
    {
        var matchedPersons = names[param[0]];
        HashSet<Person> result = new HashSet<Person>(matchedPersons);
        
        for (int i = 1; i < param.Length; i++)
        {
            matchedPersons = names[param[i]];
            var hashedSet = new HashSet<Person>(matchedPersons);
            result = new HashSet<Person>(result.Intersect(hashedSet));
        }

        return result;
    }
Example #12
0
    /// <summary>
    /// 创建一个简单路由规则
    /// </summary>
    /// <param name="name">规则名称</param>
    /// <param name="urlPattern">URL 模式</param>
    /// <param name="routeValues">静态/默认路由值</param>
    /// <param name="queryKeys">可用于 QueryString 的参数</param>
    internal SimpleRouteRule( string name, string urlPattern, IDictionary<string, string> routeValues, string[] queryKeys )
    {
      Name = name;

      if ( queryKeys == null )
      {
        LimitedQueries = false;
        queryKeys = new string[0];
      }
      else
        LimitedQueries = true;

      DataTokens = new RouteValueDictionary();


      var match = urlPatternRegex.Match( urlPattern );

      if ( !match.Success )
        throw new FormatException( "URL模式格式不正确" );

      _paragraphes = match.Groups["paragraph"].Captures.Cast<Capture>().Select( c => c.Value ).ToArray();

      _urlPattern = urlPattern;
      _staticValues = new Dictionary<string, string>( routeValues, StringComparer.OrdinalIgnoreCase );


      _routeKeys = new HashSet<string>( _staticValues.Keys, StringComparer.OrdinalIgnoreCase );

      _dynamics = new HashSet<string>( _paragraphes.Where( p => p.StartsWith( "{" ) && p.EndsWith( "}" ) ).Select( p => p.Substring( 1, p.Length - 2 ) ), StringComparer.OrdinalIgnoreCase );



      foreach ( var key in _dynamics )
      {
        if ( _routeKeys.Contains( key ) )
          throw new FormatException( "URL模式格式不正确,包含重复的动态参数名或动态参数名与预设路由键重复" );


        _routeKeys.Add( key );
      }

      if ( _routeKeys.Intersect( queryKeys, StringComparer.OrdinalIgnoreCase ).Any() )
        throw new FormatException( "URL模式格式不正确,动态参数或预设路由键与可选查询字符串名重复" );

      _queryKeys = new HashSet<string>( queryKeys, StringComparer.OrdinalIgnoreCase );

      _allKeys = new HashSet<string>( _routeKeys, StringComparer.OrdinalIgnoreCase );
      _allKeys.UnionWith( _queryKeys );

    }
        public void HashSetShouldIntersectElementCorrectly()
        {
            var set1 = new HashSet<int>();
            var set2 = new HashSet<int>();
            set1.Add(1);
            set1.Add(2);
            set1.Add(3);

            set2.Add(1);
            set2.Add(5);
            set2.Add(6);

            var intersect = set1.Intersect(set2);

            Assert.IsTrue(intersect.Find(1));
            Assert.AreEqual(1, intersect.Count);
        }
        protected override void InternalHandle(Output result, string args, DependencyGraph graph)
        {
            var projctsFiltered = FilterLibs(graph, args);

            IDictionary<Library, int> components;
            graph.StronglyConnectedComponents(out components);

            var circularDependencies = components.Select(c => new { Proj = c.Key, Group = c.Value })
                .GroupBy(c => c.Group)
                .Where(g => g.Count() > 1);

            bool found = false;
            foreach (var g in circularDependencies)
            {
                var libs = g.Select(i => i.Proj)
                    .ToList();

                var projsSet = new HashSet<Library>(libs);

                if (!projsSet.Intersect(projctsFiltered)
                    .Any())
                    continue;

                found = true;

                libs.Sort(Library.NaturalOrdering);

                result.AppendLine("Circular dependency:");
                result.IncreaseIndent();

                foreach (var lib in libs)
                {
                    var proj = lib as Project;
                    if (proj != null)
                        result.AppendLine("{0} (project path: {1})", GetName(proj), proj.ProjectPath);
                    else
                        result.AppendLine(GetName(lib));
                }

                result.DecreaseIndent();
                result.AppendLine();
            }

            if (!found)
                result.AppendLine("No circular dependency found");
        }
        public static void Main()
        {
            var firstSet = new HashSet<int>();
            var secondSet = new HashSet<int>();
            firstSet.Add(1);
            firstSet.Add(2);
            firstSet.Add(7);
            secondSet.Add(7);
            secondSet.Add(13);
            secondSet.Add(19);
            firstSet.Remove(2);

            var unionSet = firstSet.Union(secondSet);
            Console.WriteLine("Union set = {0}", unionSet);

            var intersectSet = firstSet.Intersect(secondSet);
            Console.WriteLine("Intersect set = {0}", intersectSet);
        }
        public async Task OptionsViewModel_ReconcilePlatformsWithBackendAsync_ReturnsInvalidPlatforms()
        {
            int numberOfPlatforms = 6;
            var serverPlatformNames = new string[] { "valid1", "valid2" };
            var apiPort = ApiPortWhichReturnsPlatforms(serverPlatformNames);

            var invalidLocalPlatforms = (from n in Enumerable.Range(1, numberOfPlatforms)
                                 select new TargetPlatform { Name = string.Format("invalid{0}", n), Selected = n % 2 == 0 })
                                 .ToList();

            var viewModel = new TestableOptionsViewModel(apiPort, invalidLocalPlatforms);

            var result = await viewModel.ReconcilePlatformsWithBackendAsync();

            var localHash = new HashSet<TargetPlatform>(invalidLocalPlatforms);
            var resultHash = new HashSet<TargetPlatform>(result);

            Assert.IsTrue(localHash.Intersect(resultHash).Count() == localHash.Count);
        }
            protected override void Push(IEnumerable<ParameterExpression> variables)
            {
                var newEnv = new HashSet<ParameterExpression>(variables);
                var subst = new Dictionary<ParameterExpression, ParameterExpression>();

                foreach (var env in _env)
                {
                    if (env.Overlaps(newEnv))
                    {
                        foreach (var p in newEnv.Intersect(env))
                        {
                            subst[p] = Expression.Parameter(p.Type, p.Name);
                        }
                    }
                }

                _env.Push(newEnv);
                _subst.Push(subst);
            }
Example #18
0
        static void Main(string[] args)
        {
            int[] dimentions =
                Console.ReadLine().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

            HashSet<int> set1= new HashSet<int>();
            HashSet<int> set2 = new HashSet<int>();

            for (int i = 0; i < dimentions[0]; i++)
            {
                set1.Add(int.Parse(Console.ReadLine()));
            }
            for (int i = 0; i < dimentions[1]; i++)
            {
                set2.Add(int.Parse(Console.ReadLine()));
            }

            Console.WriteLine(string.Join(" ",set1.Intersect(set2)));
        }
        static void Main(string[] args)
        {
            HashSet<string> hashSet = new HashSet<string>();

            hashSet.Add("ooo");
            hashSet.Add("qqq");
            hashSet.Add("ppp");
            hashSet.Add("iii");

            foreach (var item in hashSet.Items)
            {
                Console.WriteLine(item);
            }

            hashSet.Remove("iii");
            Console.WriteLine("\nCount after removal: {0}", hashSet.Count);


            Console.WriteLine();
            Console.WriteLine(hashSet.Find("ppp"));


            HashSet<string> secondHashSet = new HashSet<string>();
            secondHashSet.Add("www");
            secondHashSet.Add("qqq");
            secondHashSet.Add("yyy");
            secondHashSet.Add("ooo");

            Console.WriteLine("\nUnion: ");
            HashSet<string> union = hashSet.Union(secondHashSet);
            foreach (var item in union.Items)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\nIntersection: ");
            HashSet<string> intersection = hashSet.Intersect(secondHashSet);
            foreach (var item in intersection.Items)
            {
                Console.WriteLine(item);
            }
        }
		public static void MenuSelectFacesWithColor()
		{
			foreach(pb_Object pb in pbUtil.GetComponents<pb_Object>(Selection.transforms))
			{
				HashSet<Color> cols = new HashSet<Color>();
				
				foreach(pb_Face f in pb.SelectedFaces)
				{
					foreach(int i in f.distinctIndices)
						cols.Add(pb.colors[i]);
				}

				pb_Face[] faces = System.Array.FindAll(pb.faces, x => cols.Intersect(pbUtil.ValuesWithIndices(pb.colors, x.distinctIndices)).Count() > 0);

				pb.SetSelectedFaces(faces);
				if(pb_Editor.instance)
					pb_Editor.instance.UpdateSelection();
				
				EditorWindow.FocusWindowIfItsOpen(typeof(SceneView));
			}
		}
Example #21
0
        static void Main()
        {
            HashSet<string> testTable = new HashSet<string>();

            testTable.Add("stoicho");
            testTable.Add("peicho");
            testTable.Add("koicho");
            testTable.Add("koicho");
            testTable.Add("koicho");
            testTable.Add("nacho");
            testTable.Add("bochko");
            testTable.Add("zuza");
            testTable.Add("ko");

            //foreach (var key in testTable)
            //{
            //    Console.WriteLine(key);

            //}

            HashSet<string> testTable2 = new HashSet<string>();
            testTable2.Add("gosho");
             testTable2.Add("stoicho");
            testTable2.Add("peicho");
            testTable2.Add("koicho");
             testTable2.Add("asen");
            testTable2.Add("peicho");
            testTable2.Add("toshkata");

            //testTable.Union(testTable2);

            var testTable3 = testTable.Intersect(testTable2);

            foreach (var key in testTable3)
            {
                Console.WriteLine(key);

            }
        }
Example #22
0
        public bool IsConnected()
        {
            HashSet<Point> allPathablePoints = new HashSet<Point>();
            foundPathablePoints = new HashSet<Point>();

            for (int i = 0; i < thisMap.Width; i++)
            {
                for (int j = 0; j < thisMap.Height; j++)
                {
                    if(CountsAsWalkable(thisMap.getCell(i, j)))
                        allPathablePoints.Add(new Point(i, j));
                }
            }

            if(allPathablePoints.Count() == 0)
                return true;

            Stack<Point> workNodes = new Stack<Point>();

            workNodes.Push(allPathablePoints.First());

            while (workNodes.Count() > 0)
            {
                var thisNode = workNodes.Pop();
                if (CountsAsWalkable(thisMap.getCell(thisNode.x, thisNode.y)))
                {
                    foundPathablePoints.Add(thisNode);
                    var neighbours = Get4WayNeighbours(thisNode);
                    foreach (var p in neighbours)
                        workNodes.Push(p);
                }
            }

            if (allPathablePoints.Intersect(foundPathablePoints).Count() == allPathablePoints.Count())
                return true;

            return false;
        }
Example #23
0
        static void Main(string[] args)
        {
            int NewNumber = 10000000;

            int[] FirstArray = new int[NewNumber];

            int[] SecondArray = new int[NewNumber];

            int[] ThirdArray = new int[NewNumber];

            FirstArray[0] = 1;

            SecondArray[0] = 2;

            ThirdArray[0] = 2;

            for (int i = 1; i < NewNumber; i++)
            {
                FirstArray[i] = 2 * FirstArray[i - 1] + 3;
                SecondArray[i] = 3 * SecondArray[i - 1] + 1;
                ThirdArray[i] = 2 * ThirdArray[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(FirstArray);

            HashSet<int> hash2 = new HashSet<int>(SecondArray);

            HashSet<int> hash3 = new HashSet<int>(ThirdArray);

            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2));

            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }
        }
Example #24
0
        public static void Main()
        {
            try
            {
                HashSet<int> hashSet = new HashSet<int>();

                hashSet.Add(1);
                hashSet.Add(5);
                hashSet.Add(2);
                hashSet.Add(33);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                hashSet.Remove(2);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                Console.WriteLine(hashSet.Find(5));
                Console.WriteLine(hashSet.Contains(5));

                int[] numArray = new int[] { 5, 11, 33 };
                int[] array = numArray;
                hashSet.UnionWith(array);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                int[] numArray1 = new int[] { 5, 11, 22 };
                int[] array2 = numArray1;
                hashSet.Intersect(array2);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                hashSet.Clear();
                Console.WriteLine("Count is : {0}", hashSet.Count);
                Console.WriteLine(hashSet.Find(5));
            }
            catch (ArgumentException aex)
            {
                Console.WriteLine(aex.Message);
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            int number = 100000;

           
            int[] arr1 = new int[number];
            int[] arr2 = new int[number];
            int[] arr3 = new int[number];

            arr1[0] = 1;
            arr2[0] = 2;
            arr3[0] = 2;

            for (int i = 1; i < number; i++)
            {
                arr1[i] = 2 * arr1[i - 1] + 3;
                arr2[i] = 3 * arr2[i - 1] + 1;
                arr3[i] = 2 * arr3[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(arr1);
            HashSet<int> hash2 = new HashSet<int>(arr2);
            HashSet<int> hash3 = new HashSet<int>(arr3);
            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2)); 
            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));


        

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }


        }
Example #26
0
        static void Main(string[] args)
        {
            int numberOfEdges = int.Parse(Console.ReadLine());

            HashSet<int> parents = new HashSet<int>();
            HashSet<int> childrens = new HashSet<int>();
            for (int i = 0; i < numberOfEdges; i++)
            {
                string[] current = Console.ReadLine().Split();
                parents.Add(int.Parse(current[0]));
                childrens.Add(int.Parse(current[1]));
            }

            IEnumerable<int> result = parents.Intersect(childrens);
            foreach (var item in result)
            {
                childrens.Remove(item);
            }

            int[] forPrint = childrens.ToArray();
            Array.Sort(forPrint);

            Console.WriteLine(string.Join("\n", forPrint));
        }
Example #27
0
        private bool is_non_hispanic(string p_ethnicity, System.Dynamic.ExpandoObject p_source_object)
        {
            bool result = false;

            HashSet <string> bc_ethinicity = new HashSet <string> (StringComparer.InvariantCultureIgnoreCase);
            HashSet <string> dc_ethinicity = new HashSet <string> (StringComparer.InvariantCultureIgnoreCase);

            bc_ethinicity.Add(p_ethnicity);
            dc_ethinicity.Add(p_ethnicity);

            object val = get_value(p_source_object, "birth_fetal_death_certificate_parent/demographic_of_mother/is_of_hispanic_origin");

            if (val != null)
            {
                if
                (
                    "No, not Spanish/ Hispanic/ Latino".Equals(val.ToString(), StringComparison.InvariantCultureIgnoreCase) ||
                    "No, not Spanish/Hispanic/Latino".Equals(val.ToString(), StringComparison.InvariantCultureIgnoreCase)
                )
                {
                    val = get_value(p_source_object, "birth_fetal_death_certificate_parent/race/race_of_mother");
                    if (val != null)
                    {
                        HashSet <string> ethnicity_set = new HashSet <string> (StringComparer.InvariantCultureIgnoreCase);
                        foreach (string item in val as IList <object> )
                        {
                            ethnicity_set.Add(item);
                        }

                        if (ethnicity_set.Intersect(bc_ethinicity).Count() > 0)
                        {
                            result = true;
                        }
                    }
                }
                else
                {
                    val = get_value(p_source_object, "death_certificate/demographics/is_of_hispanic_origin");

                    if
                    (
                        val != null &&
                        (
                            "No, not Spanish/ Hispanic/ Latino".Equals(val.ToString(), StringComparison.InvariantCultureIgnoreCase) ||
                            "No, not Spanish/Hispanic/Latino".Equals(val.ToString(), StringComparison.InvariantCultureIgnoreCase)
                        )
                    )
                    {
                        val = get_value(p_source_object, "death_certificate/race/race");
                        if (val != null)
                        {
                            HashSet <string> ethnicity_set = new HashSet <string> (StringComparer.InvariantCultureIgnoreCase);
                            foreach (string item in val as IList <object> )
                            {
                                ethnicity_set.Add(item);
                            }
                            if (ethnicity_set.Intersect(bc_ethinicity).Count() > 0)
                            {
                                result = true;
                            }
                        }
                    }
                }
            }

            return(result);
        }
Example #28
0
        static void Main(string[] args)
        {
#if DEBUG
            folder1    = @"d:\temp\folder1";
            folder2    = @"d:\temp\folder2";
            outputPath = @"";
#else
            if (args.Length < 2)
            {
                Console.Write("Usage: FolderDiff.exe folder1 folder2 [outputpath]");
                return;
            }

            folder1    = args[0];
            folder2    = args[1];
            outputPath = args.Length > 2 ? args[2] : string.Empty;
#endif

            if (!Directory.Exists(folder1))
            {
                Console.WriteLine($"Error: {folder1} does not exist");
                return;
            }

            if (!Directory.Exists(folder2))
            {
                Console.WriteLine($"Error: {folder2} does not exist");
                return;
            }

            if (File.Exists(outputPath))
            {
                try
                {
                    File.Create(outputPath).Close();
                }
                catch (DirectoryNotFoundException ex)
                {
                    Console.Write($"Error: {ex.Message}");
                    return;
                }
                catch (IOException ex)
                {
                    Console.Write($"Error: {ex.Message}");
                    return;
                }
            }

            var folder1FileList = Directory.GetFiles(folder1, "*", SearchOption.AllDirectories);
            var folder2FileList = Directory.GetFiles(folder2, "*", SearchOption.AllDirectories);

            foreach (var file in folder1FileList)
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(file))
                    {
                        // ignore case
                        string path = file.Replace(folder1, "").ToLower();
#if DEBUG
                        Console.WriteLine("[folder1] file: {0}, path: {1}", file, path);
#endif
                        folder1Set.Add(path);
                        folder1File2MD5Mappping[path] = System.Text.Encoding.Default.GetString(md5.ComputeHash(stream));
                    }
                }
            }

            foreach (var file in folder2FileList)
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(file))
                    {
                        // ignore case
                        string path = file.Replace(folder2, "").ToLower();
#if DEBUG
                        Console.WriteLine("[folder2] file: {0}, path: {1}", file, path);
#endif
                        folder2Set.Add(path);
                        folder2File2MD5Mappping[path] = System.Text.Encoding.Default.GetString(md5.ComputeHash(stream));
                    }
                }
            }

            var inFolder2AndInFolder1Set = folder2Set.Intersect(folder1Set);
            foreach (var file in inFolder2AndInFolder1Set)
            {
                if (folder1File2MD5Mappping[file] != folder2File2MD5Mappping[file])
                {
#if DEBUG
                    Console.WriteLine("Compare: [{0}], different", file);
#endif
                    outputSD(file, SDOperation.Edit);
                }
                else
                {
#if DEBUG
                    Console.WriteLine("Compare: [{0}], the same", file);
#endif
                }
            }

            var inFolder1ButNotInFolder2Set = folder1Set.Except(folder2Set);
            foreach (var file in inFolder1ButNotInFolder2Set)
            {
#if DEBUG
                Console.WriteLine("Compare: [{0}], not exist in folder2", file);
#endif
                outputSD(file, SDOperation.Delete);
            }

            var inFolder2ButNotInFolder1Set = folder2Set.Except(folder1Set);
            foreach (var file in inFolder2ButNotInFolder1Set)
            {
#if DEBUG
                Console.WriteLine("Compare: [{0}], not exist in folder1", file);
#endif
                outputSD(file, SDOperation.Add);
            }

            if (!string.IsNullOrEmpty(outputPath) && File.Exists(outputPath))
            {
                Console.Write($"Result is successfully published to {outputPath}");
            }

#if DEBUG
            Console.ReadLine();
#endif
        }
Example #29
0
        private void UpdateServerList()
        {
            HashSet<int> HasAttribute = new HashSet<int>(from TServerAtribute I in lbServerAtributes.CheckedItems
                                                select I.ID);

            HashSet<int> NotHasAttribute = new HashSet<int>(from TServerAtribute I in cbNot.CheckedItems
                                                         select I.ID);


            IEnumerable<TServer> res1 = from TServer S in Data.Servers
                                        where HasAttribute.IsSubsetOf(S.Attributes)  &&  NotHasAttribute.Intersect(S.Attributes).Count()==0
                                        select S;
            lbServers.Items.Clear();

            foreach (TServer S in res1)
            {
                lbServers.Items.Add(S, cbSelect.Checked);
            }



            UpdateServersCount();
            
            /*
            tbDebug.Items.Clear();

            foreach (int x in res)
            {

                tbDebug.Items.Add(x);

            }
             */
        }
Example #30
0
        /// <summary>
        /// アセットバンドルをビルドします.
        /// </summary>
        /// <returns>ビルドに成功していればtrueを、それ以外はfalseを返す.</returns>
        public bool BuildAssetBundles()
        {
            try
            {
                AssetBundleManifest oldManifest = null;
                var manifestPath = Path.Combine(bundleOutputPath, actualBuildTarget.ToString());
                if (File.Exists(manifestPath))
                {
                    var manifestAssetBundle = AssetBundle.LoadFromFile(manifestPath);
                    oldManifest = manifestAssetBundle
                                                ? manifestAssetBundle.LoadAsset <AssetBundleManifest>("assetbundlemanifest")
                                                : null;
                }

                UnityEngine.Debug.Log(kLogType + "BuildAssetBundles is started.");

                Directory.CreateDirectory(bundleOutputPath);
                BuildAssetBundleOptions opt = (BuildAssetBundleOptions)bundleOptions | BuildAssetBundleOptions.DeterministicAssetBundle;
                var newManifest             = BuildPipeline.BuildAssetBundles(bundleOutputPath, opt, actualBuildTarget);

                var      sb = new StringBuilder(kLogType + "AssetBundle report");
                string[] array;
                if (oldManifest)
                {
                    // 差分をログ出力.
                    var oldBundles = new HashSet <string>(oldManifest ? oldManifest.GetAllAssetBundles() : new string[] {});
                    var newBundles = new HashSet <string>(newManifest.GetAllAssetBundles());

                    // 新規
                    array = newBundles.Except(oldBundles).ToArray();
                    sb.AppendFormat("\n[Added]: {0}\n", array.Length);
                    foreach (var bundleName in array)
                    {
                        sb.AppendLine("  > " + bundleName);
                    }

                    // 削除
                    array = oldBundles.Except(newBundles).ToArray();
                    sb.AppendFormat("\n[Deleted]: {0}\n", array.Length);
                    foreach (var bundleName in array)
                    {
                        sb.AppendLine("  > " + bundleName);
                    }

                    // 更新
                    array = oldBundles
                            .Intersect(newBundles)
                            .Where(x => !Hash128.Equals(oldManifest.GetAssetBundleHash(x), newManifest.GetAssetBundleHash(x)))
                            .ToArray();
                    sb.AppendFormat("\n[Updated]: {0}\n", array.Length);
                    foreach (var bundleName in array)
                    {
                        sb.AppendLine("  > " + bundleName);
                    }
                }
                else
                {
                    // 新規
                    array = newManifest.GetAllAssetBundles();
                    sb.AppendFormat("\n[Added]: {0}\n", array.Length);
                    foreach (var bundleName in array)
                    {
                        sb.AppendLine("  > " + bundleName);
                    }
                }
                UnityEngine.Debug.Log(sb);


                if (copyToStreamingAssets)
                {
                    var copyPath = Path.Combine(Application.streamingAssetsPath, bundleOutputPath);
                    Directory.CreateDirectory(copyPath);

                    if (Directory.Exists(copyPath))
                    {
                        FileUtil.DeleteFileOrDirectory(copyPath);
                    }

                    FileUtil.CopyFileOrDirectory(bundleOutputPath, copyPath);
                }
                UnityEngine.Debug.Log(kLogType + "BuildAssetBundles is finished successfuly.");
                return(true);
            }
            catch (System.Exception e)
            {
                UnityEngine.Debug.LogError(kLogType + "BuildAssetBundles is failed : " + e.Message);
                return(false);
            }
        }
Example #31
0
        public void HashSetWithBuiltInComparer_HashSetContainsNotUsed()
        {
            IEnumerable<string> input1 = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a" };
            IEnumerable<string> input2 = new[] { "A" };

            Assert.Equal(Enumerable.Empty<string>(), input1.Intersect(input2));
            Assert.Equal(Enumerable.Empty<string>(), input1.Intersect(input2, null));
            Assert.Equal(Enumerable.Empty<string>(), input1.Intersect(input2, EqualityComparer<string>.Default));
            Assert.Equal(new[] { "a" }, input1.Intersect(input2, StringComparer.OrdinalIgnoreCase));

            Assert.Equal(Enumerable.Empty<string>(), input2.Intersect(input1));
            Assert.Equal(Enumerable.Empty<string>(), input2.Intersect(input1, null));
            Assert.Equal(Enumerable.Empty<string>(), input2.Intersect(input1, EqualityComparer<string>.Default));
            Assert.Equal(new[] { "A" }, input2.Intersect(input1, StringComparer.OrdinalIgnoreCase));
        }
Example #32
0
 public bool End()
 {
     return(CurrentState.Intersect(FinalStateMachine).Any());
 }
Example #33
0
 public HPartitioningAttributeDefinition DesignFor(AttributeData attribute, ISet <string> operators, PrimaryKeyData relationPrimaryKey)
 {
     // if relation has primary key, attribute must be part of it
     if (relationPrimaryKey == null || relationPrimaryKey.Attributes.Select(x => x.Name).ToHashSet().Contains(attribute.Name))
     {
         // range partitioning only for NotNull numeric/datetime attributes
         if (IsTypeSuitableForRange(attribute.IsNullable, attribute.DbType))
         {
             switch (attribute.DbType)
             {
             case DbType.Byte:
             case DbType.Decimal:
             case DbType.Double:
             case DbType.Int16:
             case DbType.Int32:
             case DbType.Int64:
             case DbType.SByte:
             case DbType.Single:
             case DbType.UInt16:
             case DbType.UInt32:
             case DbType.UInt64:
             case DbType.VarNumeric:
             case DbType.Time:
             case DbType.Date:
             case DbType.DateTime:
             case DbType.DateTime2:
             case DbType.DateTimeOffset:
                 return(DesignRange(attribute));
             }
         }
         // hash partitioning only for attributes where user never applied comparison operators
         else if (supportsHashPartitioning && comparableOperators.Intersect(operators).Count() == 0) // hash
         {
             switch (attribute.DbType)
             {
             case DbType.AnsiString:
             case DbType.AnsiStringFixedLength:
             case DbType.Boolean:
             case DbType.Byte:
             case DbType.Currency:
             case DbType.Date:
             case DbType.DateTime:
             case DbType.DateTime2:
             case DbType.DateTimeOffset:
             case DbType.Decimal:
             case DbType.Double:
             case DbType.Guid:
             case DbType.Int16:
             case DbType.Int32:
             case DbType.Int64:
             case DbType.SByte:
             case DbType.Single:
             case DbType.String:
             case DbType.StringFixedLength:
             case DbType.Time:
             case DbType.UInt16:
             case DbType.UInt32:
             case DbType.UInt64:
             case DbType.VarNumeric:
                 return(DesignHash(attribute));
             }
         }
     }
     return(null);
 }
Example #34
0
        public override Widget build(BuildContext context)
        {
            List <Widget> chips = this._materials.Select <string, Widget>((string name) => {
                return(new Chip(
                           key: Key.key(name),
                           backgroundColor: this._nameToColor(name),
                           label: new Text(this._capitalize(name)),
                           onDeleted: () => { this.setState(() => { this._removeMaterial(name); }); }
                           ));
            }).ToList();

            List <Widget> inputChips = this._tools.Select <string, Widget>((string name) => {
                return(new InputChip(
                           key: ValueKey <string> .key(name),
                           avatar: new CircleAvatar(
                               backgroundImage: this._nameToAvatar(name)
                               ),
                           label: new Text(this._capitalize(name)),
                           onDeleted: () => { this.setState(() => { this._removeTool(name); }); }));
            }).ToList();

            List <Widget> choiceChips = this._materials.Select <string, Widget>((string name) => {
                return(new ChoiceChip(
                           key: ValueKey <string> .key(name),
                           backgroundColor: this._nameToColor(name),
                           label: new Text(this._capitalize(name)),
                           selected: this._selectedMaterial == name,
                           onSelected: (bool value) => {
                    this.setState(() => { this._selectedMaterial = value ? name : ""; });
                }
                           ));
            }).ToList();

            List <Widget> filterChips = ChipDemoUtils._defaultTools.Select <string, Widget>((string name) => {
                return(new FilterChip(
                           key: ValueKey <string> .key(name),
                           label: new Text(this._capitalize(name)),
                           selected: this._tools.Contains(name) ? this._selectedTools.Contains(name) : false,
                           onSelected: !this._tools.Contains(name)
                        ? (ValueChanged <bool>)null
                        : (bool value) => {
                    this.setState(() => {
                        if (!value)
                        {
                            this._selectedTools.Remove(name);
                        }
                        else
                        {
                            this._selectedTools.Add(name);
                        }
                    });
                }
                           ));
            }).ToList();

            HashSet <string> allowedActions = new HashSet <string>(new List <string> {
            });

            if (this._selectedMaterial != null && this._selectedMaterial.isNotEmpty())
            {
                foreach (string tool in this._selectedTools)
                {
                    allowedActions.UnionWith(ChipDemoUtils._toolActions[tool]);
                }

                allowedActions =
                    new HashSet <string>(
                        allowedActions.Intersect(ChipDemoUtils._materialActions[this._selectedMaterial]));
            }

            List <Widget> actionChips = allowedActions.Select <string, Widget>((string name) => {
                return(new ActionChip(
                           label: new Text(this._capitalize(name)),
                           onPressed: () => { this.setState(() => { this._selectedAction = name; }); }
                           ));
            }).ToList();

            ThemeData     theme = Theme.of(context);
            List <Widget> tiles = new List <Widget> {
                new SizedBox(height: 8.0f, width: 0.0f),
                new _ChipsTile(label: "Available Materials (Chip)", children: chips),
                new _ChipsTile(label: "Available Tools (InputChip)", children: inputChips),
                new _ChipsTile(label: "Choose a Material (ChoiceChip)", children: choiceChips),
                new _ChipsTile(label: "Choose Tools (FilterChip)", children: filterChips),
                new _ChipsTile(label: "Perform Allowed Action (ActionChip)", children: actionChips),
                new Divider(),
                new Padding(
                    padding: EdgeInsets.all(8.0f),
                    child: new Center(
                        child: new Text(this._createResult(),
                                        style: theme.textTheme.title
                                        )
                        )
                    )
            };

            return(new Scaffold(
                       appBar: new AppBar(
                           title: new Text("Chips"),
                           actions: new List <Widget> {
                new MaterialDemoDocumentationButton(ChipDemo.routeName),
                new IconButton(
                    onPressed: () => {
                    this.setState(() => { this._showShapeBorder = !this._showShapeBorder; });
                },
                    icon: new Icon(Icons.vignette)
                    )
            }
                           ),
                       body: new ChipTheme(
                           data: this._showShapeBorder
                        ? theme.chipTheme.copyWith(
                               shape: new BeveledRectangleBorder(
                                   side: new BorderSide(width: 0.66f, style: BorderStyle.solid, color: Colors.grey),
                                   borderRadius: BorderRadius.circular(10.0f)
                                   ))
                        : theme.chipTheme,
                           child: new ListView(children: tiles)
                           ),
                       floatingActionButton: new FloatingActionButton(
                           onPressed: () => this.setState(this._reset),
                           child: new Icon(Icons.refresh)
                           )
                       ));
        }
Example #35
0
        /// <summary>Group failed mods by the priority players should update them, where mods in earlier groups are more likely to fix multiple mods.</summary>
        /// <param name="failedMods">The failed mods to group.</param>
        private IEnumerable <IList <IModMetadata> > GroupFailedModsByPriority(IList <IModMetadata> failedMods)
        {
            var failedOthers  = failedMods.ToList();
            var skippedModIds = new HashSet <string>(from mod in failedMods where mod.HasID() select mod.Manifest.UniqueID, StringComparer.OrdinalIgnoreCase);

            // group B: dependencies which failed
            var failedOtherDependencies = new List <IModMetadata>();
            {
                // get failed dependency IDs
                var skippedDependencyIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                foreach (IModMetadata mod in failedMods)
                {
                    foreach (string requiredId in skippedModIds.Intersect(mod.GetRequiredModIds()))
                    {
                        skippedDependencyIds.Add(requiredId);
                    }
                }

                // group matching mods
                this.FilterThrough(
                    fromList: failedOthers,
                    toList: failedOtherDependencies,
                    match: mod => mod.HasID() && skippedDependencyIds.Contains(mod.Manifest.UniqueID)
                    );
            }

            // group A: failed root dependencies which other dependencies need
            var failedRootDependencies = new List <IModMetadata>();

            {
                var skippedDependencyIds = new HashSet <string>(failedOtherDependencies.Select(p => p.Manifest.UniqueID));
                this.FilterThrough(
                    fromList: failedOtherDependencies,
                    toList: failedRootDependencies,
                    match: mod =>
                {
                    // has no failed dependency
                    foreach (string requiredId in mod.GetRequiredModIds())
                    {
                        if (skippedDependencyIds.Contains(requiredId))
                        {
                            return(false);
                        }
                    }

                    // another dependency depends on this mod
                    bool isDependedOn = false;
                    foreach (IModMetadata other in failedOtherDependencies)
                    {
                        if (other.HasRequiredModId(mod.Manifest.UniqueID, includeOptional: false))
                        {
                            isDependedOn = true;
                            break;
                        }
                    }

                    return(isDependedOn);
                }
                    );
            }

            // return groups
            return(new[]
            {
                failedRootDependencies,
                failedOtherDependencies,
                failedOthers
            });
        }
Example #36
0
        public ActionResult Edit(
            [Bind(Include = "AlbumID,Nombre,FechaGrabacion,FechaAdquisicion,Formato_FormatoID,DiscogsReleaseCode,SpotifyID")] Album album,
            List <int> listaArtistasSeleccionados, List <string> listaCancionesSeleccionadas)
        {
            ICollection <Artista> artistasSeleccionados  = new HashSet <Artista>();
            ICollection <Cancion> cancionesSeleccionadas = new HashSet <Cancion>();
            ICollection <AlbumCancionesSeleccionadas> cancionesSeleccionadasSelectList = new HashSet <AlbumCancionesSeleccionadas>();

            TICaseFormat = new CultureInfo("es-MX", false).TextInfo;

            //cuando el álbum no contiene tracklist, inicializamos la lista de canciones para evitar errores
            if (listaCancionesSeleccionadas == null)
            {
                listaCancionesSeleccionadas = new List <string>();
            }

            try
            {
                /*debido a que listaCancionesSeleccionadas es una lista de valores "id-posicion", creamos una lista
                 * que contenga las canciones seleccionadas */
                listaCancionesSeleccionadas.ForEach(t =>
                {
                    string[] arrData = t.Split('-');    //cada item contiene el valor "id-posición"
                    //con el primer item (id) buscamos la canción
                    Cancion cancion = db.Canciones.Find(Convert.ToInt32(arrData[0]));
                    cancionesSeleccionadas.Add(cancion);

                    /*creamos una lista compatible con SelectList y la llenamos con los valores necesarios.
                     * Esta lista sólo la usaremos para asignarla a ViewBag en el caso de que el ModelState sea rechazado */
                    cancionesSeleccionadasSelectList.Add(new AlbumCancionesSeleccionadas()
                    {
                        CancionIDPosicion = t,
                        Descripcion       = string.Format(formatoArtistaCancion, cancion.Artistas.FirstOrDefault().Nombre, cancion.Nombre)
                    });
                });

                //el álbum debe tener al menos un artista asignado
                if (listaArtistasSeleccionados == null)
                {
                    ModelState.AddModelError("", "Asigna al álbum por lo menos un artista.");
                }
                else
                {
                    //asignamos los artistas a la lista de artistas obteniéndolos de la lista de ids de artistas seleccionados
                    listaArtistasSeleccionados.ForEach(a => artistasSeleccionados.Add(db.Artistas.Find(a)));

                    if (album.Formato_FormatoID > 0)
                    {
                        /*el modelo requiere que se asigne un formato y al no recibirlo de la vista
                        * genera un error de modelo. Como sí tenemos el id del formato, buscamos el formato
                        * y lo asignamos al álbum y posteriormente eliminamos el error de modelo */
                        album.Formato = db.Formatos.Find(album.Formato_FormatoID);
                        ModelState["Formato"].Errors.Clear();
                        UpdateModel(album);
                    }

                    if (ModelState.IsValid)
                    {
                        //validación de album duplicado en la BD
                        if (!db.Albums.AsEnumerable().Any(s =>
                                                          s.Nombre.ToLower() == album.Nombre.Trim().ToLower() &&
                                                          s.Artistas.Count == artistasSeleccionados.Count &&
                                                          !s.Artistas.Except(artistasSeleccionados, new Models.ComparadorArtista())
                                                          .Any() &&
                                                          s.Formato.FormatoID == album.Formato_FormatoID &&
                                                          s.AlbumID != album.AlbumID))
                        {
                            //buscamos el album de la BD porque el que usa MVC tiene estado dettached y
                            //generaría error al hacer la persistencia.
                            Album albumDB = db.Albums.Find(album.AlbumID);

                            //copiamos los datos de la copia modificada al original de la BD.
                            albumDB.Nombre             = TICaseFormat.ToTitleCase(album.Nombre.Trim());
                            albumDB.Formato_FormatoID  = album.Formato_FormatoID;
                            albumDB.Formato            = album.Formato;
                            albumDB.FechaAdquisicion   = album.FechaAdquisicion;
                            albumDB.FechaGrabacion     = album.FechaGrabacion;
                            albumDB.DiscogsReleaseCode = album.DiscogsReleaseCode;
                            albumDB.SpotifyID          = album.SpotifyID;

                            //a partir de aquí, nos olvidamos del objeto album y trabajamos con albumDB.
                            //obtenemos la lista de artistas a eliminar (los artistas desasignados por el usuario)
                            var artistasAEliminar = albumDB.Artistas.AsEnumerable()
                                                    .Except(artistasSeleccionados, new Models.ComparadorArtista());

                            artistasAEliminar.ToList().ForEach(s => albumDB.Artistas.Remove(s));

                            //obtenemos la lista de artistas a agregar (los artistas asignados por el usuario)
                            var artistasAgregados = artistasSeleccionados.Except(albumDB.Artistas.AsEnumerable(),
                                                                                 new Models.ComparadorArtista());

                            artistasAgregados.ToList().ForEach(s =>
                            {
                                albumDB.Artistas.Add(s);
                                db.Entry(s).State = System.Data.Entity.EntityState.Unchanged;
                            });

                            //creamos una estructura de datos con el tracklist final
                            ICollection <CancionAlbums> tracklistActual = new HashSet <CancionAlbums>();
                            listaCancionesSeleccionadas
                            .ForEach(t =>
                            {
                                CancionAlbums track     = new CancionAlbums();
                                string[] arrData        = t.Split('-');
                                track.Cancion           = db.Canciones.Find(Convert.ToInt32(arrData[0]));
                                track.Cancion_CancionID = track.Cancion.CancionID;
                                track.Album             = albumDB;
                                track.Album_AlbumID     = track.Album.AlbumID;
                                track.Posicion          = Convert.ToInt16(arrData[1]);
                                tracklistActual.Add(track);
                            });

                            //obtenemos la lista de canciones a eliminar (las canciones desasignadas por el usuario)
                            var cancionesAEliminar = albumDB.Tracklist.AsEnumerable()
                                                     .Except(tracklistActual, new Models.ComparadorCancionAlbums());

                            cancionesAEliminar.ToList().ForEach(s => albumDB.Tracklist.Remove(s));

                            //Actualización del orden de los tracks existentes (las canciones que permanecen)
                            var cancionesExistentes = tracklistActual.Intersect(albumDB.Tracklist.AsEnumerable(),
                                                                                new Models.ComparadorCancionAlbums());
                            cancionesExistentes.ToList().ForEach(s => db.CancionAlbums.Find(s.Cancion_CancionID, s.Album_AlbumID)
                                                                 .Posicion = s.Posicion);

                            //obtenemos la lista de canciones a agregar (las canciones asignadas por el usuario)
                            var cancionesAgregadas = tracklistActual.Except(albumDB.Tracklist.AsEnumerable(),
                                                                            new Models.ComparadorCancionAlbums());
                            cancionesAgregadas.ToList().ForEach(s => albumDB.Tracklist.Add(s));

                            //db.Entry(albumDB).State = EntityState.Modified;
                            db.SaveChanges();

                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "El álbum ya está registrado en la BD.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Ocurrió un error al agregar el álbum. " + e.Message);
            }

            //volvemos a llenar las listas de artistas y canciones para regresar la info. al usuario
            try
            {
                ViewBag.Formato_FormatoID          = new SelectList(db.Formatos.OrderBy(f => f.Descripcion), "FormatoID", "Descripcion", album.Formato_FormatoID);
                ViewBag.listaArtistas              = new SelectList(db.Artistas.AsEnumerable().Except(artistasSeleccionados).OrderBy(a => a.Nombre), "ArtistaID", "Nombre");
                ViewBag.listaArtistasSeleccionados = new SelectList(artistasSeleccionados, "ArtistaID", "Nombre");
                ViewBag.listaCanciones             = new SelectList(
                    db.Canciones.AsEnumerable().Except(cancionesSeleccionadas).OrderBy(c => c.Artistas.FirstOrDefault().Nombre).ThenBy(c => c.Nombre)
                    .Select(c => new
                {
                    CancionID   = c.CancionID,
                    Descripcion = string.Format(formatoArtistaCancion, c.Artistas.FirstOrDefault().Nombre, c.Nombre)
                }), "CancionID", "Descripcion");
                ViewBag.listaCancionesSeleccionadas = new SelectList(cancionesSeleccionadasSelectList, "CancionIDPosicion", "Descripcion");
            }
            catch (Exception)
            {
                if (ViewBag.Formato_FormatoID == null)
                {
                    ViewBag.Formato_FormatoID = new SelectList(new List <SelectList>(), "FormatoID", "Descripcion");
                }
                if (ViewBag.listaArtistas == null)
                {
                    ViewBag.listaArtistas = new SelectList(new List <SelectList>(), "ArtistaID", "Nombre");
                }
                if (ViewBag.listaArtistasSeleccionados == null)
                {
                    ViewBag.listaArtistasSeleccionados = new SelectList(new List <SelectList>(), "ArtistaID", "Nombre");
                }
                if (ViewBag.listaCanciones == null)
                {
                    ViewBag.listaCanciones = new SelectList(new List <SelectList>(), "CancionID", "Descripcion");
                }
                if (ViewBag.listaCancionesSeleccionadas == null)
                {
                    ViewBag.listaCancionesSeleccionadas = new SelectList(new List <SelectList>(), "CancionIDPosicion", "Descripcion");
                }
            }
            return(View(album));
        }
Example #37
0
        public static void ValidateArguments(Activity activity, OverloadGroupEquivalenceInfo equivalenceInfo, Dictionary <string, List <RuntimeArgument> > overloadGroups, List <RuntimeArgument> requiredArgumentsNotInOverloadGroups, IDictionary <string, object> inputs, ref IList <ValidationError>?validationErrors)
        {
            if (!requiredArgumentsNotInOverloadGroups.IsNullOrEmpty())
            {
                // 1. Check if there are any Required arguments (outside overload groups) that were not specified.
                foreach (var argument in requiredArgumentsNotInOverloadGroups)
                {
                    if (CheckIfArgumentIsNotBound(argument, inputs))
                    {
                        ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.RequiredArgumentValueNotSupplied(argument.Name), false, argument.Name, activity));
                    }
                }
            }

            if (!overloadGroups.IsNullOrEmpty())
            {
                //1. Check to see if any of the overload groups are configured.
                // An overload group is considered to be completely configured if all it's required arguments
                // are non-null. If an overload group does not have any required arguments then the group is
                // considered configured if any of the optional arguments are configured.
                var configurationResults             = new Dictionary <string, bool>();
                var configuredGroupName              = string.Empty;
                var configuredCount                  = 0;
                var overloadGroupsWithNoRequiredArgs = 0;

                foreach (var entry in overloadGroups)
                {
                    var groupName = entry.Key;
                    configurationResults.Add(groupName, false);
                    var requiredArguments = entry.Value.Where((a) => a.IsRequired);

                    if (requiredArguments.Count() > 0)
                    {
                        if (requiredArguments.All(localArgument => CheckIfArgumentIsBound(localArgument, inputs)))
                        {
                            configurationResults[groupName] = true;
                            configuredGroupName             = groupName;
                            configuredCount++;
                        }
                    }
                    else
                    {
                        overloadGroupsWithNoRequiredArgs++;
                        var optionalArguments = entry.Value.Where((a) => !a.IsRequired);
                        if (optionalArguments.Any(localArgument => CheckIfArgumentIsBound(localArgument, inputs)))
                        {
                            configurationResults[groupName] = true;
                            configuredGroupName             = groupName;
                            configuredCount++;
                        }
                    }
                }

                //2. It's an error if none of the groups are configured unless there
                // is atleast one overload group with no required arguments in it.
                if (configuredCount == 0)
                {
                    if (overloadGroupsWithNoRequiredArgs == 0)
                    {
                        ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.NoOverloadGroupsAreConfigured, false, activity));
                    }
                }
                //3. If only one overload group was configured, ensure none of the disjoint/overlapping groups have any
                // required or optional activity arguments set.
                else if (configuredCount == 1)
                {
                    var configuredOverloadSet  = new HashSet <RuntimeArgument>(overloadGroups[configuredGroupName]);
                    var checkIfArgumentIsBound = new Predicate <RuntimeArgument>(localArgument => CheckIfArgumentIsBound(localArgument, inputs));

                    List <string> disjointGroups = null;
                    if (!equivalenceInfo.DisjointGroupsDictionary.IsNullOrEmpty())
                    {
                        equivalenceInfo.DisjointGroupsDictionary.TryGetValue(configuredGroupName, out disjointGroups);
                    }

                    List <string> overlappingGroups = null;
                    if (!equivalenceInfo.OverlappingGroupsDictionary.IsNullOrEmpty())
                    {
                        equivalenceInfo.OverlappingGroupsDictionary.TryGetValue(configuredGroupName, out overlappingGroups);
                    }

                    // Iterate over the groups that may not be completely configured.
                    foreach (var groupName in configurationResults.Keys.Where((k) => configurationResults[k] == false))
                    {
                        // Check if the partially configured group name is in the disjoint groups list.
                        // If so, find all configured arguments.
                        if (disjointGroups != null && disjointGroups.Contains(groupName))
                        {
                            foreach (var configuredArgument in overloadGroups[groupName].FindAll(checkIfArgumentIsBound))
                            {
                                ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ExtraOverloadGroupPropertiesConfigured(configuredGroupName,
                                                                                                                                          configuredArgument.Name, groupName), false, activity));
                            }
                        }
                        else if (overlappingGroups != null && overlappingGroups.Contains(groupName))
                        {
                            // Find all arguments of the Overlapping group that are not in the configuredOverloadSet.
                            var overloadGroupSet = new HashSet <RuntimeArgument>(overloadGroups[groupName]);
                            var intersectSet     = overloadGroupSet.Intersect(configuredOverloadSet);
                            var exceptList       = overloadGroupSet.Except(intersectSet).ToList();

                            foreach (var configuredArgument in exceptList.FindAll(checkIfArgumentIsBound))
                            {
                                ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ExtraOverloadGroupPropertiesConfigured(configuredGroupName,
                                                                                                                                          configuredArgument.Name, groupName), false, activity));
                            }
                        }
                    }
                }
                //4. If more than one overload group is configured, generate an error.
                else
                {
                    IEnumerable <string> configuredGroups = configurationResults.Keys.Where((k) => configurationResults[k]).OrderBy((k) => k, StringComparer.Ordinal);
                    ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.MultipleOverloadGroupsConfigured(configuredGroups.AsCommaSeparatedValues()), false, activity));
                }
            }
        }
        //教师用书征订
        private int TeacherBookSubscript(int semesterCourseID, int bookSubscriptionNumber, params int[] chooseBooksIDs)
        {
            int count = 0;
            var _currentSemesterCourse = db.SemesterCourses.Include(x => x.BookSubscriptions).SingleOrDefault(x => x.SemesterCourseID == semesterCourseID); //先找出学期课程

            var alreadyBookSubscription = _currentSemesterCourse.BookSubscriptions.Where(x => x.SubscriptionType == SubscriptionType.教师用书);                 //找到的订单
            var alreadyBooksID          = (from sc in alreadyBookSubscription                                                                               //找出所有的书
                                           select sc.BookID).ToList();

            db.BookSubscriptions.RemoveRange(alreadyBookSubscription); //删除该课程对应的所有订单。
            _currentSemesterCourse.SubscriptionUserName = User.Identity.GetUserName();
            _currentSemesterCourse.SubscriptionTime     = DateTime.Now;
            count = db.SaveChanges() - 1; //执行db.SaveChanges()返回的记录数 是等于 删除的 订单 + 修改 的课程记录1项。因此,要减1.
            if (chooseBooksIDs == null)
            {
                return(count);
            }

            var selectedBooksHS       = new HashSet <int>(chooseBooksIDs); //选择的教材ID;
            var semesterCourseBooksHS = new HashSet <int>(alreadyBooksID); //已经有的ID;

            //要求的是对称差集,可以直接求,也可以使用补集减去差集。
            //var dd = selectedBooksHS.SymmetricExceptWith(semesterCourseBooksHS)
            var UnionBookIdsHSCount     = semesterCourseBooksHS.Union(selectedBooksHS).Count();
            var IntersectBookIdsHSCount = semesterCourseBooksHS.Intersect(selectedBooksHS).Count(); //求交集。 Except 求差集

            foreach (var bookIDItem in selectedBooksHS)
            {
                var _BookItem = db.Books.Find(bookIDItem);

                _currentSemesterCourse.BookSubscriptions.Add(new BookSubscription()
                {
                    BookID                 = bookIDItem,
                    SemesterCourseID       = _currentSemesterCourse.SemesterCourseID,
                    BookSubscriptionNumber = bookSubscriptionNumber,
                    SubscriptionPrice      = _BookItem.Price * bookSubscriptionNumber, //教师用书征订 是手工输入数字。
                    SubscriptionType       = SubscriptionType.教师用书,

                    //为方便汇总统计,后补加的订单中的14项信息,
                    SemesterName         = _currentSemesterCourse.Semester.SemesterName,
                    GradeName            = _currentSemesterCourse.GradeMajor.Grade.GradeName,
                    DepartmentName       = _currentSemesterCourse.GradeMajor.Major.Department.DepartmentName,
                    MajorName            = _currentSemesterCourse.GradeMajor.Major.MajorName,
                    SemesterCourseNumber = _currentSemesterCourse.SemesterCourseNumber,
                    SemesterCourseName   = _currentSemesterCourse.SemesterCourseName,
                    BookName             = _BookItem.BookName,
                    AuthorName           = _BookItem.AuthorName,
                    ISBN                 = _BookItem.ISBN,
                    Press                = _BookItem.Press,
                    PublishingDate       = _BookItem.PublishingDate,
                    Price                = _BookItem.Price,
                    BookTypeName         = _BookItem.BookType.BookTypeName, // 书的类别,是规划教材还是讲义。 这里不是枚举类型。 BookTypeName = _BookItem.BookType.ToString()
                    SubscriptionTypeName = SubscriptionType.教师用书.ToString() //征订的类别,枚举类型通过.ToString()转换为枚举项,而不是整形值。是学生教材还是教师用书。
                });
            }

            _currentSemesterCourse.SubscriptionUserName = User.Identity.GetUserName();
            _currentSemesterCourse.SubscriptionTime     = DateTime.Now;
            db.SaveChanges();

            return(UnionBookIdsHSCount - IntersectBookIdsHSCount);
        }
        public override void Update(UpdateState state)
        {
            var _3d = FSOEnvironment.Enable3D;

            base.Update(state);
            bool rotated = false;

            if (!Master.TVisible || !UIScreen.Current.Visible || !state.ProcessMouseEvents)
            {
                ScrollWheelInvalid = true;
            }

            if (!FSOEnvironment.SoftwareKeyboard)
            {
                if (!state.WindowFocused)
                {
                    ScrollWheelInvalid = true;
                }
                else if (ScrollWheelInvalid)
                {
                    LastMouseWheel     = state.MouseState.ScrollWheelValue;
                    ScrollWheelInvalid = false;
                }
                if (state.WindowFocused && state.MouseState.ScrollWheelValue != LastMouseWheel)
                {
                    var diff = state.MouseState.ScrollWheelValue - LastMouseWheel;
                    Master.TargetZoom  = Master.TargetZoom + diff / 1600f;
                    LastMouseWheel     = state.MouseState.ScrollWheelValue;
                    Master.TargetZoom  = Math.Max(MinZoom, Math.Min(Master.TargetZoom, MaxZoom));
                    Master.UserModZoom = true;
                    ZoomFreezeTime     = 10 * FSOEnvironment.RefreshRate / 60;
                }
            }

            MiceDown = new HashSet <int>(MiceDown.Intersect(state.MouseStates.Select(x => x.ID)));

            int transitionTo = -2;

            if (MiceDown.Count == 0)
            {
                if (Mode != -1)
                {
                    transitionTo = -1;
                }
            }
            else if (MiceDown.Count == 1)
            {
                if (Mode == -1)
                {
                    transitionTo = 0;
                }
                if (Mode == 2)
                {
                    transitionTo = 1;
                }
            }
            else if (MiceDown.Count >= 2)
            {
                //cannot possibly be a touch
                if (Mode < 2)
                {
                    transitionTo = 2;
                }
                if (Mode == -1)
                {
                    Mode = 0;
                }
            }

            switch (Mode)
            {
            case -1:
                if (transitionTo == 0)
                {
                    var mouse = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                    if (mouse != null)
                    {
                        TapPoint      = new Point(mouse.MouseState.X, mouse.MouseState.Y);
                        MiceDownTimer = 0;
                        Mode          = 0;
                    }
                }
                break;

            case 0:
            case 1:
                if (transitionTo == 2)
                {
                    //register the first distance between the two taps
                    var m1 = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(0));
                    var m2 = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(1));
                    BaseVector = (new Point(m2.MouseState.X, m2.MouseState.Y) - new Point(m1.MouseState.X, m1.MouseState.Y)).ToVector2();
                    StartScale = Master.TargetZoom;
                    if (_3d)
                    {
                        LastAngleX = null;
                    }

                    //scroll anchor should change to center of two touches without drastically changing scroll
                    TapPoint = new Point(m2.MouseState.X / 2, m2.MouseState.Y / 2) + new Point(m1.MouseState.X / 2, m1.MouseState.Y / 2);

                    Mode = 2;
                }
                else
                {
                    if (Mode == 0)
                    {
                        ScrollVelocity = new Vector2();
                        if (transitionTo == -1)
                        {
                            Mode = -1;
                            Master.Click(GetScaledPoint(TapPoint), state);
                        }
                        else
                        {
                            var mouse = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                            var time  = FSOEnvironment.SoftwareKeyboard ? (TAP_TIMER * FSOEnvironment.RefreshRate / 60) : 0;
                            if ((TapPoint - new Point(mouse.MouseState.X, mouse.MouseState.Y)).ToVector2().Length() > TAP_POINT_DIST)
                            {
                                Mode = 1;     //become a scroll
                            }
                            else if (++MiceDownTimer > time)
                            {
                                Mode = 3;
                                Master.Click(GetScaledPoint(TapPoint), state);
                            }
                        }
                    }
                    if (Mode == 1)
                    {
                        if (transitionTo == -1)
                        {
                            //release our scroll velocity
                            Mode = -1;
                        }
                        else
                        {
                            var mouse  = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                            var newTap = new Point(mouse.MouseState.X, mouse.MouseState.Y);
                            ScrollVelocity = (newTap - TapPoint).ToVector2();
                            TapPoint       = newTap;
                        }
                    }
                }
                break;

            case 2:
                if (transitionTo != -2)
                {
                    //release rotation gesture. todo.
                }
                if (transitionTo == 1)
                {
                    //go back to being a normal scroll
                    //again, anchor should change to single point without drastic scroll change
                    var mouse = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                    TapPoint = new Point(mouse.MouseState.X, mouse.MouseState.Y);
                    Mode     = 1;
                }
                else if (transitionTo == -1)
                {
                    Mode = -1;
                }
                else if (transitionTo == -2)
                {
                    var m1     = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(0));
                    var m2     = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(1));
                    var vector = (new Point(m2.MouseState.X, m2.MouseState.Y) - new Point(m1.MouseState.X, m1.MouseState.Y)).ToVector2();
                    var newTap = new Point(m2.MouseState.X / 2, m2.MouseState.Y / 2) + new Point(m1.MouseState.X / 2, m1.MouseState.Y / 2);
                    ScrollVelocity = (newTap - TapPoint).ToVector2();
                    TapPoint       = newTap;

                    Master.TargetZoom  = vector.Length() / BaseVector.Length() * StartScale;
                    Master.UserModZoom = true;

                    //clockwise if dot product b against a rotated 90 degrees clockwise is positive
                    var a = BaseVector;
                    var b = vector;
                    a.Normalize(); b.Normalize();
                    var clockwise = ((-a.Y) * b.X + a.X * b.Y) > 0;
                    var angle     = (float)Math.Acos(Vector2.Dot(a, b));
                    RotateAngle = clockwise ? angle : -angle;

                    if (_3d)
                    {
                        var rcState = Master.Rotate;
                        if (LastAngleX != null)
                        {
                            float rot = rcState.RotationX - (float)DirectionUtils.Difference(RotateAngle, LastAngleX.Value);
                            if (!float.IsNaN(rot))
                            {
                                rcState.RotationX = rot;
                            }
                        }
                        LastAngleX         = RotateAngle;
                        rcState.RotationY += ScrollVelocity.Y / 200;
                        ScrollVelocity     = Vector2.Zero;
                    }
                    else
                    {
                        if (Math.Abs(RotateAngle) > Math.PI / 8)
                        {
                            Master.TargetZoom = StartScale;
                        }
                    }
                }
                break;

            case 3:
                if (transitionTo == -1)
                {
                    Mode = -1;
                }
                break;
            }
            if (Mode != 2 && RotateAngle != 0 && !_3d)
            {
                if (Math.Abs(RotateAngle) > Math.PI / 4)
                {
                    //confirmed
                    var screen = (IGameScreen)GameFacade.Screens.CurrentUIScreen;
                    if (RotateAngle > 0)
                    {
                        screen.Rotation = (screen.Rotation + 1) % 4;
                    }
                    else
                    {
                        screen.Rotation = (screen.Rotation + 3) % 4;
                    }

                    HITVM.Get.PlaySoundEvent(UISounds.ObjectRotate);
                    rotated = true;
                }
                RotateAngle = 0;
            }
            ScrollVelocityHistory.Insert(0, ScrollVelocity);
            if (ScrollVelocityHistory.Count > 5)
            {
                ScrollVelocityHistory.RemoveAt(ScrollVelocityHistory.Count - 1);
            }
            if (transitionTo == -1)
            {
                //ScrollVelocity = LastValidScrollVelocity / UpdatesSinceDraw;
                if (ScrollVelocityHistory.Count > 1)
                {
                    int total = 0;
                    ScrollVelocity = new Vector2();
                    for (int i = 1; i < ScrollVelocityHistory.Count; i++)
                    {
                        total++;
                        ScrollVelocity += ScrollVelocityHistory[i];
                    }
                    ScrollVelocity /= total;
                }
                ScrollVelocityHistory.Clear();
            }

            if (Mode == -1)
            {
                ScrollVelocity *= 0.95f * Math.Min(ScrollVelocity.Length(), 1);
                if (Master.TargetZoom < 1.25f && ZoomFreezeTime == 0 && !_3d)
                {
                    Master.UserModZoom = true;
                    float snapZoom = 1f;
                    float dist     = 200f;
                    foreach (var snappable in SnapZooms)
                    {
                        var newDist = Math.Abs(Master.TargetZoom - snappable);
                        if (newDist < dist)
                        {
                            dist     = newDist;
                            snapZoom = snappable;
                        }
                    }
                    if (dist > 0)
                    {
                        var move = snapZoom - Master.TargetZoom;
                        if (move != 0)
                        {
                            if (move > 0)
                            {
                                Master.TargetZoom += 0.01f;
                            }
                            else
                            {
                                Master.TargetZoom -= 0.01f;
                            }
                        }
                        if (move * (snapZoom - Master.TargetZoom) < 0)
                        {
                            Master.TargetZoom = snapZoom;
                        }
                    }
                }
                if (ZoomFreezeTime > 0)
                {
                    ZoomFreezeTime--;
                }
            }
            if (ScrollVelocity.Length() > 0.001f)
            {
                Master.Scroll(-ScrollVelocity / (Master.TargetZoom * 128));
            }

            UpdatesSinceDraw++;
        }
Example #40
0
        public static void ProcessReceivedReplys_thread()
        {
            while (true)
            {
                Thread.Sleep(50);                 //Min time to check commands
                if (commLayer.GetQueueSize() > 0) //if there is commands
                {
                    Command mt = commLayer.RemoveFromCommandQueue();
                    //MyTuple payload = (MyTuple)mt.GetPayload();
                    Object tmp;

                    Console.WriteLine("=================" + mt.GetCommand());
                    switch (mt.GetCommand())
                    {
                    case "ack":
                        if (CommandInUse == "read" && mt.GetPrevCommand() == "read")
                        {
                            for (int i = 0; i < ClientProgram.ThreadsInAction.Count; ++i)
                            {
                                if (ClientProgram.ThreadsInAction[i].Equals(new SenderPool(null, null, mt.GetUriFromSender(), mt)) == true)
                                {
                                    ClientProgram.ThreadsInAction[i].GetThreadState().Kill_hread();
                                    ClientProgram.ThreadsInAction[i].GetThread().Join();
                                    ClientProgram.ThreadsInAction.RemoveAt(i);
                                    ClientProgram.Read_SignalEvent.Set();     //Read Ok. At least One received
                                    Console.WriteLine("Value: " + mt.GetPayload().ToString());
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag == true)
                            {
                                for (int i = 0; i < ClientProgram.ThreadsInAction.Count; ++i)
                                {
                                    ClientProgram.ThreadsInAction[i].GetThreadState().Kill_hread();
                                    ClientProgram.ThreadsInAction[i].GetThread().Join();
                                    flag = false;;
                                }
                                ClientProgram.ThreadsInAction.Clear();
                            }
                        }
                        else
                        {
                            if (CommandInUse == "add" && mt.GetPrevCommand() == "add")     //===================================================
                            {
                                for (int i = 0; i < ClientProgram.ThreadsInAction.Count; ++i)
                                {
                                    if (ClientProgram.ThreadsInAction[i].Equals(new SenderPool(null, null, mt.GetUriFromSender(), mt)) == true)     //Se está OK
                                    {
                                        if (ServersInTheView.Contains(mt.GetUriFromSender()) == false)
                                        {
                                            ServersInTheView.Add(mt.GetUriFromSender());

                                            if (ServersInTheView.Count >= (currentView.Count / 2 + 1))
                                            {
                                                //Can progress
                                                for (int j = 0; j < ClientProgram.ThreadsInAction.Count; ++j)
                                                {
                                                    for (int k = 0; k < ServersInTheView.Count; ++k)
                                                    {
                                                        if (ClientProgram.ThreadsInAction[j].GetUri().Equals(ServersInTheView[k]))
                                                        {
                                                            ClientProgram.ThreadsInAction[j].GetThreadState().Kill_hread();
                                                            ClientProgram.ThreadsInAction[j].GetThread().Join();
                                                            ClientProgram.ThreadsInAction.RemoveAt(j);
                                                            j = -1;
                                                            break;
                                                        }
                                                    }
                                                }
                                                ClientProgram.Add_SignalEvent.Set();     //Signal UpperLayer that it can evolve
                                                Console.WriteLine("(ClientServices) ADD Success in the majority of replicas: ");
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                if (CommandInUse == "take" && mt.GetPrevCommand() == "take")     //===================================================
                                {
                                    for (int i = 0; i < ClientProgram.ThreadsInAction.Count; ++i)
                                    {
                                        if (ClientProgram.ThreadsInAction[i].Equals(new SenderPool(null, null, mt.GetUriFromSender(), mt)) == true)     //Se está OK
                                        {
                                            if (ServersInTheView.Contains(mt.GetUriFromSender()) == false)
                                            {
                                                ServersInTheView.Add(mt.GetUriFromSender());
                                                AcceptedReply.Add(mt);     //Accepted stored

                                                if (ServersInTheView.Count == currentView.Count)
                                                {
                                                    //Can progress

                                                    //Check intersection of the tuple space
                                                    HashSet <MyTuple> Intersection = (HashSet <MyTuple>)AcceptedReply[0].GetPayload();
                                                    for (int j = 1; j < AcceptedReply.Count; ++j)
                                                    {
                                                        HashSet <MyTuple> mySet2 = (HashSet <MyTuple>)AcceptedReply[i].GetPayload();
                                                        Intersection.Intersect(mySet2);
                                                    }
                                                    //Test if null
                                                    if (Intersection.Count == 0)
                                                    {
                                                        //Restart FAse 1
                                                        ServersInTheView.Clear();
                                                        AcceptedReply.Clear();
                                                        break;
                                                        //ClientProgram.Take_SignalEvent.Set();
                                                    }
                                                    else
                                                    {
                                                        foreach (MyTuple t in Intersection)
                                                        {
                                                            //Console.WriteLine("(ClientServices) TAKE Success: " + i.ToString());
                                                            //ClientProgram.FinnishTake();
                                                            //ClientProgram.Take_SignalEvent.Set();

                                                            //Vou ter que mandar REMOVE

                                                            //Limpar tudo
                                                            for (int j = 0; j < ClientProgram.ThreadsInAction.Count; ++j)
                                                            {
                                                                for (int k = 0; k < ServersInTheView.Count; ++k)
                                                                {
                                                                    if (ClientProgram.ThreadsInAction[j].GetUri().Equals(ServersInTheView[k]))
                                                                    {
                                                                        ClientProgram.ThreadsInAction[j].GetThreadState().Kill_hread();
                                                                        ClientProgram.ThreadsInAction[j].GetThread().Join();
                                                                        ClientProgram.ThreadsInAction.RemoveAt(j);
                                                                        j = -1;
                                                                        break;
                                                                    }
                                                                }
                                                            }

                                                            //===================================================== Preparar REMOVE
                                                            ClientProgram.SendToView(new Command("remove", t, ClientProgram.MyAddress, ClientProgram.SequenceNumber, null));
                                                            SetCurrentCommandAndView("remove", ClientProgram.GetView());
                                                            //Console.WriteLine("Depois do Remove");
                                                            break;
                                                        }
                                                    }



                                                    //ClientProgram.SendToView(new Command("remove", t, MyAddress, ++SequenceNumber, null));

                                                    //ClientProgram.Take_SignalEvent.Set(); //Signal UpperLayer that it can evolve

                                                    Console.WriteLine("(ClientServices) TAKE Success in all the replicas: ");
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    if (CommandInUse == "remove" && mt.GetPrevCommand() == "remove")     //===================================================
                                    {
                                        for (int i = 0; i < ClientProgram.ThreadsInAction.Count; ++i)
                                        {
                                            if (ClientProgram.ThreadsInAction[i].Equals(new SenderPool(null, null, mt.GetUriFromSender(), mt)) == true)     //Se está OK
                                            {
                                                if (ServersInTheView.Contains(mt.GetUriFromSender()) == false)
                                                {
                                                    ServersInTheView.Add(mt.GetUriFromSender());

                                                    if (ServersInTheView.Count == currentView.Count)
                                                    {
                                                        //Can progress
                                                        //Limpar tudo
                                                        for (int j = 0; j < ClientProgram.ThreadsInAction.Count; ++j)
                                                        {
                                                            for (int k = 0; k < ServersInTheView.Count; ++k)
                                                            {
                                                                if (ClientProgram.ThreadsInAction[j].GetUri().Equals(ServersInTheView[k]))
                                                                {
                                                                    ClientProgram.ThreadsInAction[j].GetThreadState().Kill_hread();
                                                                    ClientProgram.ThreadsInAction[j].GetThread().Join();
                                                                    ClientProgram.ThreadsInAction.RemoveAt(j);
                                                                    j = -1;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                        ClientProgram.Take_SignalEvent.Set();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;

                    case "refuse":
                        if (CommandInUse == "refuse" && mt.GetPrevCommand() == "read")
                        {
                        }
                        else
                        {
                            if (CommandInUse == "take" && mt.GetPrevCommand() == "refuse")
                            {
                                Thread.Sleep(250);
                            }
                            else
                            {
                                if (CommandInUse == "remove" && mt.GetPrevCommand() == "refuse")
                                {
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
Example #41
0
 // set intersection
 public static HashSet <T> And <T>(this HashSet <T> hash, HashSet <T> other)
 {
     return((other == null || other.Count == 0) ? new HashSet <T>()
 : new HashSet <T>(hash.Intersect(other)));
 }
Example #42
0
        public void ExceptWith(IEnumerable <TVal> other)
        {
            var common = hashSet.Intersect(other, hashSet.Comparer);

            Parent.RemoveValues(Key, common);
        }
Example #43
0
        /// <summary>
        /// Check to make sure that no other edges will be made parallel
        /// by removing this edge. If there is an intersection between
        /// the ancestor/decendant nodes of the edge's tail node, and the
        /// ancestor/decendant nodes of the head node, then do not remove it.
        /// </summary>
        /// <param name="tailNode"></param>
        /// <param name="headNode"></param>
        /// <returns></returns>
        protected bool HaveDecendantOrAncestorOverlap(Node <T, TNodeContent> tailNode, Node <T, TNodeContent> headNode)
        {
            if (tailNode is null)
            {
                throw new ArgumentNullException(nameof(tailNode));
            }
            if (headNode is null)
            {
                throw new ArgumentNullException(nameof(headNode));
            }

            // First the decendants of the tail node.
            var tailNodeAncestorsAndDecendants = new HashSet <T>();

            if (tailNode.NodeType != NodeType.End &&
                tailNode.NodeType != NodeType.Isolated)
            {
                tailNodeAncestorsAndDecendants.UnionWith(
                    tailNode.OutgoingEdges
                    .Select(x => EdgeLookup[x])
                    .Select(x => EdgeHeadNodeLookup[x.Id].Id)
                    .Except(new[] { headNode.Id }));
            }

            // Then the ancestors of the tail node.
            if (tailNode.NodeType != NodeType.Start &&
                tailNode.NodeType != NodeType.Isolated)
            {
                tailNodeAncestorsAndDecendants.UnionWith(
                    tailNode.IncomingEdges
                    .Select(x => EdgeLookup[x])
                    .Select(x => EdgeTailNodeLookup[x.Id].Id)
                    .Except(new[] { headNode.Id }));
            }

            // Next the ancestors of the head node.
            var headNodeAncestorsAndDecendants = new HashSet <T>();

            if (headNode.NodeType != NodeType.Start &&
                headNode.NodeType != NodeType.Isolated)
            {
                headNodeAncestorsAndDecendants.UnionWith(
                    headNode.IncomingEdges
                    .Select(x => EdgeLookup[x])
                    .Select(x => EdgeTailNodeLookup[x.Id].Id)
                    .Except(new[] { tailNode.Id }));
            }

            // Then the decendants of the head node.
            if (headNode.NodeType != NodeType.End &&
                headNode.NodeType != NodeType.Isolated)
            {
                headNodeAncestorsAndDecendants.UnionWith(
                    headNode.OutgoingEdges
                    .Select(x => EdgeLookup[x])
                    .Select(x => EdgeHeadNodeLookup[x.Id].Id)
                    .Except(new[] { tailNode.Id }));
            }

            IEnumerable <T> overlap = tailNodeAncestorsAndDecendants.Intersect(headNodeAncestorsAndDecendants);

            if (overlap.Any())
            {
                return(true);
            }
            return(false);
        }
Example #44
0
        private void UpdateContextMenu()
        {
            var projects = projectMonitor.GetProjects();
              var updatedProjects = projectMonitor.GetUpdatedProjects();
              var editedProjects = projectMonitor.GetEditedProjects();
              var update = notifyIcon.ContextMenu.MenuItems[3];
              var upload = notifyIcon.ContextMenu.MenuItems[4];
              var view = notifyIcon.ContextMenu.MenuItems[5];
              var curNames = new HashSet<string>(from item in update.MenuItems.Cast<MenuItem>() select item.Text);
              var newNames = new HashSet<string>(from p in projects select p.name);
              var updNames = new HashSet<string>(from p in updatedProjects select p.name);
              var editNames = new HashSet<string>(from p in editedProjects select p.name);
              var writeNames = new HashSet<string>(from p in projects where p.can_write select p.name);

              for (int i = update.MenuItems.Count - 1; i >= 0; i--) {
            MenuItem item = update.MenuItems[i];
            if (!newNames.Contains(item.Text)) {
              update.MenuItems.Remove(item);
            } else {
              item.Checked = updNames.Contains(item.Text);
            }
              }

              for (int i = view.MenuItems.Count - 1; i >= 0; i--) {
            MenuItem item = view.MenuItems[i];
            if (!newNames.Contains(item.Text)) {
              view.MenuItems.Remove(item);
            }
              }

              const string readOnlySuffix = " (read-only)";
              for (int i = upload.MenuItems.Count - 1; i >= 0; i--) {
            MenuItem item = upload.MenuItems[i];
            string projName = item.Text;
            if (projName.EndsWith(readOnlySuffix)) {
              projName = projName.Substring(0, projName.Length - readOnlySuffix.Length);
            }
            if (!newNames.Contains(projName)) {
              upload.MenuItems.Remove(item);
            } else {
              bool canWrite = writeNames.Contains(projName);
              item.Enabled = canWrite;
              item.Checked = canWrite && editNames.Contains(projName);
              item.Text = projName + (canWrite ? "" : readOnlySuffix);
            }
              }

              foreach (var project in projects) {
            if (!curNames.Contains(project.name)) {
              var curProject = project; // closure issues
              var item = new MenuItem(project.name, CreateUpdateProjectHandler(curProject)) {
            Checked = updNames.Contains(project.name),
            RadioCheck = true
              };
              update.MenuItems.Add(item);
              item = new MenuItem(project.name + (project.can_write ? "" : readOnlySuffix),
                              CreateUploadProjectHandler(curProject)) {
            Enabled = project.can_write,
            Checked = project.can_write && editNames.Contains(project.name),
            RadioCheck = true
              };
              upload.MenuItems.Add(item);
              item = new MenuItem(project.name, CreateViewProjectHistoryHandler(curProject));
              view.MenuItems.Add(item);
            }
              }

              var updateAll = notifyIcon.ContextMenu.MenuItems[7];
              updateAll.Text = "Update All" + (updNames.Count > 0 ? String.Format(" ({0})", updNames.Count) : "");

              var uploadAll = notifyIcon.ContextMenu.MenuItems[8];
              int uploadable = writeNames.Intersect(editNames).Count();
              uploadAll.Text = "Upload All" + (uploadable > 0 ? String.Format(" ({0})", uploadable) : "");
              uploadAll.Enabled = writeNames.Count > 0;

              update.Enabled = upload.Enabled = updateAll.Enabled = view.Enabled = projects.Count > 0;

              // Hide the loading indicator and show others
              notifyIcon.Icon = updNames.Count > 0 || uploadable > 0 ? notifyIconUpdate : notifyIconBase;
              notifyIcon.Text = "SciGit\n";

              if (projectMonitor.syncing > 0) {
            notifyIcon.Icon = notifyIconLoading;
            notifyIcon.Text += "Syncing projects...";
              } else if (updNames.Count > 0) {
            notifyIcon.Text += "Project updates available.";
              } else if (uploadable > 0) {
            notifyIcon.Text += "Local changes awaiting upload.";
              } else {
            notifyIcon.Text += "All projects up to date.";
              }

              for (int i = 3; i <= 8; i++) {
            notifyIcon.ContextMenu.MenuItems[i].Visible = true;
              }
              notifyIcon.ContextMenu.MenuItems[9].Visible = false;
        }
Example #45
0
 internal void Intersect(SuggestedMove otherSuggestedMove)
 {
     suggestions.Intersect(otherSuggestedMove.suggestions);
 }
Example #46
0
        /// <summary>
        /// Checks type definition against NFTA. If this is the root note, all end states must be matched before true is returned.
        /// </summary>
        public bool IsTermValid(Dictionary <TrsTypeDefinitionTermBase, List <TrsTypeDefinitionTypeName> > transitionFunction,
                                HashSet <TrsTypeDefinitionTypeName> endStates)
        {
            CurrentNodeMatchedTypes.Clear();

            // Match leaf nodes for non-AC terms
            foreach (var arg in ArgumentMatchedTypes)
            {
                arg.IsTermValid(transitionFunction, endStates);
            }

            // Match leaf nodes for AC terms
            foreach (var arg in AcArgumentMatchedTypes)
            {
                arg.Key.IsTermValid(transitionFunction, endStates);
            }

            // If this is a type name, simply add: it is a result in itself
            if (CurrentNode is TrsTypeDefinitionTypeName)
            {
                CurrentNodeMatchedTypes.Add((TrsTypeDefinitionTypeName)CurrentNode);
            }

            ProcessLeafNodes(transitionFunction);
            ProcessEmptyTransitions(transitionFunction);

            // Only the root node has a meaningful test case for end states
            if (ParentNode == null)
            {
                // Compile list of matched end states.
                HashSet <TrsTypeDefinitionTypeName> matchedEndStates = new HashSet <TrsTypeDefinitionTypeName>(CurrentNodeMatchedTypes.Intersect(endStates));
                return(matchedEndStates.Count == endStates.Count);
            }
            else
            {
                return(true);
            }
        }
Example #47
0
        /// <summary>Write a summary of mod warnings to the console and log.</summary>
        /// <param name="mods">The loaded mods.</param>
        /// <param name="skippedMods">The mods which could not be loaded.</param>
        /// <param name="logParanoidWarnings">Whether to log issues for mods which directly use potentially sensitive .NET APIs like file or shell access.</param>
        private void LogModWarnings(IEnumerable <IModMetadata> mods, IModMetadata[] skippedMods, bool logParanoidWarnings)
        {
            // get mods with warnings
            IModMetadata[] modsWithWarnings = mods.Where(p => p.Warnings != ModWarning.None).ToArray();
            if (!modsWithWarnings.Any() && !skippedMods.Any())
            {
                return;
            }

            // log intro
            {
                int count = modsWithWarnings.Length + skippedMods.Length;
                this.Monitor.Log($"Found {count} mod{(count == 1 ? "" : "s")} with warnings:", LogLevel.Info);
            }

            // log skipped mods
            if (skippedMods.Any())
            {
                // get logging logic
                HashSet <string> loggedDuplicateIds = new HashSet <string>();
                void LogSkippedMod(IModMetadata mod)
                {
                    string message = $"      - {mod.DisplayName}{(mod.Manifest?.Version != null ? " " + mod.Manifest.Version.ToString() : "")} because {mod.Error}";

                    // handle duplicate mods
                    // (log first duplicate only, don't show redundant version)
                    if (mod.FailReason == ModFailReason.Duplicate && mod.HasManifest())
                    {
                        if (!loggedDuplicateIds.Add(mod.Manifest.UniqueID))
                        {
                            return; // already logged
                        }
                        message = $"      - {mod.DisplayName} because {mod.Error}";
                    }

                    // log message
                    this.Monitor.Log(message, LogLevel.Error);
                    if (mod.ErrorDetails != null)
                    {
                        this.Monitor.Log($"        ({mod.ErrorDetails})");
                    }
                }

                // group mods
                List <IModMetadata> skippedDependencies = new List <IModMetadata>();
                List <IModMetadata> otherSkippedMods    = new List <IModMetadata>();
                {
                    // track broken dependencies
                    HashSet <string> skippedDependencyIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                    HashSet <string> skippedModIds        = new HashSet <string>(from mod in skippedMods where mod.HasID() select mod.Manifest.UniqueID, StringComparer.OrdinalIgnoreCase);
                    foreach (IModMetadata mod in skippedMods)
                    {
                        foreach (string requiredId in skippedModIds.Intersect(mod.GetRequiredModIds()))
                        {
                            skippedDependencyIds.Add(requiredId);
                        }
                    }

                    // collect mod groups
                    foreach (IModMetadata mod in skippedMods)
                    {
                        if (mod.HasID() && skippedDependencyIds.Contains(mod.Manifest.UniqueID))
                        {
                            skippedDependencies.Add(mod);
                        }
                        else
                        {
                            otherSkippedMods.Add(mod);
                        }
                    }
                }

                // log skipped mods
                this.Monitor.Log("   Skipped mods", LogLevel.Error);
                this.Monitor.Log("   " + "".PadRight(50, '-'), LogLevel.Error);
                this.Monitor.Log("      These mods could not be added to your game.", LogLevel.Error);
                this.Monitor.Newline();

                if (skippedDependencies.Any())
                {
                    foreach (IModMetadata mod in skippedDependencies.OrderBy(p => p.DisplayName))
                    {
                        LogSkippedMod(mod);
                    }
                    this.Monitor.Newline();
                }

                foreach (IModMetadata mod in otherSkippedMods.OrderBy(p => p.DisplayName))
                {
                    LogSkippedMod(mod);
                }
                this.Monitor.Newline();
            }

            // log warnings
            if (modsWithWarnings.Any())
            {
                // broken code
                this.LogModWarningGroup(modsWithWarnings, ModWarning.BrokenCodeLoaded, LogLevel.Error, "Broken mods",
                                        "These mods have broken code, but you configured SMAPI to load them anyway. This may cause bugs,",
                                        "errors, or crashes in-game."
                                        );

                // changes serializer
                this.LogModWarningGroup(modsWithWarnings, ModWarning.ChangesSaveSerializer, LogLevel.Warn, "Changed save serializer",
                                        "These mods change the save serializer. They may corrupt your save files, or make them unusable if",
                                        "you uninstall these mods."
                                        );

                // patched game code
                this.LogModWarningGroup(modsWithWarnings, ModWarning.PatchesGame, LogLevel.Info, "Patched game code",
                                        "These mods directly change the game code. They're more likely to cause errors or bugs in-game; if",
                                        "your game has issues, try removing these first. Otherwise you can ignore this warning."
                                        );

                // unvalidated update tick
                this.LogModWarningGroup(modsWithWarnings, ModWarning.UsesUnvalidatedUpdateTick, LogLevel.Info, "Bypassed safety checks",
                                        "These mods bypass SMAPI's normal safety checks, so they're more likely to cause errors or save",
                                        "corruption. If your game has issues, try removing these first."
                                        );

                // paranoid warnings
                if (logParanoidWarnings)
                {
                    this.LogModWarningGroup(
                        modsWithWarnings,
                        match: mod => mod.HasUnsuppressedWarnings(ModWarning.AccessesConsole, ModWarning.AccessesFilesystem, ModWarning.AccessesShell),
                        level: LogLevel.Debug,
                        heading: "Direct system access",
                        blurb: new[]
                    {
                        "You enabled paranoid warnings and these mods directly access the filesystem, shells/processes, or",
                        "SMAPI console. (This is usually legitimate and innocent usage; this warning is only useful for",
                        "further investigation.)"
                    },
                        modLabel: mod =>
                    {
                        List <string> labels = new List <string>();
                        if (mod.HasUnsuppressedWarnings(ModWarning.AccessesConsole))
                        {
                            labels.Add("console");
                        }
                        if (mod.HasUnsuppressedWarnings(ModWarning.AccessesFilesystem))
                        {
                            labels.Add("files");
                        }
                        if (mod.HasUnsuppressedWarnings(ModWarning.AccessesShell))
                        {
                            labels.Add("shells/processes");
                        }

                        return($"{mod.DisplayName} ({string.Join(", ", labels)})");
                    }
                        );
                }

                // no update keys
                this.LogModWarningGroup(modsWithWarnings, ModWarning.NoUpdateKeys, LogLevel.Debug, "No update keys",
                                        "These mods have no update keys in their manifest. SMAPI may not notify you about updates for these",
                                        "mods. Consider notifying the mod authors about this problem."
                                        );

                // not crossplatform
                this.LogModWarningGroup(modsWithWarnings, ModWarning.UsesDynamic, LogLevel.Debug, "Not crossplatform",
                                        "These mods use the 'dynamic' keyword, and won't work on Linux/Mac."
                                        );
            }
        }
Example #48
0
        // TODO: change sentence to obs?
        private static Tuple <double, List <string> > ViterbiCut(string sentence)
        {
            var v       = new List <IDictionary <string, double> >();
            var memPath = new List <IDictionary <string, string> >();

            var allStates = _transProbs.Keys.ToList();

            // Init weights and paths.
            v.Add(new Dictionary <string, Double>());
            memPath.Add(new Dictionary <string, string>());
            foreach (var state in _stateTab.GetDefault(sentence[0], allStates))
            {
                var emP = _emitProbs[state].GetDefault(sentence[0], Constants.MinProb);
                v[0][state]       = _startProbs[state] + emP;
                memPath[0][state] = string.Empty;
            }

            // For each remaining char
            for (var i = 1; i < sentence.Length; ++i)
            {
                v.Add(new Dictionary <string, double>());
                memPath.Add(new Dictionary <string, string>());

                var prevStates        = memPath[i - 1].Keys.Where(k => _transProbs[k].Count > 0);
                var curPossibleStates = new HashSet <string>(prevStates.SelectMany(s => _transProbs[s].Keys));

                IEnumerable <string> obsStates = _stateTab.GetDefault(sentence[i], allStates);
                obsStates = curPossibleStates.Intersect(obsStates);

                if (!obsStates.Any())
                {
                    if (curPossibleStates.Count > 0)
                    {
                        obsStates = curPossibleStates;
                    }
                    else
                    {
                        obsStates = allStates;
                    }
                }

                foreach (var y in obsStates)
                {
                    var emp = _emitProbs[y].GetDefault(sentence[i], Constants.MinProb);

                    var prob  = double.MinValue;
                    var state = string.Empty;

                    foreach (var y0 in prevStates)
                    {
                        var tranp = _transProbs[y0].GetDefault(y, double.MinValue);
                        tranp = v[i - 1][y0] + tranp + emp;
                        // TODO: compare two very small values;
                        // TODO: how to deal with negative infinity
                        if (prob < tranp ||
                            (prob == tranp && string.Compare(state, y0, StringComparison.CurrentCultureIgnoreCase) < 0))
                        {
                            prob  = tranp;
                            state = y0;
                        }
                    }

                    v[i][y]       = prob;
                    memPath[i][y] = state;
                }
            }

            var vLast    = v.Last();
            var last     = memPath.Last().Keys.Select(y => new { State = y, Prob = vLast[y] });
            var endProb  = double.MinValue;
            var endState = string.Empty;

            foreach (var endPoint in last)
            {
                // TODO: compare two very small values;
                if (endProb < endPoint.Prob ||
                    (endProb == endPoint.Prob && String.Compare(endState, endPoint.State, StringComparison.CurrentCultureIgnoreCase) < 0))
                {
                    endProb  = endPoint.Prob;
                    endState = endPoint.State;
                }
            }

            var route    = new string[sentence.Length];
            var n        = sentence.Length - 1;
            var curState = endState;

            while (n >= 0)
            {
                route[n] = curState;
                curState = memPath[n][curState];
                n--;
            }

            return(new Tuple <double, List <string> >(endProb, route.ToList()));
        }
Example #49
0
        public CreeperGameState GetGameState(CreeperColor playerTurn)
        {
            if (TeamCount(playerTurn, PieceType.Peg) == 0 || TeamCount(playerTurn.Opposite(), PieceType.Peg) == 0)
            {
                return CreeperGameState.Draw;
            }

            bool gameOver = false;
            bool stackEmpty = false;
            Stack<AIBoardNode> stack = new Stack<AIBoardNode>();
            HashSet<AIBoardNode> foundTiles = new HashSet<AIBoardNode>();
            HashSet<AIBoardNode> endTiles = new HashSet<AIBoardNode>();
            Position start = (playerTurn == CreeperColor.Fire) ? _WhiteStart : _BlackStart;
            Position end = (playerTurn == CreeperColor.Fire) ? _WhiteEnd : _BlackEnd;
            AIBoardNode winTile1 = TileBoard[end.Row - 1, end.Column];
            AIBoardNode winTile2 = TileBoard[end.Row, IsValidPosition(end.Row, end.Column - 1, PieceType.Tile)? end.Column - 1: end.Column + 1];
            if (winTile1.Color == playerTurn) endTiles.Add(winTile1);
            if (winTile2.Color == playerTurn) endTiles.Add(winTile2);

            if (!endTiles.Any())
            {
                return CreeperGameState.Unfinished;
            }

            AIBoardNode currentTile = TileBoard[start.Row, start.Column];
            IEnumerable<AIBoardNode> neighbors = GetNeighbors(currentTile, playerTurn);
            while (!stackEmpty && !(currentTile.Row == end.Row && currentTile.Column == end.Column))
            {
                foreach (AIBoardNode neighbor in neighbors)
                {
                    if (!foundTiles.Contains(neighbor))
                    {
                        stack.Push(neighbor);
                    }
                }

                foundTiles.UnionWith(neighbors);
                if (foundTiles.Intersect(endTiles).Any())
                {
                    gameOver = true;
                    break;
                }

                if (stack.Any())
                {
                    currentTile = stack.Pop();
                }
                else
                {
                    stackEmpty = true;
                }

                neighbors = GetNeighbors(currentTile, playerTurn);
            }

            return gameOver ? CreeperGameState.Complete : CreeperGameState.Unfinished;
        }
Example #50
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tran"></param>
        /// <param name="tableName"></param>
        /// <param name="documentId"></param>
        /// <param name="containsWords"></param>
        /// <param name="fullMatchWords"></param>
        /// <param name="deferredIndexing"></param>
        /// <param name="containsMinimalLength"></param>
        /// <param name="iMode"></param>
        public void InsertDocumentText(Transaction tran, string tableName, byte[] documentId, string containsWords, string fullMatchWords, bool deferredIndexing, int containsMinimalLength, eInsertMode iMode)
        {
            //tran._transactionUnit.TransactionsCoordinator._engine.Configuration.
            if (String.IsNullOrEmpty(tableName) || documentId == null)
            {
                return;
            }

            if ((iMode == eInsertMode.Append || iMode == eInsertMode.Remove) && (String.IsNullOrEmpty(containsWords) && String.IsNullOrEmpty(fullMatchWords)))
            {
                return;
            }

            //tran._transactionUnit.TransactionsCoordinator._engine.Configuration.TextSearchConfig.QuantityOfWordsInBlock
            SortedDictionary <string, WordDefinition> pST = this.GetWordsDefinitionFromText(containsWords, fullMatchWords, containsMinimalLength,
                                                                                            tran._transactionUnit.TransactionsCoordinator._engine.Configuration.TextSearchConfig.MaximalWordSize); //flattend searchables

            StringBuilder sbPs = new StringBuilder();

            //Registering all tables for text-search in current transaction
            ITS its = null;

            if (!itbls.TryGetValue(tableName, out its))
            {
                its = new ITS()
                {
                    e2i  = tran.InsertTable <byte>(tableName, 1, 0),
                    i2e  = tran.InsertTable <byte>(tableName, 2, 0),
                    srch = tran.InsertTable <byte>(tableName, 3, 0),
                };

                its.e2i.ValuesLazyLoadingIsOn  = false;
                its.i2e.ValuesLazyLoadingIsOn  = false;
                its.srch.ValuesLazyLoadingIsOn = false;

                itbls.Add(tableName, its);
            }

            //Internal document ID
            int iId = 0;

            //Searching document by externalID
            var r1 = its.e2i.Select <byte[], int>(documentId);

            if (r1.Exists)          //DOCUMENT EXISTS
            {
                iId = r1.Value;

                //Getting old searchables for this document
                byte[]           oldSrch        = its.srch.Select <byte[], byte[]>(iId.To_4_bytes_array_BigEndian().Concat(new byte[] { 0 }), true).Value;
                HashSet <string> oldSearchables = GetSearchablesFromByteArray_AsHashSet(oldSrch); //always instantiated hashset

                switch (iMode)
                {
                case eInsertMode.Insert:
                    //Comparing
                    if (oldSearchables.Intersect(pST.Keys).Count() == oldSearchables.Count && oldSearchables.Count == pST.Keys.Count)
                    {
                        return;     //Going out, nothing to insert
                    }
                    foreach (var ps1i in pST)
                    {
                        sbPs.Append(ps1i.Key);
                        sbPs.Append(" ");
                    }
                    break;

                case eInsertMode.Append:
                case eInsertMode.Remove:

                    if ((iMode == eInsertMode.Append)
                        &&
                        oldSearchables.Intersect(pST.Keys).Count() == oldSearchables.Count
                        &&
                        oldSearchables.Count == pST.Keys.Count
                        )
                    {
                        return;     //Going out, nothing to insert
                    }
                    foreach (var ew in pST.Keys)
                    {
                        if (iMode == eInsertMode.Append)
                        {
                            oldSearchables.Add(ew);
                        }
                        else
                        {
                            oldSearchables.Remove(ew);
                        }
                    }

                    foreach (var el in oldSearchables)
                    {
                        sbPs.Append(el);
                        sbPs.Append(" ");
                    }

                    break;
                }
            }
            else
            {
                //DOCUMENT NEW
                if (pST.Count < 1)
                {
                    return; //Going out, nothing to insert
                }
                //Document is new
                if (iMode == eInsertMode.Append)
                {
                    iMode = eInsertMode.Insert;
                }
                else if (iMode == eInsertMode.Remove)
                {
                    return; //Going out
                }
                iId = its.i2e.Max <int, byte[]>().Key;
                iId++;

                its.e2i.Insert <byte[], int>(documentId, iId);
                its.i2e.Insert <int, byte[]>(iId, documentId);

                foreach (var ps1i in pST)
                {
                    sbPs.Append(ps1i.Key);
                    sbPs.Append(" ");
                }
            }

            this.InsertWasPerformed = true;

            //Inserting into affected table
            if (!deferredIndexing)
            {
                its.ChangedDocIds.Add(iId);
            }
            else
            {
                if (!defferedDocIds.ContainsKey(tableName))
                {
                    defferedDocIds[tableName] = new HashSet <uint>();
                }

                defferedDocIds[tableName].Add((uint)iId);
            }

            //Inserting searchables to be indexed
            its.srch.Insert <byte[], byte[]>(iId.To_4_bytes_array_BigEndian().Concat(new byte[] { 1 }), GetByteArrayFromSearchbles(sbPs.ToString()));
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            bool showConcealed = true;
            if (words.Length > 0 && words[0].ToLower() == "revealed")
                showConcealed = false;

            if (showConcealed)
            {
                HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Concealed Entities ===");
                int count = 0;
                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                        continue;

                    if (entity.InScene)
                        continue;

                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId = 0;
                    string ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                        ownerName = "No one";

                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition())));
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total concealed entities: {0}", count));
            }
            else
            {
                HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Revealed Entities ===");
                Communication.SendPrivateInformation(userId, "==== Unconnected Entities ===");
                HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>();
                CubeGrids.GetGridsUnconnected(entitiesFound, entities);
                int count = 0;
                List<IMySlimBlock> slimBlocks = new List<IMySlimBlock>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                        continue;

                    if (!entity.InScene)
                        continue;

                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId = 0;
                    string ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                        ownerName = "No one";

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total unconnected revealed entities: {0}", count));

                Communication.SendPrivateInformation(userId, "==== Connected Entities ===");
                HashSet<IMyEntity> connectedFound = new HashSet<IMyEntity>();
                CubeGrids.GetConnectedGrids(connectedFound);
                Console.WriteLine("Here: {0} : {1} {2}", connectedFound.Intersect(entitiesFound).Count(), entitiesFound.Count, connectedFound.Count);
                count = 0;
                slimBlocks.Clear();
                foreach (IMyEntity entity in connectedFound)
                {
                    if (!(entity is IMyCubeGrid))
                        continue;

                    if (entitiesFound.Contains(entity))
                        continue;

                    if (!entity.InScene)
                        continue;

                    if (CubeGrids.GetRecursiveGridList((IMyCubeGrid)entity).Count < 2)
                        continue;

                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId = 0;
                    string ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                        ownerName = "No one";

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count, CubeGrids.GetRecursiveGridList(grid).Count));
                    //Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total connected revealed entities: {0}", count));

            }

            return true;
        }
Example #52
0
        /// <summary>
        /// Remove unreachable state.
        /// </summary>
        /// <returns></returns>
        private DFATable RemoveUnreachable()
        {
            // All the state that can be reached from 0.

            // Find all reachable states.
            Func <int, HashSet <int> > FindReachableClosure = x => {
                Stack <int>   stack   = new Stack <int>();
                HashSet <int> closure = new HashSet <int> {
                    x
                };
                stack.Push(x);
                while (stack.Count() > 0)
                {
                    int s = stack.Pop();
                    foreach (int t in table[s])
                    {
                        if (t != -1 && !closure.Contains(t))
                        {
                            stack.Push(t);
                            closure.Add(t);
                        }
                    }
                }
                return(closure);
            };

            HashSet <int> startClosure = FindReachableClosure(0);

            //
            // Helper function to check if this state should be deleted.
            // A state should be deleted when
            // 1. Starting from 0, there is no way to reach it OR
            // 2. Starting from it, there is no way to reach final state.
            //
            Func <int, bool> IsDeletable = s => {
                if (!startClosure.Contains(s))
                {
                    return(true);
                }
                HashSet <int> reachable = FindReachableClosure(s);
                return(reachable.Intersect(finals).Count() == 0);
            };

            DFATable dfa = new DFATable(map, revMap);

            bool[] deleted = new bool[table.Count()];
            int[]  newId   = new int[table.Count()];

            // Find all the state to be deleted.
            for (int i = 0; i < table.Count(); ++i)
            {
                deleted[i] = IsDeletable(i);
                if (!deleted[i])
                {
                    // Create the new state in the simplified DFA.
                    newId[i] = dfa.AddState();
                }
            }

            // Copy the transitions.
            for (int s = 0; s < table.Count(); ++s)
            {
                // Is this state deleted?
                if (!deleted[s])
                {
                    for (int i = 0; i < table[s].Count(); ++i)
                    {
                        int t = table[s][i];
                        // Is t deleted?
                        if (t != -1 && !deleted[t])
                        {
                            dfa.AddTransition(newId[s], newId[t], revMap[i]);
                        }
                    }
                }
            }

            // Set the final states.
            foreach (int s in finals)
            {
                if (!deleted[s])
                {
                    dfa.SetStateFinal(newId[s]);
                }
            }

            return(dfa);
        }
Example #53
0
 private static bool IsSetsEqual(HashSet <string> left, HashSet <string> right)
 {
     return(left.Count == right.Count && left.Count == left.Intersect(right).Count());
 }
Example #54
0
        protected virtual async Task UpdateProductAttributesAsync(Product product, CreateUpdateProductDto input)
        {
            var isProductSkusEmpty = product.ProductSkus.IsNullOrEmpty();

            var usedAttributeOptionIds = new HashSet <Guid>();

            foreach (var serializedAttributeOptionIds in product.ProductSkus.Select(sku => sku.SerializedAttributeOptionIds))
            {
                foreach (var attributeOptionId in await _attributeOptionIdsSerializer.DeserializeAsync(serializedAttributeOptionIds))
                {
                    usedAttributeOptionIds.Add(attributeOptionId);
                }
            }

            foreach (var attributeDto in input.ProductAttributes)
            {
                var attribute = product.ProductAttributes.FirstOrDefault(a => a.DisplayName == attributeDto.DisplayName);

                if (attribute == null)
                {
                    if (!isProductSkusEmpty)
                    {
                        throw new ProductAttributesModificationFailedException();
                    }

                    attribute = new ProductAttribute(GuidGenerator.Create(),
                                                     attributeDto.DisplayName, attributeDto.Description);

                    product.ProductAttributes.Add(attribute);
                }

                foreach (var optionDto in attributeDto.ProductAttributeOptions)
                {
                    var option = attribute.ProductAttributeOptions.FirstOrDefault(o => o.DisplayName == optionDto.DisplayName);

                    if (option == null)
                    {
                        option = new ProductAttributeOption(GuidGenerator.Create(),
                                                            optionDto.DisplayName, optionDto.Description);

                        attribute.ProductAttributeOptions.Add(option);
                    }
                }

                var removedOptionNames = attribute.ProductAttributeOptions.Select(o => o.DisplayName)
                                         .Except(attributeDto.ProductAttributeOptions.Select(o => o.DisplayName)).ToList();

                if (!isProductSkusEmpty && removedOptionNames.Any() && usedAttributeOptionIds
                    .Intersect(attribute.ProductAttributeOptions
                               .Where(option => removedOptionNames.Contains(option.DisplayName))
                               .Select(option => option.Id)).Any())
                {
                    throw new ProductAttributeOptionsDeletionFailedException();
                }

                attribute.ProductAttributeOptions.RemoveAll(o => removedOptionNames.Contains(o.DisplayName));
            }

            var removedAttributeNames = product.ProductAttributes.Select(a => a.DisplayName)
                                        .Except(input.ProductAttributes.Select(a => a.DisplayName)).ToList();

            if (!isProductSkusEmpty && removedAttributeNames.Any())
            {
                throw new ProductAttributesModificationFailedException();
            }

            product.ProductAttributes.RemoveAll(a => removedAttributeNames.Contains(a.DisplayName));
        }
Example #55
0
        protected void CalculateApplicationsToBeRemovedAndInserted(
            IEnumerable <ConceptApplication> oldApplications, IEnumerable <NewConceptApplication> newApplications,
            out List <ConceptApplication> toBeRemoved, out List <NewConceptApplication> toBeInserted)
        {
            var oldApplicationsByKey = oldApplications.ToDictionary(a => a.GetConceptApplicationKey());
            var newApplicationsByKey = newApplications.ToDictionary(a => a.GetConceptApplicationKey());


            // Find directly inserted and removed concept applications:
            var directlyRemoved  = oldApplicationsByKey.Keys.Except(newApplicationsByKey.Keys).ToList();
            var directlyInserted = newApplicationsByKey.Keys.Except(oldApplicationsByKey.Keys).ToList();

            foreach (string ca in directlyRemoved)
            {
                _logger.Trace("Directly removed concept application: " + ca);
            }
            foreach (string ca in directlyInserted)
            {
                _logger.Trace("Directly inserted concept application: " + ca);
            }


            // Find changed concept applications (different create sql query):
            var existingApplications = oldApplicationsByKey.Keys.Intersect(newApplicationsByKey.Keys).ToList();
            var changedApplications  = existingApplications.Where(appKey => !string.Equals(
                                                                      oldApplicationsByKey[appKey].CreateQuery,
                                                                      newApplicationsByKey[appKey].CreateQuery)).ToList();

            foreach (string ca in changedApplications)
            {
                _logger.Trace("Changed concept application: " + ca);
            }


            // Find dependent concepts applications to be regenerated:
            var toBeRemovedKeys = directlyRemoved.Union(changedApplications).ToList();
            var oldDependencies = GetDependencyPairs(oldApplications).Select(dep => Tuple.Create(dep.Item1.GetConceptApplicationKey(), dep.Item2.GetConceptApplicationKey()));
            var dependentRemovedApplications = Graph.IncludeDependents(toBeRemovedKeys, oldDependencies).Except(toBeRemovedKeys);

            var toBeInsertedKeys = directlyInserted.Union(changedApplications).ToList();
            var newDependencies  = GetDependencyPairs(newApplications).Select(dep => Tuple.Create(dep.Item1.GetConceptApplicationKey(), dep.Item2.GetConceptApplicationKey()));
            var dependentInsertedApplications = Graph.IncludeDependents(toBeInsertedKeys, newDependencies).Except(toBeInsertedKeys);

            var refreshDependents = dependentRemovedApplications.Union(dependentInsertedApplications).ToList();

            toBeRemovedKeys.AddRange(refreshDependents.Intersect(oldApplicationsByKey.Keys));
            toBeInsertedKeys.AddRange(refreshDependents.Intersect(newApplicationsByKey.Keys));


            // Log dependencies for items that need to be refreshed:
            var newDependenciesByDependent = newDependencies.GroupBy(dep => dep.Item2, dep => dep.Item1).ToDictionary(group => group.Key, group => group.ToList());
            var oldDependenciesByDependent = oldDependencies.GroupBy(dep => dep.Item2, dep => dep.Item1).ToDictionary(group => group.Key, group => group.ToList());
            var toBeInsertedIndex          = new HashSet <string>(toBeInsertedKeys);
            var toBeRemovedIndex           = new HashSet <string>(toBeRemovedKeys);
            var changedApplicationsIndex   = new HashSet <string>(changedApplications);

            foreach (string ca in refreshDependents.Intersect(newApplicationsByKey.Keys))
            {
                LogDatabaseChanges(newApplicationsByKey[ca], "Refresh", () =>
                {
                    var report             = new List <string>();
                    var refreshBecauseNew  = new HashSet <string>(newDependenciesByDependent.GetValueOrEmpty(ca).Intersect(toBeInsertedIndex));
                    var refreshBecauseOld  = new HashSet <string>(oldDependenciesByDependent.GetValueOrEmpty(ca).Intersect(toBeRemovedIndex));
                    var dependsOnNew       = string.Join(", ", refreshBecauseNew.Except(refreshBecauseOld));
                    var dependsOnOld       = string.Join(", ", refreshBecauseOld.Except(refreshBecauseNew));
                    var dependsOnExisting  = refreshBecauseNew.Intersect(refreshBecauseOld);
                    var dependsOnChanged   = string.Join(", ", dependsOnExisting.Intersect(changedApplicationsIndex));
                    var dependsOnRefreshed = string.Join(", ", dependsOnExisting.Except(changedApplicationsIndex));
                    if (!string.IsNullOrEmpty(dependsOnNew))
                    {
                        report.Add("It depends on new concepts: " + dependsOnNew + ".");
                    }
                    if (!string.IsNullOrEmpty(dependsOnChanged))
                    {
                        report.Add("It depends on changed concepts: " + dependsOnChanged + ".");
                    }
                    if (!string.IsNullOrEmpty(dependsOnRefreshed))
                    {
                        report.Add("It depends on refreshed concepts: " + dependsOnRefreshed + ".");
                    }
                    if (!string.IsNullOrEmpty(dependsOnOld))
                    {
                        report.Add("It depended on removed concepts: " + dependsOnOld + ".");
                    }
                    return(string.Join(" ", report));
                });
            }


            // Result:
            toBeRemoved  = toBeRemovedKeys.Select(key => oldApplicationsByKey[key]).ToList();
            toBeInserted = toBeInsertedKeys.Select(key => newApplicationsByKey[key]).ToList();
        }
Example #56
0
        /// <summary>
        /// Convert MSBuild items to a DependencyGraphSpec.
        /// </summary>
        public static DependencyGraphSpec GetDependencySpec(IEnumerable <IMSBuildItem> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            // Unique names created by the MSBuild restore target are project paths, these
            // can be different on case-insensitive file systems for the same project file.
            // To workaround this unique names should be compared based on the OS.
            var uniqueNameComparer = PathUtility.GetStringComparerBasedOnOS();

            var graphSpec         = new DependencyGraphSpec();
            var itemsById         = new Dictionary <string, List <IMSBuildItem> >(uniqueNameComparer);
            var restoreSpecs      = new HashSet <string>(uniqueNameComparer);
            var validForRestore   = new HashSet <string>(uniqueNameComparer);
            var projectPathLookup = new Dictionary <string, string>(uniqueNameComparer);
            var toolItems         = new List <IMSBuildItem>();

            // Sort items and add restore specs
            foreach (var item in items)
            {
                var projectUniqueName = item.GetProperty("ProjectUniqueName");

                if (item.IsType("restorespec"))
                {
                    restoreSpecs.Add(projectUniqueName);
                }
                else if (!string.IsNullOrEmpty(projectUniqueName))
                {
                    List <IMSBuildItem> idItems;
                    if (!itemsById.TryGetValue(projectUniqueName, out idItems))
                    {
                        idItems = new List <IMSBuildItem>(1);
                        itemsById.Add(projectUniqueName, idItems);
                    }

                    idItems.Add(item);
                }
            }

            // Add projects
            var validProjectSpecs = itemsById.Values.Select(GetPackageSpec).Where(e => e != null);

            foreach (var spec in validProjectSpecs)
            {
                // Keep track of all project path casings
                var uniqueName = spec.RestoreMetadata.ProjectUniqueName;
                if (uniqueName != null && !projectPathLookup.ContainsKey(uniqueName))
                {
                    projectPathLookup.Add(uniqueName, uniqueName);
                }

                var projectPath = spec.RestoreMetadata.ProjectPath;
                if (projectPath != null && !projectPathLookup.ContainsKey(projectPath))
                {
                    projectPathLookup.Add(projectPath, projectPath);
                }

                if (spec.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference ||
                    spec.RestoreMetadata.ProjectStyle == ProjectStyle.ProjectJson ||
                    spec.RestoreMetadata.ProjectStyle == ProjectStyle.DotnetCliTool ||
                    spec.RestoreMetadata.ProjectStyle == ProjectStyle.Standalone ||
                    spec.RestoreMetadata.ProjectStyle == ProjectStyle.DotnetToolReference)
                {
                    validForRestore.Add(spec.RestoreMetadata.ProjectUniqueName);
                }

                graphSpec.AddProject(spec);
            }

            // Fix project reference casings to match the original project on case insensitive file systems.
            NormalizePathCasings(projectPathLookup, graphSpec);

            // Remove references to projects that could not be read by restore.
            RemoveMissingProjects(graphSpec);

            // Add valid projects to restore section
            foreach (var projectUniqueName in restoreSpecs.Intersect(validForRestore))
            {
                graphSpec.AddRestore(projectUniqueName);
            }

            return(graphSpec);
        }
Example #57
0
        protected Objective LoadObjective(XElement objectiveRoot, string[] allRoles)
        {
            var allRolesSet = new HashSet <string>(allRoles);
            var result      = new Objective
            {
                ShuffleGoalsCount = objectiveRoot.GetAttributeInt("shuffleGoalsCount", -1)
            };
            var objectiveRoles = objectiveRoot.GetAttributeStringArray("roles", allRoles);

            if (!allRolesSet.IsSupersetOf(objectiveRoles))
            {
                var unrecognized = new HashSet <string>(objectiveRoles);
                unrecognized.ExceptWith(allRoles);
                GameServer.Log($"Undefined role(s) \"{string.Join(", ", unrecognized)}\" set for Objective.", ServerLog.MessageType.Error);
            }
            result.Roles.UnionWith(allRolesSet.Intersect(objectiveRoles));

            foreach (var element in objectiveRoot.Elements())
            {
                using (var checker = new AttributeChecker(element))
                {
                    switch (element.Name.ToString().ToLowerInvariant())
                    {
                    case "infotext":
                        checker.Required("id");
                        result.InfoText = element.GetAttributeString("id", null);
                        break;

                    case "startmessage":
                        checker.Required("id");
                        result.StartMessageTextId = element.GetAttributeString("id", null);
                        break;

                    case "startmessageserver":
                        checker.Required("id");
                        result.StartMessageServerTextId = element.GetAttributeString("id", null);
                        break;

                    case "endmessagesuccess":
                        checker.Required("id");
                        result.EndMessageSuccessTextId = element.GetAttributeString("id", null);
                        break;

                    case "endmessagesuccessdead":
                        checker.Required("id");
                        result.EndMessageSuccessDeadTextId = element.GetAttributeString("id", null);
                        break;

                    case "endmessagesuccessdetained":
                        checker.Required("id");
                        result.EndMessageSuccessDetainedTextId = element.GetAttributeString("id", null);
                        break;

                    case "endmessagefailure":
                        checker.Required("id");
                        result.EndMessageFailureTextId = element.GetAttributeString("id", null);
                        break;

                    case "endmessagefailuredead":
                        checker.Required("id");
                        result.EndMessageFailureDeadTextId = element.GetAttributeString("id", null);
                        break;

                    case "endmessagefailuredetained":
                        checker.Required("id");
                        result.EndMessageFailureDetainedTextId = element.GetAttributeString("id", null);
                        break;

                    case "goal":
                    {
                        var goal = LoadGoal(element);
                        if (goal != null)
                        {
                            result.Goals.Add(goal);
                        }
                        break;
                    }

                    default:
                        GameServer.Log($"Unrecognized element \"{element.Name}\" under Objective.", ServerLog.MessageType.Error);
                        break;
                    }
                }
            }
            return(result);
        }
Example #58
0
        public void Load_Playlist(string playlist_file)
        {
            progress.Value = 1;

            StreamReader         reader;
            string               line;
            IEnumerable <string> intersection;
            IEnumerable <string> union;
            IEnumerable <string> files_in_different_folder;

            liste.Items.Clear();
            paths.Clear();
            files_in_playlist.Clear();
            files_in_folders.Clear();
            extensions.Clear();

            playlist_folder = Path.GetDirectoryName(playlist_file);

            reader = new StreamReader(playlist_file, Encoding.Default);
            try
            {
                while ((line = reader.ReadLine()) != null)
                {
                    if (Path.IsPathRooted(line))
                    {
                        files_in_playlist.Add(line);
                        paths.Add(Path.GetDirectoryName(line));
                    }
                    else
                    {
                        files_in_playlist.Add(Path.Combine(playlist_folder, line));
                        paths.Add(Path.Combine(playlist_folder, Path.GetDirectoryName(line)));
                    }

                    extensions.Add(Path.GetExtension(line));
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception while reading playlist:" + Environment.NewLine + exc);
            }
            finally
            {
                reader.Close();
            }

            progress.Value = 33;

            foreach (string path in paths)
            {
                if (Directory.Exists(path))
                {
                    foreach (string file in Directory.GetFiles(path))
                    {
                        if (extensions.Contains(Path.GetExtension(file)))
                        {
                            files_in_folders.Add(file);
                        }
                    }
                }
            }

            progress.Value = 50;

            intersection = files_in_folders.Intersect(files_in_playlist);
            union        = files_in_folders.Union(files_in_playlist);

            files_in_different_folder = union.GroupBy((string s) => { return(Path.GetFileNameWithoutExtension(s)); }).Where(g => g.Count() > 1).Select(x => x.Key);

            progress.Value = 75;

            foreach (string file in union)
            {
                ListBoxItem item = new ListBoxItem();

                item.ToolTip = file;
                item.Content = file;

                if (intersection.Contains(file))
                {
                    item.Background = Brushes.LightGreen;
                    item.ToolTip   += " OK";
                }
                else
                if (files_in_different_folder.Contains(Path.GetFileNameWithoutExtension(file)))
                {
#warning untested here

                    item.Background = Brushes.Blue;

                    if (files_in_playlist.Contains(file))
                    {
                        item.ToolTip = files_in_folders.Where(path => path.Contains(Path.GetFileNameWithoutExtension(file))).First() + " File in different folder";
                    }
                    else
                    {
                        item.ToolTip = files_in_playlist.Where(path => path.Contains(Path.GetFileNameWithoutExtension(file))).First() + " File in different folder";
                    }
                    //item.ToolTip += " File in different folder";
                }
                else
                if (files_in_playlist.Contains(file))
                {
                    item.Background = Brushes.Black;
                    item.Foreground = Brushes.White;
                    item.ToolTip   += " File in playlist only";
                }
                else
                if (!File.Exists(file))
                {
                    item.Background = Brushes.Red;
                    item.ToolTip   += " File not on disk";
                }
                else
                {
                    item.Background = Brushes.Black;
                    item.Foreground = Brushes.White;
                    item.ToolTip   += " File not in playlist";
                }

                item.ContextMenu = this.Resources["ListItemContextMenu"] as ContextMenu;

                liste.Items.Add(item);
            }

            progress.Value = 100;

            this.Activate();

            if (intersection.Count() == union.Count())
            {
                if (this.Title == default_Title)
                {
                    this.Title = "Playlist Check (All green)";
                }
            }
            else
            if (this.Title != default_Title)
            {
                this.Title = default_Title;
            }
        }
Example #59
0
        public static void RunTest(string filesLocation)
        {
            string[] folders = Directory.GetDirectories(filesLocation);
            foreach (string fldr in folders)
            {
                Console.WriteLine("Running for site:" + fldr);
                string[] innerfolders = Directory.GetDirectories(fldr);
                foreach (string innerdir in innerfolders)
                {
                    Console.Out.Flush();
                    Console.WriteLine("Running for att:" + innerdir);


                    DomPool.LoadDocuments(innerdir);
                    //for(int i= (DomPool.allDocsNames.Count() - 1); i <= (DomPool.allDocsNames.Count()-1)/*DomPool.allDocsNames.Count()*/; i++)
                    for (int i = 1; i <= (DomPool.allDocsNames.Count() - 1); i++)
                    {
                        string[] tools     = new string[] { "our", "our-not-forgiving", "j48", "nb", "xpath-align", "svm" };
                        int      toolStart = 0;
                        Dictionary <string, string> xpathNonForgiving = new Dictionary <string, string>();
                        for (int tool = toolStart; tool < 1; tool++)
                        {
                            Console.WriteLine("[-] running for training set size=" + i);
                            IEnumerable <IEnumerable <int> > subsetsIndexes = /*SequenceUpTo(DomPool.allDocsNames.Count(), i);*/ Subsets(DomPool.allDocsNames.Count(), i);
                            //Reduce size ...for testing only
                            //subsetsIndexes = subsetsIndexes.Take(30);
                            double totalAccuracy = 0;
                            double totalRecall   = 0;
                            long   totalTime     = 0;
                            Console.WriteLine("[-] tool:" + tools[tool]);
                            Console.WriteLine("+ will run " + subsetsIndexes.Count() + " different iterations for the current set size");
                            int s = 0;
                            Dictionary <String, double> SiteTotalRecall    = new Dictionary <string, double>();
                            Dictionary <String, double> SiteTotalPrecision = new Dictionary <string, double>();
                            Dictionary <String, double> SiteTotalTests     = new Dictionary <string, double>();
                            foreach (string site in DomPool.allDocsNames)
                            {
                                SiteTotalPrecision[site] = 0;
                                SiteTotalRecall[site]    = 0;
                                SiteTotalTests[site]     = 0;
                            }


                            foreach (IEnumerable <int> currSubsetIndexes in subsetsIndexes)
                            {
                                List <int> listRep   = new List <int>(currSubsetIndexes);
                                string     stringRep = listRep.Aggregate("", (b, x) => b + "," + x);
                                s++;
                                if (s % 10 == 0)
                                {
                                    //Console.Write("(" + s + "/" + subsetsIndexes.Count() + ") ");

                                    Console.Write(".");
                                }
                                //if (tool == toolStart)
                                //{
                                HashSet <String> currSubset = GetSubSet(DomPool.allDocsNames, currSubsetIndexes);
                                DomPool.Initiate(currSubset);
                                DomPool.ExtractAllFeatures();
                                //}
                                var runres = new HashSet <HtmlNode>();
                                //our method
                                if (tool < 2)
                                {
                                    string xpath = "";
                                    if (tool == 0)
                                    {
                                        DecisionNode dn = new DecisionNode();
                                        dn.InitialNodeSet   = new HashSet <HtmlNode>(DomPool.TargetNodes.Union(DomPool.NonTargetNodes));
                                        dn.SelectedNegative = new HashSet <HtmlNode>(DomPool.NonTargetNodes.Except(DomPool.TargetNodesPrecision));
                                        dn.SelectedPositive = new HashSet <HtmlNode>(DomPool.TargetNodes);
                                        dn.FeatureSet       = new HashSet <Feature>();
                                        dn.CalculateEntropy();

                                        DecisionTreeLearning.RecursiveTreeImprovement(dn);


                                        xpath = XpathTools.GenerateAForgivingXpath(dn);

                                        xpathNonForgiving[stringRep] = XpathTools.DecisionTreeToXpath(dn, new HashSet <Feature>(), 1);
                                        xpathNonForgiving[stringRep] = "//*" + (xpathNonForgiving[stringRep].Equals("") ? "" : ("[" + xpathNonForgiving[stringRep] + "]"));
                                    }

                                    if (tool == 1)
                                    {
                                        xpath = xpathNonForgiving[stringRep];
                                    }

                                    Console.WriteLine("Query:" + xpath);

                                    var watch = Stopwatch.StartNew();
                                    runres = DomPool.TESTRunXpathQuery(xpath);
                                    watch.Stop();
                                    var elapsedMs = watch.ElapsedMilliseconds;
                                    totalTime = totalTime + elapsedMs;
                                }
                                else
                                {
                                    if (tool == 2)
                                    {
                                        ModelLearner model = new ModelLearner();
                                        model.LearnModel();
                                        var watch = Stopwatch.StartNew();
                                        runres = model.RunOnTestSet();

                                        watch.Stop();
                                        var elapsedMs = watch.ElapsedMilliseconds;
                                        totalTime = totalTime + elapsedMs;
                                    }
                                    else
                                    {
                                        if (tool == 3)
                                        {
                                            NB model = new NB();
                                            model.LearnModel();
                                            var watch = Stopwatch.StartNew();
                                            runres = model.RunOnTestSet();
                                            watch.Stop();
                                            var elapsedMs = watch.ElapsedMilliseconds;
                                            totalTime = totalTime + elapsedMs;
                                        }
                                        else
                                        {
                                            if (tool == 4)
                                            {
                                                XpathAlignment model = new XpathAlignment();
                                                model.LearnModel();
                                                var watch = Stopwatch.StartNew();
                                                runres = model.RunOnTestSet();
                                                watch.Stop();
                                                var elapsedMs = watch.ElapsedMilliseconds;
                                                totalTime = totalTime + elapsedMs;
                                            }
                                            else
                                            {
                                                SVM model = new SVM();
                                                model.LearnModel();
                                                var watch = Stopwatch.StartNew();
                                                runres = model.RunOnTestSet();
                                                watch.Stop();
                                                var elapsedMs = watch.ElapsedMilliseconds;
                                                totalTime = totalTime + elapsedMs;
                                            }
                                        }
                                    }
                                }


                                HashSet <HtmlNode> spos          = new HashSet <HtmlNode>(DomPool.TESTTargetNodes.Intersect(runres));
                                HashSet <HtmlNode> sposprecision = new HashSet <HtmlNode>(DomPool.TESTTargetNodesPrecision.Intersect(runres));

                                foreach (var entry in DomPool.docsAndNames)
                                {
                                    if (DomPool.trainingDocsNames.Contains(entry.Key))
                                    {
                                        continue;
                                    }

                                    HashSet <HtmlNode> docNodes          = new HashSet <HtmlNode>(entry.Value.SelectNodes("//*"));
                                    HashSet <HtmlNode> currspos          = new HashSet <HtmlNode>(spos.Intersect(docNodes));
                                    HashSet <HtmlNode> currrunres        = new HashSet <HtmlNode>(runres.Intersect(docNodes));
                                    HashSet <HtmlNode> currsposprecision = new HashSet <HtmlNode>(sposprecision.Intersect(docNodes));
                                    HashSet <HtmlNode> currTargetNodes   = new HashSet <HtmlNode>(DomPool.TESTTargetNodes.Intersect(docNodes));
                                    double             currSiteAccuracy  = (currsposprecision.Count() / ((double)currrunres.Count()));
                                    double             currSiteRecall    = (currspos.Count() / ((double)currTargetNodes.Count()));
                                    if (((double)currrunres.Count()) > 0)
                                    {
                                        SiteTotalPrecision[entry.Key] = SiteTotalPrecision[entry.Key] + currSiteAccuracy;
                                        SiteTotalRecall[entry.Key]    = SiteTotalRecall[entry.Key] + currSiteRecall;
                                    }

                                    SiteTotalTests[entry.Key] = SiteTotalTests[entry.Key] + 1;
                                }

                                double currAccuracy = (sposprecision.Count() / ((double)runres.Count()));
                                double currRecall   = (spos.Count() / ((double)DomPool.TESTTargetNodes.Count()));
                                if (runres.Count() > 0)
                                {
                                    totalAccuracy = totalAccuracy + currAccuracy;
                                    totalRecall   = totalRecall + currRecall;
                                }
                            }

                            totalAccuracy = totalAccuracy / subsetsIndexes.Count();
                            totalRecall   = totalRecall / subsetsIndexes.Count();
                            Console.WriteLine("########## Results " + tools[tool] + " for i=" + i + "##########");

                            Console.WriteLine("+++++++++ Detailed Results for i=" + i + "++++++++++#");
                            double count             = 0;
                            double totalSumPrecision = 0;
                            double totalSumRecall    = 0;
                            double avgRecall         = 0;
                            double avgPrecision      = 0;
                            double avgFscore         = 0;
                            double numPrecision      = 0;

                            foreach (string site in DomPool.allDocsNames)
                            {
                                if (SiteTotalTests[site] < 1)
                                {
                                    continue;
                                }             // SiteTotalTests[site]++; }
                                else
                                {
                                    numPrecision++;
                                }

                                double sitePrecision = SiteTotalPrecision[site] / SiteTotalTests[site];
                                double siteRecall    = SiteTotalRecall[site] / SiteTotalTests[site];
                                double siteFscore    = 2 * (sitePrecision * siteRecall) / (sitePrecision + siteRecall);
                                if (siteRecall == 0 && sitePrecision == 0)
                                {
                                    siteFscore = 0;
                                }

                                count++;
                                avgRecall    = avgRecall + siteRecall;
                                avgPrecision = avgPrecision + sitePrecision;
                                avgFscore    = avgFscore + siteFscore;

                                // Console.WriteLine(">" + site + ": Precision:" + sitePrecision + " , Recall:" + siteRecall+", F-score:"+siteFscore);
                            }
                            Console.WriteLine("++++++++++++++++Total+++++++++++++++++");
                            avgRecall    = avgRecall / count;
                            avgPrecision = avgPrecision / numPrecision;
                            avgFscore    = avgFscore / count;

                            Console.WriteLine("Recall:" + avgRecall);
                            Console.WriteLine("Precision:" + avgPrecision);
                            Console.WriteLine("F-score:" + avgFscore);
                            Console.WriteLine("Time:" + totalTime);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
Example #60
0
        private SchedulerResponseViewModel ImportSchedule(DataTable tableSchedules, string loggedinUserId, string loggedinUserName, bool SkipErrors, string impType)
        {
            var listColumns = new List <string>();
            SchedulerResponseViewModel response = new SchedulerResponseViewModel();

            // generate columns list
            foreach (DataColumn col in tableSchedules.Columns)
            {
                if (!listColumns.Contains(col.ColumnName) && col.ColumnName.ToLower() != "date")
                {
                    listColumns.Add(col.ColumnName);
                }
            }

            // if there are column to import
            if (listColumns.Count() == 0)
            {
                return(response);
            }

            // get user's info based on initials in CSV
            var listUsers = _unitOfWork.ApplicationUsers
                            .Where(x => listColumns.Contains(x.UserInitial))
                            .Select(x => new { x.UserInitial, x.Id, x.FirstName, x.LastName })
                            .ToList();
            var distinctScheduleUserIds = listUsers.Select(x => x.Id).ToList();
            // temp schedules
            var listSchedule = new List <user_schedule_sleep>();
            var currentTime  = DateTime.Now.ToEST();

            // process all columns
            int rowCount = 2; // first row is header that's why initializing it from 2
            int colCount = 1;

            foreach (DataRow row in tableSchedules.Rows)
            {
                colCount = 1;
                DateTime schDate      = new DateTime();
                bool     hasValidDate = true;
                if (string.IsNullOrEmpty(row["Date"].ToString()))
                {
                    continue;
                }

                try { schDate = Convert.ToDateTime(row["Date"]); } catch { hasValidDate = false; }
                if (hasValidDate)
                {
                    foreach (string currentColumn in listColumns)
                    {
                        string columnData = Convert.ToString(row[currentColumn]);
                        if (!string.IsNullOrEmpty(currentColumn) && !string.IsNullOrEmpty(columnData))
                        {
                            var splitShift = columnData.Split('|');
                            foreach (string schItem in splitShift)
                            {
                                string[] times  = null;
                                string   userId = null;
                                try
                                {
                                    try { if (!string.IsNullOrEmpty(schItem.Trim()))
                                          {
                                              times = schItem.Trim().Split('-').Where(m => !string.IsNullOrEmpty(m)).ToArray();
                                          }
                                    } catch { response.ParseErrors.Add($"Invalid Time {schItem} on Row {rowCount} and Column {colCount}"); }
                                    if (userId == null)
                                    {
                                        try { userId = listUsers.Where(x => x.UserInitial.ToLower() == currentColumn.ToLower()).FirstOrDefault()?.Id; } catch { response.ParseErrors.Add($"Invalid Initial {currentColumn} on Row {rowCount} and Column {colCount}"); }
                                    }

                                    if (userId != null && times != null)
                                    {
                                        if (times.Length == 2)
                                        {
                                            var schEntry = new user_schedule_sleep
                                            {
                                                uss_date            = schDate,
                                                uss_user_id         = userId,
                                                uss_time_from       = ParseScheduleTime(times[0]), //TimeSpan.Parse(times[0]).Ticks,
                                                uss_time_to         = ParseScheduleTime(times[1]), //TimeSpan.Parse(times[1]).Ticks,
                                                uss_is_active       = true,
                                                uss_created_by      = loggedinUserId,
                                                uss_created_by_name = loggedinUserName,
                                                uss_created_date    = currentTime,
                                            };



                                            // next day's time check
                                            if (schEntry.uss_time_to < schEntry.uss_time_from)
                                            {
                                                schEntry.uss_time_to = schEntry.uss_time_to + TimeSpan.TicksPerDay;
                                            }

                                            schEntry.uss_time_from_calc = schEntry.uss_date.Date.AddTicks(schEntry.uss_time_from);
                                            schEntry.uss_time_to_calc   = schEntry.uss_date.Date.AddTicks(schEntry.uss_time_to);

                                            listSchedule.Add(schEntry);
                                        }
                                        else
                                        {
                                            response.ParseErrors.Add($"Invalid Time {schItem} on Row {rowCount} and Column {colCount}");
                                            response.Success = false;
                                        }
                                    }
                                }
                                catch
                                {
                                    response.ParseErrors.Add($"Parse Data issue on Row {rowCount} and Column {colCount}");
                                }
                            }
                        }
                        colCount++;
                    }
                }
                else
                {
                    response.Success = false;
                    response.ParseErrors.Add($"Invalid Date {row["Date"].ToString()} on Row {rowCount} and Column {colCount}");
                }
                rowCount++;
            }
            if (listSchedule != null && listSchedule.Count() > 0 && response.Success || (listSchedule != null && listSchedule.Count() > 0 && SkipErrors))
            {
                try
                {
                    var distinctDates = listSchedule.Select(x => x.uss_date).Distinct().ToList();
                    var oldEntries    = _unitOfWork.SleepRepository.Query().Where(x => distinctDates.Any(y => y == x.uss_date)).ToList();

                    #region Get Only Required Physician
                    PhysicianDictionary physicianDictionary = new PhysicianDictionary();
                    var ids                 = physicianDictionary.GetRecordAsList(impType);
                    var foundIds            = _adminService.GetAllUsersIds(ids);
                    HashSet <string> resIds = new HashSet <string>(oldEntries.Select(s => s.uss_user_id.ToString()));
                    var matchIds            = resIds.Intersect(foundIds).ToList();
                    //var _oldEntries = oldEntries.Where(x => matchIds.Contains(x.uss_user_id)).ToList();
                    var _oldEntries = oldEntries.Where(x => matchIds.Contains(x.uss_user_id)).Where(x => distinctScheduleUserIds.Contains(x.uss_user_id)).ToList();
                    #endregion
                    _unitOfWork.BeginTransaction();
                    // remove old entries
                    if (_oldEntries != null && _oldEntries.Count() > 0)
                    {
                        _unitOfWork.SleepRepository.DeleteRange(_oldEntries);
                        _unitOfWork.Save();
                    }
                    // add schedule entries
                    if (listSchedule.Count() > 0)
                    {
                        _unitOfWork.SleepRepository.InsertRange(listSchedule);
                        _unitOfWork.Save();
                    }
                    _unitOfWork.Commit();
                    return(new SchedulerResponseViewModel {
                        Message = "Schedule is updated.", Success = true
                    });
                }
                catch (Exception ex)
                {
                    try { _unitOfWork.Rollback(); }
                    catch
                    {
                        throw ex;
                    }
                }
                finally { listSchedule = null; }
            }
            return(response);
        }