Example #1
0
        private static void SetPathsDijkstra(List<SiteNode> siteList)
        {
            List<SiteNode> Sites = new List<SiteNode>(siteList);
            foreach (SiteNode node in Sites)
            {
                node.Distance = double.MaxValue;
                node.Previous = null;
            }

            if (Sites.Count > 0)
                Sites.First().Distance = 0;
            while (Sites.Count > 0)
            {
                SiteNode current = Sites.First();
                foreach (SiteNode site in Sites)
                    if (site.Distance < current.Distance) current = site;
                if (current.Distance == double.MaxValue) break;
                Sites.Remove(current);


                foreach (SitePath path in current.Paths)
                {
                    double distance = current.Distance + path.Weight;
                    if (distance < path.SiteNode.Distance)
                    {
                        path.SiteNode.Distance = distance;
                        path.SiteNode.Previous = current;
                    }
                }
            }
        }
        public bool Update(List<EditPermissionViewModel> editPermissionViewModels)
        {
            var modelLdapName = editPermissionViewModels.First().LdapId.Replace('_', '.');
            var userModelList = UserModuleService.GetAllUserModule().Where(x => x.LdapName == modelLdapName);

            if (userModelList.Any())
            {
                UserModuleService.DeleteUserModule(new UserModule()
                {
                    LdapName = editPermissionViewModels.First().LdapId.Replace('_', '.')
                });
            }

            foreach (var editPermissionViewModel in editPermissionViewModels)
            {

                var userModel = new UserModule()
                {
                    IsAdd = editPermissionViewModel.IsAdd,
                    IsEdit = editPermissionViewModel.IsEdit,
                    IsApprover = editPermissionViewModel.IsApprover,
                    LdapName = editPermissionViewModel.LdapId.Replace('_', '.'),
                    ModuleId = editPermissionViewModel.ModuleId
                };
                UserModuleService.InsertUserModule(userModel);

            }
            return true;
        }
 public PMS.Model.QueryModel.Redis_SMSContent CheckTimeOut_RedisList(List<PMS.Model.QueryModel.Redis_SMSContent> list_final, double seconds_add,string key_redis)
 {
     //3 判断集合第一个对象的时间是否已经超过规定的时间
     if (list_final.Count > 0)
     {
         if (list_final.First().Dt < DateTime.Now.AddSeconds(seconds_add))
         {
             //7月28日添加若发送人数超过一百人需要连续进行两次查询
             Console.WriteLine("*******首元素满足条件*******");
             var model = list_final.First();
             //context.SetValue(First_Obj, model);
             //3.2 并从redis中删除第一个对象
            // redisListhelper.Delete(key_redis);
             Console.WriteLine("删除首元素!!");
             return model;
         }
         else
         {
             //ToShow("现有Redis集合中以没有时间范围内的对象");
             //ToShow("现Redis集合中共有:" + list_final.Count());
             return null;
         }
     }
     //直到出现集合第一个对象时间已经不再超过规定时间则跳出
     else
     {
         //ToShow("现有Redis集合中以没有时间范围内的对象");
         //ToShow("现Redis集合中共有:" + list_final.Count());
         return null;
     }
 }
Example #4
0
        public static List<CharacteristicType> GenerateCharacteristicType(List<StateType> stateTypes)
        {
            var maxHp = stateTypes.First(x => x.Name == MaxHp);
            var hp = stateTypes.First(x => x.Name == Hp);
            var dodge = stateTypes.First(x => x.Name == Dodge);
            var gold = stateTypes.First(x => x.Name == Gold);
            var characteristicType = new List<CharacteristicType>();

            characteristicType.Add(new CharacteristicType
            {
                Name = Strength,
                Desc = "Чем сильней, тем тупей, шутят над орками. А те почему-то смеются и бьют себя в голову",
                EffectState = new List<State>
                {
                    new State { StateType = maxHp, Number = 5 },
                    new State { StateType = hp, Number = 5 }
                }
            });

            characteristicType.Add(new CharacteristicType
            {
                Name = Agility,
                Desc = "Удержать яйцо на иголке? Легко!",
                EffectState = new List<State> { new State { StateType = dodge, Number = 5 } }
            });

            characteristicType.Add(new CharacteristicType
            {
                Name = Charism,
                Desc = "Это не честно кричала некрасивая девочка, глядя как выходит за муж очередная подруга",
                EffectState = new List<State> { new State { StateType = gold, Number = 10 } }
            });

            return characteristicType;
        }
        public static string[,] ObjectArr2StringArray(object[] objArr)
        {
            if (objArr.Length == 0) return new string[1,1] {{"no entries."}};
            List<Dictionary<string, string>> listDicts = new List<Dictionary<string,string>>();

            foreach (var item in objArr) listDicts.Add(Object2StringDict(item));
            int nrObjs = objArr.Length;
            int nrCols = listDicts.First().Count;

            string[,] ret = new string[nrObjs + 1,nrCols];

            //add names
            int k = 0;
            foreach (var name in listDicts.First().Keys.OrderBy(j => j).ToList())
            {
                ret[0, k] = name; k+=1;
            }

            int i = 1;
            foreach( var item in listDicts)
            {
                for (k = 0; k < nrCols; k++)
                {
                    ret[i,k] = item[ret[0,k]];
                }
                i += 1;
            }

            return ret;
        }
Example #6
0
        public static string GetInputArgument(List<string> inputFiles, MediaProtocol protocol)
        {
            if (protocol == MediaProtocol.Http)
            {
                var url = inputFiles.First();

                return string.Format("\"{0}\"", url);
            }
            if (protocol == MediaProtocol.Rtmp)
            {
                var url = inputFiles.First();

                return string.Format("\"{0}\"", url);
            }
            if (protocol == MediaProtocol.Rtsp)
            {
                var url = inputFiles.First();

                return string.Format("\"{0}\"", url);
            }
            if (protocol == MediaProtocol.Udp)
            {
                var url = inputFiles.First();

                return string.Format("\"{0}\"", url);
            }

            return GetConcatInputArgument(inputFiles);
        }
