Lookup() public static method

public static Lookup ( String animal ) : string
animal String
return string
        public void DictionaryLookup()
        {
            var dicResult = Dictionary.Lookup(DictionaryDirectory.EnRu, "time");

            var def0 = dicResult.Definitions[0];
            var def1 = dicResult.Definitions[1];

            Assert.AreEqual("time", def0.Text);
            Assert.AreEqual(6, def0.Translations.Count);
            var tr = def0.Translations[0];

            Assert.AreEqual("noun", tr.PartOfSpeech);
            Assert.AreEqual("время", tr.Text);

            Assert.AreEqual("раз", tr.Synonyms[0].Text);
            Assert.AreEqual("момент", tr.Synonyms[1].Text);

            Assert.AreEqual("period", tr.Meanings[0].Text);
            Assert.AreEqual("once", tr.Meanings[1].Text);
            Assert.AreEqual("moment", tr.Meanings[2].Text);
            Assert.AreEqual("pore", tr.Meanings[3].Text);

            Assert.AreEqual("daylight saving time", tr.Examples[0].Text);
            Assert.AreEqual("летнее время", tr.Examples[0].Translations[0].Text);
            Assert.AreEqual("take some time", tr.Examples[1].Text);
            Assert.AreEqual("занять некоторое время", tr.Examples[1].Translations[0].Text);
            Assert.AreEqual("real time mode", tr.Examples[2].Text);
            Assert.AreEqual("режим реального времени", tr.Examples[2].Translations[0].Text);

            Assert.AreEqual("verb", def1.PartOfSpeech);
            Assert.AreEqual("taɪm", def1.Transcription);
            Assert.AreEqual("time", def1.Text);
            Assert.AreEqual("verb", def1.Translations[0].PartOfSpeech);
            Assert.AreEqual("приурочивать", def1.Translations[0].Text);
        }
Esempio n. 2
0
        public static void Main()
        {
            var dictionary = new Dictionary<string, int>
            {
                {"one", 1},
                {"two", 4},
                {"three", 9},
                {"four", 16}
            };

            var result1 =
                from x in dictionary.Lookup("two")
                from y in ToStringIfLessThenTen(x)
                select y;

            var result2 =
                from x in dictionary.Lookup("four")
                from y in ToStringIfLessThenTen(x)
                select y;

            var result3 =
                from x in dictionary.Lookup("five")
                from y in ToStringIfLessThenTen(x)
                select y;

            PrintMaybe(result1);
            PrintMaybe(result2);
            PrintMaybe(result3);

            PrintResult(result1.OrElse("some default value"));
            PrintResult(result2.OrElse("some default value"));
            PrintResult(result3.OrElse("some default value"));
        }
        public void DictionaryLookup()
        {
            var dicResult = Dictionary.Lookup(LangPair.EnRu, "time");

            var def0 = dicResult.Definitions[0];
            var def1 = dicResult.Definitions[1];

            Assert.AreEqual("time", def0.Text);
            Assert.AreEqual(1, def0.Translations.Count);
            var tr = def0.Translations[0];

            Assert.AreEqual("существительное", tr.PartOfSpeech);
            Assert.AreEqual("время", tr.Text);

            Assert.AreEqual("раз", tr.Synonyms[0].Text);
            Assert.AreEqual("тайм", tr.Synonyms[1].Text);

            Assert.AreEqual("timing", tr.Meanings[0].Text);
            Assert.AreEqual("fold", tr.Meanings[1].Text);
            Assert.AreEqual("half", tr.Meanings[2].Text);

            Assert.AreEqual("thromboplastin time", tr.Examples[0].Text);
            Assert.AreEqual("тромбопластиновое время", tr.Examples[0].Translations[0].Text);
            Assert.AreEqual("umpteenth time", tr.Examples[1].Text);
            Assert.AreEqual("энный раз", tr.Examples[1].Translations[0].Text);
            Assert.AreEqual("second time", tr.Examples[2].Text);
            Assert.AreEqual("второй тайм", tr.Examples[2].Translations[0].Text);

            Assert.AreEqual("adverbial participle", def1.PartOfSpeech);
            Assert.AreEqual("taɪm", def1.Transcription);
            Assert.AreEqual("time", def1.Text);
            Assert.AreEqual("деепричастие", def1.Translations[0].PartOfSpeech);
            Assert.AreEqual("временя", def1.Translations[0].Text);
        }
