public static void AddToMenu(Menu menu,
            string uniqueId,
            HealthCheckType checkType,
            HealthValueType valueType,
            string prefix = null,
            int value = 30,
            int minValue = 0,
            int maxValue = 100)
        {
            try
            {
                if (Menues.ContainsKey(uniqueId))
                {
                    throw new ArgumentException(
                        string.Format("HealthHealthger: UniqueID \"{0}\" already exist.", uniqueId));
                }

                menu.AddItem(
                    new MenuItem(
                        menu.Name + ".health-" + uniqueId,
                        (!string.IsNullOrEmpty(prefix) ? prefix + " " : string.Empty) +
                        (checkType == HealthCheckType.Minimum ? "Min. Health" : "Max. Health") +
                        (valueType == HealthValueType.Percent ? " %" : string.Empty)).SetValue(
                            new Slider(value, minValue, maxValue)));

                Menues[uniqueId] = new Tuple<Menu, HealthCheckType, HealthValueType>(menu, checkType, valueType);
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
        }
Ejemplo n.º 2
0
 public void DoubleMaxOnTwoTuple()
 {
     var sut = new Tuple<double, double>(1, 2);
       double expected = sut.AsEnumerable().Cast<double>().Max();
       double actual = sut.Max(x => (double) x);
       Assert.AreEqual(expected, actual);
 }
        public Task TestGetSession()
        {
            var response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted,
              new Dictionary<string, object>() {
            { "__type", "Object" },
            { "className", "Session" },
            { "sessionToken", "S0m3Se551on" },
            { "restricted", true }
              });
              var mockRunner = CreateMockRunner(response);

              var controller = new ParseSessionController(mockRunner.Object);
              return controller.GetSessionAsync("S0m3Se551on", CancellationToken.None).ContinueWith(t => {
            Assert.False(t.IsFaulted);
            Assert.False(t.IsCanceled);
            mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/sessions/me"),
              It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
              It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(),
              It.IsAny<CancellationToken>()), Times.Exactly(1));

            var session = t.Result;
            Assert.AreEqual(2, session.Count());
            Assert.True((bool)session["restricted"]);
            Assert.AreEqual("S0m3Se551on", session["sessionToken"]);
              });
        }
Ejemplo n.º 4
0
        private void ProcessPublicBags(Random rand, Tuple<Player, int>[] dat)
        {
            var lootCount = PublicBag.BaseLootCount + PublicBag.PersonMultiplier*dat.Length;
            if (lootCount < PublicBag.MinLootCount) lootCount = PublicBag.MinLootCount;
            if (lootCount > PublicBag.MaxLootCount) lootCount = PublicBag.MaxLootCount;

            var loots = new HashSet<Item>();
            var pots = new List<Item>();
            for (var i = 0;
                i < lootCount ||
                (loots.Count < PublicBag.MinLootCount &&
                 pots.Count < PublicBag.MinLootCount);
                i++)
            {
                var loot = PublicBag.GetRandomLoot(rand);
                if (loot != null)
                {
                    if (loot.Potion)
                        pots.Add(loot);
                    else
                        loots.Add(loot);
                }
            }
            ShowBags(rand, loots.Concat(pots), null);
        }
Ejemplo n.º 5
0
 public void IntegerAverageOnTwoTuple()
 {
     var sut = new Tuple<int, int>(1, 2);
       double expected = sut.AsEnumerable().Cast<int>().Average();
       double actual = sut.Average(x => (int) x);
       Assert.AreEqual(expected, actual);
 }
Ejemplo n.º 6
0
        private static void InsertSeparator(Tuple<ICommandItem, Menu> previous, Tuple<ICommandItem, Menu> current)
        {
            // Get lineage of each
            IMenu[] previousLineage = previous.Item2.Lineage().Reverse<IMenu>().ToArray<IMenu>();
            IMenu[] currentLineage = current.Item2.Lineage().Reverse<IMenu>().ToArray<IMenu>();

            // Find lowest common ancestor
            // (Assumes common ancestor exists)
            int minLength = Math.Min(previousLineage.Length, currentLineage.Length);

            IMenuItem insertBefore = null;
            IList<IMenuItem> collection = null;
        
            for (int i = 0; i < minLength; i++)
            {
                if (previousLineage[i] != currentLineage[i])
                {
                    insertBefore = currentLineage[i];
                    collection = ((Menu)currentLineage[i - 1]).ChildCollection;
                }
            }

            if (insertBefore == null)
            {
                insertBefore = minLength < currentLineage.Length ? currentLineage[minLength] as IMenuItem
                    : current.Item1;
                collection = ((Menu)currentLineage[minLength - 1]).ChildCollection;
            }

            int idx = collection.IndexOf(insertBefore);
            System.Diagnostics.Debug.Assert(idx >= 0);
            collection.Insert(idx, new Separator());
        }
Ejemplo n.º 7
0
        public static int Main(string[] args)
        {
            List<string> pargs = ndclTools.ParamForm(args);
            if (pargs.FindParam("-h") || pargs.FindParam("--help"))
            {
                outputHelp();
                return 0;
            }
            int timeout;
            if (!getTimeout(pargs, out timeout))
                return 1;

            watch = new FileSystemWatcher();
            if(!getPath(pargs, watch))
                return 1;

            if (pargs.FindParam("-d"))
                watch.Deleted += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-c"))
                watch.Changed += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-C"))
                watch.Created += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-r"))
                watch.Renamed += new RenamedEventHandler(handler);
            watch.IncludeSubdirectories = pargs.FindParam("-s");

            last = new Tuple<string, DateTime>("", DateTime.Now);

            watch.EnableRaisingEvents = true;
            if (timeout == -1)
                while (Console.Read() != 'q') ;
            else
                System.Threading.Thread.Sleep(timeout);
            return 0;
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Tuple<string, int>[] tuples = new Tuple<string, int>[] {
                new Tuple<string, int>("a", 3),
                new Tuple<string, int>("b", 2),
                new Tuple<string, int>("b", 5) };

            MapReduce<string, int> letters = new MapReduce<string, int>(tuples);
            IEnumerable<Tuple<string, int>> newmap;

            letters.Map<string, int>((input) =>
                {
                    return new Tuple<string, int>[] { new Tuple<string, int>(input.Item1, input.Item2 * input.Item2) };
                }, out newmap);

            IEnumerable<Tuple<string, int>> reduction = letters.Reduce<string, int>(newmap, (key, values) =>
                {
                    int total = 0;
                    foreach (var item in values)
                    {
                        total += item;
                    }
                    return total;
                });

            foreach (var item in reduction)
            {
                Console.WriteLine("{0} = {1}", item.Item1, item.Item2);
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 9
0
        static void Main()
        {
            rows = int.Parse(Console.ReadLine());
            cols = int.Parse(Console.ReadLine());
            int startRow = int.Parse(Console.ReadLine());
            int startCol = int.Parse(Console.ReadLine());

            matrix = new int[rows, cols];
            matrix[startRow, startCol] = 1;
            var pointValue = new Dictionary<Tuple<int, int>, int>();
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    var point = new Tuple<int, int>(row, col);
                    int value = matrix[row, col];
                    pointValue.Add(point, value);
                }
            }

            Console.WriteLine("Output:");
            var numbersOfMiddleColumn = VisitAllCells(pointValue, startRow, startCol);
            foreach (var number in numbersOfMiddleColumn)
            {
                Console.WriteLine(number);
            }

            //PrintMatrix();
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();
            Tuple<uint, BigInteger> max = new Tuple<uint, BigInteger>(0, 0);
            for (uint i = 2; i <= 1000; i++)
            {
                if ((uint)Math.Sqrt(i) != Math.Sqrt(i))
                {
                    BigInteger xSolution = getMinimumSolution((int)i);
                    if (xSolution > max.Item2)
                    {
                        max = new Tuple<uint, BigInteger>(i, xSolution);
                    }
                  //  Console.WriteLine(i + " => " + xSolution);
                }
                
            }

            Console.WriteLine("Answer = " + max.Item1 + " => " + max.Item2);
            Console.WriteLine("DONE in " + sw.ElapsedMilliseconds + " s" );
                Console.ReadKey();
            

         

        }
Ejemplo n.º 11
0
 public override void addOpcode()
 {
     base.addOpcode();
     Tuple<ParameterType, ParameterType> tuple =
         new Tuple<ParameterType, ParameterType>(_param1.GetType(), _param2.GetType());
     _instruction += (opcodes[tuple]);
 }
Ejemplo n.º 12
0
        private static bool AddExtension( XElement extensions, Func<string, bool> resolveOption, Tuple<string, string, Func<XElement>> mapping )
        {
            Contract.Requires( extensions != null );
            Contract.Requires( resolveOption != null );
            Contract.Requires( mapping != null );

            var option = mapping.Item1;

            // the option is not enabled
            if ( !resolveOption( option ) )
                return false;

            var category = mapping.Item2;

            // the extension is already configured
            if ( extensions.Elements( ExtensionName ).Any( e => ( (string) e.Attribute( "Category" ) ) == category ) )
                return false;

            // create and add extension
            var factory = mapping.Item3;
            var extension = factory();

            extensions.Add( extension );
            return true;
        }
		/// <summary>
		/// Serializes the page parameter.
		/// </summary>
		public override object SerializeParameter(object parameter)
		{
			if (parameter.IsNull())
			{
				return null;
			}
			var parameterString = parameter as string;
			if (parameterString.IsNotNull())
			{
				return parameterString;
			}

			// Check for last object
			var last = this.lastObject;
			if (last.Item1 == parameter)
			{
				return last.Item2;
			}

			// Serialize object to json
			var sb = new StringBuilder();
			sb.Append((char)9);
			sb.Append(parameter.GetType().AssemblyQualifiedName);
			sb.Append((char)9);
			string data = JsonConvert.SerializeObject(parameter);
			sb.Append(data);
			parameterString = sb.ToString();

			// Save last object
			this.lastObject = new Tuple<object, string>(parameter, parameterString);

			return parameterString;
		}
 public ItemsWithConflictingHighestScoreException(Tuple<IValueProvider, IProbe>[] itemsWithConflictingScore, int highestScore)
     : base(string.Format(
         "items: {0} with conflicting highest score of {1} exists, cannot determine default", string.Concat(itemsWithConflictingScore.Select(x=>x.Item1.ToString())), highestScore))
 {
     ItemsWithConflictingScore = itemsWithConflictingScore;
     HighestScore = highestScore;
 }
Ejemplo n.º 15
0
 public Tuple<TokenType, string> Next()
 {
     EnsureToken();
     var cur = mCurrent;
     mCurrent = null;
     return cur;
 }
        public override void Update(object sender, Tuple<Sale, SaleState> item)
        {
            using (SalesDBEntities context = new SalesDBEntities())
            {
                Product product = context.Products
                    .Where(p => p.ProductID == item.Item1.ProductID)
                    .SingleOrDefault<Product>();

                switch (item.Item2)
                {
                    case SaleState.SALE_ADD:
                        product.TotalSalesAmount += item.Item1.Quantity;
                        break;
                    case SaleState.SALE_UPDATE:
                        product.TotalSalesAmount = item.Item1.Quantity;
                        break;
                    case SaleState.SALE_DELETE:
                        product.TotalSalesAmount -= item.Item1.Quantity;
                        break;
                    default:
                        break;
                }   
                context.SaveChanges();
            }
        }
Ejemplo n.º 17
0
 public void AddSystemCallsAddToGame()
 {
     var result = new Tuple<string, IGame>(null, null);
     var system = new MockSystem((sys, action, game) => result = new Tuple<string, IGame>(action, (IGame) game));
     _game.AddSystem(system, 0);
     Assert.AreEqual(new Tuple<string, IGame>("added", _game), result);
 }
Ejemplo n.º 18
0
        //
        // GET: /Home/
        public ActionResult Index(string sortOrder, int? page)
        {
            ViewBag.DateSortParm = string.IsNullOrEmpty(sortOrder) ? "date_desc" : "";
            ViewBag.CostSortParm = sortOrder == "Cost" ? "cost_desc" : "Cost";

            var products = WebApiHelper.GetProductsFromServer("api/product/all", Method.GET);

            switch (sortOrder)
            {
                case "date_desc":
                    products = products.OrderBy(s => s.Id).ToList();
                    break;
                case "Cost":
                    products = products.OrderBy(s => s.Price).ToList();
                    break;
                case "cost_desc":
                    products = products.OrderByDescending(s => s.Price).ToList();
                    break;
                default:
                    products = products.OrderByDescending(s => s.Id).ToList();
                    break;
            }

            int pageSize = 10;
            int pageNumber = (page ?? 1);

            IPagedList<DataTransferLayer.Products.Product> pl = products.ToPagedList(pageNumber, pageSize);

            var a = new Tuple<IPagedList<DataTransferLayer.Products.Product>, string>(pl, "");

            return View(a);
        }