Example #7
0
        public Cbr GenerateCbr(List<KeyInfo> keys, bool isExport = false, KeyStoreContext context = null)
        {
            if (keys.Count == 0 || keys.Count > Constants.BatchLimit)
                throw new ArgumentOutOfRangeException("Keys are invalid to generate CBR.");
            string soldTo = keys.First().SoldToCustomerId;
            if (keys.Any(k => k.SoldToCustomerId != soldTo))
                throw new ApplicationException("Keys are not sold to the same customer.");
            string shipTo = keys.First().ShipToCustomerId;
            if (keys.Any(k => k.ShipToCustomerId != shipTo))
                throw new ApplicationException("Keys are not shipped to the same customer.");

            Guid customerReportId = Guid.NewGuid();
            Cbr cbr = new Cbr()
            {
                CbrUniqueId = customerReportId,
                CbrStatus = (isExport ? CbrStatus.Reported : CbrStatus.Generated),
                SoldToCustomerId = soldTo,
                ReceivedFromCustomerId = shipTo,
                CbrKeys = keys.Select(k => new CbrKey()
                {
                    CustomerReportUniqueId = customerReportId,
                    KeyId = k.KeyId,
                    HardwareHash = k.HardwareHash,
                    OemOptionalInfo = k.OemOptionalInfo.ToString(),
                }).ToList()
            };
            cbrRepository.InsertCbrAndCbrKeys(cbr, context = null);
            return cbr;
        }
        public async Task InitializeContextAsync()
        {
            //simulates a network delay
            await Task.Delay(TimeSpan.FromSeconds(2.5d));

            Tables = new List<Table>
            {
                new Table() {Description = "Back-Corner Two Top"},
                new Table() {Description = "Front Booth"}
            };

            StandardMenuItems = new List<MenuItem>
            {
                new MenuItem { Title = "French Bread & Fondue Dip", Price = 5.75m },
                new MenuItem { Title = "Curried Chicken and Rice", Price = 9.00m },
                new MenuItem { Title = "Feta-Stuffed Chicken", Price = 8.25m },
                new MenuItem { Title = "Grilled Pork Loin", Price = 11.50m },
                new MenuItem { Title = "Carnitas Tacos", Price = 7.50m },
                new MenuItem { Title = "Fillet Mignon & Asparagus", Price = 15.75m },
                new MenuItem { Title = "T-Bone Steak", Price = 12.25m },
                new MenuItem { Title = "Pineapple and Pear Salad", Price = 6.25m },
                new MenuItem { Title = "Sautéed Broccoli", Price = 3.75m },
                new MenuItem { Title = "Mashed Peas", Price = 3.25m }
            };

            Orders = new ObservableCollection<Order>
            {
                new Order { Complete = false, Expedite = true, SpecialRequests = "Allergic to Shellfish", Table = Tables.Last(), Items = new List<MenuItem> { StandardMenuItems.First() } },
                new Order { Complete = false, Expedite = false, SpecialRequests = string.Empty, Table = Tables.Last(), Items = new List<MenuItem> { StandardMenuItems.Last(), StandardMenuItems.First() } },
            };
        }
  public HTTPRequest(List<string> request)
  {
      _httpFields = new Dictionary<string, string>();
      string[] requestHeaderTokens = request.First().Split(' ');
      HTTPVersion = requestHeaderTokens[PROTOCOL_IN_HEADER_POSITION];
      Path = requestHeaderTokens[PATH_IN_HEADER_POSITION].Trim();
      if (Path[0] == PATH_DIRECTORY_SEPARATOR)
      {
          Path = Path.Substring(1);
      }
      string httpMethod = requestHeaderTokens[METHOD_IN_HEADER_POSITION];
      if (_httpMethods.ContainsKey(httpMethod))
      {
          HTTPMethod = _httpMethods[httpMethod];
      }
      else
      {
          HTTPMethod = HTTPMethods.Other;
      }
      request.Remove(request.First());
      foreach (string line in request)
      {
          int colonPosition = line.IndexOf(":");
          string fieldName = line.Substring(STRING_BEGINNING, colonPosition - 1).Trim();
          string fieldValue = line.Substring(colonPosition + 1).Trim();
          _httpFields[fieldName]=fieldValue;                
      }
 }
Example #10
0
        private string IsCountWithPeriodsDataValid(int windowPeriod, int numberOfSegmentsOfEachUnit, List <TModel> listOfModels)
        {
            string validationMessage = string.Empty;
            int    colLength         = listOfModels[0].CountWithPeriods.Count;

            foreach (var model in listOfModels)
            {
                if (model.CountWithPeriods.Count != colLength)
                {
                    validationMessage = "All models don't have the same data as columns in CountWithPeriods attribute";
                    break;
                }
            }

            if (!validationMessage.Equals(string.Empty))
            {
                return(validationMessage);
            }

            if (listOfModels?.First()?.CountWithPeriods.Count < (windowPeriod * numberOfSegmentsOfEachUnit) &&
                listOfModels?.First()?.CountWithPeriods.Count > ((windowPeriod + 1) * numberOfSegmentsOfEachUnit))
            {
                validationMessage = "Insufficient data as columns in the countWithPeriods attribute of the models";
            }

            return(validationMessage);
        }
Example #11
0
        public static int GetMinCut(DirectedGraph<int> graph)
        {
            var nodes = new List<MergedNode>();
            var edges = new List<Edge>();
            foreach (var node in graph.Keys)
            {
                nodes.Add(new MergedNode(node));
                edges.AddRange(graph.GetOutNodes(node).Select(x => new Edge(node, x)));
            }

            var random = new Random();

            while (nodes.Count > 2)
            {
                var edgeIndex = random.Next(edges.Count);
                var edge = edges[edgeIndex];
                var node1 = nodes.First(node => node.Nodes.Contains(edge.From));
                var node2 = nodes.First(node => node.Nodes.Contains(edge.To));
                edges.RemoveAt(edgeIndex);
                if (node1 == node2)
                {
                    continue;
                }

                nodes.Remove(node1);
                nodes.Remove(node2);
                nodes.Add(node1.Merge(node2));
            }

            return GetCrossingEdgesCount(nodes[0], nodes[1], graph);
        }
Example #12
0
        public List<IMergedLine> GetMergeResult(
            List<String> originalText, 
            List<IChangedLine> firstVariatChanges,
            List<IChangedLine> secondVariatChanges,
            string firstVariantName,
            string secondVariantName)
        {
            var result = new List<IMergedLine>();

            if (firstVariatChanges.Any(line => line.Status == LineStatus.FirstEmptyRow)
                && secondVariatChanges.Any(line => line.Status == LineStatus.FirstEmptyRow))
            {
                result.Add(Merge.Merge(
                    "",
                    firstVariatChanges.First(line => line.Status == LineStatus.FirstEmptyRow),
                    secondVariatChanges.First(line => line.Status == LineStatus.FirstEmptyRow),
                    firstVariantName,
                    secondVariantName));
            }

            for (int origTextIndex = 0; origTextIndex < originalText.Count; origTextIndex++)
            {
                result.Add(Merge.Merge(
                    originalText[origTextIndex],
                    firstVariatChanges.First(line => line.OriginalLineIndex == origTextIndex),
                    secondVariatChanges.First(line => line.OriginalLineIndex == origTextIndex),
                    firstVariantName,
                    secondVariantName));
            }

            return result;
        }
Example #13
0
 public SyncData(List<TransData> tables)
 {
     Tables = tables;
     MdaId = Tables.First().MdaId;
     EmployeeId = Tables.First().EmployeeID;
     State = (SyncState)Tables.First().state;
 }
Example #14
0
        private static List<int> Merge(List<int> left, List<int> right)
        {
            List<int> result = new List<int>();

            while(left.Count > 0 || right.Count>0)
            {
                if (left.Count > 0 && right.Count > 0)
                {
                    if (left.First() <= right.First())  //Comparing First two elements to see which is smaller
                    {
                        result.Add(left.First());
                        left.Remove(left.First());      //Rest of the list minus the first element
                    }
                    else
                    {
                        result.Add(right.First());
                        right.Remove(right.First());
                    }
                }
                else if(left.Count>0)
                {
                    result.Add(left.First());
                    left.Remove(left.First());
                }
                else if (right.Count > 0)
                {
                    result.Add(right.First());
                    right.Remove(right.First());
                }
            }
            return result;
        }
        public void Select_Finds_FirstToSatisfyAllConstraints()
        {
            var mockery = new MockRepository();
            var constraint1 = mockery.StrictMock<IResidentConstraint>();
            var constraint2 = mockery.StrictMock<IResidentConstraint>();
            var selector = new ResidentSelector();
            selector.Constraints.Clear();
            selector.Constraints.Add(constraint1);
            selector.Constraints.Add(constraint2);

            var residents = new List<Resident> { new Resident(), new Resident(), new Resident() };
            var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today);
            using (mockery.Record()) {
                SetupResult.For(constraint1.Assignable(residents.First(), shift)).Return(false);
                SetupResult.For(constraint2.Assignable(residents.First(), shift)).Return(true);

                SetupResult.For(constraint1.Assignable(residents.Skip(1).First(), shift)).Return(true);
                SetupResult.For(constraint2.Assignable(residents.Skip(1).First(), shift)).Return(false);

                SetupResult.For(constraint1.Assignable(residents.Skip(2).First(), shift)).Return(true);
                SetupResult.For(constraint2.Assignable(residents.Skip(2).First(), shift)).Return(true);
            }
            using (mockery.Playback()) {
                Assert.AreEqual(residents.Skip(2).First(), selector.Select(residents, shift));
            }
        }