Esempio n. 4
0
        public void dictionary_lookup_to_OptionT()
        {
            // Arrange
            var xs = new Dictionary <string, string>
            {
                ["a"] = "AA",
                ["b"] = "BB",
            };

            // Act

            // Assert

            // the usual dictionary stuff
            Assert.Equal("AA", xs["a"]);
            Assert.Equal("BB", xs["b"]);

            //
            Assert.Equal(xs.Lookup("-NOT-THERE"), None);
            Assert.Equal(xs.Lookup("a"), Some("AA"));

            //
            var actualA = xs.Lookup("a").Match(() => "", v => v);
            //Assert.Equal(actualA, "AA");

            var actualANotExist = xs.Lookup("a-key-there-").Match(() => "", v => v);
            //Assert.Equal(actualANotExist, "");
        }
Esempio n. 5
0
 public void MaybeTest()
 {
     var dict = new Dictionary<int, int>();
     dict[0] = 1;
     dict[2] = 3;
     Assert.IsTrue(dict.Lookup(0).HasValue);
     Assert.IsFalse(dict.Lookup(1).HasValue);
     Assert.AreEqual(dict.Lookup(1).GetOrElse(8), 8);
     Assert.AreEqual(dict.Lookup(2).Map(x => x + 1).GetOrElse(0), 4);
 }
Esempio n. 6
0
        public async static Task Main(string[] args)
        {
            var cliExamples = new Dictionary <string, Action>
            {
                ["HOFs"]                  = Chapter2.HOFs.Run,
                ["OptionBind"]            = Chapter6.AskForValidAgeAndPrintFlatteringMessage.Run,
                ["Greetings"]             = Chapter9.Greetings.Run,
                ["Timer"]                 = Chapter16.CreatingObservables.Timer.Run,
                ["Subjects"]              = Chapter16.CreatingObservables.Subjects.Run,
                ["Create"]                = Chapter16.CreatingObservables.Create.Run,
                ["Generate"]              = Chapter16.CreatingObservables.Generate.Run,
                ["CurrencyLookup_Unsafe"] = Chapter16.CurrencyLookup_Unsafe.Run,
                ["CurrencyLookup_Safe"]   = Chapter16.CurrencyLookup_Safe.Run,
                ["VoidContinuations"]     = Chapter16.VoidContinuations.Run,
                ["KeySequences"]          = Chapter16.KeySequences.Run,
            };

            if (args.Length > 0)
            {
                cliExamples.Lookup(args[0])
                .Match(
                    None: () => Console.WriteLine($"Unknown option: '{args[0]}'"),
                    Some: (main) => main()
                    );
            }

            else
            {
                await Boc.Chapter9.Program.Run();
            }
            //StartWebApi();
        }
Esempio n. 7
0
        public static void Main(string[] args)
        {
            var cliExamples = new Dictionary <string, Action>
            {
                ["HOFs"]                  = Chapter1.HOFs.Run,
                ["Greetings"]             = Chapter7.Greetings.Run,
                ["Timer"]                 = Chapter14.CreatingObservables.Timer.Run,
                ["Subjects"]              = Chapter14.CreatingObservables.Subjects.Run,
                ["Create"]                = Chapter14.CreatingObservables.Create.Run,
                ["Generate"]              = Chapter14.CreatingObservables.Generate.Run,
                ["CurrencyLookup_Unsafe"] = Chapter14.CurrencyLookup_Unsafe.Run,
                ["CurrencyLookup_Safe"]   = Chapter14.CurrencyLookup_Safe.Run,
                ["VoidContinuations"]     = Chapter14.VoidContinuations.Run,
                ["KeySequences"]          = Chapter14.KeySequences.Run,
                ["PingPongAgents"]        = Examples.Agents.PingPongAgents.main,           // Chapter15
                ["TestViaCmdLine"]        = Examples.Agents.CurrencyLookup.TestViaCmdLine, // Chapter15
                ["Counter"]               = Examples.Agents.Counter.main                   // Chapter15
            };

            if (args.Length > 0)
            {
                cliExamples.Lookup(args[0])
                .Match(
                    None: () => WriteLine($"Unknown option: '{args[0]}'"),
                    Some: (main) => main()
                    );
            }

            else
            {
                StartWebApi();
            }
        }