Ejemplo n.º 19
0
        private void RunSelected_Click(object sender, RoutedEventArgs e)
        {
            int nbCases = 0;
            foreach (UnitTestSuite suite in Suites)
            {
                foreach (UnitTestCase c in suite.Cases)
                {
                    if (c.Selected) nbCases++;
                }
            }
            if (nbCases == 0) return;

            PrepareRun(nbCases);

            var tup = new Tuple<IEnumerable<UnitTestSuite>, bool?>(Suites, Verbose.IsChecked);
            var t = Task.Factory.StartNew(async (object parameters) =>
            {
                var p = parameters as Tuple<IEnumerable<UnitTestSuite>, bool?>;
                IEnumerable<UnitTestSuite> suites = p.Item1;
                bool verbose = p.Item2 != null ? (bool)p.Item2 : false;
                foreach (UnitTestSuite suite in suites)
                {
                    foreach (UnitTestCase c in suite.Cases)
                    {
                        if (c.Selected)
                        {
                            await RunUnitTestCase(c, verbose);
                        }
                    }
                }
            }, tup);
        }
 public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken,
     string accessTokenSecret)
 {
     _tokens.Remove(requestToken);
     _tokens[accessToken] = new Tuple<string, TokenType>(accessTokenSecret, TokenType.AccessToken);
     _tokenRepository.Save(new Token(accessToken, accessTokenSecret));
 }
Ejemplo n.º 21
0
 public static List<Tuple<bool, string>> GetMessageTypes()
 {
     List<Tuple<bool, string>> ret = new List<Tuple<bool, string>>();
     XmlDocument doc = OpenXMLFile();
     XmlNodeList nodeList = doc.GetElementsByTagName("type");
     foreach (XmlNode node in nodeList)
     {
         bool multiLine = false;
         string messageType = string.Empty;
         for(int i = 0; i < node.ChildNodes.Count;i++)
         {
             XmlNode subNode = node.ChildNodes.Item(i);
             if (subNode.Name == "name")
             {
                 messageType = subNode.InnerText;
             }
             if (subNode.Name == "multiline")
             {
                 bool.TryParse(subNode.InnerText, out multiLine);
             }
         }
         Tuple<bool, string> tuple = new Tuple<bool, string>(multiLine, messageType);
         ret.Add(tuple);
     }
     return (ret);
 }
        public string AddProduct(string name, double price, string producer)
        {
            Tuple<string, double, string> item = new Tuple<string, double, string>(name, price, producer);

            if (!names.ContainsKey(name))
            {
                names.Add(name, item);
            }
            else
            {
                names[name].Add(item);
            }

            if (!prices.ContainsKey(price))
            {
                prices.Add(price, item);
            }
            else
            {
                prices[price].Add(item);
            }

            if (!producers.ContainsKey(producer))
            {
                producers.Add(producer, item);
            }
            else
            {
                producers[producer].Add(item);
            }

            return "Product added";
        }
Ejemplo n.º 23
0
        public Dictionary<Tuple<int, string>, Tuple<string, string>> GetRatesData()
        {
            int count = 0;

            XmlNodeList nodeList = doc.DocumentElement.ChildNodes;

            foreach (XmlNode node in nodeList)
            {
                if (node.Name == "Cube")
                {
                    foreach (XmlNode node2 in node.ChildNodes)
                    {

                        foreach (XmlNode node3 in node2.ChildNodes)
                        {
                            count++;
                            var tuple = new Tuple<string, string>(node3.Attributes[0].Value, node3.Attributes[1].Value);
                            var tuple2 = new Tuple<int, string>(count, node2.Attributes[0].Value);
                            currencies.Add(tuple2, tuple);
                        }
                    }
                }
            }
            return currencies;

            //foreach(KeyValuePair<Tuple<int, string>, Tuple<string, string>> entry in currencies)
            //{
            //    Console.WriteLine(entry.Key.Item1 + " " + entry.Key.Item2 + " " + entry.Value.Item1 + " " + entry.Value.Item2);
            //}
        }
Ejemplo n.º 24
0
        public void Draw(SpriteBatch sbatch)
        {
            for (int i = 0; i < size + 1; i++)
            {

                Tuple<Vector2, Vector2> line4 = new Tuple<Vector2, Vector2>(gridEdgeCoords(new Vector2(i, 0)), gridEdgeCoords(new Vector2(i, size))); //CartesianCoords(new Vector2(x, 0)), CartesianCoords(new Vector2(x, (float) rows-1))

                float angle4 = (float)Math.Atan2(line4.Item2.Y - line4.Item1.Y, line4.Item2.X - line4.Item1.X);
                float length4 = Vector2.Distance(line4.Item1, line4.Item2);

                sbatch.Draw(blank, line4.Item1 + new Vector2(0, 0), null, Microsoft.Xna.Framework.Color.Red, angle4, Vector2.Zero, new Vector2(length4, 1.0f), SpriteEffects.None, 0.49f);

            }

            for (int j = 0; j < size + 1; j++)
            {
                Tuple<Vector2, Vector2> line4 = new Tuple<Vector2, Vector2>(gridEdgeCoords(new Vector2(0, j)), gridEdgeCoords(new Vector2(size, j))); //CartesianCoords(new Vector2(x, 0)), CartesianCoords(new Vector2(x, (float) rows-1))

                float angle4 = (float)Math.Atan2(line4.Item2.Y - line4.Item1.Y, line4.Item2.X - line4.Item1.X);
                float length4 = Vector2.Distance(line4.Item1, line4.Item2);

                sbatch.Draw(blank, line4.Item1 + new Vector2(0, 0), null, Microsoft.Xna.Framework.Color.Red, angle4, Vector2.Zero, new Vector2(length4, 1.0f), SpriteEffects.None, 0.49f);

            }
        }
Ejemplo n.º 25
0
        public ActionResult GetPostByCategory(int id,int ?page)
        {
            _pagingHandler.PageIndex = page ?? 1;
            var postList = _pagingHandler.GetPagingList(c=>c.CategoryId==id,c => new PostModel()
            {
                Title = c.Title,
                DateTime = c.DateTime,
                ShortDescription = c.ShortDescription,
                FullName = c.User.FirstName + " " + c.User.LastName,
                Id = c.Id
            }, c => c.DateTime, ListSortDirection.Descending).ToList();

            var pagingModel = new PagingModel()
            {
                HasNextPage = _pagingHandler.HasNextPage,
                HasPreviousPage = _pagingHandler.HasPreviousPage,
                PageIndex = _pagingHandler.PageIndex,
                IsFirstPage = _pagingHandler.IsFirstPage,
                IsLastPage = _pagingHandler.IsLastPage,
                PageCount = _pagingHandler.PageCount,
                PageNumber = _pagingHandler.PageNumber,
                PageSize = _pagingHandler.PageSize
            };

            var model = new Tuple<List<PostModel>, PagingModel>(postList, pagingModel);
            return View("_ListPost", model);
        }
Ejemplo n.º 26
0
 public string FormatLine(int id, Tuple<float, float, float> xyz, Tuple<int, int, int> rgb)
 {
     return String.Format(CultureInfo.InvariantCulture,
         "{0} {1} {2} {3} {4} {5}\n",
         xyz.Item1, xyz.Item2, xyz.Item3,
         rgb.Item1, rgb.Item2, rgb.Item3);
 }
        static public List<Tuple<String, double>> readPriceList()
        {
            List<Tuple<String, double>> priceList = new List<Tuple<String, double>>();

            try
            {
                string[] lines = System.IO.File.ReadAllLines("PriceData.txt");

                foreach (String line in lines)
                {
                    String[] split_string = line.Split('[');
                    split_string[1] = split_string[1].Trim(']');
                    Tuple<String, double> pair = new Tuple<String, double>(split_string[0], Convert.ToDouble(split_string[1]));
                    priceList.Add(pair);
                }
            }

            // This can catch either a file not found exception, or a format exception for the double conversion
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return priceList;
        }