Example #16
0
        public static PointCollection FindConvexPolygon(List<Point> points)
        {
            List<Point> top = new List<Point>();
            List<Point> bottom = new List<Point>();

            IEnumerable<Point> finalTop;
            IEnumerable<Point> finalBottom;

            points.Sort((x, y) => { return (int) (x.X - y.X); });

            double deltaX = points.Last().X - points.First().X;
            double deltaY = points.Last().Y - points.First().Y;
            double denominator = (Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));

            for (int i = 1; i < points.Count - 1; i++)
                if (MinimumDistanceBetweenPointAndLine2D(points.First(), points.Last(), points[i], deltaX, deltaY,
                                                         denominator))
                    bottom.Add(points[i]);
                else
                    top.Add(points[i]);

            top.Insert(0, points.First());
            top.Add(points.Last());
            bottom.Insert(0, points.First());
            bottom.Add(points.Last());

            finalTop = ConvexHullCore(top, true);
            finalBottom = ConvexHullCore(bottom, false);

            return new PointCollection(finalTop.Union(finalBottom.Reverse()));
        }
Example #17
0
    public void UpdateGrade(List<string> grade, string courseName)
    {
      cours course = new cours();
      try
      {
        using (var context = new BAProjectEntities())
        {
          course = context.courses.FirstOrDefault(x => x.name.Equals(courseName));

          foreach (var gradeDatabase in course.grades_database)
          {
            gradeDatabase.grade = grade.First();
            grade.Remove(grade.First());
          }
          context.SaveChanges();
        }
      }
      catch (Exception ex)
      {
        if (ex is EntityException || ex is NullReferenceException)
        {
          MessageBox.Show("Couldn't connect to the database. Please try again later.");
        }
        else
        {
          throw;
        }
      }
            Response.Redirect("~/ReportCard/LecturerView/" + course.course_id);
    }
        private List<IGeometry> GetGeometriesFromWays(IEnumerable<CompleteWay> ways)
        {
            var nodesGroups = new List<List<Node>>();
            var waysToGroup = new List<CompleteWay>(ways.Where(w => w.Nodes.Any()));
            while (waysToGroup.Any())
            {
                var wayToGroup = waysToGroup.FirstOrDefault(w =>
                    nodesGroups.Any(g => CanBeLinked(w.Nodes, g)));

                if (wayToGroup == null)
                {
                    nodesGroups.Add(new List<Node>(waysToGroup.First().Nodes));
                    waysToGroup.RemoveAt(0);
                    continue;
                }
                var currentNodes = new List<Node>(wayToGroup.Nodes);
                waysToGroup.Remove(wayToGroup);
                var group = nodesGroups.First(g => CanBeLinked(currentNodes, g));
                if (currentNodes.First().Id == group.First().Id || currentNodes.Last().Id == group.Last().Id)
                {
                    currentNodes.Reverse(); // direction of this way is incompatible with other ways.
                }
                if (currentNodes.First().Id == group.Last().Id)
                {
                    currentNodes.Remove(currentNodes.First());
                    group.AddRange(currentNodes);
                    continue;
                }
                currentNodes.Remove(currentNodes.Last());
                group.InsertRange(0, currentNodes);
            }
            return nodesGroups.Select(GetGeometryFromNodes).ToList();
        }
Example #19
0
 private static void PrintMostProfitableCategory(List<Order> allOrders, 
     List<Product> allProducts, List<Category> allCategories)
 {
     var mostProfitableCategory = allOrders
         .GroupBy(order => order.ProductID)
         .Select(grouping => new
         {
             categoryID = allProducts
                 .First(product => product.ID == grouping.Key)
                 .CategoryID,
             price = allProducts
                 .First(product => product.ID == grouping.Key)
                 .UnitPrice,
             quantity = grouping.Sum(order => order.Quantity)
         })
         .GroupBy(product => product.categoryID)
         .Select(grouping => new
         {
             categoryName = allCategories
                 .First(category => category.ID == grouping.Key).Name,
             totalQuantity = grouping
                 .Sum(groupingCategory => groupingCategory.quantity * groupingCategory.price)
         })
         .OrderByDescending(groupingCategory => groupingCategory.totalQuantity)
         .First();
     Console.WriteLine("{0}: {1}", mostProfitableCategory.categoryName, mostProfitableCategory.totalQuantity);
 }
Example #20
0
        private void CheckPeriod(List<Expression> result, string start, string end)
        {
            var nrOfComponents = 0;
            if (!String.IsNullOrWhiteSpace(start)) nrOfComponents++;
            if (!String.IsNullOrWhiteSpace(end)) nrOfComponents++;

            Assert.AreEqual(1, result.Count);
            Assert.IsInstanceOfType(result.First(), typeof(CompositeValue));
            var comp = result.First() as CompositeValue;
            Assert.AreEqual(nrOfComponents, comp.Components.Count());

            var currentComponent = 0;
            if (!String.IsNullOrWhiteSpace(start))
            {
                Assert.IsInstanceOfType(comp.Components[currentComponent], typeof(IndexValue));
                var ixValue = comp.Components[currentComponent] as IndexValue;
                Assert.AreEqual("start", ixValue.Name);
                Assert.AreEqual(1, ixValue.Values.Count());
                Assert.IsInstanceOfType(ixValue.Values[0], typeof(DateTimeValue));
                var dtValue = ixValue.Values[0] as DateTimeValue;
                Assert.AreEqual(new DateTimeValue(start).Value, dtValue.Value);
                currentComponent++;
            }

            if (!String.IsNullOrWhiteSpace(end))
            {
                Assert.IsInstanceOfType(comp.Components[currentComponent], typeof(IndexValue));
                var ixValue = comp.Components[currentComponent] as IndexValue;
                Assert.AreEqual("end", ixValue.Name);
                Assert.AreEqual(1, ixValue.Values.Count());
                Assert.IsInstanceOfType(ixValue.Values[0], typeof(DateTimeValue));
                var dtValue = ixValue.Values[0] as DateTimeValue;
                Assert.AreEqual(new DateTimeValue(end).Value, dtValue.Value);
            }
        }
Example #21
0
        public static TacticCard GetMovementCard()
        {
            var nodes = new List<Node> {
                new Node {X = 0, Y = 0},
                new Node {X = 0, Y = 1}
            };

            return new TacticCard {
                Id = 1,
                Name = "Movement",
                Nodes = nodes,
                StartNode = nodes.First(),
                Movements = new List<Movement> {
                    new Movement {
                        Start = nodes.First(node => node.Y == 0),
                        End = nodes.First(node => node.Y == 1)
                    }
                },
                Passes = new List<Movement> {
                    new Movement {
                        Start = nodes.First(node => node.Y == 0),
                        End = nodes.First(node => node.Y == 1)
                    }
                },
                Shot = nodes.Last()
            };
        }