Esempio n. 8
0
        public static void Main(string[] args)
        {
            var cliExamples = new Dictionary <string, Action>
            {
                //["test"] = () => new AutoRun(typeof(Program).GetTypeInfo().Assembly)
                //    .Execute(args, new ExtendedTextWrapper(Console.Out), Console.In),
                ["HOFs"]                  = Chapter1.HOFs.Run,
                ["Greetings"]             = Chapter7.Greetings.Run,
                ["Timer"]                 = Chapter14.CreatingObservables.Timer.Run,
                ["Subjects"]              = Chapter14.CreatingObservables.Subjects.Run,
                ["Create"]                = Chapter14.CreatingObservables.Create.Run,
                ["Generate"]              = Chapter14.CreatingObservables.Generate.Run,
                ["CurrencyLookup_Unsafe"] = Chapter14.CurrencyLookup_Unsafe.Run,
                ["CurrencyLookup_Safe"]   = Chapter14.CurrencyLookup_Safe.Run,
                ["VoidContinuations"]     = Chapter14.VoidContinuations.Run,
                ["KeySequences"]          = Chapter14.KeySequences.Run,
            };

            if (args.Length > 0)
            {
                cliExamples.Lookup(args[0])
                .Match(
                    None: () => WriteLine($"Unknown option: '{args[0]}'"),
                    Some: (main) => main()
                    );
            }

            else
            {
                StartWebApi();
            }
        }
Esempio n. 9
0
        public static void Main(string[] args)
        {
            var cliExamples = new Dictionary <string, Action>
            {
                ["HOFs"]                  = Chapter2.HOFs.Run,
                ["Greetings"]             = Chapter8.Greetings.Run,
                ["Timer"]                 = Chapter15.CreatingObservables.Timer.Run,
                ["Subjects"]              = Chapter15.CreatingObservables.Subjects.Run,
                ["Create"]                = Chapter15.CreatingObservables.Create.Run,
                ["Generate"]              = Chapter15.CreatingObservables.Generate.Run,
                ["CurrencyLookup_Unsafe"] = Chapter15.CurrencyLookup_Unsafe.Run,
                ["CurrencyLookup_Safe"]   = Chapter15.CurrencyLookup_Safe.Run,
                ["VoidContinuations"]     = Chapter15.VoidContinuations.Run,
                ["KeySequences"]          = Chapter15.KeySequences.Run,
            };

            if (args.Length > 0)
            {
                cliExamples.Lookup(args[0])
                .Match(
                    None: () => Console.WriteLine($"Unknown option: '{args[0]}'"),
                    Some: (main) => main()
                    );
            }

            else
            {
                StartWebApi();
            }
        }
Esempio n. 10
0
        private void UpdateDictionaryResult()
        {
            this.Invoke(new Action(() =>
            {
                try
                {
                    LookupOptions lookupOptions = 0;
                    if (cbFamily.Checked)
                    {
                        lookupOptions |= LookupOptions.Family;
                    }
                    if (cbMorpho.Checked)
                    {
                        lookupOptions |= LookupOptions.Morpho;
                    }
                    if (cbPartOfSpeech.Checked)
                    {
                        lookupOptions |= LookupOptions.PartOfSpeechFilter;
                    }
                    var response = Dictionary.Lookup((LangPair)cmbDictionaryLangPairs.SelectedItem,
                                                     tbDictionaryInput.Text, cmbDictionaryLangUi.SelectedItem.ToString().ToLowerInvariant(), lookupOptions);

                    rbDictionaryOutput.Text = response.ToString(cbDictionaryFormatting.Checked, tbDictionaryIndent.Text);
                }
                catch (Exception ex)
                {
                    rbDictionaryOutput.Text = ex.ToString();
                }
            }));
        }
Esempio n. 11
0
        static void Main()
        {
            var shoppingList = new List <string> {
                "coffee beans", "BANANAS", "Dates"
            };

            ListFormatter
            .Format(shoppingList)
            .ForEach(Console.WriteLine);

            var age = Age.Of(100).Match(
                () => $"-1",
                value => $"{value}"
                );

            Console.WriteLine($"Option age: {age}\n");
            //WriteLine($"Age is {CalculateRiskProfile(age, Gender.Female)}");



            Option <string> _    = None;
            Option <string> john = Some("John");

            WriteLine(Greet(None));
            WriteLine(Greet(Some("Vitax")));

            WriteLine(GreetingFor(new Subscriber {
                Email = "*****@*****.**", Name = "vITAX"
            }) + "\n");
            WriteLine($"Parse: {Parse("10")}");

            try
            {
                var empty = new NameValueCollection();
                var green = empty.Lookup("green");
                WriteLine($"green!: {green}");

                var alsoEmpty = new Dictionary <string, string>();
                var blue      = alsoEmpty.Lookup("blue");
                WriteLine($"blue!: {blue}");
            }
            catch (Exception e)
            {
                WriteLine(e.GetType().Name);
            }

            new List <int>().Lookup2(IsOdd);

            var email = Email.Create("*****@*****.**");

            Console.WriteLine(email.Match(() => $"Mail is not valid format.", email1 => $"Mails is {email1}"));

            // Map can be defined in terms of select
            Func <int, int> f = x => x * 3;

            Enumerable.Range(1, 9).Map2(f).ForEach(Write);
            Enumerable.Range(1, 9).ForEach2(Write);

            //RiskOf(new Subject {Age = new Option<Age>(), Gender = new Option<Gender>()});
        }
        public void LookupDictionaryWhenNotPresent()
        {
            var dictionary = new Dictionary <int, string>();

            var result = dictionary.Lookup(1);

            Assert.IsFalse(result.HasValue);
        }
