private async Task<Deck> ImportDeckFromWeb()
		{
			var settings = new MetroDialogSettings();
			var clipboard = Clipboard.GetText();
			var validUrls = new[]
				{
					"hearthstats", "hss.io", "hearthpwn", "hearthhead", "hearthstoneplayers", "tempostorm",
					"hearthstonetopdeck", "hearthnews.fr", "arenavalue", "hearthstone-decks"
				};
			if(validUrls.Any(clipboard.Contains))
				settings.DefaultText = clipboard;

			//import dialog
			var url = await this.ShowInputAsync("Import deck", "Supported websites:\n" + validUrls.Aggregate((x, next) => x + ", " + next), settings);
			if(string.IsNullOrEmpty(url))
				return null;

			var controller = await this.ShowProgressAsync("Loading Deck...", "please wait");

			//var deck = await this._deckImporter.Import(url);
			var deck = await DeckImporter.Import(url);
			deck.Url = url;

			await controller.CloseAsync();
			return deck;
		}
Example #2
0
        public override BaseResult VerifyCallBack(HttpRequest request)
        {
            var result = new YeepayResult();
            //var coll = (string.IsNullOrEmpty(request.Form["r6_Order"]) ? request.QueryString : request.Form);
            var list = Decode(request);
            result.TradeNum = list["r6_Order"];
            result.Amount = Convert.ToDecimal(list["r3_Amt"]);
            result.NeedResponse = (list["r9_BType"] == "2");
            result.Code = list["r1_Code"];

            result.PayDate = Utils.StrToDate(list["rp_PayDate"], DateTime.Now);
            result.TrxId = list["r2_TrxId"];
            if (result.Code != "1")
            {
                result.State = false;
                result.ErrMsg = "支付状态失败!";
                return result;
            }
            var qs = new[]
                         {
                             "p1_MerId", "r0_Cmd", "r1_Code", "r2_TrxId", "r3_Amt", "r4_Cur", "r5_Pid", "r6_Order",
                             "r7_Uid", "r8_MP", "r9_BType"
                         };
            var nhmac = qs.Aggregate("", (current, t) => current + list[t]);
            var ourSign = Digest.HmacSign(nhmac, Configs.GetKey());
            var sign = list["hmac"];
            if (sign != ourSign)
            {
                result.State = false;
                result.ErrMsg = string.Format("签名验证失败--{0}|{1}", sign, ourSign);
            }
            else
                result.State = true;
            return result;
        }