Ejemplo n.º 28
0
 static double Distance(Tuple<int, int> coords1, Tuple<int, int> coords2)
 {
     return Math.Sqrt(
         (coords1.Item1 - coords2.Item1) * (coords1.Item1 - coords2.Item1) +
         (coords1.Item2 - coords2.Item2) * (coords1.Item2 - coords2.Item2)
     );
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Ctor is based on single line from the fed's text report
 /// </summary>
 /// <param name="li"></param>
 internal Bank(dynamic li)
 {
     const string COMMA = ",";
     const string LETTER_Y = "Y";
     UpsertName(KindsOfNames.Legal, li.BankName);
     UpsertName(KindsOfNames.Abbrev, li.BankName);
     Rssd = new ResearchStatisticsSupervisionDiscount { Value = li.BankId };
     UsCityStateZip cityOut;
     if (UsCityStateZip.TryParse(li.Location, out cityOut))
         BusinessAddress = new Tuple<UsStreetPo, UsCityStateZip>(null, cityOut);
     if (FedLrgBnk.TypeOfBankAbbrev3Enum.ContainsKey(li.Chtr))
         BankType = FedLrgBnk.TypeOfBankAbbrev3Enum[li.Chtr];
     var assets = new FinancialAssets { Src = FedLrgBnk.RELEASE_URL };
     decimal conAssts = 0;
     decimal domAssts = 0;
     if (decimal.TryParse(li.ConsolAssets.Replace(COMMA, string.Empty), out conAssts))
         assets.TotalAssets = new Pecuniam(conAssts * ONE_THOUSAND);
     if (decimal.TryParse(li.DomesticAssets.Replace(COMMA, string.Empty), out domAssts))
         assets.DomesticAssets = new Pecuniam(domAssts * ONE_THOUSAND);
     int domBranches = 0;
     int frnBranches = 0;
     int pfo = 0;
     if (int.TryParse(li.NumOfDomBranches.Replace(COMMA, string.Empty), out domBranches))
         assets.DomesticBranches = domBranches;
     if (int.TryParse(li.NumOfFgnBranches.Replace(COMMA, string.Empty), out frnBranches))
         assets.ForeignBranches = frnBranches;
     IsInternational = li.Ibf == LETTER_Y;
     if (int.TryParse(li.PercentFgnOwned, out pfo))
         assets.PercentForeignOwned = Math.Round((double)pfo / 100, 2);
     Assets = new Dictionary<DateTime, FinancialAssets> { { li.RptDate, assets } };
 }
Ejemplo n.º 30
0
        private void OnKeyInputProcessed(object sender, Tuple<KeyInput, ProcessResult> tuple)
        {
            if (_ignoreNextKeyProcessedEvent)
            {
                _ignoreNextKeyProcessedEvent = false;
                return;
            }

            switch (_buffer.ModeKind)
            {
                case ModeKind.Command:
                    _margin.StatusLine = ":" + _buffer.CommandMode.Command;
                    break;
                case ModeKind.Normal:
                    {
                        var mode = _buffer.NormalMode;
                        var search = mode.IncrementalSearch;
                        if (search.InSearch && search.CurrentSearch.IsSome())
                        {
                            var data = search.CurrentSearch.Value;
                            _margin.StatusLine = "/" + data.Text.RawText;
                        }
                        else
                        {
                            _margin.StatusLine = mode.Command;
                        }
                    }
                    break;
                case ModeKind.Disabled:
                    _margin.StatusLine = _buffer.DisabledMode.HelpMessage;
                    break;
            }
        }
Ejemplo n.º 31
0
 public int CompareTo(GenericType other)
 {
     return(Comparer <Tuple <GenericTypeKind, string> > .Default.Compare(Tuple.Create(TypeKind, ElementTypes), Tuple.Create(other.TypeKind, other.ElementTypes)));
 }
Ejemplo n.º 32
0
 public VertexLinked(ModelBase.VertexDef vertex)
 {
     m_VertexLinkedTriangleIndices = new Tuple <ModelBase.VertexDef, List <int> >(vertex, new List <int>());
 }
Ejemplo n.º 33
0
        public List <ModelBase.FaceListDef> Stripify(bool keepVertexOrderDuringStripping = false)
        {
            for (int i = 0; i < m_Triangles.Count; i++)
            {
                ModelBase.FaceDef triangle = m_Triangles[i].m_Triangle;

                List <int> vertexALinked = GetVertex(triangle.m_Vertices[0]).m_LinkedTriangles;
                List <int> vertexBLinked = GetVertex(triangle.m_Vertices[1]).m_LinkedTriangles;
                List <int> vertexCLinked = GetVertex(triangle.m_Vertices[2]).m_LinkedTriangles;

                // Shares edge AB if both triangles reference vertices A and B
                var edgeAB = vertexALinked.Intersect(vertexBLinked).Except(new int[] { i });
                var edgeBC = vertexBLinked.Intersect(vertexCLinked).Except(new int[] { i });
                var edgeCA = vertexCLinked.Intersect(vertexALinked).Except(new int[] { i });

                if (edgeAB.Count() > 0)
                {
                    m_Triangles[i].m_LinkedTriangles[(int)TriangleEdge.Edge_AB].AddRange(edgeAB);
                }
                if (edgeBC.Count() > 0)
                {
                    m_Triangles[i].m_LinkedTriangles[(int)TriangleEdge.Edge_BC].AddRange(edgeBC);
                }
                if (edgeCA.Count() > 0)
                {
                    m_Triangles[i].m_LinkedTriangles[(int)TriangleEdge.Edge_CA].AddRange(edgeCA);
                }
            }

            m_TrianglesToProcess.AddRange(m_Triangles);

            // Sort by number of neighbours
            if (!keepVertexOrderDuringStripping)
            {
                m_TrianglesToProcess.Sort((a, b) => GetNumLinked(a).CompareTo(GetNumLinked(b)));
            }

            List <ModelBase.FaceListDef> tStrips = new List <ModelBase.FaceListDef>();

            // For storing triangles that have no neighbours or don't end up in a strip
            ModelBase.FaceListDef separateTriangles = new ModelBase.FaceListDef(ModelBase.PolyListType.Triangles);

            TriangleLinked currentTriangle = null;

            while (m_TrianglesToProcess.Count > 0)
            {
                while (true)
                {
                    if (m_TrianglesToProcess.Count <= 0)
                    {
                        currentTriangle = null;
                        break;
                    }

                    currentTriangle = m_TrianglesToProcess[0];
                    m_TrianglesToProcess.RemoveAt(0);
                    if (currentTriangle.m_Marked)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                if (currentTriangle == null)
                {
                    break;
                }

                List <TriangleLinked>[] linked = GetLinked(currentTriangle);
                int numLinked = GetNumLinked(currentTriangle);

                currentTriangle.m_Marked = true;

                if (numLinked == 0)
                {
                    separateTriangles.m_Faces.Add(currentTriangle.m_Triangle);
                    continue;
                }

                // For each face build a strip off each of its edges and keep the longest one, discarding the
                // rest. Not part of SGI.
                Tuple <ModelBase.FaceListDef, List <int> > tStripAB =
                    GetStripAndIndicesForStartingEvenEdge(currentTriangle, TriangleEdge.Edge_AB);
                Tuple <ModelBase.FaceListDef, List <int> > tStripBC =
                    GetStripAndIndicesForStartingEvenEdge(currentTriangle, TriangleEdge.Edge_BC);
                Tuple <ModelBase.FaceListDef, List <int> > tStripCA =
                    GetStripAndIndicesForStartingEvenEdge(currentTriangle, TriangleEdge.Edge_CA);

                List <Tuple <ModelBase.FaceListDef, List <int> > > candidates = new List <Tuple <ModelBase.FaceListDef, List <int> > >()
                {
                    tStripAB, tStripBC, tStripCA
                };

                List <int> stripLengths = new List <int>();
                foreach (Tuple <ModelBase.FaceListDef, List <int> > strip in candidates)
                {
                    stripLengths.Add(strip.Item1.m_Faces.Count);
                }
                int longestStripIndex = stripLengths.IndexOf(stripLengths.Max());

                Tuple <ModelBase.FaceListDef, List <int> > longestStrip = candidates[longestStripIndex];

                if (longestStrip.Item1.m_Faces.Count == 0)
                {
                    separateTriangles.m_Faces.Add(currentTriangle.m_Triangle);
                    continue;
                }

                foreach (int tri in longestStrip.Item2)
                {
                    m_Triangles[tri].m_Marked = true;
                }

                tStrips.Add(longestStrip.Item1);
            }

            if (separateTriangles.m_Faces.Count > 0)
            {
                tStrips.Add(separateTriangles);
            }

            return(tStrips);
        }
 private void OnTimePeriodChanged(object sender, DateRangeEventArgs e)
 {
     GlobalSettings.Instance.CurrentDateRange = Tuple.Create(e.DateFrom, e.DateTo);
 }
Ejemplo n.º 35
0
 internal static bool TupleEquals <T1, T2>(Tuple <T1, T2> a, Tuple <T1, T2> b)
 {
     return(a.Item1.Equals(b.Item1) && a.Item2.Equals(b.Item2));
 }
        /// <summary>
        /// Does the Analysis
        /// Returns a DataTable
        /// </summary>
        /// <param name="fiSegmentOfSourceFile"></param>
        /// <param name="configDict"></param>
        /// <param name="diOutputDir"></param>
        /// <param name="opFileName"></param>
        /// <param name="segmentStartOffset"></param>
        /// <param name="config"></param>
        /// <param name="segmentAudioFile"></param>
        public static Tuple <BaseSonogram, double[, ], double[], List <AcousticEvent>, TimeSpan> Analysis(FileInfo fiSegmentOfSourceFile, Dictionary <string, string> configDict, DirectoryInfo diOutputDir, string opFileName, TimeSpan segmentStartOffset)
        {
            //set default values
            int    bandWidth          = 500; //detect bars in bands of this width.
            int    frameSize          = 1024;
            double windowOverlap      = 0.0;
            double intensityThreshold = double.Parse(configDict[key_INTENSITY_THRESHOLD]);
            //intensityThreshold = 0.01;

            AudioRecording recording = AudioRecording.GetAudioRecording(fiSegmentOfSourceFile, RESAMPLE_RATE, diOutputDir.FullName, opFileName);

            if (recording == null)
            {
                LoggedConsole.WriteLine("############ WARNING: Recording could not be obtained - likely file does not exist.");
                return(null);
            }
            int      sr                   = recording.SampleRate;
            double   binWidth             = recording.SampleRate / (double)frameSize;
            double   frameDuration        = frameSize / (double)sr;
            double   frameOffset          = frameDuration * (1 - windowOverlap); //seconds between start of each frame
            double   framesPerSecond      = 1 / frameOffset;
            TimeSpan tsRecordingtDuration = recording.Duration;
            int      colStep              = (int)Math.Round(bandWidth / binWidth);

            //i: GET SONOGRAM AS MATRIX
            double epsilon  = Math.Pow(0.5, recording.BitsPerSample - 1);
            var    results2 = DSP_Frames.ExtractEnvelopeAndAmplSpectrogram(recording.WavReader.Samples, sr, epsilon, frameSize, windowOverlap);

            double[] avAbsolute = results2.Average;                //average absolute value over the minute recording
            //double[] envelope = results2.Item2;
            double[,] spectrogram = results2.AmplitudeSpectrogram; //amplitude spectrogram. Note that column zero is the DC or average energy value and can be ignored.
            double windowPower = results2.WindowPower;

            //############################ NEXT LINE FOR DEBUGGING ONLY
            //spectrogram = GetTestSpectrogram(spectrogram.GetLength(0), spectrogram.GetLength(1), 0.01, 0.03);

            var output         = DetectGratingEvents(spectrogram, colStep, intensityThreshold);
            var amplitudeArray = output.Item2; //for debug purposes only

            //convert List of Dictionary events to List of ACousticevents.
            //also set up the hits matrix.
            int rowCount       = spectrogram.GetLength(0);
            int colCount       = spectrogram.GetLength(1);
            var hitsMatrix     = new double[rowCount, colCount];
            var acousticEvents = new List <AcousticEvent>();

            double minFrameCount = 8; //this assumes that the minimum grid is 2 * 4 = 8 long

            foreach (Dictionary <string, double> item in output.Item1)
            {
                int minRow     = (int)item[key_START_FRAME];
                int maxRow     = (int)item[key_END_FRAME];
                int frameCount = maxRow - minRow + 1;
                if (frameCount < minFrameCount)
                {
                    continue;                             //only want events that are over a minimum length
                }
                int    minCol      = (int)item[key_MIN_FREQBIN];
                int    maxCol      = (int)item[key_MAX_FREQBIN];
                double periodicity = item[key_PERIODICITY];

                double[] subarray = DataTools.Subarray(avAbsolute, minRow, maxRow - minRow + 1);
                double   severity = 0.1;
                int[]    bounds   = DataTools.Peaks_CropToFirstAndLast(subarray, severity);
                minRow = minRow + bounds[0];
                maxRow = minRow + bounds[1];
                if (maxRow >= rowCount)
                {
                    maxRow = rowCount - 1;
                }

                Oblong o  = new Oblong(minRow, minCol, maxRow, maxCol);
                var    ae = new AcousticEvent(segmentStartOffset, o, results2.NyquistFreq, frameSize, frameDuration, frameOffset, frameCount);
                ae.Name            = string.Format("p={0:f0}", periodicity);
                ae.Score           = item[key_SCORE];
                ae.ScoreNormalised = item[key_SCORE] / 0.5;
                acousticEvents.Add(ae);

                //display event on the hits matrix
                for (int r = minRow; r < maxRow; r++)
                {
                    for (int c = minCol; c < maxCol; c++)
                    {
                        hitsMatrix[r, c] = periodicity;
                    }
                }
            } //foreach

            //set up the songogram to return. Use the existing amplitude sonogram
            int bitsPerSample = recording.WavReader.BitsPerSample;
            //NoiseReductionType nrt = SNR.Key2NoiseReductionType("NONE");
            NoiseReductionType nrt = SNR.KeyToNoiseReductionType("STANDARD");
            var sonogram           = (BaseSonogram)SpectrogramStandard.GetSpectralSonogram(recording.BaseName, frameSize, windowOverlap, bitsPerSample, windowPower, sr, tsRecordingtDuration, nrt, spectrogram);

            sonogram.DecibelsNormalised = new double[sonogram.FrameCount];
            for (int i = 0; i < sonogram.FrameCount; i++) //foreach frame or time step
            {
                sonogram.DecibelsNormalised[i] = 2 * Math.Log10(avAbsolute[i]);
            }
            sonogram.DecibelsNormalised = DataTools.normalise(sonogram.DecibelsNormalised);

            return(Tuple.Create(sonogram, hitsMatrix, amplitudeArray, acousticEvents, tsRecordingtDuration));
        } //Analysis()
Ejemplo n.º 37
0
		/// <summary>
		/// Handles the signal RD ata received.
		/// </summary>
		/// <returns>The signal RD ata received.</returns>
		/// <param name="sender">Sender.</param>
		/// <param name="e">E.</param>
		protected void HandleSignalRDataReceived(object sender, Tuple<string, string> e)
		{
			_signalREvents[e.Item1](e.Item2);
		}
Ejemplo n.º 38
0
        public Dictionary <A, HashSet <B> > ComputeSimulationRelation()
        {
            Dictionary <A, HashSet <B> >            prevsim;
            Dictionary <A, HashSet <B> >            sim;
            Dictionary <Tuple <A, L>, HashSet <B> > remove;
            Queue <Tuple <A, L> > workQueue;

            prevsim   = new Dictionary <A, HashSet <B> >();
            sim       = new Dictionary <A, HashSet <B> >();
            remove    = new Dictionary <Tuple <A, L>, HashSet <B> >();
            workQueue = new Queue <Tuple <A, L> >();
            foreach (var a in aGraph.Nodes)
            {
                prevsim[a] = new HashSet <B>(bGraph.Nodes);
                sim[a]     = new HashSet <B>();
                HashSet <L> aOutgoingLabels = new HashSet <L>(aGraph.PostLabels(a));
                foreach (var b in bGraph.Nodes)
                {
                    IEnumerable <L> bOutgoingLabels = bGraph.PostLabels(b);
                    if (aOutgoingLabels.IsSubsetOf(bOutgoingLabels))
                    {
                        sim[a].Add(b);
                    }
                }
                if (initialConstraints.ContainsKey(a))
                {
                    sim[a].IntersectWith(initialConstraints[a]);
                }

                foreach (var l in aGraph.PreLabels(a))
                {
                    Tuple <A, L> x = new Tuple <A, L>(a, l);
                    remove[x] = new HashSet <B>(bGraph.Pre(prevsim[a], l).Except(bGraph.Pre(sim[a], l)));
                    if (remove[x].Count > 0)
                    {
                        workQueue.Enqueue(x);
                    }
                }
            }

            while (workQueue.Count > 0)
            {
                Tuple <A, L> x = workQueue.Dequeue();
                A            v = x.Item1;
                foreach (A u in aGraph.Pre(v, x.Item2))
                {
                    foreach (B w in remove[x])
                    {
                        if (sim[u].Contains(w))
                        {
                            sim[u].Remove(w);
                            foreach (L l in bGraph.PreLabels(w))
                            {
                                foreach (B b in bGraph.Pre(w, l))
                                {
                                    if (bGraph.Post(b, l).Intersect(sim[u]).Count() == 0)
                                    {
                                        Tuple <A, L> z = new Tuple <A, L>(u, l);
                                        if (!remove.ContainsKey(z))
                                        {
                                            remove[z] = new HashSet <B>();
                                        }
                                        remove[z].Add(b);
                                        workQueue.Enqueue(z);
                                    }
                                }
                            }
                        }
                    }
                }
                prevsim[v] = new HashSet <B>(sim[v]);
                remove[x]  = new HashSet <B>();
            }

            return(sim);
        }
Ejemplo n.º 39
0
 public bool Equals(Tuple <Simulation.Traffic.Node, Simulation.Traffic.Node> x, Tuple <Simulation.Traffic.Node, Simulation.Traffic.Node> y)
 {
     return((x.Item1 == y.Item1 && x.Item2 == y.Item2) || (x.Item2 == y.Item1 && x.Item1 == y.Item2));
 }
Ejemplo n.º 40
0
 public override int GetHashCode()
 {
     return(Tuple.Create(this.TypeKind, this.ElementTypes).GetHashCode());
 }
        public override void Execute()
        {
            
            #line 6 "..\..\Views\MatchLocation.cshtml"
  
    Html.RequiresJs("https://maps.google.co.uk/maps/api/js?key=" + Model.GoogleMapsApiKey, 50);
    Html.RequiresJs("~/js/maps.js", 90);
    Html.RequiresJs("~/matchlocations/match-location.js");
    Html.RequiresJs("~/matchlocations/show-all-teams.js");
    var authorizedToEdit = Model.IsAuthorized[AuthorizedAction.EditMatchLocation] || Model.IsAuthorized[AuthorizedAction.DeleteMatchLocation];

            
            #line default
            #line hidden
WriteLiteral("\r\n<div");

WriteLiteral(" class=\"container-xl\"");

WriteLiteral(">\r\n    <h1>");

            
            #line 14 "..\..\Views\MatchLocation.cshtml"
   Write(Model.MatchLocation.NameAndLocalityOrTownIfDifferent());

            
            #line default
            #line hidden
WriteLiteral("</h1>\r\n\r\n    <ul");

WriteAttribute("class", Tuple.Create(" class=\"", 736), Tuple.Create("\"", 813)
, Tuple.Create(Tuple.Create("", 744), Tuple.Create("nav", 744), true)
, Tuple.Create(Tuple.Create(" ", 747), Tuple.Create("nav-tabs", 748), true)
            
            #line 16 "..\..\Views\MatchLocation.cshtml"
, Tuple.Create(Tuple.Create("", 756), Tuple.Create<System.Object, System.Int32>(authorizedToEdit ? " nav-tabs-has-edit" : string.Empty
            
            #line default
            #line hidden
, 756), false)
);

WriteLiteral(">\r\n        <li");

WriteLiteral(" class=\"nav-item\"");

WriteLiteral(">\r\n            <em");

WriteLiteral(" class=\"nav-link active\"");

WriteLiteral(">Summary</em>\r\n        </li>\r\n        <li");

WriteLiteral(" class=\"nav-item\"");

WriteLiteral(">\r\n            <a");

WriteLiteral(" class=\"nav-link\"");

WriteAttribute("href", Tuple.Create(" href=\"", 979), Tuple.Create("\"", 1033)
            
            #line 21 "..\..\Views\MatchLocation.cshtml"
, Tuple.Create(Tuple.Create("", 986), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.MatchLocationRoute
            
            #line default
            #line hidden
, 986), false)
, Tuple.Create(Tuple.Create("", 1025), Tuple.Create("/matches", 1025), true)
);

WriteLiteral(">Matches</a>\r\n        </li>\r\n        <li");

WriteLiteral(" class=\"nav-item\"");

WriteLiteral(">\r\n            <a");

WriteLiteral(" class=\"nav-link\"");

WriteAttribute("href", Tuple.Create(" href=\"", 1125), Tuple.Create("\"", 1182)
            
            #line 24 "..\..\Views\MatchLocation.cshtml"
, Tuple.Create(Tuple.Create("", 1132), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.MatchLocationRoute
            
            #line default
            #line hidden
, 1132), false)
, Tuple.Create(Tuple.Create("", 1171), Tuple.Create("/statistics", 1171), true)
);

WriteLiteral(">Statistics</a>\r\n        </li>\r\n");

            
            #line 26 "..\..\Views\MatchLocation.cshtml"
        
            
            #line default
            #line hidden
            
            #line 26 "..\..\Views\MatchLocation.cshtml"
         if (authorizedToEdit)
        {

            
            #line default
            #line hidden
WriteLiteral("            <li");

WriteLiteral(" class=\"nav-item nav-item-admin\"");

WriteLiteral(">\r\n                <a");

WriteLiteral(" class=\"nav-link nav-link-edit\"");

WriteAttribute("href", Tuple.Create(" href=\"", 1357), Tuple.Create("\"", 1408)
            
            #line 29 "..\..\Views\MatchLocation.cshtml"
, Tuple.Create(Tuple.Create("", 1364), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.MatchLocationRoute
            
            #line default
            #line hidden
, 1364), false)
, Tuple.Create(Tuple.Create("", 1403), Tuple.Create("/edit", 1403), true)
);

WriteLiteral(">Edit ground or sports centre</a>\r\n            </li>\r\n");

            
            #line 31 "..\..\Views\MatchLocation.cshtml"
        }

            
            #line default
            #line hidden