Example #22
0
        private static int[] Merge(int[] left, int[] right)
        {
            List<int> output = new List<int>();
            List<int> l = new List<int>(left);
            List<int> r = new List<int>(right);

            while (l.Count() > 0 || r.Count() > 0)
            {
                if (l.Count() > 0 && r.Count() > 0)
                {
                    if (l.First<int>() <= r.First<int>())
                    {
                        output.Add(l.First<int>());
                        l.RemoveAt(0);
                    }
                    else
                    {
                        output.Add(r.First<int>());
                        r.RemoveAt(0);
                    }
                }
                else if (l.Count() > 0)
                {
                    output.Add(l.First<int>());
                    l.RemoveAt(0);
                }
                else if (r.Count() > 0)
                {
                    output.Add(r.First<int>());
                    r.RemoveAt(0);
                }
            }

            return output.ToArray();
        }
        public void GetRoadLimit()
        {
            // arrange
            var hwy = "036B";
            var dir = 2;
            decimal fromMeasure = 34.7m;
            decimal toMeasure = 57.494m;

            // act
            var data = new Massive.DynamicModel("DefaultConnection").Query("SELECT HWY, DIR, FROMMEASURE, TOMEASURE FROM RoadLimits ORDER BY HWY, DIR, FROMMEASURE, TOMEASURE");
            var roadLimits = new List<RoadLimit>();
            foreach (var d in data)
            {
                roadLimits.Add(new RoadLimit()
                {
                    HWY = d.HWY.ToString(),
                    DIR = int.Parse(d.DIR.ToString()),
                    FROMMEASURE = decimal.Parse(d.FROMMEASURE.ToString()),
                    TOMEASURE = decimal.Parse(d.TOMEASURE.ToString())
                });
            }
            roadLimits = roadLimits.Where(x => x.HWY == hwy && x.DIR == dir && x.FROMMEASURE >= fromMeasure && x.TOMEASURE <= toMeasure).ToList();
            //            Assert.Equal(dir, data.First().HWY);
            Assert.True(roadLimits.Count() == 1);
            Assert.Equal(roadLimits.First().FROMMEASURE, fromMeasure);
            Assert.Equal(roadLimits.First().TOMEASURE, toMeasure);
        }
Example #24
0
        public Route Solve(List<Point> points)
        {
            this.startPoint = points.First(p => p.Type == PointType.Start);
            this.endPoint = points.First(p => p.Type == PointType.End);

            // init route
            Route route = new Route();
            route.Points.Add(this.startPoint);

            // remaining points
            List<Point> unvisitedPoints = points.Where(p => p.Type == PointType.Waypoiny).ToList();

            // loop nodes
            Point nextPoint = this.startPoint;
            while(nextPoint != null)
            {
                nextPoint = GetNearPoint(nextPoint, unvisitedPoints);

                if(nextPoint != null)
                {
                    route.Points.Add(nextPoint);
                    unvisitedPoints.Remove(nextPoint);
                }
            }

            route.Points.Add(this.endPoint);
            route.Points = route.Points;
            //route.Result = String.Join(" - ", route.Points.Select(p => p.Name)) + " " + route.Cost.ToString("#.0");
            route.Result = "Cost: " + Convert.ToInt32(route.Cost).ToString();

            return route;
        }
Example #25
0
        public GeometryOperation(IEndpoint endpoint,
                                 List <Feature <T> > features,
                                 SpatialReference outputSpatialReference,
                                 string operation,
                                 Action beforeRequest = null, Action <string> afterRequest = null)
            : base((endpoint is AbsoluteEndpoint)
                ? (IEndpoint) new AbsoluteEndpoint(endpoint.RelativeUrl.Trim('/') + "/" + operation)
                : (IEndpoint) new ArcGISServerEndpoint(endpoint.RelativeUrl.Trim('/') + "/" + operation),
                   beforeRequest, afterRequest)
        {
            Features = features;
            if (features.Any())
            {
                Geometries = new GeometryCollection <T> {
                    Geometries = new List <T>(features.Select(f => f.Geometry))
                };

                if (Geometries.Geometries.First()?.SpatialReference == null && features?.First()?.Geometry?.SpatialReference != null)
                {
                    Geometries.Geometries.First().SpatialReference = new SpatialReference {
                        Wkid = features?.First()?.Geometry?.SpatialReference?.Wkid
                    }
                }
                ;
            }
            OutputSpatialReference = outputSpatialReference;
        }
Example #26
0
        public LogControl()
        {
            InitializeComponent();


            this.SuspendLayout();
            var levels = new Level[] { Level.Debug, Level.Info, Level.Warn, Level.Error, Level.Fatal };
            chkLevels = new List<CheckBox>(levels.Length);
            foreach (var level in levels)
            {
                var chkLevel = new CheckBox();
                chkLevel.Checked = level != Level.Debug;
                chkLevel.Text = level.ToString();
                chkLevel.Tag = level;
                chkLevel.CheckedChanged += new EventHandler(chkLevel_CheckedChanged);
                pnlFilter.Controls.Add(chkLevel);
                chkLevels.Add(chkLevel);
            }
            btnClean = new Button();
            btnClean.Margin = chkLevels.First().Margin;
            btnClean.Text = "clean";
            btnClean.Click += new EventHandler(btnClean_Click);
            pnlFilter.Controls.Add(btnClean);

            lblCount = new Label();
            lblCount.Margin = chkLevels.First().Margin;
            lblCount.Text = "0";
            pnlFilter.Controls.Add(lblCount);
            this.ResumeLayout(true);
        }
Example #27
0
        public void PreetyPrint()
        {
            var printList = new List<PrintNode>();
            var queue = new Queue<Node>();
            var parentNode = new PrintNode { val = Root.value, row = 1, childType = Child.NONE };
            queue.Enqueue(Root);
            printList.Add(parentNode);
            while (queue.Count > 0)
            {
                var cur = queue.Dequeue();
                if (cur.left != null)
                {
                    var leftChild = new PrintNode { val = cur.left.value, childType = Child.LEFT, parent = printList.First(x => x.val == cur.value) };
                    leftChild.row = leftChild.parent.row + 1;
                    queue.Enqueue(cur.left);
                    printList.Add(leftChild);
                }
                if (cur.right != null)
                {
                    var rightChild = new PrintNode { val = cur.right.value, childType = Child.RIGHT, parent = printList.First(x => x.val == cur.value) };
                    rightChild.row = rightChild.parent.row + 1;
                    queue.Enqueue(cur.right);
                    printList.Add(rightChild);
                }
            }
            var levelCount = printList.Max(x => x.row);
            int maxColumn = (int)Math.Pow(2, levelCount) - 1;
            int level = 1;
            int curColumn = 0;
            foreach (var node in printList)
            {
                if (node.row > level)
                {
                    Console.WriteLine();
                    ++level;
                    curColumn = 0;
                }
                if (level == 1)
                {
                    node.column = maxColumn / 2 + 1;
                }
                else
                {
                    int diff = (int)Math.Pow(2, levelCount - node.row);
                    if (node.childType == Child.LEFT)
                    {
                        diff = -diff;
                    }
                    node.column = node.parent.column + diff;
                }

                for (; curColumn < node.column-1; ++curColumn)
                {
                    Console.Write("  ");
                }
                Console.Write(string.Format("{0:00}",node.val));
                ++curColumn;
            }
            Console.WriteLine();
        }
 public static TransportRequisitionViewModel BindTransportRequisitionViewModel(TransportRequisition transportRequisition,List<WorkflowStatus> statuses,string datePrefrence,List<UserInfo> users  )
 {
     TransportRequisitionViewModel transportRequisitionViewModel = null;
     if (transportRequisition != null)
     {
         transportRequisitionViewModel = new TransportRequisitionViewModel();
         transportRequisitionViewModel.CertifiedBy =users.First(t=>t.UserProfileID==transportRequisition.CertifiedBy).FullName;
         transportRequisitionViewModel.CertifiedDate = transportRequisition.CertifiedDate;
         transportRequisitionViewModel.DateCertified = transportRequisition.CertifiedDate.ToCTSPreferedDateFormat(datePrefrence);
         //EthiopianDate.GregorianToEthiopian(transportRequisition.CertifiedDate);
         transportRequisitionViewModel.Remark = transportRequisition.Remark;
         transportRequisitionViewModel.RequestedBy = users.First(t => t.UserProfileID == transportRequisition.RequestedBy).FullName;
         transportRequisitionViewModel.RequestedDate = transportRequisition.RequestedDate;
         transportRequisitionViewModel.DateRequested = transportRequisition.RequestedDate.ToCTSPreferedDateFormat(datePrefrence);
         //EthiopianDate.GregorianToEthiopian( transportRequisition.RequestedDate);
         transportRequisitionViewModel.Status = statuses.First(t=>t.StatusID==transportRequisition.Status).Description;
         transportRequisitionViewModel.StatusID = transportRequisition.Status;
         transportRequisitionViewModel.TransportRequisitionID = transportRequisition.TransportRequisitionID;
         transportRequisitionViewModel.TransportRequisitionNo = transportRequisition.TransportRequisitionNo;
         transportRequisitionViewModel.Program = transportRequisition.Program.Name;
         transportRequisitionViewModel.Month =
             RequestHelper.MonthName(
                 transportRequisition.TransportRequisitionDetails.FirstOrDefault().ReliefRequisition.Month);
         transportRequisitionViewModel.Round =transportRequisition.TransportRequisitionDetails.FirstOrDefault().ReliefRequisition.Round;
         transportRequisitionViewModel.Date = DateTime.Now.ToCTSPreferedDateFormat(datePrefrence);
     }
     return transportRequisitionViewModel;
 }