Example #3
0
            public void FuncIsAppliedToAllElementsInTheSequence()
            {
                var ints = new[] { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
                var numEven = ints.Aggregate(0, (total, next) => next % 2 == 0 ? total + 1 : total);

                Assert.That(numEven, Is.EqualTo(6));
            }
Example #4
0
 public static void LogPublicElements()
 {
     using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"API.csv"))
     {
         foreach (Type type in Assembly.GetAssembly(typeof(World)).GetTypes().Where(t => t.IsPublic))
         {
             if (!type.GetMembers(BindingFlags.Public
                                 | BindingFlags.Instance
                                 | BindingFlags.DeclaredOnly
                                 | BindingFlags.InvokeMethod).Any())
                 continue;
             file.WriteLine(type.Name);
             foreach (ConstructorInfo member in type.GetConstructors())
                 file.WriteLine(";Constructor"+"(" + (member.GetParameters().Any() ? string.Join(", ", member.GetParameters().Select(p => p.ParameterType.Name)) : "")+")");
             foreach (MethodInfo member in type.GetMethods())
             {
                 if (!(new[] { "ToString", "GetHashCode", "Equals", "GetType" }).Contains(member.Name))
                 {
                     if (member.DeclaringType != null && member.DeclaringType.IsInterface)
                     {
                         if(!member.DeclaringType.IsPublic)
                             continue;
                     }
                     var toBeDeleted = new[] { "System.", "Collections.Generic.", "`1", "`2", "Alpha.Core.Realms.", "Alpha.Core.Provinces.", "Alpha.Core.Fleets.", "Alpha.Core.Commands.", "Alpha.Core.Calendars.", "Alpha.Toolkit.Math." };
                     string name = member.ToString();
                     name = toBeDeleted.Aggregate(name, (current, value) => current.Replace(value, string.Empty));
                     name = name.Replace(" ", ";");
                     file.WriteLine(name);
                 }
             }
             file.WriteLine();
         }
     }
 }
        /// <summary>
        /// Masks the username and password from a connection string
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        internal static string RemoveConnectionStringSecurity(this string connectionString)
        {
            var securityQualifiers = new[] { "user", "uid", "password", "pwd", "user id" };

            return securityQualifiers.Aggregate(connectionString, (current, qualifier)
                => Regex.Replace(current, qualifier + "\\s*=([^;]*)(?:$|;)", qualifier + "=********;", RegexOptions.IgnoreCase));
        }
        public static string ToProperUrlEscape(this string stringToEscape)
        {
            if (string.IsNullOrEmpty(stringToEscape))
            {
                return null;
            }

            // URL encoding podľa Microsoftu
            var urlEncode = WebUtility.UrlEncode(stringToEscape);
            if (urlEncode != null)
            {
                var result = urlEncode.Replace("+", "%20");

                // lower-case -> upper-case
                var hexRegex = new Regex("%[0-9a-f]{2}", RegexOptions.IgnoreCase);
                var matches = hexRegex.Matches(result);

                result = matches.Cast<object>()
                    .Aggregate(result, (current, m) => current.Replace(m.ToString(), m.ToString().ToUpper()));

                // C# nekóduje (, ), $, !, * a "
                var notEncodedChars = new[] {"(", ")", "$", "!", "*", "\'"};
                result = notEncodedChars.Aggregate(result,
                    (current, c) => current.Replace(c, string.Format("%{0}", ((int) Convert.ToChar(c)).ToString("X"))));

                // tilda nesmie byť zakódovaná
                result = result.Replace("%7E", "~");

            }
            return string.Empty;
        }
        public static string CleanMsWordHtml(this string html)
        {
            if (string.IsNullOrWhiteSpace(html))
            {
                return html;
            }
            else
            {
                // http://www.codinghorror.com/blog/2006/01/cleaning-words-nasty-html.html
                var sc =
                    new[]
                {
                    @"<!--(\w|\W)+?-->",
                    @"<title>(\w|\W)+?</title>",
                    @"\s?class=\w+",
                    @"\s?class='[^']+'",
                    @"\s?class=""[^""]+""",
                    @"\s+style='[^']+'",
                    @"\s+style=""[^""]+""",
                    @"<(meta|link|/?o:|/?style|/?div|/?st\d|/?head|/?html|body|/?body|/?span|!\[)[^>]*?>",
                    @"(<[^>]+>)+&nbsp;(</\w+>)+",
                    @"\s+v:\w+=""[^""]+""",
                    @"(\n\r){2,}"
                };
                // get rid of unnecessary tag spans (comments and title)
                // Get rid of classes and styles
                // Get rid of unnecessary tags
                // Get rid of empty paragraph tags
                // remove bizarre v: element attached to <img> tag
                // remove extra lines

                return sc.Aggregate(html, (current, s) => Regex.Replace(current, s, String.Empty, RegexOptions.IgnoreCase));
            }
        }
Example #8
0
        public static string Fonetizar(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;

            str = RemoveAcentos(str.ToUpperInvariant());

            if (str.Equals("H"))
            {
                str = "AGA";
            }

            str = SomenteLetras(str);

            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }

            //Eliminar palavras especiais
            str = str.Replace(" LTDA ", " ");

            //Eliminar preposições
            var preposicoes = new[] { " DE ", " DA ", " DO ", " AS ", " OS ", " AO ", " NA ", " NO ", " DOS ", " DAS ", " AOS ", " NAS ", " NOS ", " COM " };
            str = preposicoes.Aggregate(str, (current, preposicao) => current.Replace(preposicao, " "));

            //Converte algarismos romanos para números
            var algRomanos = new[] { " V ", " I ", " IX ", " VI ", " IV ", " II ", " VII ", " III ", " X ", " VIII " };
            var numeros = new[] { " 5 ", " 1 ", " 9 ", " 6 ", " 4 ", " 2 ", " 7 ", " 3 ", " 10 ", " 8 " };
            for (int i = 0; i < algRomanos.Length; i++)
            {
                str = str.Replace(algRomanos[i], numeros[i]);
            }

            //Converte numeros para literais
            var algarismosExtenso = new[] { "ZERO", "UM", "DOIS", "TRES", "QUATRO", "CINCO", "SEIS", "SETE", "OITO", "NOVE" };
            for (int i = 0; i < 10; i++)
            {
                str = str.Replace(i.ToString(), algarismosExtenso[i]);
            }

            //Elimina preposições e artigos
            var letras = new[] { " A ", " B ", " C ", " D ", " E ", " F ", " G ", " H ", " I ", " J ", " K ", " L ", " M ", " N ", " O ", " P ", " Q ", " R ", " S ", " T ", " U ", " V ", " X ", " Z ", " W ", " Y " };
            str = letras.Aggregate(str, (current, letra) => current.Replace(letra, " "));

            str = str.Trim();
            var particulas = str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var fonetizados = new string[particulas.Length];
            for (var i = 0; i < particulas.Length; i++)
            {
                fonetizados[i] = FonetizarParticula(particulas[i]);
            }
            string fonetizado = string.Join(" ", fonetizados).Trim();

            return fonetizado;
        }