WriteLiteral("    </ul>\r\n\r\n");

            
            #line 34 "..\..\Views\MatchLocation.cshtml"
    
            
            #line default
            #line hidden
            
            #line 34 "..\..\Views\MatchLocation.cshtml"
      
        var addressLines = new List<string>();
        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.SecondaryAddressableObjectName))
        {
            addressLines.Add(Model.MatchLocation.SecondaryAddressableObjectName);
        }
        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.PrimaryAddressableObjectName))
        {
            addressLines.Add(Model.MatchLocation.PrimaryAddressableObjectName);
        }
        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.StreetDescription))
        {
            addressLines.Add(Model.MatchLocation.StreetDescription);
        }

        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.Locality))
        {
            addressLines.Add(Model.MatchLocation.Locality);
        }
        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.Town))
        {
            addressLines.Add(Model.MatchLocation.Town);
        }
        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.AdministrativeArea))
        {
            addressLines.Add(Model.MatchLocation.AdministrativeArea);
        }
        if (!string.IsNullOrWhiteSpace(Model.MatchLocation.Postcode))
        {
            if (addressLines.Count > 0)
            {
                addressLines[addressLines.Count - 1] += " " + Model.MatchLocation.Postcode.ToUpper(CultureInfo.CurrentCulture);
            }
            else
            {
                addressLines.Add(Model.MatchLocation.Postcode.ToUpper(CultureInfo.CurrentCulture));
            }
        }
        if (addressLines.Count > 0)
        {

            
            #line default
            #line hidden
WriteLiteral("            <p>\r\n");

            
            #line 75 "..\..\Views\MatchLocation.cshtml"
                
            
            #line default
            #line hidden
            
            #line 75 "..\..\Views\MatchLocation.cshtml"
                 foreach (var line in addressLines)
                {
                    
            
            #line default
            #line hidden
            
            #line 77 "..\..\Views\MatchLocation.cshtml"
               Write(line);

            
            #line default
            #line hidden
WriteLiteral("<br />\r\n");

            
            #line 78 "..\..\Views\MatchLocation.cshtml"
                }

            
            #line default
            #line hidden
WriteLiteral("            </p>\r\n");

            
            #line 80 "..\..\Views\MatchLocation.cshtml"
        }
    
            
            #line default
            #line hidden
WriteLiteral("\r\n");

            
            #line 82 "..\..\Views\MatchLocation.cshtml"
    
            
            #line default
            #line hidden
            
            #line 82 "..\..\Views\MatchLocation.cshtml"
     if (Model.MatchLocation.Teams?.Count > 0)
    {
        var currentTeams = Model.MatchLocation.Teams.Where(x => !x.UntilYear.HasValue).ToList();

            
            #line default
            #line hidden
WriteLiteral("        <h2>Teams based here</h2>\r\n");

            
            #line 86 "..\..\Views\MatchLocation.cshtml"
        if (currentTeams.Any())
        {

            
            #line default
            #line hidden
WriteLiteral("        <div");

WriteLiteral(" class=\"team-list__current\"");

WriteLiteral(">\r\n");

WriteLiteral("            ");

            
            #line 89 "..\..\Views\MatchLocation.cshtml"
       Write(Html.Partial("_TeamList", currentTeams));

            
            #line default
            #line hidden
WriteLiteral("\r\n        </div>\r\n");

            
            #line 91 "..\..\Views\MatchLocation.cshtml"
        }
        if (currentTeams.Count < Model.MatchLocation.Teams.Count)
        {

            
            #line default
            #line hidden
WriteLiteral("            <div");

WriteLiteral(" class=\"team-list__all d-none\"");

WriteLiteral(">\r\n");

WriteLiteral("                ");

            
            #line 95 "..\..\Views\MatchLocation.cshtml"
           Write(Html.Partial("_TeamList", Model.MatchLocation.Teams));

            
            #line default
            #line hidden
WriteLiteral("\r\n            </div>\r\n");

            
            #line 97 "..\..\Views\MatchLocation.cshtml"
        }
    }

            
            #line default
            #line hidden
WriteLiteral("\r\n");

            
            #line 100 "..\..\Views\MatchLocation.cshtml"
    
            
            #line default
            #line hidden
            
            #line 100 "..\..\Views\MatchLocation.cshtml"
     if (Model.MatchLocation.Latitude.HasValue && Model.MatchLocation.Longitude.HasValue)
    {
        var mapTitle = string.Empty;
        var precisionWarning = string.Empty;
        switch (Model.MatchLocation.GeoPrecision)
        {
            case GeoPrecision.Exact:
                mapTitle = Model.MatchLocation.NameAndLocalityOrTownIfDifferent();
                break;
            case GeoPrecision.Postcode:
                mapTitle = Model.MatchLocation.Postcode;
                precisionWarning = "Note: This map shows the nearest postcode. The ground or sports centre should be nearby.";
                break;
            case GeoPrecision.Street:
                mapTitle = Model.MatchLocation.StreetDescription + ", " + Model.MatchLocation.Town;
                precisionWarning = "Note: This map shows the nearest road. The ground or sports centre should be nearby.";
                break;
            case GeoPrecision.Town:
                mapTitle = Model.MatchLocation.Town;
                precisionWarning = "Note: This map shows the town or village. Contact the home team to find the ground or sports centre.";
                break;
        }

            
            #line default
            #line hidden
WriteLiteral("        <h2>Map of ");

            
            #line 122 "..\..\Views\MatchLocation.cshtml"
              Write(mapTitle);

            
            #line default
            #line hidden
WriteLiteral("</h2>\r\n");

            
            #line 123 "..\..\Views\MatchLocation.cshtml"
        if (!string.IsNullOrEmpty(precisionWarning))
        {

            
            #line default
            #line hidden
WriteLiteral("            <p>");

            
            #line 125 "..\..\Views\MatchLocation.cshtml"
          Write(precisionWarning);

            
            #line default
            #line hidden
WriteLiteral("</p>\r\n");

            
            #line 126 "..\..\Views\MatchLocation.cshtml"
        }

            
            #line default
            #line hidden
WriteLiteral("        <div");

WriteLiteral(" id=\"location-map\"");

WriteLiteral(" data-latitude=\"");

            
            #line 127 "..\..\Views\MatchLocation.cshtml"
                                         Write(Model.MatchLocation.Latitude);

            
            #line default
            #line hidden
WriteLiteral("\"");

WriteLiteral(" data-longitude=\"");

            
            #line 127 "..\..\Views\MatchLocation.cshtml"
                                                                                        Write(Model.MatchLocation.Longitude);

            
            #line default
            #line hidden
WriteLiteral("\"");

WriteLiteral(" data-precision=\"");

            
            #line 127 "..\..\Views\MatchLocation.cshtml"
                                                                                                                                        Write(Model.MatchLocation.GeoPrecision.ToString().ToLowerInvariant());

            
            #line default
            #line hidden
WriteLiteral("\"");

WriteLiteral(">\r\n            <p><a");

WriteAttribute("href", Tuple.Create(" href=\"", 5412), Tuple.Create("\"", 5658)
, Tuple.Create(Tuple.Create("", 5419), Tuple.Create("https://maps.google.co.uk/?z=16&amp;q=", 5419), true)
            
            #line 128 "..\..\Views\MatchLocation.cshtml"
, Tuple.Create(Tuple.Create("", 5457), Tuple.Create<System.Object, System.Int32>(HttpUtility.UrlEncode(Model.MatchLocation.NameAndLocalityOrTown())
            
            #line default
            #line hidden
, 5457), false)
            
            #line 128 "..\..\Views\MatchLocation.cshtml"
                                                  , Tuple.Create(Tuple.Create("", 5524), Tuple.Create<System.Object, System.Int32>("@"
            
            #line default
            #line hidden
, 5524), false)
            
            #line 128 "..\..\Views\MatchLocation.cshtml"
                                                       , Tuple.Create(Tuple.Create("", 5530), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.Latitude
            
            #line default
            #line hidden
, 5530), false)
, Tuple.Create(Tuple.Create("", 5559), Tuple.Create(",", 5559), true)
            
            #line 128 "..\..\Views\MatchLocation.cshtml"
                                                                                     , Tuple.Create(Tuple.Create("", 5560), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.Longitude
            
            #line default
            #line hidden
, 5560), false)
, Tuple.Create(Tuple.Create("", 5590), Tuple.Create("&amp;ll=", 5590), true)
            
            #line 128 "..\..\Views\MatchLocation.cshtml"
                                                                                                                           , Tuple.Create(Tuple.Create("", 5598), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.Latitude
            
            #line default
            #line hidden
, 5598), false)
, Tuple.Create(Tuple.Create("", 5627), Tuple.Create(",", 5627), true)
            
            #line 128 "..\..\Views\MatchLocation.cshtml"
                                                                                                                                                         , Tuple.Create(Tuple.Create("", 5628), Tuple.Create<System.Object, System.Int32>(Model.MatchLocation.Longitude
            
            #line default
            #line hidden
, 5628), false)
);

WriteLiteral(">Map of ");

            
            #line 128 "..\..\Views\MatchLocation.cshtml"
                                                                                                                                                                                                                                                                           Write(mapTitle);

            
            #line default
            #line hidden
WriteLiteral(" on Google Maps</a></p>\r\n        </div>\r\n");

            
            #line 130 "..\..\Views\MatchLocation.cshtml"
    }

            
            #line default
            #line hidden
WriteLiteral("\r\n");

WriteLiteral("    ");

            
            #line 132 "..\..\Views\MatchLocation.cshtml"