Esempio n. 13
0
 public static Option <WorkPermit> GetWorkPermit(Dictionary <string, Employee> people, string employeeId)
 => people.Lookup(employeeId)
 .Bind(x => x.WorkPermit)
 .Match(
     () => None,
     (s) => s.Expiry < DateTime.Now
                             ? None
                             : Some(s));
Esempio n. 14
0
        public Optional <TObject> Lookup(TKey key)
        {
            Optional <TObject> result;

            lock (_locker)
                result = _data.Lookup(key);

            return(result);
        }
Esempio n. 15
0
 public IObservable <MarketData> Watch(string currencyPair)
 {
     if (currencyPair == null)
     {
         throw new ArgumentNullException(nameof(currencyPair));
     }
     return(_prices.Lookup(currencyPair)
            .ValueOrThrow(() => new Exception(currencyPair + " is an unknown currency pair")));
 }
        private void Messages_ItemInserted(IOMessage msg, int i)
        {
            int[] indicies_listeners;

            lock (locker) {
                var lookup_subject_this =
                    lookup_subject.Lookup(
                        msg.Subject,
                        () =>
                        new KeyValuePair <ShiftableBitArray, ShiftableBitArray>(
                            new ShiftableBitArray(),
                            new ShiftableBitArray()
                            )
                        );

                var lookup_verb_this =
                    lookup_verb.Lookup(
                        msg.Verb,
                        () =>
                        new KeyValuePair <ShiftableBitArray, ShiftableBitArray>(
                            new ShiftableBitArray(),
                            new ShiftableBitArray()
                            )
                        );

                indicies_listeners = lookup_subject_this.Key.AllOnes(lookup_verb_this.Key).ToArray();

                foreach (var subject in lookup_subject)
                {
                    subject.Value.Value.Insert(i, subject.Key == msg.Subject);
                }

                foreach (var verb in lookup_verb)
                {
                    verb.Value.Value.Insert(i, verb.Key == msg.Verb);
                }
            }

            for (int j = 0; j < indicies_listeners.Length; j++)
            {
                Listeners[indicies_listeners[j]].Responder(msg);
            }
        }
Esempio n. 17
0
        protected void RecalcualteTrustValue()
        {
            const float PUBLISHPOINTSSPERSUBNET = 10.0f;

            // The trustvalue is supposed to be an indicator how trustworthy/important (or spamy) this entry is and lies between 0 and ~10000,
            // but mostly we say everything below 1 is bad, everything above 1 is good. It is calculated by looking at how many differnt
            // IPs/24 have published this entry and how many entries each of those IPs have.
            // Each IP/24 has x (say 3) points. This means if one IP publishs 3 differnt entries without any other IP publishing those entries,
            // each of those entries will have 3 / 3 = 1 Trustvalue. Thats fine. If it publishes 6 alone, each entry has 3 / 6 = 0.5 trustvalue - not so good
            // However if there is another publisher for entry 5, which only publishes this entry then we have 3/6 + 3/1 = 3.5 trustvalue for this entry
            //
            // Whats the point? With this rating we try to avoid getting spammed with entries for a given keyword by a small IP range, which blends out
            // all other entries for this keyword do to its amount as well as giving an indicator for the searcher. So if we are the node to index "Knoppix", and someone
            // from 1 IP publishes 500 times "knoppix casino 500% bonus.txt", all those entries will have a trsutvalue of 0.006 and we make sure that
            // on search requests for knoppix, those entries are only returned after all entries with a trustvalue > 1 were sent (if there is still space).
            //
            // Its important to note that entry with < 1 do NOT get ignored or singled out, this only comes into play if we have 300 more results for
            // a search request rating > 1
            if (m_pliPublishingIPs == NULL)
            {
                ASSERT(false);
                return;
            }
            dwLastTrustValueCalc = ::GetTickCount();
            m_fTrustValue        = 0;
            ASSERT(!m_pliPublishingIPs->IsEmpty());
            for (POSITION pos = m_pliPublishingIPs->GetHeadPosition(); pos != NULL; m_pliPublishingIPs->GetNext(pos))
            {
                structPublishingIP curEntry = m_pliPublishingIPs->GetAt(pos);
                uint32             nCount   = 0;
                s_mapGlobalPublishIPs.Lookup(curEntry.m_uIP & 0xFFFFFF00 /* /24 netmask, take care of endian if needed*/, nCount);
                if (nCount > 0)
                {
                    m_fTrustValue += PUBLISHPOINTSSPERSUBNET / nCount;
                }
                else
                {
                    DebugLogError(_T("Kad: EntryTrack: Inconsistency RecalcualteTrustValue()"));
                    ASSERT(false);
                }
            }
        }