Example #29
0
        public override void DataBind()
        {
            if (blogContext.Action == "SendBox")
            {
                List<Ncuhome.Blog.Core.MailServices.SendeBox> l = new List<Ncuhome.Blog.Core.MailServices.SendeBox>();
                foreach (SendeBox s in BMail.GetSendeBox(1,1000))
                {
                    if (s.MailAttri_ID == blogContext.ID)
                        l.Add(s);
                }
                Repeater1.DataSource = l;
                MsgReceiver.Text = l.First().Sender.ToString();
                MsgTitle.Text ="re:"+ l.First().Title;
                BMail.UpdateNewMaid(Convert.ToInt32( l.First().MailAttri_ID));
            }
            else
            {

                List<Ncuhome.Blog.Core.MailServices.InBox> l = new List<Ncuhome.Blog.Core.MailServices.InBox>();
                foreach (InBox s in BMail.GetInbox(1,1000))
                {
                    if (s.MailAttri_ID ==blogContext.ID)
                        l.Add(s);
                }
                Repeater1.DataSource =l;
                MsgReceiver.Text = l.First().Sender.ToString();
                MsgTitle.Text = "re:" + l.First().Title;
                BMail.UpdateNewMaid(Convert.ToInt32( l.First().MailAttri_ID));
            }
            Repeater1.DataBind();
            base.DataBind();
        }
Example #30
0
        static void Main(string[] args)
        {
            var players = new List<Player>();
            var shaker = new DiceShaker();

            for (var i = 0; i < 100; i++)
            {
                var player = Factory.CreatePlayer(shaker);
                System.Console.WriteLine(string.Format("Player {0}:\r\nThrowing Power: {1}\r\nTAS: {2}:\r\nTAM: {3}",
                    i,
                    player.ThrowPower.GetValue<double>(),
                    player.ThrowAccuracyShort.GetValue<double>(),
                    player.ThrowAccuracyMid.GetValue<double>()));
                players.Add(player);
            }

            var maxPotential = players.Select(w => w.GetPotential()).Max();
            var bestPlayer = players.First(w => w.GetPotential() == maxPotential);

            var maxMidAcc = players.Max(w => w.ThrowAccuracyMid.GetValue<double>());

            bestPlayer = players.First(w => w.ThrowAccuracyMid.GetValue<double>() == maxMidAcc);

            var maxShortAcc = players.Max(w => w.ThrowAccuracyShort.GetValue<double>());

            bestPlayer = players.First(w => w.ThrowAccuracyShort.GetValue<double>() == maxShortAcc);

            if (bestPlayer != null)
            {

            }
        }
        public void CheckRecurringTransactions_None_NewEntryForRecurring()
        {
            var repoSetup = new Mock<ITransactionRepository>();
            var resultList = new List<FinancialTransaction>();

            var testList = new List<FinancialTransaction>
            {
                new FinancialTransaction
                {
                    Id = 1,
                    Amount = 99,
                    ChargedAccountId = 2,
                    ChargedAccount = new Account {Id = 2},
                    Date = DateTime.Now.AddDays(-3),
                    ReccuringTransactionId = 3,
                    RecurringTransaction = new RecurringTransaction
                    {
                        Id = 3,
                        Recurrence = (int) TransactionRecurrence.Daily,
                        ChargedAccountId = 2,
                        ChargedAccount = new Account {Id = 2},
                        Amount = 95
                    },
                    IsCleared = true,
                    IsRecurring = true
                },
                new FinancialTransaction
                {
                    Id = 2,
                    Amount = 105,
                    Date = DateTime.Now.AddDays(-3),
                    ChargedAccountId = 2,
                    ChargedAccount = new Account {Id = 2},
                    ReccuringTransactionId = 4,
                    RecurringTransaction = new RecurringTransaction
                    {
                        Id = 4,
                        Recurrence = (int) TransactionRecurrence.Weekly,
                        ChargedAccountId = 2,
                        ChargedAccount = new Account {Id = 2},
                        Amount = 105
                    },
                    IsRecurring = true
                }
            };

            repoSetup.Setup(x => x.Save(It.IsAny<FinancialTransaction>()))
                .Callback((FinancialTransaction transaction) => resultList.Add(transaction));

            repoSetup.SetupGet(x => x.Data).Returns(new ObservableCollection<FinancialTransaction>(testList));

            repoSetup.Setup(x => x.LoadRecurringList(null)).Returns(testList);

            new RecurringTransactionManager(repoSetup.Object).CheckRecurringTransactions();

            resultList.Any().ShouldBeTrue();
            resultList.First().Amount.ShouldBe(95);
            resultList.First().ChargedAccountId.ShouldBe(2);
            resultList.First().ReccuringTransactionId.ShouldBe(3);
        }
        protected virtual int DamageCalculation(Dictionary<BodyPart, IWeapon> weaponSet, List<IAttribute> attributes)
        {
            //Will change
            int strbonusModifier = Convert.ToInt32(Math.Round(attributes.First(x => x.Type == AttributeType.Strength).Value * .25));
            int totalDmg = strbonusModifier;
            foreach (var key in weaponSet)
            {
                int critIndicator = new Random().Next(0, 101);
                if (critIndicator <= attributes.First(x => x.Type == AttributeType.CritChance).Value)
                {
                    //crit
                    totalDmg += Convert.ToInt32(Math.Round(key.Value.DamageOutput() * 1.5));
                }
                else
                    totalDmg += key.Value.DamageOutput();
            }

            //need to think about two handers
            if (weaponSet.Keys.Count > 1)
            {
                return Convert.ToInt32(totalDmg * .80);
            }
            else
            {
                return totalDmg;
            }
        }