Write(Html.Raw(Model.MatchLocation.MatchLocationNotes));

            
            #line default
            #line hidden
WriteLiteral("\r\n</div>");

        }
Ejemplo n.º 42
0
 public int GetHashCode(Tuple <Simulation.Traffic.Node, Simulation.Traffic.Node> obj)
 {
     return(obj.Item1.GetHashCode() ^ obj.Item2.GetHashCode());
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Determines if the specified access token is valid.
 /// It considers an access token as not valid if it is null, or it has expired.
 /// </summary>
 /// <param name="accessToken">The access token to verify.</param>
 /// <returns>True if the access token is valid.</returns>
 protected static bool IsAccessTokenValid(Tuple <string, DateTime> accessToken)
 {
     return(accessToken != null &&
            !string.IsNullOrEmpty(accessToken.Item1) &&
            accessToken.Item2 > DateTime.UtcNow);
 }
Ejemplo n.º 44
0
 private static Tuple <Security, Portfolio> GetKey(Order order)
 {
     return(Tuple.Create(order.Security, order.Portfolio));
 }
Ejemplo n.º 45
0
 public static MonadicParser <TIn, TOut> Always <TIn, TOut>()
 {
     return(scanner => Tuple.Create(default(TOut), new Match <TIn>(scanner, 0)));
 }
Ejemplo n.º 46
0
        /// <summary>
        /// Ensures the access token is valid and returns it.
        /// </summary>
        /// <param name="accessToken">The access token to verify.</param>
        /// <param name="tokenRenewalHandler">The token renewal handler.</param>
        /// <returns>The access token string.</returns>
        private static string GetAccessTokenString(ref Tuple <string, DateTime> accessToken, Func <string> tokenRenewalHandler)
        {
            RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);

            return(IsAccessTokenValid(accessToken) ? accessToken.Item1 : null);
        }
 public void headhunterNotifyPerson(string companyName, string department, string level, int experiencedWage)
 {
     Console.WriteLine($"*** {Name} HeadHunter notify that he has something to you");
     person?.Invoke(this, Tuple.Create(companyName, department, level, experiencedWage));
     Console.WriteLine();
 }
Ejemplo n.º 48
0
 public static MonadicParser <TIn, TOut> Never <TIn, TOut>()
 {
     return(scanner => Tuple.Create(default(TOut), new Match <TIn>(scanner, "Epic fail.")));
 }
Ejemplo n.º 49
0
        internal static Tuple <Type, string> Generate <TKey, TLeft, TRight, TResult>(
            BinaryStreamable <TKey, TLeft, TRight, TResult> stream,
            Expression <Func <TLeft, TRight, TResult> > selector)
        {
            Contract.Requires(stream != null);
            Contract.Ensures(Contract.Result <Tuple <Type, string> >() == null || typeof(BinaryPipe <TKey, TLeft, TRight, TResult>).GetTypeInfo().IsAssignableFrom(Contract.Result <Tuple <Type, string> >().Item1));

            string errorMessages = null;

            try
            {
                var template = new EquiJoinTemplate($"GeneratedEquiJoin_{EquiJoinSequenceNumber++}", typeof(TKey), typeof(TLeft), typeof(TRight), typeof(TResult));

                var keyAndLeftGenericParameters  = template.tm.GenericTypeVariables(template.keyType, template.leftType).BracketedCommaSeparatedString();
                var keyAndRightGenericParameters = template.tm.GenericTypeVariables(template.keyType, template.rightType).BracketedCommaSeparatedString();
                template.TKeyTResultGenericParameters = template.tm.GenericTypeVariables(template.keyType, template.resultType).BracketedCommaSeparatedString();
                template.genericParameters            = template.tm.GenericTypeVariables(template.keyType, template.leftType, template.rightType, template.resultType).BracketedCommaSeparatedString();

                template.leftMessageRepresentation  = new ColumnarRepresentation(template.leftType);
                template.rightMessageRepresentation = new ColumnarRepresentation(template.rightType);
                var resultMessageRepresentation = new ColumnarRepresentation(template.resultType);

                var batchGeneratedFrom_TKey_TLeft  = Transformer.GetBatchClassName(template.keyType, template.leftType);
                var batchGeneratedFrom_TKey_TRight = Transformer.GetBatchClassName(template.keyType, template.rightType);
                template.BatchGeneratedFrom_TKey_TResult = Transformer.GetBatchClassName(template.keyType, template.resultType);

                template.LeftBatchType  = batchGeneratedFrom_TKey_TLeft + keyAndLeftGenericParameters;
                template.RightBatchType = batchGeneratedFrom_TKey_TRight + keyAndRightGenericParameters;

                template.leftFields   = template.leftMessageRepresentation.AllFields;
                template.rightFields  = template.rightMessageRepresentation.AllFields;
                template.resultFields = resultMessageRepresentation.AllFields;

                template.ActiveEventTypeLeft  = template.leftType.GetTypeInfo().IsValueType ? template.TLeft : "Active_Event_Left";
                template.ActiveEventTypeRight = template.rightType.GetTypeInfo().IsValueType ? template.TRight : "Active_Event_Right";

                #region Key Equals
                var keyComparer = stream.Properties.KeyEqualityComparer.GetEqualsExpr();
                template.keyComparerEquals =
                    (left, right) =>
                    keyComparer.Inline(left, right);
                if (template.keyType.IsAnonymousType())
                {
                    template.keyComparerEquals =
                        (left, right) => $"keyComparerEquals({left}, {right})";
                }
                #endregion

                #region Left Payload Equals
                {
                    var leftPayloadComparer = stream.Left.Properties.PayloadEqualityComparer.GetEqualsExpr();
                    var newLambda           = Extensions.TransformFunction <TKey, TLeft>(leftPayloadComparer, "leftIndex", 0);
                    template.leftComparerEquals = (left, right) => newLambda.Inline(left, right);
                }
                #endregion

                #region Right Payload Equals
                {
                    var rightPayloadComparer = stream.Right.Properties.PayloadEqualityComparer.GetEqualsExpr();
                    var newLambda            = Extensions.TransformFunction <TKey, TRight>(rightPayloadComparer, "rightIndex", 0);
                    template.rightComparerEquals = (left, right) => newLambda.Inline(left, right);
                }
                #endregion

                #region Result Selector
                {
                    var leftMessageType  = StreamMessageManager.GetStreamMessageType <TKey, TLeft>();
                    var rightMessageType = StreamMessageManager.GetStreamMessageType <TKey, TRight>();

                    if (!ConstantExpressionFinder.IsClosedExpression(selector))
                    {
                        errorMessages = "result selector is not a closed expression";
                        throw new InvalidOperationException();
                    }

                    #region LeftBatchSelector
                    {
                        var parameterSubsitutions = new List <Tuple <ParameterExpression, SelectParameterInformation> >()
                        {
                            Tuple.Create(selector.Parameters[0], new SelectParameterInformation()
                            {
                                BatchName = "leftBatch", BatchType = leftMessageType, IndexVariableName = "i", parameterRepresentation = template.leftMessageRepresentation,
                            }),
                        };
                        var projectionResult = SelectTransformer.Transform(selector, parameterSubsitutions, resultMessageRepresentation, true);
                        if (projectionResult.Error)
                        {
                            errorMessages = "error while transforming the result selector";
                            throw new InvalidOperationException();
                        }
                        template.leftBatchSelector = (leftBatch, leftIndex, rightEvent) =>
                        {
                            var d = new Dictionary <ParameterExpression, string>
                            {
                                { Expression.Variable(leftMessageType, "leftBatch"), leftBatch },
                                { Expression.Variable(typeof(int), "i"), leftIndex },
                                { selector.Parameters[1], rightEvent }
                            };
                            var sb = new System.Text.StringBuilder();
                            sb.AppendLine("{");
                            foreach (var kv in projectionResult.ComputedFields)
                            {
                                var f = kv.Key;
                                var e = kv.Value;
                                if (f.OptimizeString())
                                {
                                    sb.AppendFormat(
                                        "output.{0}.AddString({1});\n",
                                        f.Name,
                                        e.ExpressionToCSharpStringWithParameterSubstitution(d));
                                }
                                else
                                {
                                    sb.AppendFormat(
                                        "output.{0}.col[index] = {1};\n",
                                        f.Name,
                                        e.ExpressionToCSharpStringWithParameterSubstitution(d));
                                }
                            }
                            sb.AppendLine("}");
                            return(sb.ToString());
                        };
                    }
                    #endregion
                    #region RightBatchSelector
                    {
                        var parameterSubsitutions = new List <Tuple <ParameterExpression, SelectParameterInformation> >()
                        {
                            Tuple.Create(selector.Parameters[1], new SelectParameterInformation()
                            {
                                BatchName = "rightBatch", BatchType = rightMessageType, IndexVariableName = "j", parameterRepresentation = template.rightMessageRepresentation,
                            }),
                        };
                        var projectionResult = SelectTransformer.Transform(selector, parameterSubsitutions, resultMessageRepresentation, true);
                        if (projectionResult.Error)
                        {
                            errorMessages = "error while transforming the result selector";
                            throw new InvalidOperationException();
                        }
                        template.rightBatchSelector = (leftEvent, rightBatch, rightIndex) =>
                        {
                            var d = new Dictionary <ParameterExpression, string>
                            {
                                { selector.Parameters[0], leftEvent },
                                { Expression.Variable(rightMessageType, "rightBatch"), rightBatch },
                                { Expression.Variable(typeof(int), "j"), rightIndex }
                            };
                            var sb = new System.Text.StringBuilder();
                            sb.AppendLine("{");
                            foreach (var kv in projectionResult.ComputedFields)
                            {
                                var f = kv.Key;
                                var e = kv.Value;
                                if (f.OptimizeString())
                                {
                                    sb.AppendFormat(
                                        "output.{0}.AddString({1});\n",
                                        f.Name,
                                        e.ExpressionToCSharpStringWithParameterSubstitution(d));
                                }
                                else
                                {
                                    sb.AppendFormat(
                                        "output.{0}.col[index] = {1};\n",
                                        f.Name,
                                        e.ExpressionToCSharpStringWithParameterSubstitution(d));
                                }
                            }
                            sb.AppendLine("}");
                            return(sb.ToString());
                        };
                    }
                    #endregion
                    #region ActiveSelector
                    {
                        var parameterSubsitutions = new List <Tuple <ParameterExpression, SelectParameterInformation> >();
                        var projectionResult      = SelectTransformer.Transform(selector, parameterSubsitutions, resultMessageRepresentation, true);
                        if (projectionResult.Error)
                        {
                            errorMessages = "error while transforming the result selector";
                            throw new InvalidOperationException();
                        }
                        template.activeSelector = (leftEvent, rightEvent) =>
                        {
                            var d = new Dictionary <ParameterExpression, string>
                            {
                                { selector.Parameters[0], leftEvent },
                                { selector.Parameters[1], rightEvent }
                            };
                            var sb = new System.Text.StringBuilder();
                            sb.AppendLine("{");
                            foreach (var kv in projectionResult.ComputedFields)
                            {
                                var f = kv.Key;
                                var e = kv.Value;
                                if (f.OptimizeString())
                                {
                                    sb.AppendFormat(
                                        "output.{0}.AddString({1});\n",
                                        f.Name,
                                        e.ExpressionToCSharpStringWithParameterSubstitution(d));
                                }
                                else
                                {
                                    sb.AppendFormat(
                                        "output.{0}.col[index] = {1};\n",
                                        f.Name,
                                        e.ExpressionToCSharpStringWithParameterSubstitution(d));
                                }
                            }
                            sb.AppendLine("}");
                            return(sb.ToString());
                        };
                    }
                    #endregion
                }
                #endregion

                if (stream.Left.Properties.IsIntervalFree && stream.Right.Properties.IsConstantDuration)
                {
                    template.endPointHeap = "EndPointQueue";
                }
                else if (stream.Right.Properties.IsIntervalFree && stream.Left.Properties.IsConstantDuration)
                {
                    template.endPointHeap = "EndPointQueue";
                }
                else if (stream.Left.Properties.IsConstantDuration && stream.Right.Properties.IsConstantDuration &&
                         stream.Left.Properties.ConstantDurationLength == stream.Right.Properties.ConstantDurationLength)
                {
                    template.endPointHeap = "EndPointQueue";
                }
                else
                {
                    template.endPointHeap = "EndPointHeap";
                }

                return(template.Generate <TKey, TLeft, TRight, TResult>());
            }
            catch
            {
                if (Config.CodegenOptions.DontFallBackToRowBasedExecution)
                {
                    throw new InvalidOperationException("Code Generation failed when it wasn't supposed to!");
                }
                return(Tuple.Create((Type)null, errorMessages));
            }
        }
 public void personGetNotifiedFromHeadHunterHandler(object sender, Tuple<string , string , string , int> data )
 {
     Console.WriteLine($"I'm {Name}.I received Message From {(sender as HeadHunter).Name} about {data.Item1} company");
     Console.WriteLine($"=={data.Item1}  : {data.Item2}, {data.Item3} {data.Item4} KRW job==");
 }