Esempio n. 18
0
        private async void OnCheckButtonClick(object sender, EventArgs e)
        {
            success = false;
            string deckName = NameTextBox.Text.Trim();

            deckName = deckName == "" ? null : deckName;

            if (deckName == null)
            {
                MessageBox.Show("Deck name can not be empty");
                return;
            }
            if (!await Deck.CheckNameCollision(deckName))
            {
                if (MessageBox.Show("The name of the deck already exists. The new Flashcards will be appended to the existing Deck", "Are you sure", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                {
                    return;
                }
            }

            String words = WordsTextBox.Text.Trim();

            words = words == "" ? null : words;

            if (words == null)
            {
                MessageBox.Show("Can't create an empty deck.");
                return;
            }

            string[] s    = words.Split(" ".ToCharArray());
            Deck     deck = new Deck(deckName);

            foreach (string ss in s)
            {
                try
                {
                    FlashCard fc = await Dictionary.Lookup(ss);

                    deck.FlashCards.Add(fc);
                }
                catch (Exception ee)
                {
                    MessageBox.Show("Something went wrong. Check your Internet connection and try again please");
                    return;
                }
            }
            success = true;
            NavigationService.GoBack();
            BeginWork();
            await deck.Write();

            EndWork();
        }
Esempio n. 19
0
        public void Lookup_NonExistantKeyReturnsNull()
        {
            // Arrange
            var dictionary = new Dictionary<InstructionType, Action<ExecutionContext, Instruction>>();

            // Act
            var value = dictionary.Lookup(InstructionType.Call);

            // Assert
            value.Should().BeNull();
        }
        public void LookupDictionaryWhenPresent()
        {
            var dictionary = new Dictionary <int, string> {
                { 1, "A" }
            };

            var result = dictionary.Lookup(1);

            Assert.IsTrue(result.HasValue);
            Assert.AreEqual("A", result.Value);
        }
        public void LookupWhenFound()
        {
            var dict =
                new Dictionary<int, string>
                {
                    [1] = "A",
                    [2] = "B"
                };

            Assert.AreEqual("B", dict.Lookup(2).Value);
        }
Esempio n. 22
0
 public object this[T obj, string view] {
     get {
         return
             (viewersmap
              .Lookup(view)
              .Lookup(
                  obj,
                  () =>
                  boundlist
                  .ViewerSet
                  .CreateView(obj, view)
                  ));
     }
 }
        public void ShouldReturnAnOptionWhenValueExists()
        {
            var dictionary = new Dictionary <int, string>();

            dictionary.TryAdd(1, "First");
            dictionary.TryAdd(2, "Second");

            var result = dictionary.Lookup(1);

            _ = result.Match(null, value =>
            {
                Assert.Equal("First", value);
                return(true);
            });
        }
Esempio n. 24
0
        public void Lookup_ReturnsValueForExistingKey()
        {
            // Arrange
            Action<ExecutionContext, Instruction> action = (e, i) => { /* Do nothing */ };
            var dictionary = new Dictionary<InstructionType, Action<ExecutionContext, Instruction>>
            {
                { InstructionType.Mult, action }
            };

            // Act
            var value = dictionary.Lookup(InstructionType.Mult);

            // Assert
            value.Should().Be(action);
        }
        public void ShouldReturnNoneWhenValueDoesNotExists()
        {
            var dictionary = new Dictionary <int, string>();

            dictionary.TryAdd(1, "First");
            dictionary.TryAdd(2, "Second");

            var result = dictionary.Lookup(3);

            _ = result.Match(() =>
            {
                Assert.True(true);
                return(true);
            }, null);
        }
Esempio n. 26
0
        public ColourProvider()
        {
            var swatches = new SwatchesProvider().Swatches.AsArray();

            Swatches = swatches.ToDictionary(s => s.Name);

            var accents = swatches.Where(s => s.IsAccented).ToArray();
            var orders  = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);

            ThemeConstants.Themes.Select((str, idx) => new { str, idx })
            .ForEach(x => orders[x.str] = x.idx);

            var greys = swatches//.Where(s => !s.IsAccented)
                        .Where(s => s.Name == "bluegrey")
                        .SelectMany(swatch =>
            {
                var hues = swatch.PrimaryHues
                           .Where(hue => hue.Name == "Primary200" ||
                                  hue.Name == "Primary300" ||
                                  hue.Name == "Primary400" ||
                                  hue.Name == "Primary500")
                           .Select(hue => new Hue(swatch.Name, hue.Name, hue.Foreground, hue.Color));


                var withNumber = hues.Select(h =>
                {
                    var num = GetNumber(h.Name);
                    return(new { hue = h, Num = num });
                }).OrderBy(h => h.Num)
                                 .Take(8)
                                 .Select(x => x.hue);

                return(withNumber);
            });

            Hues = accents
                   .OrderBy(x => orders.Lookup(x.Name).ValueOr(() => 100))
                   .SelectMany(swatch =>
            {
                return(swatch.AccentHues.Select(hue => new Hue(swatch.Name, hue.Name, hue.Foreground, hue.Color)));
            })
                   .Union(greys)
                   .ToArray();

            HueCache = Hues.ToDictionary(h => h.Key);
        }
Esempio n. 27
0
        public async static Task Main(string[] args)
        {
            var cliExamples = new Dictionary <string, Action>
            {
                ["ParallelSortUnsafe"] = Chapter1.MutationShouldBeAvoided.WithArrayItBreaks,
                ["ParallelSortSafe"]   = Chapter1.MutationShouldBeAvoided.WithIEnumerableItWorks,
                ["HOFs"]       = Chapter2.HOFs.Run,
                ["NaivePar"]   = Chapter3.ListFormatter.Parallel.Naive.ListFormatter.Run,
                ["OptionBind"] = Chapter6.AskForValidAgeAndPrintFlatteringMessage.Run,
                ["Greetings"]  = Chapter9.Greetings.Run,

                ["CurrencyLookup_Stateless"]      = Chapter15.CurrencyLookup_Stateless.Run,
                ["CurrencyLookup_StatefulUnsafe"] = Chapter15.CurrencyLookup_StatefulUnsafe.Run,
                ["CurrencyLookup_StatefulSafe"]   = Chapter15.CurrencyLookup_StatefulSafe.Run,

                ["Timer"]    = Chapter18.CreatingObservables.Timer.Run,
                ["Subjects"] = Chapter18.CreatingObservables.Subjects.Run,
                ["Create"]   = Chapter18.CreatingObservables.Create.Run,
                ["Generate"] = Chapter18.CreatingObservables.Generate.Run,
                ["CurrencyLookup_Unsafe"] = Chapter18.CurrencyLookup_Unsafe.Run,
                ["CurrencyLookup_Safe"]   = Chapter18.CurrencyLookup_Safe.Run,
                ["VoidContinuations"]     = Chapter18.VoidContinuations.Run,
                ["KeySequences"]          = Chapter18.KeySequences.Run,
            };

            if (args.Length > 0)
            {
                cliExamples.Lookup(args[0])
                .Match(
                    None: () => Console.WriteLine($"Unknown option: '{args[0]}'"),
                    Some: (main) => main()
                    );
            }

            else
            {
                await Boc.Chapter9.Program.Run();
            }
            //StartWebApi();
        }
Esempio n. 28
0
        public ColourProvider()
        {
            var swatches = new SwatchesProvider().Swatches.AsArray();

            Swatches = swatches.ToDictionary(s => s.Name);

            var accents = swatches.Where(s => s.IsAccented).ToArray();
            var orders  = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);

            ThemeConstants.Themes.Select((str, idx) => new { str, idx })
            .ForEach(x => orders[x.str] = x.idx);

            Hues = accents
                   .OrderBy(x => orders.Lookup(x.Name).ValueOr(() => 100))
                   .SelectMany(swatch =>
            {
                return(swatch.AccentHues.Select(hue => new Hue(swatch.Name, hue.Name, hue.Foreground, hue.Color)));
            })
                   .ToArray();

            HueCache = Hues.ToDictionary(h => h.Key);
        }