Example #33
0
 private void AddDungeonRunIfNextMap(Guid currentGuid, MapType mapType)
 {
     if (_lastGuid != null && _dungeons.Any(x => x.GuidList.Contains(currentGuid) && x.GuidList.Contains((Guid)_lastGuid)) && mapType != MapType.CorruptedDungeon)
     {
         var dun = _dungeons?.First(x => x.GuidList.Contains(currentGuid));
         dun?.AddEndTime(DateTime.UtcNow);
     }
 }
Example #34
0
        public IMusic ParseUri(string uri)
        {
            //https://open.spotify.com/track/2fTdRdN73RgIgcUZN33dvt
            //https://open.spotify.com/album/2N367tN1eIXrHNVe86aVy4?si=A-1kS4F4Tfy2I_PYEDVhMA
            //https://open.spotify.com/artist/5cj0lLjcoR7YOSnhnX0Po5

            uri = NormalizeSpotifyUri(uri);

            string[] uriParts = uri.Split("/");

            if (uriParts.Contains("track"))
            {
                FullTrack sTrack = ConverterBot.Clients.SpotifyClient.Tracks.Get(uriParts.Last( )).Result;

                return(new Track(sTrack.Name,
                                 sTrack.Artists.First( ).Name,
                                 sTrack.Album.Name,
                                 0,
                                 sTrack.Id));
            }

            if (uriParts.Contains("album"))
            {
                string id;
                if (uriParts.Last( ).Contains("?"))
                {
                    id = uriParts.Last( ).Split("?").First( );
                }
                else
                {
                    id = uriParts.Last( );
                }

                FullAlbum sAlbum = ConverterBot.Clients.SpotifyClient.Albums.Get(id).Result;

                return(new Album(sAlbum.Name,
                                 sAlbum.Artists.First( ).Name,
                                 sAlbum.ReleaseDate,
                                 sAlbum.Id));
            }

            if (uriParts.Contains("artist"))
            {
                FullArtist         sArtist       = ConverterBot.Clients.SpotifyClient.Artists.Get(uriParts.Last( )).Result;
                List <SimpleAlbum>?sArtistAlbums = ConverterBot.Clients.SpotifyClient.Artists.GetAlbums(uriParts.Last( )).Result.Items;
                SimpleAlbum        sSampleAlbum  = sArtistAlbums?.First( );

                Album sampleAlbum = new Album(sSampleAlbum?.Name,
                                              sArtist.Name,
                                              sSampleAlbum?.ReleaseDate,
                                              sSampleAlbum?.Id);

                return(new Artist(sArtist.Name,
                                  sampleAlbum,
                                  null,
                                  sArtist.Id));
            }

            return(null);
        }
        async Task PerformSearch(CancellationToken token)
        {
            Searching = true;
            await Invoke(StateHasChanged);

            await Task.Delay(1);

            var options = GitterApi.GetNewOptions();

            options.Query = SearchText;
            options.Limit = 100;
            SearchResult  = new List <IChatMessage>();
            var messages = await GitterApi.SearchChatMessages(ChatRoom.Id, options);

            while ((messages?.Any() ?? false) && !token.IsCancellationRequested)
            {
                SearchResult?.AddRange(messages.OrderBy(m => m.Sent).Reverse());
                Console.WriteLine($"Got {messages.Count()} results. First is {SearchResult?.First().Id} Last is {SearchResult?.Last().Id} Token is {token.IsCancellationRequested}");
                await Invoke(StateHasChanged);

                await Task.Delay(1000);

                options.Skip += messages.Count();
                messages      = await GitterApi.SearchChatMessages(ChatRoom.Id, options);
            }

            Searching = false;
            await Invoke(StateHasChanged);

            await Task.Delay(1);
        }
        private static IEnumerable <SourceBlock> GetNaiveBlocks(IEnumerable <SourceLine> codeLines)
        {
            var codeBlocks = new List <SourceBlock>();
            List <SourceLine> currentBlock = null;

            foreach (var codeLine in codeLines)
            {
                if (codeLine.Code == currentBlock?.First().Code) // same block
                {
                    currentBlock.Add(codeLine);
                }
                else // new block
                {
                    if (currentBlock != null)
                    {
                        codeBlocks.Add(new SourceBlock(currentBlock));
                    }

                    currentBlock = new List <SourceLine> {
                        codeLine
                    };
                }
            }

            if (currentBlock != null)
            {
                codeBlocks.Add(new SourceBlock(currentBlock));
            }

            return(codeBlocks.ToList());
        }
Example #37
0
        private void CreateDatabaseOrModifyDatabase(List <VehicleDetails> vehicleList)
        {
            DeleteDatabase(FuelDB.Singleton.DBPath);
            FuelDB.Singleton.CreateTable <VehicleDetails>();
            FuelDB.Singleton.CreateTable <BillDetails>();

            //FuelDB.Singleton.CreateDatabase<Fuel>();

            var details = vehicleList?.First();

            vehicleList.RemoveAt(0);
            var billDetails = new BillDetails
            {
                AvailableLiters   = details.VID,
                BillCurrentNumber = details.DriverID_PK,
                BillPrefix        = details.RegNo,
                DeviceStatus      = details.DriverName
            };

            AppPreferences.SaveString(this, Utilities.DEVICESTATUS, billDetails.DeviceStatus);
            AppPreferences.SaveBool(this, Utilities.IsDownloaded, true);
            FuelDB.Singleton.InsertValues(vehicleList);
            btnDownloadData.Clickable = false;
            FuelDB.Singleton.InsertBillDetails(billDetails);
        }
Example #38
0
        public void ProcessResults_ForShowWelcomeMessage_HandlesSingleResult()
        {
            var wmReqProc = new WelcomeMessageRequestProcessor <WelcomeMessage>
            {
                BaseUrl = "https://api.twitter.com/1.1/",
                Type    = WelcomeMessageType.ShowMessage
            };

            List <WelcomeMessage> msgs = wmReqProc.ProcessResults(TestQuerySingleWelcomeMessageResponse);

            WelcomeMessage welcomeMsg = msgs?.First();

            Assert.IsNotNull(welcomeMsg);
            WelcomeMessageValue val = welcomeMsg.Value;

            Assert.IsNotNull(val);
            WelcomeMsg msg = val.WelcomeMessage;

            Assert.IsNotNull(msg);
            Assert.AreEqual("950134376347574276", msg.Id);
            Assert.AreEqual("1515364662621", msg.CreatedTimestamp);
            Assert.AreEqual("472356", msg.SourceAppId);
            Assert.AreEqual("New Welcome Message", msg.Name);
            WelcomeMessageData data = msg.MessageData;

            Assert.IsNotNull(data);
            Assert.AreEqual("Welcome!", data.Text);
            JObject app       = val.Apps;
            JObject appDetail = app.Value <JObject>("472356");

            Assert.AreEqual("472356", appDetail.Value <string>("id"));
            Assert.AreEqual("LINQ to Tweeter", appDetail.Value <string>("name"));
            Assert.AreEqual("https://github.com/JoeMayo/LinqToTwitter", appDetail.Value <string>("url"));
        }