Example #9
0
        public void CustomComparer()
        {
            var strings = new[] {"a", "A", "b", "B"};

            var set = strings.Aggregate(
                Set.Empty(StringComparer.OrdinalIgnoreCase),
                (s, v) => s.Add(v));

            Assert.That(set.Select(s => s.ToLower()).ToArray(),Is.EqualTo(new[]{"a","b"}));
        }
Example #10
0
        public Ihdr(UInt32 width, UInt32 height, BitDepth bitDepth, ColorType colorType, CompressionMethod compressionMethod = CompressionMethod.Default, FilterMethod filterMethod = FilterMethod.Default, InterlaceMethod interlaceMethod = InterlaceMethod.None)
            : base(ChunkType.IHDR)
        {
            #region Sanity
            if(width == 0 || width > Int32.MaxValue)
                throw new ArgumentOutOfRangeException("width", "width must be greater than 0 and smaller than In32.MaxValue(2^31-1)");
            if(height == 0 || height > Int32.MaxValue)
                throw new ArgumentOutOfRangeException("height", "height must be greater than 0 and smaller than In32.MaxValue(2^31-1)");

            BitDepth[] allowedBitDepths;
            switch (colorType)
                {
                case ColorType.Grayscale:
                    if(!(allowedBitDepths = new[] { BitDepth._1, BitDepth._2, BitDepth._4, BitDepth._8, BitDepth._16 }).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.Rgb:
                    if(!(allowedBitDepths = new[]{BitDepth._8, BitDepth._16}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.Palette:
                    if(!(allowedBitDepths = new[] { BitDepth._1, BitDepth._2, BitDepth._4, BitDepth._8}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.GrayscaleWithAlpha:
                    if(!(allowedBitDepths = new[] { BitDepth._8, BitDepth._16}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                case ColorType.Rgba:
                    if(!(allowedBitDepths = new[] { BitDepth._8, BitDepth._16}).Contains(bitDepth))
                        throw new ArgumentOutOfRangeException("bitDepth", String.Format("bitDepth must be one of {0} for colorType {1}", allowedBitDepths.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2)), colorType));
                    break;
                default:
                    throw new ArgumentOutOfRangeException("colorType", String.Format("Unknown colorType: {0}", colorType));
                }

            if(compressionMethod != CompressionMethod.Default)
                throw new ArgumentOutOfRangeException("compressionMethod", String.Format("Unknown compressionMethod: {0}", compressionMethod));
            if(filterMethod != FilterMethod.Default)
                throw new ArgumentOutOfRangeException("filterMethod", String.Format("Unknown filterMethod: {0}", filterMethod));

            var allowedInterlaceMethods = new[] {InterlaceMethod.None, InterlaceMethod.Adam7};
            if(!allowedInterlaceMethods.Contains(interlaceMethod))
                throw new ArgumentOutOfRangeException("interlaceMethod", String.Format("interlaceMethod must be one of {0}", allowedInterlaceMethods.Aggregate("", (s, bd) => s + bd + ", ", s => s.Trim().Substring(0, s.Length - 2))));

            #endregion

            Width = width;
            Height = height;
            BitDepth = bitDepth;
            ColorType = colorType;
            CompressionMethod = compressionMethod;
            FilterMethod = filterMethod;
            InterlaceMethod = interlaceMethod;
        }
Example #11
0
        /// <summary>
        /// Remove Html tags and unnecessary scripts from a Html content string.
        /// </summary>
        /// <param name="source">Specifies the string containing the HTML content.</param>
        /// <returns>Plain text from the HTML content string.</returns>
        public static string StripHtmlTags(this string source)
        {
            var output = source;

            // remove invisible content
            var searchFor = new[]
            {
                "<head[^>]*?>.*?</head>",
                "<style[^>]*?>.*?</style>",
                "<script[^>]*?.*?</script>",
                "<object[^>]*?.*?</object>",
                "<embed[^>]*?.*?</embed>",
                "<applet[^>]*?.*?</applet>",
                "<noframes[^>]*?.*?</noframes>",
                "<noscript[^>]*?.*?</noscript>",
                "<noembed[^>]*?.*?</noembed>",
            };
            output = searchFor.Aggregate(output, (current, search) => Regex.Replace(current, search, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant));

            // add line break before and after blocks to prevent word joining
            searchFor = new[] {
                "</?((address)|(blockquote)|(center)|(del))",
                "</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))",
                "</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))",
                "</?((table)|(th)|(td)|(caption))",
                "</?((form)|(button)|(fieldset)|(legend)|(input))",
                "</?((label)|(select)|(optgroup)|(option)|(textarea))",
                "</?((frameset)|(frame)|(iframe))"
            };
            output = searchFor.Aggregate(output, (current, search) => Regex.Replace(current, search, "\r\n$0", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant));

            // strip tags
            output = Regex.Replace(output, @"<[^>]*>", string.Empty);

            // remove extra spaces
            output = Regex.Replace(output, @"\s{2,}", " ");
            output = Regex.Replace(output, @"(\t){2,}", " ");
            output = Regex.Replace(output, @"(\r\n){2,}", " ");
            output = Regex.Replace(output, @"(\r|\n){2,}", "\n");

            return output;
        }
Example #12
0
 public static string BreakUpCamelCase(this string s)
 {
     var patterns = new[]
     {
         "([a-z])([A-Z])",
         "([0-9])([a-zA-Z])",
         "([a-zA-Z])([0-9])"
     };
     var output = patterns.Aggregate(s, (current, pattern) => Regex.Replace(current, pattern, "$1 $2", RegexOptions.IgnorePatternWhitespace));
     return output.Replace('_', ' ');
 }
Example #13
0
        public static void Test1()
        {
            var array = new[] { "a", "b", "c", "d", "e" };

             
            var result = array.Aggregate( new StringBuilder(), (a,n) =>
            {
                a.Append(n + ",");
                return a;
            });
            Console.WriteLine(result.ToString().TrimEnd(','));
        }
Example #14
0
 /// <summary> Escapes the input string. </summary>
 /// <param name="input"> The unescaped input string. </param>
 /// <returns> Escaped output string. </returns>
 public static string Escape(string input)
 {
     var escapeChars = new[]
         {
             _escapeCharacter.ToString(CultureInfo.InvariantCulture),
             _fieldSeparator.ToString(CultureInfo.InvariantCulture),
             _commandSeparator.ToString(CultureInfo.InvariantCulture),
             "\0"
         };
     input = escapeChars.Aggregate(input,
                                   (current, escapeChar) =>
                                   current.Replace(escapeChar, _escapeCharacter + escapeChar));
     return input;
 }
Example #15
0
        public static string getTextoLimpo(this string str, bool consulta = false)
        {
            //Eliminar tags HTML
            str = Regex.Replace(str, "<[^>]*>", string.Empty);

            str = RemoveAcentos(str.ToUpperInvariant());

            str = RemovePalavrasEspecificas(str);

            str = SomenteLetras(str);

            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }

            //Eliminar preposições
            var preposicoes = new[] { " DE ", " DA ", " DO ", " AS ", " OS ", " AO ", " NA ", " NO ", " DOS ", " DAS ", " AOS ", " NAS ", " NOS ", " COM " };
            str = preposicoes.Aggregate(str, (current, preposicao) => current.Replace(preposicao, " "));

            //Converte algarismos romanos para números
            var algRomanos = new[] { " V ", " I ", " IX ", " VI ", " IV ", " II ", " VII ", " III ", " X ", " VIII " };
            var numeros = new[] { " 5 ", " 1 ", " 9 ", " 6 ", " 4 ", " 2 ", " 7 ", " 3 ", " 10 ", " 8 " };
            for (int i = 0; i < algRomanos.Length; i++)
            {
                str = str.Replace(algRomanos[i], numeros[i]);
            }

            //Converte numeros para literais
            var algarismosExtenso = new[] { "ZERO", "UM", "DOIS", "TRES", "QUATRO", "CINCO", "SEIS", "SETE", "OITO", "NOVE" };
            for (int i = 0; i < 10; i++)
            {
                str = str.Replace(i.ToString(), algarismosExtenso[i]);
            }

            //Elimina artigos
            var letras = new[] { " A ", " B ", " C ", " D ", " E ", " F ", " G ", " H ", " I ", " J ", " K ", " L ", " M ", " N ", " O ", " P ", " Q ", " R ", " S ", " T ", " U ", " V ", " X ", " Z ", " W ", " Y " };
            str = letras.Aggregate(str, (current, letra) => current.Replace(letra, " "));

            str = str.Trim();

            return str;
        }
        static void StarWars()
        {
            Console.CursorVisible = false;

            var arr = new[]
            {
                @"     =###:                   *#-  ",
                @"       -#:                   *#-  ",
                @"       -#: :#-  *@. *###*  :#####%",
                @"       -#: :#-  *@.-#:  =-   *#-  ",
                @"       -#: :#-  *@.-#=       *#-  ",
                @"       -#: :#-  *@. :###=    *#-  ",
                @"   :-  :#- :#-  *@.    *#-   *#-  ",
                @"   *#- [email protected] -#* [email protected]@.:+  *#-   :#:  ",
                @"    =###-   *###[email protected] =###:     %##%",
                @"                                  ",
                @"                                  ",
                @"    *#####:                       ",
                @"    *@.                           ",
                @"    *@.      %%###* -###%   [email protected]##[email protected]",
                @"    *@.      %#:    %% [email protected]=  %% [email protected]@",
                @"    *####%   %=    -#:  *@.-#:  *@",
                @"    *@.      %=    :#-  *@.:#-  *@",
                @"    *@.      %=    -#:  *@.-#:  *@",
                @"    *@.      %=     %% [email protected]=  %% [email protected]@",
                @"    *@.      %=     [email protected]##%   [email protected]##[email protected]",
                @"                                *@",
                @"                            ** [email protected]=",
                @"                             %##% ",

            };

            var maxLength = arr.Aggregate(0, (max, line) => Math.Max(max, line.Length));
            var x = Console.BufferWidth / 2 - maxLength / 2;
            //for (int y = -arr.Length; y < Console.WindowHeight + arr.Length; y++)
            for (int y = -arr.Length; y < 2; y++)
            {
                ConsoleDraw(arr, x, y);
                Thread.Sleep(100);
            }
            Console.ReadKey(true);
        }
Example #17
0
        public static void Main(String[] Args)
        {
            var arr = new[]
            {
                    @" /$$      /$$ /$$                 /$$       /$$$$$$$                     ",
                    @"| $$$    /$$$|__/                | $$      | $$__  $$                    ",
                    @"| $$$$  /$$$$ /$$ /$$$$$$$   /$$$$$$$      | $$  \ $$  /$$$$$$  /$$   /$$",
                    @"| $$ $$/$$ $$| $$| $$__  $$ /$$__  $$      | $$$$$$$  /$$__  $$|  $$ /$$/",
                    @"| $$  $$$| $$| $$| $$  \ $$| $$  | $$      | $$__  $$| $$  \ $$ \  $$$$/ ",
                    @"| $$\  $ | $$| $$| $$  | $$| $$  | $$      | $$  \ $$| $$  | $$  >$$  $$ ",
                    @"| $$ \/  | $$| $$| $$  | $$|  $$$$$$$      | $$$$$$$/|  $$$$$$/ /$$/\  $$",
                    @"|__/     |__/|__/|__/  |__/ \_______/      |_______/  \______/ |__/  \__/",

                                        @"             OOOOOOOOOOO",
                                        @"         OOOOOOOOOOOOOOOOOOO",
                                        @"      OOOOOO  OOOOOOOOO  OOOOOO",
                                        @"    OOOOOO      OOOOO      OOOOOO",
                                        @"  OOOOOOOO  #   OOOOO  #   OOOOOOOO",
                                        @" OOOOOOOOOO    OOOOOOO    OOOOOOOOOO",
                                        @"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
                                        @"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
                                        @"OOOO  OOOOOOOOOOOOOOOOOOOOOOOOO  OOOO",
                                        @" OOOO  OOOOOOOOOOOOOOOOOOOOOOO  OOOO",
                                        @"  OOOO   OOOOOOOOOOOOOOOOOOOO  OOOO",
                                        @"    OOOOO   OOOOOOOOOOOOOOO   OOOO",
                                        @"      OOOOOO   OOOOOOOOO   OOOOOO",
                                        @"         OOOOOO         OOOOOO",
                                        @"             OOOOOOOOOOOO",

            };
            Console.WindowWidth = 160;
            Console.WriteLine("\n\n");
            var maxLength = arr.Aggregate(0, (max, line) => Math.Max(max, line.Length));
            var x = Console.BufferWidth / 2 - maxLength / 2;
            for (int y = -arr.Length; y < Console.WindowHeight + arr.Length; y++)
            {
                ConsoleDraw(arr, x, y);
                Thread.Sleep(100);
            }
            Console.ReadKey();
        }
Example #18
0
        static void Main(string[] args)
        {
            var strArray = new[] { "Maya", "Something", "And One More", "PET" };
            Print(strArray); Console.WriteLine();

            var res2 = strArray.OrderByDescending(x => x.Length).First();
            Console.WriteLine(res2);

            var res3 = strArray.Max(x => x.Length);
            Console.WriteLine(res3);

            var res4 = strArray.Aggregate("", (x, y) => x.Length > y.Length ? x : y);
            Console.WriteLine(res4);

            var res5 =
                from x in strArray
                where GetLongestString(x)
                select x;
            // Print(res5);
            Console.WriteLine(res5.Last());
        }
        private SymbolTable DefaultSymbolsTable()
        {
            var defs = new[] {
                new {name = "wood", type = BlockType.WOOD},
                new {name = "woodplank", type = BlockType.WOOD_PLANK},
                new {name = "stone", type = BlockType.STONE},
                new {name = "sand", type = BlockType.SAND},
                new {name = "sandstone", type = BlockType.SANDSTONE},
                new {name = "wool", type = BlockType.WOOL},
                new {name = "cobblestone", type = BlockType.COBBLESTONE},
                new {name = "door", type = BlockType.WOOD_DOOR},
                new {name = "glass", type = BlockType.GLASS},
                new {name = "glasspane", type = BlockType.GLASS_PANE},
                new {name = "air", type = BlockType.AIR},
                new {name = "rose", type = BlockType.RED_ROSE},
                new {name = "grass", type = BlockType.GRASS},
            };

            return defs.Aggregate(SymbolTable.BaseSymbolTable,
                (acc, x) => acc.AddSymbol(x.name, new SingleBlock(new AlphaBlock(x.type))));
        }
        public void Tarjans_Case1()
        {
            // Assign
            var lines = new[]
            {
                "visa foreignpassport",
                "visa hotel",
                "visa bankstatement",
                "bankstatement nationalpassport",
                "hotel creditcard",
                "creditcard nationalpassport",
                "nationalpassport birthcertificate",
                "foreignpassport nationalpassport",
                "foreignpassport militarycertificate",
                "militarycertificate nationalpassport"
            };
            var graph = new Graph();
            var expectedStrings = new[]
            {
                "birthcertificate",
                "nationalpassport",
                "bankstatement",
                "creditcard",
                "hotel",
                "militarycertificate",
                "foreignpassport",
                "visa"
            };
            var expected = expectedStrings.Aggregate((x, y) => x + Environment.NewLine + y);

            // Act
            graph.Parse(lines, true);
            var result = graph.Tarjan();
            var actual = result.Select(x => x.Label).Aggregate((x, y) => x + Environment.NewLine + y);

            // Assert
            Assert.AreEqual(expected, actual);
        }
        public void Tarjans_Case2()
        {
            // Assign
            var lines = new[]
            {
                "visa foreignpassport"
            };
            var graph = new Graph();
            var expectedStrings = new[]
            {
                "foreignpassport",
                "visa"
            };
            var expected = expectedStrings.Aggregate((x, y) => x + Environment.NewLine + y);

            // Act
            graph.Parse(lines, true);
            var result = graph.Tarjan();
            var actual = result.Select(x => x.Label).Aggregate((x, y) => x + Environment.NewLine + y);

            // Assert
            Assert.AreEqual(expected, actual);
        }
Example #22
0
        private void Validate()
        {
            if (_sourceType == TargetType.Default)
                throw new ApplicationException("source error.please input a source.");

            if (_destType == TargetType.Default)
                throw new ApplicationException("dest error.please input a dest.");

            var supportFilters = new[] { "Resize", "Segment", "X264", "AudioRate", "AudioBitrate" };

            if (_filters.Any(x => !supportFilters.Contains(x.Name)))
            {
                throw new ApplicationException(string.Format("filter not support.only support:{0}",
                    supportFilters.Aggregate(string.Empty, (current, filter) => current + (filter + ",")).TrimEnd(new[] { ',' })));
            }
        }
		private async Task<string> InputDeckURL()
		{
			var settings = new MessageDialogs.Settings();
			var clipboard = Clipboard.ContainsText() ? Clipboard.GetText() : "";
			var validUrls = new[]
			{
				"hearthstats",
				"hss.io",
				"hearthpwn",
				"hearthhead",
				"hearthstoneplayers",
				"tempostorm",
				"hearthstonetopdeck",
				"hearthnews.fr",
				"arenavalue",
				"hearthstone-decks",
				"heartharena",
				"hearthstoneheroes",
				"elitedecks",
				"icy-veins",
				"hearthbuilder"
			};
			if(validUrls.Any(clipboard.Contains))
				settings.DefaultText = clipboard;

			if(Config.Instance.DisplayNetDeckAd)
			{
				var result =
					await
					this.ShowMessageAsync("NetDeck",
					                      "For easier (one-click!) web importing check out the NetDeck Chrome Extension!\n\n(This message will not be displayed again, no worries.)",
					                      MessageDialogStyle.AffirmativeAndNegative,
					                      new MessageDialogs.Settings {AffirmativeButtonText = "Show me!", NegativeButtonText = "No thanks"});

				if(result == MessageDialogResult.Affirmative)
				{
					Process.Start("https://chrome.google.com/webstore/detail/netdeck/lpdbiakcpmcppnpchohihcbdnojlgeel");
					var enableOptionResult =
						await
						this.ShowMessageAsync("Enable one-click importing?",
						                      "Would you like to enable one-click importing via NetDeck?\n(options > other > importing)",
						                      MessageDialogStyle.AffirmativeAndNegative,
						                      new MessageDialogs.Settings {AffirmativeButtonText = "Yes", NegativeButtonText = "No"});
					if(enableOptionResult == MessageDialogResult.Affirmative)
					{
						Options.OptionsTrackerImporting.CheckboxImportNetDeck.IsChecked = true;
						Config.Instance.NetDeckClipboardCheck = true;
						Config.Save();
					}
				}

				Config.Instance.DisplayNetDeckAd = false;
				Config.Save();
			}


			//import dialog
			var url =
				await this.ShowInputAsync("Import deck", "Supported websites:\n" + validUrls.Aggregate((x, next) => x + ", " + next), settings);
			return url;
		}
 internal HelpText AddToHelpText(HelpText helpText, Func<string, HelpText> func)
 {
     var strArray = new[] { line1, line2, line3, line4, line5 };
     return strArray.Aggregate(helpText, (current, line) => func(line));
 }
Example #25
0
 public void AggregateWithSeedAndResult()
 {
     var array = new[] { 1, 2, 3 };
     var result = array.Aggregate(10, (x, y) => x + y, x => x.ToString());
     AssertEquals(result, "16");
 }
Example #26
0
 public void AggregateWithSeed()
 {
     var array = new[] { 1, 2, 3 };
     var result = array.Aggregate(10, (x, y) => x + y);
     AssertEquals(result, 16);
 }
Example #27
0
        /// <summary>
        /// The static output generator - http://patternlab.io/docs/net-command-line.html
        /// </summary>
        /// <param name="destination">The name of the destination directory</param>
        /// <param name="enableCss">Generate CSS for each pattern. Currently unsupported</param>
        /// <param name="patternsOnly">Generate only the patterns. Does NOT clean the destination folder</param>
        /// <param name="noCache">Set the cacheBuster value to 0</param>
        /// <returns>The results of the generator</returns>
        public string Generate(string destination, bool? enableCss = null, bool? patternsOnly = null, bool? noCache = null)
        {
            var start = DateTime.Now;
            var content = new StringBuilder("configuring pattern lab...<br/>");
            var controller = new Controllers.PatternLabController { ControllerContext = _controllerContext };
            var url = new UrlHelper(_controllerContext.RequestContext);

            // Set location to copy from as root of app
            var sourceDirectory = new DirectoryInfo(HttpRuntime.AppDomainAppPath);
            var destinationDirectory = new DirectoryInfo(string.Format("{0}{1}\\", HttpRuntime.AppDomainAppPath, destination));

            // Determine value for {{ cacheBuster }} variable
            var cacheBuster = noCache.HasValue && noCache.Value ? "0" : _provider.CacheBuster();

            // If not only generating patterns, and cleanPubnlic config setting set to true clean destination directory
            if ((patternsOnly.HasValue && !patternsOnly.Value) || !patternsOnly.HasValue &&
                _provider.Setting("cleanPublic").Equals(bool.TrueString, StringComparison.InvariantCultureIgnoreCase))
            {
                // Clean all files
                CleanAll(destinationDirectory);

                // Copy all files and folders from source to public
                CopyAll(sourceDirectory, destinationDirectory);

                // Create 'Viewer' page
                var view = controller.Index();

                // Capture the view and write its contents to the file
                CreateFile(string.Format("~/{0}", PatternProvider.FileNameViewer), view.Capture(_controllerContext),
                    sourceDirectory, destinationDirectory);

                // Create latest-change.txt
                CreateFile("~/latest-change.txt", cacheBuster, sourceDirectory, destinationDirectory);

                // Create /styleguide/html/styleguide.html
                view = controller.ViewAll(string.Empty, enableCss.HasValue && enableCss.Value,
                    noCache.HasValue && noCache.Value);

                // Capture the view and write its contents to the file
                CreateFile(url.RouteUrl("PatternLabStyleguide"), view.Capture(_controllerContext), sourceDirectory,
                    destinationDirectory);

                // Parse embedded resources for required assets
                const string assetRootFolder = "styleguide";
                var assembly = Assembly.GetExecutingAssembly();
                var assetFolders = new[] {"css", "fonts", "html", "images", "js", "vendor"};
                var assetNamespace = string.Format("{0}.EmbeddedResources.{1}.", assembly.GetName().Name, assetRootFolder);
                var assetNames = assembly.GetManifestResourceNames().Where(r => r.Contains(assetNamespace));

                // Create assets from embedded resources
                foreach (var assetName in assetNames)
                {
                    var virtualPath = assetName.Replace(assetNamespace, string.Empty);
                    virtualPath = assetFolders.Aggregate(virtualPath,
                        (current, assetFolder) =>
                            current.Replace(string.Format("{0}.", assetFolder), string.Format("{0}/", assetFolder)));

                    var embeddedResource = new EmbeddedResource(assetName);

                    // Get the contents of the embedded resource and write it to the file
                    CreateFile(string.Format("~/{0}/{1}", assetRootFolder, virtualPath), embeddedResource.Open(),
                        sourceDirectory, destinationDirectory);
                }
            }

            // Clean all files in /patterns
            CleanAll(destinationDirectory.GetDirectories("patterns").FirstOrDefault());

            // Find all patterns that aren't hidden from navigation
            var patterns = _provider.Patterns().Where(p => !p.Hidden).ToList();
            var typeDashes =
                patterns.Where(p => !string.IsNullOrEmpty(p.SubType))
                    .Select(p => p.TypeDash)
                    .Where(s => !string.IsNullOrEmpty(s))
                    .Distinct()
                    .ToList();

            // Create view-all HTML files
            foreach (var typeDash in typeDashes)
            {
                var view = controller.ViewAll(typeDash, enableCss.HasValue && enableCss.Value,
                    noCache.HasValue && noCache.Value);

                // Capture the view and write its contents to the file
                CreateFile(url.RouteUrl("PatternLabViewAll", new { id = typeDash }), view.Capture(_controllerContext),
                    sourceDirectory, destinationDirectory);
            }

            // Create pattern files
            foreach (var pattern in patterns)
            {
                var virtualPath =
                    url.RouteUrl("PatternLabViewSingle", new { id = pattern.PathDash, path = pattern.PathDash }) ??
                    string.Empty;

                // Create .html
                var view = controller.ViewSingle(pattern.PathDash, PatternProvider.FileNameMaster, null,
                    enableCss.HasValue && enableCss.Value, noCache.HasValue && noCache.Value);

                // Capture the view and write its contents to the file
                CreateFile(virtualPath, view.Capture(_controllerContext), sourceDirectory, destinationDirectory);

                // Create .mustache
                view = controller.ViewSingle(pattern.PathDash, string.Empty, null, enableCss.HasValue && enableCss.Value,
                    noCache.HasValue && noCache.Value);

                // Capture the view and write its contents to the file
                CreateFile(
                    virtualPath.Replace(PatternProvider.FileExtensionHtml, PatternProvider.FileExtensionMustache),
                    view.Capture(_controllerContext), sourceDirectory, destinationDirectory);

                // Create .escaped.html
                view = controller.ViewSingle(pattern.PathDash, string.Empty, true, enableCss.HasValue && enableCss.Value,
                    noCache.HasValue && noCache.Value);

                // Capture the view and write its contents to the file
                CreateFile(
                    virtualPath.Replace(PatternProvider.FileExtensionHtml, PatternProvider.FileExtensionEscapedHtml),
                    view.Capture(_controllerContext), sourceDirectory, destinationDirectory);
            }

            // Determine the time taken the run the generator
            var elapsed = DateTime.Now - start;

            content.Append("your site has been generated...<br/>");
            content.AppendFormat("site generation took {0} seconds...<br/>", elapsed.TotalSeconds);

            // Randomly prints a saying after the generate is complete
            var random = new Random().Next(60);
            var sayings = new[]
            {
                "have fun storming the castle",
                "be well, do good work, and keep in touch",
                "may the sun shine, all day long",
                "smile",
                "namaste",
                "walk as if you are kissing the earth with your feet",
                "to be beautiful means to be yourself",
                "i was thinking of the immortal words of socrates, who said \"...i drank what?\"",
                "let me take this moment to compliment you on your fashion sense, particularly your slippers",
                "42",
                "he who controls the spice controls the universe",
                "the greatest thing you'll ever learn is just to love and be loved in return",
                "nice wand",
                "i don't have time for a grudge match with every poseur in a parka"
            };

            if (sayings.Length > random)
            {
                content.AppendFormat("{0}...<br />", sayings[random]);
            }

            // Display the results of the generator
            return content.ToString();
        }
Example #28
0
 static void M2()
 {
     var items = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
     var sum = items.Aggregate(0, (x, y) => x + y);
     var prod = items.Aggregate(0, (x, y) => x * y);
 }
Example #29
0
 private static string RemovePlusMinusSpaceFromLine(string input)
 {
     var charsToRemove = new[] { " ", "-", "+",  "(", ")", "/"};
     input = charsToRemove.Aggregate(input, (current, s) => current.Replace(s, ""));
     if (!Regex.IsMatch(input.Last().ToString(), @"^\d+$")) input = input.Replace(input.Last().ToString(), "");
     return input;
 }
Example #30
0
 public void Aggregate()
 {
     var array = new[] { 1, 2, 3 };
     var result = array.Aggregate((x, y) => x + y);
     AssertEquals(result, 6);
 }