Esempio n. 29
0
        public ColourProvider()
        {
            var swatches = new SwatchesProvider()
                           .Swatches.Where(s => s.IsAccented).ToArray();

            var orders = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);

            _order.Select((str, idx) => new { str, idx })

            .ForEach(x => orders[x.str] = x.idx);

            Hues = swatches
                   .OrderBy(x => orders.Lookup(x.Name).ValueOr(() => 100))
                   .SelectMany(swatch =>
            {
                return(swatch.AccentHues.Select(hue => new Hue(swatch.Name, hue.Name, hue.Foreground, hue.Color)));
            })
                   .ToArray();

            DefaultHighlight = Hues
                               .Last(s => s.Swatch.Equals("amber", StringComparison.OrdinalIgnoreCase));
        }
Esempio n. 30
0
        public MemoryStorageGraph()
        {
            usedIDs.Add(StorageObjectID.Zero.ID);
            usedIDs.Add(StorageObjectID.Any.ID);

            root = new RootMemoryStorageObject(this);

            arrows_to_sink.Lookup(StorageObjectID.Zero);
            arrows_to_sink_inverse.Lookup(StorageObjectID.Zero);
            arrows_to_source.Lookup(StorageObjectID.Zero);
            arrows_to_source_inverse.Lookup(StorageObjectID.Zero);
            node_refcount.Add(StorageObjectID.Zero, 0);

            messagestore =
                new TreeIOMessageReactor(
                    Messages,
                    Listeners
                    );
            //new BruteIOMessageReactor(
            //        Messages,
            //        Listeners
            //    );
        }
        public void LookupWhenNotFound()
        {
            var dict = new Dictionary<int, string>();

            Assert.IsFalse(dict.Lookup(2).HasValue);
        }