Example #39
0
        private List <Entity> GetKillableMonsters()
        {
            // Called from different threads.
            try
            {
                if (bufferedNearestValidEntity?.IsAlive == false)
                {
                    LastKilledMonsterTime = DateTime.Now;
                }
                var validMonsters = new List <Entity>(GameController.EntityListWrapper.ValidEntitiesByType[EntityType.Monster]);
                validMonsters = validMonsters?.Where(x => IsEntityAKillableMonster(x, maxDistance: 1000))?.OrderBy(x => x.DistancePlayer)?.ToList();

                if (validMonsters != null && validMonsters.Count > 0)
                {
                    bufferedNearestValidEntity = validMonsters?.First();
                    return(validMonsters);
                }
                return(null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(null);
            }
        }
Example #40
0
        public void ProcessResults_ForListWelcomeMessages_HandlesMultipleResults()
        {
            var wmReqProc = new WelcomeMessageRequestProcessor <WelcomeMessage>
            {
                BaseUrl = "https://api.twitter.com/1.1/",
                Type    = WelcomeMessageType.ListMessages
            };

            List <WelcomeMessage> msgs = wmReqProc.ProcessResults(TestQueryMultipleWelcomeMessageResponses);

            WelcomeMessage welcomeMsg = msgs?.First();

            Assert.IsNotNull(welcomeMsg);
            WelcomeMessageValue val = welcomeMsg.Value;

            Assert.IsNotNull(val);
            List <WelcomeMsg> msgList = val.WelcomeMessages;
            WelcomeMsg        msg     = msgList.FirstOrDefault();

            Assert.IsNotNull(msg);
            Assert.AreEqual("New Welcome Message", msg.Name);
            WelcomeMessageData data = msg.MessageData;

            Assert.IsNotNull(data);
            Assert.AreEqual("Welcome!", data.Text);
        }
Example #41
0
        public async Task <Experiencia> GetExperiencia(string IdExperiencia)
        {
            string             sql    = "SELECT * FROM dbo.Experiencia WHERE IdExperiencia = '" + IdExperiencia + "'";
            List <Experiencia> result = await _dataAccess.LoadData <Experiencia, dynamic>(sql, new { });

            return(result?.First());
        }
Example #42
0
        public async Task <IEnumerable <GithubRepository> > GetAllReposAsync(string organization, int resultsPerPage)
        {
            string cacheKey       = $"repos|{organization}|{resultsPerPage}";
            var    cachedResponse = _cache.Get <List <OrganizationRepository> >(cacheKey);

            if (cachedResponse != null)
            {
                return(cachedResponse);
            }

            var results      = new List <OrganizationRepository>();
            var parsedHeader = new LinkHeader();
            var url          = $"{_remoteServiceBaseUrl}/orgs/{organization}/repos?page=1&per_page={resultsPerPage}";

            do
            {
                var response = await _httpClient.GetAsync(url);

                var linkHeader = new List <string>().AsEnumerable();
                response.Headers.TryGetValues("Link", out linkHeader);
                parsedHeader = linkHeader?.First().FromHeader();

                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();

                    results.AddRange(JsonConvert.DeserializeObject <List <OrganizationRepository> >(data));
                    url = parsedHeader?.NextLink;
                }
            } while (parsedHeader?.NextLink != null);

            _cache.Set(cacheKey, results, DateTimeOffset.Now.AddHours(1));

            return(results);
        }
        public IList <ControlResult> Evaluate(IList <ResourceControlSet> resourceControlSets, List <ResourceModel> resources)
        {
            var featureName = resources?.First().FeatureName;
            var controlSet  = resourceControlSets?.FirstOrDefault(x => x.FeatureName.Equals(featureName, StringComparison.OrdinalIgnoreCase));
            var results     = new List <ControlResult>();

            foreach (var control in controlSet.Controls)
            {
                List <string> resourcePathList = new List <string>();
                ControlResult controlResult    = null;
                foreach (var resource in resources)
                {
                    controlResult = _controlEvaluator.Evaluate(control, resource.Resource);
                    resourcePathList.Add(controlResult.ResourceDataMarker.JsonPath);
                    if (!controlResult.IsTokenNotFound)
                    {
                        break;
                    }
                }
                if (controlResult != null)
                {
                    if (controlResult.IsTokenNotFound)
                    {
                        controlResult.ResourceDataMarker.JsonPath = resourcePathList.ToArray().ToSingleString(" , ");
                    }
                    results.Add(controlResult);
                }
            }
            foreach (var resource in resources)
            {
                EvaluateNestedResources(controlSet, resource.Resource, results);
            }

            return(results);
        }
Example #44
0
        public void CreateDatabaseOrModifyDatabase(List <VehicleDetails> vehicleList)
        {
            DeleteDatabase(FuelDB.Singleton.DBPath);
            FuelDB.Singleton.CreateTable <VehicleDetails>();
            FuelDB.Singleton.CreateTable <BillDetails>();

            var details = vehicleList?.First();

            vehicleList.RemoveAt(0);
            var billDetails = new BillDetails
            {
                AvailableLiters   = details.VID,
                BillCurrentNumber = details.DriverID_PK,
                BillPrefix        = details.RegNo,
                DeviceStatus      = details.DriverName
            };

            AppPreferences.SaveString(this, Utilities.DEVICESTATUS, billDetails.DeviceStatus);
            AppPreferences.SaveBool(this, Utilities.IsDownloaded, true);
            FuelDB.Singleton.InsertValues(vehicleList);
            btnDownloadData.Clickable = false;
            FuelDB.Singleton.InsertBillDetails(billDetails);

            RunOnUiThread(() =>
            {
                loader.Visibility = Android.Views.ViewStates.Gone;
                mainHolder.Alpha  = 1f;
                Window.ClearFlags(Android.Views.WindowManagerFlags.NotTouchable);
                Toast.MakeText(this, "success..", ToastLength.Short).Show();
                btnDownloadData.Clickable = false;
                AppPreferences.SaveBool(this, Utilities.IsDownloaded, true);
            });
            ExceptionLog.LogDetails(this, "Database created successfully");
        }
Example #45
0
 private Port GetPortByNumber(PhoneNumber number)
 {
     if (number == null)
     {
         throw new NullReferenceException();
     }
     return(_portCollection?.First(port => port.Terminal.Number == number));
 }
Example #46
0
        private bool IsMemeberInGroup(List <GroupMemberOutput> memebers, Guid employeeId)
        {
            if (memebers?.Count == 0)
            {
                return(false);
            }
            var u = memebers?.First((m) => employeeId.Equals(m?.EmployeeId));

            return(u != null);
        }
Example #47
0
        public void DeleteSelectedItem()
        {
            if (SelectedItem == null)
            {
                return;
            }

            _items.Remove(SelectedItem);
            SelectedItem = _items?.First();
            OnPropertyChanged(nameof(Items));
        }
Example #48
0
        public bool TryGetRegistration(out IComponentRegistration registration)
        {
            RequiresInitialization();

            registration = _defaultImplementation ?? (_defaultImplementation =
                                                          _defaultImplementations.LastOrDefault() ??
                                                          _sourceImplementations?.First() ??
                                                          _preserveDefaultImplementations?.First());

            return(registration != null);
        }
Example #49
0
        public ComboBoxViewModel(IParent parent, List <ComboBoxItem <T> > values, string caption, TryParse tryParse) :
            base(parent, caption, tryParse)
        {
            Values        = values;
            SelectedValue = Values?.First();

            if (tryParse != null)
            {
                OtherCaption = new OtherInputViewModel <T>(this, tryParse);
                Values?.Add(Other);
            }
        }
Example #50
0
        private static void SaveChara(ChaFile chaFile, Action <string> action)
        {
            var fullPath = lastFileList?.First(x => x.FileName == chaFile.charaFileName.Remove(chaFile.charaFileName.Length - 4)).FullPath;

            lastFileList = null;

            if (!string.IsNullOrEmpty(fullPath))
            {
                action(fullPath);
                SaveXml();
            }
        }