Ejemplo n.º 51
0
        private void RecieveCardAnimation(int seatNumber, int cardSlotNumber, Card card)
        {
            Console.WriteLine("---recieveCard: " + card.ToString());

            NameScope.SetNameScope(this, new NameScope());

            // 创建card
            UserControls.Card viewCard = new UserControls.Card();
            userDeckViewCards[seatNumber, cardSlotNumber] = viewCard;            
            viewCard.CardInView = card;

            // 创建card的旋转效果
            RotateTransform cardTransform = new RotateTransform();            
            viewCard.RenderTransform = cardTransform;
            
            canvas.Children.Add(viewCard);

            string cardTransformName = "CardTransform" + card.ID;
            string cardName = "Card" + card.ID;
            Console.WriteLine("cardName: " + cardName);
            // 注册name
            this.RegisterName(cardTransformName, cardTransform);
            this.RegisterName(cardName, viewCard);
            
            // 初始化card至主牌堆
            Canvas.SetLeft(viewCard, Canvas.GetLeft(decks));
            Canvas.SetTop(viewCard, Canvas.GetTop(decks));

            this.Content = canvas;

            // 获取用户牌堆位置<top, left, rotate> (相对于canvas)
            UserControls.UserCardDeck userDeck;
            if (seatNumber == bankerSeatNumber) userDeck = ViewHelper.FindChild<UserControls.UserCardDeck>(canvas, "bankerDeck");
            else userDeck = ViewHelper.FindChild<UserControls.UserCardDeck>(canvas, "playerDeck" + seatNumber);
            var startPosition = new Tuple<double, double, double>(Canvas.GetTop(decks), Canvas.GetLeft(decks), 0);
            var keyFramePosition1 = new Tuple<double, double, double>(Canvas.GetTop(userDeck), Canvas.GetLeft(userDeck), userDeck.RotateAngle);

            // 定义贝塞尔曲线
            KeySpline keySpline = new KeySpline(0.25, 0.5, 0.75, 1);
            // 定义动画时间
            TimeSpan timeSpan = TimeSpan.FromMilliseconds(100);            
            // 定义动画时间戳
            KeyTime keyTime1 = KeyTime.FromTimeSpan(timeSpan);

            // Top
            var animationX = new DoubleAnimationUsingKeyFrames() { Duration = timeSpan };
            animationX.FillBehavior = FillBehavior.Stop;
            animationX.KeyFrames.Add(new SplineDoubleKeyFrame(keyFramePosition1.Item1, keyTime1, keySpline));
            
            // Left
            var animationY = new DoubleAnimationUsingKeyFrames() { Duration = timeSpan };
            animationY.FillBehavior = FillBehavior.Stop;
            animationY.KeyFrames.Add(new SplineDoubleKeyFrame(keyFramePosition1.Item2, keyTime1, keySpline));

            // Rotate
            var animationR = new DoubleAnimationUsingKeyFrames() { Duration = timeSpan };
            animationR.FillBehavior = FillBehavior.Stop;
            animationR.KeyFrames.Add(new SplineDoubleKeyFrame(keyFramePosition1.Item3, keyTime1, keySpline));

            // 绑定动画
            Storyboard.SetTargetName(animationX, cardName);
            Storyboard.SetTargetName(animationY, cardName);
            Storyboard.SetTargetName(animationR, cardTransformName);
            Storyboard.SetTargetProperty(animationX, new PropertyPath(Canvas.TopProperty));
            Storyboard.SetTargetProperty(animationY, new PropertyPath(Canvas.LeftProperty));
            Storyboard.SetTargetProperty(animationR, new PropertyPath(RotateTransform.AngleProperty));

            Storyboard storyboard1 = new Storyboard();
            storyboard1.Children.Add(animationX);
            storyboard1.Children.Add(animationY);
            storyboard1.Children.Add(animationR);

            // 获取用户牌位置
            var viewCardSlot = ViewHelper.FindChild<Border>(userDeck.canvas, "cardSlot" + cardSlotNumber);
            var viewCardSlotRender = (RotateTransform)userDeck.FindName("cardSlotRotateAngle" + cardSlotNumber);
            var keyFramePosition2 =
                new Tuple<double, double, double>(Canvas.GetTop(viewCardSlot), Canvas.GetLeft(viewCardSlot), viewCardSlotRender.Angle);

            Console.WriteLine(keyFramePosition2);

            var animationXs = new DoubleAnimationUsingKeyFrames() { Duration = timeSpan };
            animationXs.FillBehavior = FillBehavior.Stop;
            animationXs.KeyFrames.Add(new SplineDoubleKeyFrame(keyFramePosition2.Item1, keyTime1, keySpline));
            var animationYs = new DoubleAnimationUsingKeyFrames() { Duration = timeSpan };
            animationYs.FillBehavior = FillBehavior.Stop;
            animationYs.KeyFrames.Add(new SplineDoubleKeyFrame(keyFramePosition2.Item2, keyTime1, keySpline));
            var animationRs = new DoubleAnimationUsingKeyFrames() { Duration = timeSpan };
            animationRs.FillBehavior = FillBehavior.Stop;
            animationRs.KeyFrames.Add(new SplineDoubleKeyFrame(keyFramePosition2.Item3, keyTime1, keySpline));

            Storyboard.SetTargetName(animationXs, cardName);
            Storyboard.SetTargetName(animationYs, cardName);
            Storyboard.SetTargetName(animationRs, cardTransformName);
            Storyboard.SetTargetProperty(animationXs, new PropertyPath(Canvas.TopProperty));
            Storyboard.SetTargetProperty(animationYs, new PropertyPath(Canvas.LeftProperty));
            Storyboard.SetTargetProperty(animationRs, new PropertyPath(RotateTransform.AngleProperty));

            Storyboard storyboard2 = new Storyboard();
            storyboard2.Children.Add(animationXs);
            storyboard2.Children.Add(animationYs);
            storyboard2.Children.Add(animationRs);

            int cardLoadCount = 0;
            viewCard.Loaded += delegate (object sender, RoutedEventArgs e)
            {
                switch (cardLoadCount)
                {
                    case 0:
                        Console.WriteLine("animation " + animationCount + "start");
                        storyboard1.Begin(this);
                        animationLock.Status = Card.StatusEnum.Invisible;

                        Console.WriteLine(animationCount + " lock release");
                        break;
                    case 1:
                        storyboard2.Begin(this);
                        break;
                    default:
                        break;
                }
                cardLoadCount++;            
            };
            storyboard1.Completed += delegate (object sender, EventArgs e)
            {
                Canvas.SetLeft(viewCard, 0);
                Canvas.SetTop(viewCard, 0);
                cardTransform.Angle = 0;
                viewCard.RenderTransform = cardTransform;
                if (cardSlotNumber < 6) viewCard.RenderTransformOrigin = new Point(0, 1.5);
                else viewCard.RenderTransformOrigin = new Point(0, 1);

                // 将牌送入用户牌堆
                canvas.Children.Remove(viewCard);
                userDeck.canvas.Children.Add(viewCard);                          
            };
            storyboard2.Completed += delegate (object senders, EventArgs es)
            {
                Canvas.SetLeft(viewCard, 0);
                Canvas.SetTop(viewCard, 0);                
                cardTransform.Angle = 0;
                viewCard.RenderTransform = cardTransform;
                userDeck.canvas.Children.Remove(viewCard);

                viewCardSlot.Child = viewCard;
                viewCardSlot.Visibility = Visibility.Visible;

                Console.WriteLine("animation " + animationCount + "finish");

                animationCount--;
                if(animationQueue.Count > 0)
                    HandleDealCardEvent(animationQueue.Dequeue());
                if (animationCount == 0)
                {
                    HandleAnimations(room.Next());
                    if (room.CurrentPlayerIsYou)
                    {
                        chooseWantCardPanel.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        chooseWantCardPanel.Visibility = Visibility.Hidden;
                    }
                }
            };            
        }
 public void headhunterGetNotifiedFromCompanyHandler(object sender, Tuple<string, string, int> data)
 {
     Console.WriteLine($"I'm {Name} HeadHunter. I received {(sender as Company).Name} notification.");
     headhunterNotifyPerson((sender as Company).Name, data.Item1, data.Item2,data.Item3);
 }
Ejemplo n.º 53
0
 public bool TryGetVariableInLocalScope(string name, out Variable variable)
 {
     return globalVariables.TryGetValue(name, out variable) || localVariables.TryGetValue(Tuple.Create(CurrentScope, name), out variable);
 }
        public override Tuple <List <AccountBank>, int, Dictionary <string, string>, List <string> > ReadModel(int Page = 1, int Size = 25, string Order = "{}", List <string> Select = null, string Keyword = null, string Filter = "{}")
        {
            IQueryable <AccountBank> Query = this.DbContext.AccountBanks;

            Dictionary <string, object> FilterDictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(Filter);

            Query = ConfigureFilter(Query, FilterDictionary);

            Dictionary <string, string> OrderDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(Order);

            /* Search With Keyword */
            if (Keyword != null)
            {
                List <string> SearchAttributes = new List <string>()
                {
                    "BankName", "BankAddress", "AccountName", "AccountNumber", "BankCode"
                };

                Query = Query.Where(General.BuildSearch(SearchAttributes), Keyword);
            }

            /* Const Select */
            List <string> SelectedFields = new List <string>()
            {
                "Id", "Code", "BankCode", "BankName", "BankAddress", "AccountName", "AccountNumber", "SwiftCode", "Currency", "Division", "AccountCOA"
            };

            Query = Query
                    .Select(a => new AccountBank
            {
                Id               = a.Id,
                Code             = a.Code,
                BankCode         = a.BankCode,
                BankName         = a.BankName,
                BankAddress      = a.BankAddress,
                AccountName      = a.AccountName,
                AccountNumber    = a.AccountNumber,
                SwiftCode        = a.SwiftCode,
                CurrencyId       = a.CurrencyId,
                CurrencyCode     = a.CurrencyCode,
                DivisionCode     = a.DivisionCode,
                DivisionId       = a.DivisionId,
                DivisionName     = a.DivisionName,
                _LastModifiedUtc = a._LastModifiedUtc,
                AccountCOA       = a.AccountCOA
            });

            /* Order */
            if (OrderDictionary.Count.Equals(0))
            {
                OrderDictionary.Add("_LastModifiedUtc", General.DESCENDING);

                Query = Query.OrderByDescending(b => b._LastModifiedUtc); /* Default Order */
            }
            else
            {
                string Key          = OrderDictionary.Keys.First();
                string OrderType    = OrderDictionary[Key];
                string TransformKey = General.TransformOrderBy(Key);

                BindingFlags IgnoreCase = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;

                Query = OrderType.Equals(General.ASCENDING) ?
                        Query.OrderBy(b => b.GetType().GetProperty(TransformKey, IgnoreCase).GetValue(b)) :
                        Query.OrderByDescending(b => b.GetType().GetProperty(TransformKey, IgnoreCase).GetValue(b));
            }

            /* Pagination */
            Pageable <AccountBank> pageable = new Pageable <AccountBank>(Query, Page - 1, Size);
            List <AccountBank>     Data     = pageable.Data.ToList <AccountBank>();

            int TotalData = pageable.TotalCount;

            return(Tuple.Create(Data, TotalData, OrderDictionary, SelectedFields));
        }
Ejemplo n.º 55
0
        private void Button_Tapped_Spin(object sender, TappedRoutedEventArgs e)
        {
            Tuple <int, int> result = SpinCalculator.run(8);

            spin(result.Item1);
        }
Ejemplo n.º 56
0
 public bool TryGetVariableFromReference(ReferenceValue reference, out Variable variable)
 {
     return globalVariables.TryGetValue(reference.Value, out variable) || 
                           localVariables.TryGetValue(Tuple.Create(reference.Scope, reference.Value), out variable);
 }