Esempio n. 32
0
        static void ProcessTestResult(TestResult testResult, Dictionary<string, ReferenceData> referenceActionLogs)
        {
            Log.Info("Processing test result: {0}", testResult.Name);

            foreach (var testResultActionLog in testResult.ActionLogs)
            {
                Log.Info("Processing test result action log: {0}", testResultActionLog.ActionLogName);
                var referenceDataActionLog = referenceActionLogs
                    .Lookup(testResultActionLog.ActionLogName)
                    ;

                if (referenceDataActionLog == null)
                {
                    Log.Warning("No matching reference action log found: {0}", testResultActionLog.ActionLogName);
                    continue;
                }

                try
                {
                    ProcessActionLog(referenceDataActionLog, testResult, testResultActionLog);
                }
                catch (ExitCodeException)
                {
                    throw;
                }
                catch (Exception exc)
                {
                    Log.Warning("Error while processing result action log: {0}", exc.Message);
                }
            }
        }
Esempio n. 33
0
        public void Reload()
        {
            var homeDir = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH");

            Dictionary<string, string> ini;
            try {
                ini = ReadIniFile(Path.Combine(homeDir, ".souse"));
            } catch (IOException) {
                ini = new Dictionary<string, string>();
            }

            AudioRate = ini.Lookup("audio-in-sample-rate").Select(int.Parse).OrElse(44100);
            AudioBits = ini.Lookup("audio-in-bits").Select(int.Parse).OrElse(16);
            AudioChannels = ini.Lookup("audio-in-channels").Select(int.Parse).OrElse(1);
            AudioBufferSize = ini.Lookup("audio-in-buffer-size").Select(int.Parse).OrElse(6144);
            AudioBufferCount = ini.Lookup("audio-in-buffer-count").Select(int.Parse).OrElse(4);
            AnalysisHighPassFreq = ini.Lookup("analysis-high-pass-frequency").Select(int.Parse).OrElse(1000);
            AnalysisLowPassFreq = ini.Lookup("analysis-low-pass-frequency").Select(int.Parse).OrElse(20000);
            AnalysisTotalSensitivity = ini.Lookup("analysis-total-sensitivity").Select(double.Parse).OrElse(0.015);
            AnalysisBucketSensitivity = ini.Lookup("analysis-bucket-sensitivity").Select(double.Parse).OrElse(0.015);
            AnalysisA440 = ini.Lookup("analysis-a440").Select(double.Parse).OrElse(440);
            RPCBindPrefix = ini.Lookup("rpc-bind-prefix").OrElse((string) null);
        }