Example #51
0
        /// <summary>
        /// Gerar sequência de numereção
        /// </summary>
        /// <param name="tableId">Chave da tabela</param>
        /// <param name="field">Nome do campo</param>
        /// <returns>Sequência gerada</returns>
        public int?GerarSequencia(int tableId, string field)
        {
            IList <AutomaticNumbering> autNumering = new List <AutomaticNumbering>();

            var sql = "Update AutomaticNumbering Set NextNumber = NextNumber + 1 " +
                      "Where DbTableId = @p0 and FieldName = @p1 " +
                      "Select * From AutomaticNumbering " +
                      "Where DbTableId = @p0 and FieldName = @p1 ";

            autNumering = _epr.SqlQuery(sql, tableId, field);

            return(autNumering.Any() ? autNumering?.First()?.NextNumber : null);
        }
Example #52
0
        public void PokeAttribute()
        {
            const string query = "//class[1]/@AccessModifier";
            const string value = "<Test>Testing</Test>";

            XmlDocument xmlDocument = ExecuteXmlPoke(query: query, value: value);

            List <XmlAttribute> nodes = xmlDocument.SelectNodes(query)?.Cast <XmlAttribute>().ToList();

            Assert.True(nodes?.Count == 1, $"There should be 1 <class /> element with an AccessModifier attribute {Environment.NewLine}{xmlDocument.OuterXml}");

            Assert.Equal(value, nodes?.First().Value);
        }
Example #53
0
 private static void Test()
 {
     try
     {
         List <int> items = new List <int>();
         var        a     = items?.FirstOrDefault();
         var        b     = items?.First();
     }
     catch (Exception ex)
     {
         System.Console.WriteLine(ex.Message);
     }
 }
Example #54
0
 protected override FetchObservables CreateObservables(
     ISinceParameters since = null,
     List <IUser> entity    = null)
 => new FetchObservables(
     since ?? new SinceParameters(null),
     Observable.Return(new List <IWorkspace>()),
     Observable.Return(new List <IWorkspaceFeatureCollection>()),
     Observable.Return(entity?.First()),
     Observable.Return(new List <IClient>()),
     Observable.Return(new List <IProject>()),
     Observable.Return(new List <ITimeEntry>()),
     Observable.Return(new List <ITag>()),
     Observable.Return(new List <ITask>()),
     Observable.Return(Substitute.For <IPreferences>()));
Example #55
0
 protected PropertyType GetPreferredPropertyType(List <PropertyType> types)
 {
     if (types.Count == 2 && (types.Except(new List <PropertyType> {
         PropertyType.Bytes, PropertyType.UShortArray
     })?.Any() ?? true))
     {
         return(PropertyType.UShortArray);
     }
     else if (types.Count == 2 && (types.Except(new List <PropertyType> {
         PropertyType.UShortArray, PropertyType.LongArray
     })?.Any() ?? true))
     {
         return(PropertyType.LongArray);
     }
     return(types?.First() ?? PropertyType.Undefined);
 }
Example #56
0
        private void poofCrop(string soundCue, bool big)
        {
            if (!Context.IsMainPlayer)
            {
                return;
            }
            float   radius = 32f * (cropTile.giantCrop ? 3f : 1f);
            Vector2 center = cropPosition +
                             new Vector2(-radius + (cropTile.giantCrop ? 64f : 0f), -radius);
            int   count = (big ? 12 : 3) * (cropTile.giantCrop ? 6 : 1);
            Color color = Color.Lerp(beasts?.First()?.primaryColor ?? Color.White,
                                     Color.Orange, big ? 0f : 0.5f);

            Utilities.MagicPoof(location, center, radius, count,
                                color, soundCue);
        }
Example #57
0
        public void PokeChildren()
        {
            const string query = "//class/.";
            const string value = "<Test>Testing</Test>";

            XmlDocument xmlDocument = ExecuteXmlPoke(query: query, value: value);

            List <XmlElement> nodes = xmlDocument.SelectNodes(query)?.Cast <XmlElement>().ToList();

            Assert.True(nodes?.Count == 1, $"There should be 1 <class /> element {Environment.NewLine}{xmlDocument.OuterXml}");

            var testNodes = nodes?.First().ChildNodes.Cast <XmlElement>().ToList();

            Assert.True(testNodes?.Count == 1, $"There should be 1 <class /> element with one child Test element {Environment.NewLine}{xmlDocument.OuterXml}");

            Assert.Equal("Testing", testNodes?.First().InnerText);
        }
Example #58
0
        private void RTC_NE_Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            UICore.NoteBoxSize     = this.Size;
            UICore.NoteBoxPosition = this.Location;

            string cleanText = string.Join("\n", tbNote.Lines.Select(it => it.Trim()));

            if (cleanText == "[DIFFERENT]")
            {
                return;
            }

            var oldText = note.Note;

            if (String.IsNullOrEmpty(cleanText))
            {
                note.Note = String.Empty;
                if (cells != null)
                {
                    foreach (DataGridViewCell cell in cells)
                    {
                        cell.Value = String.Empty;
                    }
                }
            }
            else
            {
                note.Note = cleanText;
                if (cells != null)
                {
                    foreach (DataGridViewCell cell in cells)
                    {
                        cell.Value = "📝";
                    }
                }
            }

            //If our cell comes from the GH's dgv and the text changed, prompt unsavededits
            if (oldText != cleanText && cells?.First()
                ?.DataGridView == S.GET <RTC_StockpileManager_Form>()
                .dgvStockpile)
            {
                S.GET <RTC_StockpileManager_Form>().UnsavedEdits = true;
            }
        }
Example #59
0
        private void setupPageLayout()
        {
            List <PageLayout> found = new List <PageLayout>();

            this.FindChildren <PageLayout>(found, Window.Current.Content);

            foreach (var pl in found)
            {
                var sp = (SketchPage)pl.DataContext;

                if (sp.SelectedLayer != null)
                {
                    List <PageContent> foundPCs = new List <PageContent>();
                    pl.FindChildren(foundPCs, pl);
                    _foundSelectedPageContent = foundPCs?.First();
                }
            }
        }
Example #60
0
        /// <summary>
        /// Chooses and spawns a drop based on player progression and random chance.
        /// </summary>
        protected virtual void GenerateDrop()
        {
            if (settings.chanceToDropItem >= Random.value)
            {
                return;
            }
            var availableItems = itemsToDrop.FindAll(itemSettings =>
                                                     GameMaster.Instance.PlayerStats.Level >=
                                                     itemSettings.minimumPlayerLevelToSpawn);
            var amountOfCoins =
                Mathf.RoundToInt(Random.Range(2,
                                              Mathf.Lerp(25, maxAmountOfCoinsToDrop,
                                                         Mathf.InverseLerp(0, 30,
                                                                           GameMaster.Instance.PlayerStats.Level))) *
                                 GameMaster.Instance.GameDifficultyReversed);

            if (availableItems.Count < 1)
            {
                FindObjectOfType <PlayerController>()
                .AddCoins(amountOfCoins);
                return;
            }


            var rng           = Random.value;
            var possibleItems = availableItems.FindAll(itemSettings => itemSettings.itemRarity >= rng);

            possibleItems = new List <ItemSettings>(possibleItems.OrderBy(x => x.itemRarity));
            var selectedItem = rng >= 0.5f ? possibleItems?.First() : possibleItems[Random.Range(0, possibleItems.Count)];

            if (availableItems.Count < 1)
            {
                FindObjectOfType <PlayerController>()
                .AddCoins(amountOfCoins);
            }

            if (selectedItem == null)
            {
                return;
            }
            Instantiate(selectedItem.itemPrefab, transform.position, Quaternion.identity).GetComponent <ItemDrop>()
            .SetItemBasedOnSettings(selectedItem);
        }