Ejemplo n.º 57
0
        private int BuildSummaryTable()
        {
            var rb = sheet.Cells[1, "B"] as ExcelInterop.Range;

            rb.ColumnWidth = 10;
            Utility.AddNativieResource(rb);
            var rc = sheet.Cells[1, "C"] as ExcelInterop.Range;

            rc.ColumnWidth = 20;
            Utility.AddNativieResource(rc);

            string[,] cols = new string[, ]
            {
                { "分类", "个数", "占比", "说明" },
                { "已完成数", "", "", "已完成数:【已发布】及【已完成】状态的、或者根据验收标准已完成的Backlog总数\r\n占比:已完成数 / 本迭代计划总数" },
                { "进行中数", "", "", "进行中数:本迭代计划总数-已完成数-未启动数-中止/移除数\r\n占比:进行中数 / 本迭代计划总数" },
                { "未启动数", "", "", "未启动数:【已承诺】、【新建】、【已批准】、【提交评审】状态的Backlog总数\r\n占比:未启动数 / 本迭代计划总数" },
                { "拖期数", "", "", "拖期数:本迭代计划总数-已完成数-中止数/移除数\r\n占比:拖期数 / 本迭代计划总数" },
                { "中止/移除数", "", "", "中止/移除数:本迭代已中止或已移除的Backlog总数\r\n占比:移除数 / 本迭代计划总数" },
                { "本迭代计划总数", "", "", "本迭代规划的所有backlog总数(包括当前已经被移除、中止的)" },
            };
            List <Tuple <string, string> > colsname = new List <Tuple <string, string> >()
            {
                Tuple.Create <string, string>("B", "C"),
                Tuple.Create <string, string>("D", "D"),
                Tuple.Create <string, string>("E", "E"),
                Tuple.Create <string, string>("F", "M"),
            };

            for (int row = 0; row < cols.GetLength(0); row++)
            {
                for (int col = 0; col < colsname.Count; col++)
                {
                    ExcelInterop.Range colRange = sheet.Range[sheet.Cells[6 + row, colsname[col].Item1], sheet.Cells[6 + row, colsname[col].Item2]];
                    Utility.AddNativieResource(colRange);
                    colRange.RowHeight = 40;
                    colRange.Merge();
                    sheet.Cells[6 + row, colsname[col].Item1] = cols[row, col];

                    var border = colRange.Borders;
                    Utility.AddNativieResource(border);
                    border.LineStyle = ExcelInterop.XlLineStyle.xlContinuous;

                    if (col == 3)
                    {
                        colRange.ColumnWidth = 12;
                    }
                }
            }

            BuildSummaryTableTitle();

            sheet.Cells[7, "D"]  = this.backlogList[0].Count;
            sheet.Cells[7, "E"]  = "=IF(D7<>0,D7/$D$12,\"\")";
            sheet.Cells[8, "D"]  = "=D12-D7-D9-D11";
            sheet.Cells[8, "E"]  = "=IF(D8<>0,D8/$D$12,\"\")";
            sheet.Cells[9, "D"]  = this.backlogList[1].Count;
            sheet.Cells[9, "E"]  = "=IF(D9<>0,D9/$D$12,\"\")";
            sheet.Cells[10, "D"] = "=D12-D7-D11";
            sheet.Cells[10, "E"] = "=IF(D10<>0,D10/$D$12,\"\")";
            sheet.Cells[11, "D"] = this.backlogList[2].Count;
            sheet.Cells[11, "E"] = "=IF(D11<>0,D11/$D$12,\"\")";
            sheet.Cells[12, "D"] = this.backlogList[3].Count;
            sheet.Cells[12, "E"] = "'--";
            //sheet.Cells[13, "D"] = this.backlogList[4].Count;
            //sheet.Cells[13, "E"] = "=IF(D13<>0,D13/$D$16,\"\")";
            //sheet.Cells[14, "D"] = this.backlogList[5].Count;
            //sheet.Cells[14, "E"] = "=IF(D14<>0,D14/$D$16,\"\")";
            //sheet.Cells[15, "D"] = "=D16-D14";
            //sheet.Cells[15, "E"] = "=IF(D15<>0,D15/$D$16,\"\")";
            //sheet.Cells[16, "D"] = this.backlogList[6].Count;
            //sheet.Cells[16, "E"] = "'--";

            Utility.SetCellPercentFormat(sheet.get_Range("E7:E12"));
            Utility.SetCellGreenColor(sheet.get_Range("E7:E12"));
            Utility.SetCellGreenColor(sheet.get_Range("D8:D8"));
            Utility.SetCellGreenColor(sheet.get_Range("D10:D10"));
            //Utility.SetCellGreenColor(sheet.get_Range("D15:D15"));

            sheet.Cells[7, "D"]  = this.backlogList[0].Count;
            sheet.Cells[9, "D"]  = this.backlogList[1].Count;
            sheet.Cells[11, "D"] = this.backlogList[2].Count;
            sheet.Cells[12, "D"] = this.backlogList[3].Count;
            //sheet.Cells[13, "D"] = this.backlogList[4].Count;
            //sheet.Cells[14, "D"] = this.backlogList[5].Count;
            //sheet.Cells[16, "D"] = this.backlogList[6].Count;

            Utility.SetFormatBigger(sheet.Cells[10, "D"], 0.0001d);
            Utility.SetFormatBigger(sheet.Cells[11, "D"], 0.0001d);
            Utility.SetFormatBigger(sheet.Cells[15, "D"], 0.0001d);
            return(14);
        }
Ejemplo n.º 58
0
        public AuthorizationModule()
        {
            Get["/connect/authorize", runAsync : true] = async(parameters, cancellationToken) => {
                this.CreateNewCsrfToken();
                this.RequiresMSOwinAuthentication();

                // Note: when a fatal error occurs during the request processing, an OpenID Connect response
                // is prematurely forged and added to the ASP.NET context by OpenIdConnectServerHandler.
                // You can safely remove this part and let ASOS automatically handle the unrecoverable errors
                // by switching ApplicationCanDisplayErrors to false in Startup.cs.
                var response = OwinContext.GetOpenIdConnectResponse();
                if (response != null)
                {
                    return(View["Error.cshtml", response]);
                }

                // Extract the authorization request from the OWIN environment.
                var request = OwinContext.GetOpenIdConnectRequest();
                if (request == null)
                {
                    return(View["Error.cshtml", new OpenIdConnectMessage {
                                    Error = "invalid_request",
                                    ErrorDescription = "An internal error has occurred"
                                }]);
                }

                // Note: ASOS automatically ensures that an application corresponds to the client_id specified
                // in the authorization request by calling IOpenIdConnectServerProvider.ValidateAuthorizationRequest.
                // In theory, this null check shouldn't be needed, but a race condition could occur if you
                // manually removed the application details from the database after the initial check made by ASOS.
                var application = await GetApplicationAsync(request.ClientId, cancellationToken);

                if (application == null)
                {
                    return(View["Error.cshtml", new OpenIdConnectMessage {
                                    Error = "invalid_client",
                                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                                }]);
                }

                // Note: in a real world application, you'd probably
                // prefer creating a specific view model.
                return(View["Authorize.cshtml", new { Application = application, Request = request }]);
            };

            Post["/connect/authorize/accept", runAsync : true] = async(parameters, cancellationToken) => {
                this.RequiresMSOwinAuthentication();
                this.ValidateCsrfToken();

                var response = OwinContext.GetOpenIdConnectResponse();
                if (response != null)
                {
                    return(View["Error.cshtml", response]);
                }

                var request = OwinContext.GetOpenIdConnectRequest();
                if (request == null)
                {
                    return(View["Error.cshtml", new OpenIdConnectMessage {
                                    Error = "invalid_request",
                                    ErrorDescription = "An internal error has occurred"
                                }]);
                }

                // Create a new ClaimsIdentity containing the claims that
                // will be used to create an id_token, a token or a code.
                var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationType);

                foreach (var claim in OwinContext.Authentication.User.Claims)
                {
                    // Allow ClaimTypes.Name to be added in the id_token.
                    // ClaimTypes.NameIdentifier is automatically added, even if its
                    // destination is not defined or doesn't include "id_token".
                    // The other claims won't be visible for the client application.
                    if (claim.Type == ClaimTypes.Name)
                    {
                        claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                              OpenIdConnectConstants.Destinations.IdentityToken);
                    }

                    identity.AddClaim(claim);
                }

                var application = await GetApplicationAsync(request.ClientId, CancellationToken.None);

                if (application == null)
                {
                    return(View["Error.cshtml", new OpenIdConnectMessage {
                                    Error = "invalid_client",
                                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                                }]);
                }

                // Create a new ClaimsIdentity containing the claims associated with the application.
                // Note: setting identity.Actor is not mandatory but can be useful to access
                // the whole delegation chain from the resource server (see ResourceModule.cs).
                identity.Actor = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationType);
                identity.Actor.AddClaim(ClaimTypes.NameIdentifier, application.ApplicationID);

                identity.Actor.AddClaim(ClaimTypes.Name, application.DisplayName,
                                        OpenIdConnectConstants.Destinations.AccessToken,
                                        OpenIdConnectConstants.Destinations.IdentityToken);

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

                // Set the list of scopes granted to the client application.
                // Note: this sample always grants the "openid", "email" and "profile" scopes
                // when they are requested by the client application: a real world application
                // would probably display a form allowing to select the scopes to grant.
                ticket.SetScopes(new[] {
                    /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                    /* email: */ OpenIdConnectConstants.Scopes.Email,
                    /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                    /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess
                }.Intersect(request.GetScopes()));

                // Set the resources servers the access token should be issued for.
                ticket.SetResources("resource_server");

                // This call will ask ASOS to serialize the specified identity to build appropriate tokens.
                // Note: you should always make sure the identities you return contain ClaimTypes.NameIdentifier claim.
                // In this sample, the identity always contains the name identifier returned by the external provider.
                OwinContext.Authentication.SignIn(ticket.Properties, ticket.Identity);

                return(HttpStatusCode.OK);
            };

            Post["/connect/authorize/deny"] = parameters => {
                this.RequiresMSOwinAuthentication();
                this.ValidateCsrfToken();

                var response = OwinContext.GetOpenIdConnectResponse();
                if (response != null)
                {
                    return(View["Error.cshtml", response]);
                }

                // Extract the authorization request from the cache, the query string or the request form.
                var request = OwinContext.GetOpenIdConnectRequest();
                if (request == null)
                {
                    return(View["Error.cshtml", new OpenIdConnectMessage {
                                    Error = "invalid_request",
                                    ErrorDescription = "An internal error has occurred"
                                }]);
                }

                // Notify ASOS that the authorization grant has been denied by the resource owner.
                // Note: OpenIdConnectServerHandler will automatically take care of redirecting
                // the user agent to the client application using the appropriate response_mode.
                OwinContext.Authentication.Forbid(OpenIdConnectServerDefaults.AuthenticationType);

                return(HttpStatusCode.Forbidden);
            };

            Get["/connect/logout", runAsync : true] = async(parameters, cancellationToken) => {
                var response = OwinContext.GetOpenIdConnectResponse();
                if (response != null)
                {
                    return(View["Error.cshtml", response]);
                }

                // When invoked, the logout endpoint might receive an unauthenticated request if the server cookie has expired.
                // When the client application sends an id_token_hint parameter, the corresponding identity can be retrieved
                // using AuthenticateAsync or using User when the authorization server is declared as AuthenticationMode.Active.
                var identity = await OwinContext.Authentication.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationType);

                // Extract the logout request from the OWIN environment.
                var request = OwinContext.GetOpenIdConnectRequest();
                if (request == null)
                {
                    return(View["Error.cshtml", new OpenIdConnectMessage {
                                    Error = "invalid_request",
                                    ErrorDescription = "An internal error has occurred"
                                }]);
                }

                return(View["Logout.cshtml", Tuple.Create(request, identity)]);
            };

            Post["/connect/logout"] = parameters => {
                this.ValidateCsrfToken();

                var response = OwinContext.GetOpenIdConnectResponse();
                if (response != null)
                {
                    return(View["Error.cshtml", response]);
                }

                // Ask the cookies middleware to delete the local cookie created
                // when the user agent is redirected from the external identity provider
                // after a successful authentication flow (e.g Google or Facebook) and
                // redirect the user agent to the post_logout_redirect_uri specified by the client application.
                OwinContext.Authentication.SignOut("ServerCookie", OpenIdConnectServerDefaults.AuthenticationType);

                return(HttpStatusCode.OK);
            };
        }