Esempio n. 34
0
        protected void AdjustGlobalTracking(uint uIP, bool bIncrease)
        {
            // IP
            uint nSameIPCount = 0;

            s_mapGlobalContactIPs.Lookup(uIP, nSameIPCount);
            if (bIncrease)
            {
                if (nSameIPCount >= MAX_CONTACTS_IP)
                {
                    Debug.Assert(false);
                    //DebugLogError("RoutingBin Global IP Tracking inconsitency on increase (%s)", ipstr(ntohl(uIP)));
                }
                nSameIPCount++;
            }
            else if (!bIncrease)
            {
                if (nSameIPCount == 0)
                {
                    Debug.Assert(false);
                    //DebugLogError("RoutingBin Global IP Tracking inconsitency on decrease (%s)", ipstr(ntohl(uIP)));
                }
                else
                {
                    nSameIPCount--;
                }
            }
            if (nSameIPCount != 0)
            {
                s_mapGlobalContactIPs.SetAt(uIP, nSameIPCount);
            }
            else
            {
                s_mapGlobalContactIPs.RemoveKey(uIP);
            }

            // Subnet
            uint nSameSubnetCount = 0;

            s_mapGlobalContactSubnets.Lookup(uIP & 0xFFFFFF00, nSameSubnetCount);
            if (bIncrease)
            {
                if (nSameSubnetCount >= MAX_CONTACTS_SUBNET && !OtherFunctions.IsLANIP((uint)IPAddress.NetworkToHostOrder(uIP)))
                {
                    Debug.Assert(false);
                    //DebugLogError("RoutingBin Global Subnet Tracking inconsitency on increase (%s)", ipstr(ntohl(uIP)));
                }
                nSameSubnetCount++;
            }
            else if (!bIncrease)
            {
                if (nSameSubnetCount == 0)
                {
                    Debug.Assert(false);
                    //DebugLogError("RoutingBin Global IP Subnet inconsitency on decrease (%s)", ipstr(ntohl(uIP)));
                }
                else
                {
                    nSameSubnetCount--;
                }
            }
            if (nSameSubnetCount != 0)
            {
                s_mapGlobalContactSubnets.SetAt(uIP & 0xFFFFFF00, nSameSubnetCount);
            }
            else
            {
                s_mapGlobalContactSubnets.RemoveKey(uIP & 0xFFFFFF00);
            }
        }
Esempio n. 35
0
        private static IChangeSet <TValue> Process(Dictionary <TValue, int> values, ChangeAwareList <TValue> result, IChangeSet <ItemWithMatch> changes)
        {
            void AddAction(TValue value) => values.Lookup(value)
            .IfHasValue(count => values[value] = count + 1)
            .Else(() =>
            {
                values[value] = 1;
                result.Add(value);
            });

            void RemoveAction(TValue value)
            {
                var counter = values.Lookup(value);

                if (!counter.HasValue)
                {
                    return;
                }

                //decrement counter
                var newCount = counter.Value - 1;

                values[value] = newCount;
                if (newCount != 0)
                {
                    return;
                }

                //if there are none, then remove and notify
                result.Remove(value);
                values.Remove(value);
            }

            foreach (var change in changes)
            {
                switch (change.Reason)
                {
                case ListChangeReason.Add:
                {
                    var value = change.Item.Current.Value;
                    AddAction(value);
                    break;
                }

                case ListChangeReason.AddRange:
                {
                    change.Range.Select(item => item.Value).ForEach(AddAction);
                    break;
                }

                case ListChangeReason.Refresh:
                {
                    var value    = change.Item.Current.Value;
                    var previous = change.Item.Current.Previous;
                    if (value.Equals(previous))
                    {
                        continue;
                    }

                    RemoveAction(previous);
                    AddAction(value);
                    break;
                }

                case ListChangeReason.Replace:
                {
                    var value    = change.Item.Current.Value;
                    var previous = change.Item.Previous.Value.Value;
                    if (value.Equals(previous))
                    {
                        continue;
                    }

                    RemoveAction(previous);
                    AddAction(value);
                    break;
                }

                case ListChangeReason.Remove:
                {
                    var previous = change.Item.Current.Value;
                    RemoveAction(previous);
                    break;
                }

                case ListChangeReason.RemoveRange:
                {
                    change.Range.Select(item => item.Value).ForEach(RemoveAction);
                    break;
                }

                case ListChangeReason.Clear:
                {
                    result.Clear();
                    values.Clear();
                    break;
                }
                }
            }

            return(result.CaptureChanges());
        }
Esempio n. 36
0
 public Optional <TObject> Lookup(TKey key)
 {
     return(_data.Lookup(key));
 }
        // Then enrich the implementation so that `GetWorkPermit`
        // returns `None` if the work permit has expired.

        static Option <WorkPermit> GetValidWorkPermit(Dictionary <string, Employee> employees, string employeeId)
        => employees
        .Lookup(employeeId)
        .Bind(e => e.WorkPermit)
        .Where(HasExpired.Negate());
        // 3 Use Bind and an Option-returning Lookup function (such as the one we defined
        // in chapter 3) to implement GetWorkPermit, shown below.

        static Option <WorkPermit> GetWorkPermit(Dictionary <string, Employee> employees, string employeeId)
        => employees.Lookup(employeeId).Bind(e => e.WorkPermit);