Ejemplo n.º 59
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resultCode"></param>
        /// <returns>Tuple with Item1: result code message and Item2: errorMessage</returns>
        public static Tuple <string, string> StatusCodeToMessage(int resultCode)
        {
            var resultCodeMessage = "";
            var errorMessage      = "";


            switch (resultCode)
            {
            case 0:
                resultCodeMessage = resultCode + " (OK)";
                errorMessage      =
                    "";
                break;

            case 1:
                resultCodeMessage = resultCode + " (REQUIRES_MANUAL_REVIEW)";
                errorMessage      =
                    "Request performed successfully but requires manual review from merchant. Applicable PaymentMethod: PAYPAL.";
                break;

            case 100:
                resultCodeMessage = resultCode + " (INTERNAL_ERROR)";
                errorMessage      = "Invalid – contact integrator.";
                break;

            case 101:
                resultCodeMessage = resultCode + " (XMLPARSEFAIL)";
                errorMessage      = "Invalid XML.";
                break;

            case 102:
                resultCodeMessage = resultCode + " (ILLEGAL_ENCODING)";
                errorMessage      = "Invalid encoding.";
                break;

            case 104:
                resultCodeMessage = resultCode + " (ILLEGAL_URL)";
                errorMessage      = "Illegal Url.";
                break;

            case 105:
                resultCodeMessage = resultCode + " (ILLEGAL_TRANSACTIONSTATUS)";
                errorMessage      = "Invalid transaction status.";
                break;

            case 106:
                resultCodeMessage = resultCode + " (EXTERNAL_ERROR)";
                errorMessage      = "Failure at third party e.g. failure at the bank.";
                break;

            case 107:
                resultCodeMessage = resultCode + " (DENIED_BY_BANK)";
                errorMessage      = "Transaction rejected by bank.";
                break;

            case 108:
                resultCodeMessage = resultCode + " (CANCELLED)";
                errorMessage      = "Transaction cancelled.";
                break;

            case 109:
                resultCodeMessage = resultCode + " (NOT_FOUND_AT_BANK)";
                errorMessage      = "Transaction not found at the bank.";
                break;

            case 110:
                resultCodeMessage = resultCode + " (ILLEGAL_TRANSACTIONID)";
                errorMessage      = "Invalid transaction ID.";
                break;

            case 111:
                resultCodeMessage = resultCode + " (MERCHANT_NOT_CONFIGURED)";
                errorMessage      = "Merchant not configured.";
                break;

            case 112:
                resultCodeMessage = resultCode + " (MERCHANT_NOT_CONFIGURED_AT_BANK)";
                errorMessage      = "Merchant not configured at the bank.";
                break;

            case 113:
                resultCodeMessage = resultCode + " (PAYMENTMETHOD_NOT_CONFIGURED)";
                errorMessage      = "Payment method not configured for merchant.";
                break;

            case 114:
                resultCodeMessage = resultCode + " (TIMEOUT_AT_BANK)";
                errorMessage      = "Timeout at the bank.";
                break;

            case 115:
                resultCodeMessage = resultCode + " (MERCHANT_NOT_ACTIVE)";
                errorMessage      = "The merchant is disabled.";
                break;

            case 116:
                resultCodeMessage = resultCode + " (PAYMENTMETHOD_NOT_ACTIVE)";
                errorMessage      = "The payment method is disabled.";
                break;

            case 117:
                resultCodeMessage = resultCode + " (ILLEGAL_AUTHORIZED_AMOUNT)";
                errorMessage      = "Invalid authorized amount.";
                break;

            case 118:
                resultCodeMessage = resultCode + " (ILLEGAL_CAPTURED_AMOUNT)";
                errorMessage      = "Invalid captured amount.";
                break;

            case 119:
                resultCodeMessage = resultCode + " (ILLEGAL_CREDITED_AMOUNT)";
                errorMessage      = "Invalid credited amount.";
                break;

            case 120:
                resultCodeMessage = resultCode + " (NOT_SUFFICIENT_FUNDS)";
                errorMessage      = "Not enough founds.";
                break;

            case 121:
                resultCodeMessage = resultCode + " (EXPIRED_CARD)";
                errorMessage      = "The card has expired.";
                break;

            case 122:
                resultCodeMessage = resultCode + " (STOLEN_CARD)";
                errorMessage      = "Stolen card.";
                break;

            case 123:
                resultCodeMessage = resultCode + " (LOST_CARD)";
                errorMessage      = "Lost card.";
                break;

            case 124:
                resultCodeMessage = resultCode + " (EXCEEDS_AMOUNT_LIMIT)";
                errorMessage      = "Amount exceeds the limit.";
                break;

            case 125:
                resultCodeMessage = resultCode + " (EXCEEDS_FREQUENCY_LIMIT)";
                errorMessage      = "Frequency limit exceeded.";
                break;

            case 126:
                resultCodeMessage = resultCode + " (TRANSACTION_NOT_BELONGING_TO_MERCHANT)";
                errorMessage      = "Transaction does not belong to merchant.";
                break;

            case 127:
                resultCodeMessage = resultCode + " (CUSTOMERREFNO_ALREADY_USED)";
                errorMessage      = "Customer reference number already used in another transaction.";
                break;

            case 128:
                resultCodeMessage = resultCode + " (NO_SUCH_TRANS)";
                errorMessage      = "Transaction does not exist.";
                break;

            case 129:
                resultCodeMessage = resultCode + " (DUPLICATE_TRANSACTION)";
                errorMessage      = "More than one transaction found for the given customer reference number.";
                break;

            case 130:
                resultCodeMessage = resultCode + " (ILLEGAL_OPERATION)";
                errorMessage      = "Operation not allowed for the given payment method.";
                break;

            case 131:
                resultCodeMessage = resultCode + " (COMPANY_NOT_ACTIVE)";
                errorMessage      = "Company inactive.";
                break;

            case 132:
                resultCodeMessage = resultCode + " (SUBSCRIPTION_NOT_FOUND)";
                errorMessage      = "No subscription exist.";
                break;

            case 133:
                resultCodeMessage = resultCode + " (SUBSCRIPTION_NOT_ACTIVE)";
                errorMessage      = "Subscription not active.";
                break;

            case 134:
                resultCodeMessage = resultCode + " (SUBSCRIPTION_NOT_SUPPORTED)";
                errorMessage      = "Payment method doesn’t support subscriptions.";
                break;

            case 135:
                resultCodeMessage = resultCode + " (ILLEGAL_DATE_FORMAT)";
                errorMessage      = "Illegal date format.";
                break;

            case 136:
                resultCodeMessage = resultCode + " (ILLEGAL_RESPONSE_DATA)";
                errorMessage      = "Illegal response data.";
                break;

            case 137:
                resultCodeMessage = resultCode + " (IGNORE_CALLBACK)";
                errorMessage      = "Ignore callback.";
                break;

            case 138:
                resultCodeMessage = resultCode + " (CURRENCY_NOT_CONFIGURED)";
                errorMessage      = "Currency not configured.";
                break;

            case 139:
                resultCodeMessage = resultCode + " (CURRENCY_NOT_ACTIVE)";
                errorMessage      = "Currency not active.";
                break;

            case 140:
                resultCodeMessage = resultCode + " (CURRENCY_ALREADY_CONFIGURED)";
                errorMessage      = "Currency is already configured.";
                break;

            case 141:
                resultCodeMessage = resultCode + " (ILLEGAL_AMOUNT_OF_RECURS_TODAY)";
                errorMessage      = "Ilegal amount of recurs per day.";
                break;

            case 142:
                resultCodeMessage = resultCode + " (NO_VALID_PAYMENT_METHODS)";
                errorMessage      = "No valid PaymentMethod.";
                break;

            case 143:
                resultCodeMessage = resultCode + " (CREDIT_DENIED_BY_BANK)";
                errorMessage      = "Credit denied by bank.";
                break;

            case 144:
                resultCodeMessage = resultCode + " (ILLEGAL_CREDIT_USER)";
                errorMessage      = "User is not allowed to perform credit operation.";
                break;

            case 300:
                resultCodeMessage = resultCode + " (BAD_CARDHOLDER_NAME)";
                errorMessage      = "Invalid value for cardholder name.";
                break;

            case 301:
                resultCodeMessage = resultCode + " (BAD_TRANSACTION_ID)";
                errorMessage      = "Invalid value for transaction id.";
                break;

            case 302:
                resultCodeMessage = resultCode + " (BAD_REV)";
                errorMessage      = "Invalid value for rev.";
                break;

            case 303:
                resultCodeMessage = resultCode + " (BAD_MERCHANT_ID)";
                errorMessage      = "nvalid value for merchant id.";
                break;

            case 304:
                resultCodeMessage = resultCode + " (BAD_LANG)";
                errorMessage      = "Invalid value for lang.";
                break;

            case 305:
                resultCodeMessage = resultCode + " (BAD_AMOUNT)";
                errorMessage      = "Invalid value for amount.";
                break;

            case 306:
                resultCodeMessage = resultCode + " (BAD_CUSTOMERREFNO)";
                errorMessage      = "Invalid value for customer refno.";
                break;

            case 307:
                resultCodeMessage = resultCode + " (BAD_CURRENCY)";
                errorMessage      = "Invalid value for currency.";
                break;

            case 308:
                resultCodeMessage = resultCode + " (BAD_PAYMENTMETHOD)";
                errorMessage      = "Invalid value for payment method.";
                break;

            case 309:
                resultCodeMessage = resultCode + " (BAD_RETURNURL)";
                errorMessage      = "Invalid value for return url.";
                break;

            case 310:
                resultCodeMessage = resultCode + " (BAD_LASTBOOKINGDAY)";
                errorMessage      = "Invalid value for last booking day.";
                break;

            case 311:
                resultCodeMessage = resultCode + " (BAD_MAC)";
                errorMessage      = "Invalid value for mac.";
                break;

            case 312:
                resultCodeMessage = resultCode + " (BAD_TRNUMBER)";
                errorMessage      = "Invalid value for tr number.";
                break;

            case 313:
                resultCodeMessage = resultCode + " (BAD_AUTHCODE)";
                errorMessage      = "Invalid value for authcode.";
                break;

            case 314:
                resultCodeMessage = resultCode + " (BAD_CC_DESCR)";
                errorMessage      = "Invalid value for cc_descr.";
                break;

            case 315:
                resultCodeMessage = resultCode + " (BAD_ERROR_CODE)";
                errorMessage      = "Invalid value for error_code.";
                break;

            case 316:
                resultCodeMessage = resultCode + " (BAD_CARDNUMBER_OR_CARDTYPE_NOT_CONFIGURED)";
                errorMessage      = "Card type not configured for merchant.";
                break;

            case 317:
                resultCodeMessage = resultCode + " (BAD_SSN)";
                errorMessage      = "Invalid value for ssn.";
                break;

            case 318:
                resultCodeMessage = resultCode + " (BAD_VAT)";
                errorMessage      = "Invalid value for vat.";
                break;

            case 319:
                resultCodeMessage = resultCode + " (BAD_CAPTURE_DATE)";
                errorMessage      = "Invalid value for capture date.";
                break;

            case 320:
                resultCodeMessage = resultCode + " (BAD_CAMPAIGN_CODE_INVALID)";
                errorMessage      = "Invalid value for campaign code. There are no valid matching campaign codes.";
                break;

            case 321:
                resultCodeMessage = resultCode + " (BAD_SUBSCRIPTION_TYPE)";
                errorMessage      = "Invalid subscription type.";
                break;

            case 322:
                resultCodeMessage = resultCode + " (BAD_SUBSCRIPTION_ID)";
                errorMessage      = "Invalid subscription id.";
                break;

            case 323:
                resultCodeMessage = resultCode + " (BAD_BASE64)";
                errorMessage      = "Invalid base64.";
                break;

            case 324:
                resultCodeMessage = resultCode + " (BAD_CAMPAIGN_CODE)";
                errorMessage      = "Invalid campaign code. Missing value.";
                break;

            case 325:
                resultCodeMessage = resultCode + " (BAD_CALLBACKURL)";
                errorMessage      = "Invalid callbackurl.";
                break;

            case 326:
                resultCodeMessage = resultCode + " (THREE_D_CHECK_FAILED)";
                errorMessage      = "3D check failed.";
                break;

            case 327:
                resultCodeMessage = resultCode + " (CARD_NOT_ENROLLED)";
                errorMessage      = "Card not enrolled in 3D secure.";
                break;

            case 328:
                resultCodeMessage = resultCode + " (BAD_IPADDRESS)";
                errorMessage      = "Provided ip address is incorrect.";
                break;

            case 329:
                resultCodeMessage = resultCode + " (BAD_MOBILE)";
                errorMessage      = "Bad mobile phone number.";
                break;

            case 330:
                resultCodeMessage = resultCode + " (BAD_COUNTRY)";
                errorMessage      = "Bad country parameter.";
                break;

            case 331:
                resultCodeMessage = resultCode + " (THREE_D_CHECK_NOT_AVAILABLE)";
                errorMessage      = "Merchants 3D configuration invalid.";
                break;

            case 332:
                resultCodeMessage = resultCode + " (TIMEOUT)";
                errorMessage      = "Timeout at Svea.";
                break;

            case 500:
                resultCodeMessage = resultCode + " (ANTIFRAUD_CARDBIN_NOT_ALLOWED)";
                errorMessage      = "Antifraud - cardbin not allowed.";
                break;

            case 501:
                resultCodeMessage = resultCode + " (ANTIFRAUD_IPLOCATION_NOT_ALLOWED)";
                errorMessage      = "Antifraud – iplocation not allowed.";
                break;

            case 502:
                resultCodeMessage = resultCode + " (ANTIFRAUD_IPLOCATION_AND_BIN_DOESNT_MATCH)";
                errorMessage      = "Antifraud – ip-location and bin does not match.";
                break;

            case 503:
                resultCodeMessage = resultCode + " (ANTIFRAUD_MAX_AMOUNT_PER_IP_EXCEEDED)";
                errorMessage      = "Antofraud – max amount per ip exceeded.";
                break;

            case 504:
                resultCodeMessage = resultCode + " (ANTIFRAUD_MAX_TRANSACTIONS_PER_IP_EXCEEDED)";
                errorMessage      = "Antifraud – max transactions per ip exceeded.";
                break;

            case 505:
                resultCodeMessage = resultCode + " (ANTIFRAUD_MAX_TRANSACTIONS_PER_CARDNO_EXCEEDED)";
                errorMessage      = "Antifraud – max transactions per card number exceeded.";
                break;

            case 506:
                resultCodeMessage = resultCode + " (ANTIFRAUD_MAX_AMOUNT_PER_CARDNO_EXCEEDED)";
                errorMessage      = "Antifraud – max amount per cardnumer exceeded.";
                break;

            case 507:
                resultCodeMessage = resultCode + " (ANTIFRAUD_IP_ADDRESS_BLOCKED)";
                errorMessage      = "Antifraud – IP address blocked.";
                break;

            default:
                resultCodeMessage = resultCode + " (UNKNOWN_ERROR)";
                errorMessage      = "Unknown error.";
                break;
            }

            Tuple <string, string> resultTuple = new Tuple <string, string>(resultCodeMessage, errorMessage);

            return(resultTuple);
        }
Ejemplo n.º 60
0
 /// <summary>
 /// Partitions sum into groups with max elements per group.
 /// </summary>
 /// <param name="this"></param>
 /// <param name="partitionSize"></param>
 /// <returns></returns>
 internal static IEnumerable <Tuple <int, int> > PartitionSum(this int @this, NonZeroInt partitionSize) =>
 Enumerable.Range(0, @this)
 .GroupBy(index => index / partitionSize.IntValue)
 .Select(index => Tuple.Create(index.Key, index.Count()));