Ejemplo n.º 1
0
        public void Append(Block <T> block, DateTimeOffset currentTime)
        {
            try
            {
                _rwlock.EnterWriteLock();

                Validate(Enumerable.Append(this, block), currentTime);
                Blocks[block.Hash] = block;
                EvaluateActions(block);

                long        index = Store.AppendIndex(Id.ToString(), block.Hash);
                ISet <TxId> txIds = block.Transactions
                                    .Select(t => t.Id)
                                    .ToImmutableHashSet();

                Store.UnstageTransactionIds(Id.ToString(), txIds);
                foreach (Transaction <T> tx in block.Transactions)
                {
                    Store.AppendAddressTransactionId(
                        Id.ToString(), tx.Recipient, tx.Id
                        );
                }
            }
            finally
            {
                _rwlock.ExitWriteLock();
            }
        }
        void Adding(object[] sut, object item)
        {
            var items = Enumerable.Append(sut, item);

            Assert.Equal(item, items.Last());
            Assert.Equal(sut.First(), items.First());
        }
        public async Task AppendWithNullableDecimalSourceWithElementIsEquivalentToAppendTest()
        {
            // Arrange

            // Arrange 'queryAdapter' parameter
            var queryAdapter = await GetQueryAdapterAsync(DisallowAll);

            // Arrange 'source' parameter
            var source = GetQueryable <decimal?>();

            // Arrange 'asyncSource' parameter
            var asyncSource = queryAdapter.GetAsyncQueryable <decimal?>();

            // Arrange 'element' parameter
            var element = 5;

            // Arrange 'expectedResult' parameter
            var expectedResult =
                Enumerable
                .Append <decimal?>(source, element);

            // Act
            var result = await AsyncQueryable.Append <decimal?>(asyncSource, element).ToListAsync().ConfigureAwait(false);

            // Assert
            Assert.Equal(expectedResult, result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Converts 4 chars
        /// </summary>
        /// <returns>be int value</returns>
        public static int GetMagicBytesBE(params byte[] chars)
        {
            if (chars.Length > 4)
            {
                return(0);
            }

            IEnumerable <byte> v = chars.AsEnumerable();

            if (chars.Length == 3)
            {
                v = Enumerable.Append(v, (byte)0);
            }
            else if (chars.Length < 4)
            {
                v = Enumerable.Concat(v, Enumerable.Repeat((byte)0, chars.Length - 4));
            }

            unsafe
            {
                fixed(byte *chs = v.ToArray())
                {
                    return(Marshal.ReadInt32((IntPtr)chs));
                }
            }
        }
Ejemplo n.º 5
0
        public void Append(Block <T> block, DateTimeOffset currentTime)
        {
            try
            {
                _rwlock.EnterWriteLock();

                HashDigest <SHA256>?tip =
                    Store.IndexBlockHash(Id.ToString(), -1);

                block.Validate(
                    currentTime,
                    a => GetStates(new[] { a }, tip).GetValueOrDefault(a));
                Validate(Enumerable.Append(this, block), currentTime);

                Blocks[block.Hash] = block;
                EvaluateActions(block);

                Store.AppendIndex(Id.ToString(), block.Hash);
                ISet <TxId> txIds = block.Transactions
                                    .Select(t => t.Id)
                                    .ToImmutableHashSet();

                Store.UnstageTransactionIds(txIds);
            }
            finally
            {
                _rwlock.ExitWriteLock();
            }
        }
Ejemplo n.º 6
0
 public void EnumAppendTest()
 {
     var l1 = new List <string> {
         "123"
     };
     var l2 = Enumerable.Append(l1, "11111");
     var l3 = Enumerable.Prepend(l1, "2222");
 }
Ejemplo n.º 7
0
        public async Task RunAsync()
        {
            var thisTask   = EndPoint.RunAsync();
            var otherTasks = from service in _Services
                             where service != this
                             select service.RunAsync();

            var allTasks = Enumerable.Append(otherTasks, thisTask);

            await Task.WhenAll(allTasks);
        }
Ejemplo n.º 8
0
        public async Task RunAsync()
        {
            var tasks = new List <Task>();
            Task <HttpListenerContext> listenerTask = HttpListener.GetContextAsync();

            while (true)
            {
                // Wait until client connects
                // We need to let client connections keep running, so await everything.

                Logger.Log(Constants.Component, $"{HttpListener.Prefixes.First()} listing for new connections and on {tasks.Count} existing connections");

                // And wait for something to happen. Note that multiple things can happen at the
                // same time.
                Task completedTask = await Task.WhenAny(Enumerable.Append(tasks, listenerTask));

                // If it's one of the client connection tasks ending then we just need to stop waiting for it.
                if (completedTask != listenerTask)
                {
                    tasks.Remove(completedTask);
                }
                // If we got a new connection we need to start handling that connection, and start
                // listening for new connections.
                else
                {
                    // Otherwise we know it's a new connection we need to handle.
                    HttpListenerContext context = listenerTask.Result;

                    if (context.Request.IsWebSocketRequest)
                    {
                        // Turn the HTTP connection into a websocket connection
                        var client = (await context.AcceptWebSocketAsync(null)).WebSocket;

                        // Create the client connection and run it.
                        tasks.Add(new ClientConnection(client,
                                                       CommandDecoder,
                                                       CommandDispatcher,
                                                       Logger)
                                  .RunAsync()
                                  );
                    }
                    else
                    {
                        // Return empty body in case http message and return bad request as we only expect websocket
                        // The 400 Bad Request error is an HTTP status code that means that the request you sent to the website server,
                        // often something simple like a request to load a web page, was somehow incorrect or corrupted and the server couldn't understand it.
                        context.Response.StatusCode = 400;
                        context.Response.Close();
                    }
                    // Restart listening for new connections.
                    listenerTask = HttpListener.GetContextAsync();
                }
            }
        }
Ejemplo n.º 9
0
        public Task Insert(TransactionPayment elem, int merchantId)
        {
            if (!transactions.ContainsKey(merchantId))
            {
                transactions.Add(merchantId, new ConcurrentBag <TransactionPayment>()
                {
                    elem
                });
                return(Task.CompletedTask);
            }

            var transaction = transactions[merchantId];

            transactions[merchantId] = Enumerable.Append(transaction, elem);

            return(Task.CompletedTask);
        }
Ejemplo n.º 10
0
        public void Append(Block <T> block)
        {
            Validate(Enumerable.Append(this, block));
            Blocks[block.Hash] = block;
            EvaluateActions(block);

            long        index = Store.AppendIndex(block.Hash);
            ISet <TxId> txIds = block.Transactions
                                .Select(t => t.Id)
                                .ToImmutableHashSet();

            Store.UnstageTransactionIds(txIds);
            foreach (Transaction <T> tx in block.Transactions)
            {
                Store.AppendAddressTransactionId(tx.Recipient, tx.Id);
            }
        }
Ejemplo n.º 11
0
        public static IEnumerable <INamedTypeSymbol> GetAllTypes(this INamespaceOrTypeSymbol symbol, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            IEnumerable <INamedTypeSymbol> result = Enumerable.Empty <INamedTypeSymbol>();

            if (symbol is INamespaceSymbol ns)
            {
                result = result.Concat(ns.GetMembers().SelectMany(subNs => GetAllTypes(subNs, cancellationToken)));
            }
            else if (symbol is INamedTypeSymbol ts)
            {
                result = Enumerable.Append(result, ts);
                result = result.Concat(ts.GetTypeMembers().SelectMany(subType => GetAllTypes(subType, cancellationToken)));
            }

            return(result);
        }
Ejemplo n.º 12
0
        public async Task <GetNotesNoteModel> GetNotesAsync(string noteId = null)
        {
            GetNotesNoteModel response = new GetNotesNoteModel();

            if (noteId is null)
            {
                var items = await _homeRepository.GetAllAsync();

                response.Items = _mapper.Map <IEnumerable <GetNotesHomeModelItem> >(items);
            }
            if (!(noteId is null))
            {
                var item = await _homeRepository.GetByIdAsync(noteId);

                response.Items = new List <GetNotesHomeModelItem>();
                response.Items = Enumerable.Append(response.Items, _mapper.Map <GetNotesHomeModelItem>(item));
            }

            return(response);
        }
Ejemplo n.º 13
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var items = (IEnumerable <object>)value;

            return(Enumerable.Append(items, parameter));
        }
Ejemplo n.º 14
0
    public static long Solve(string[] lines)
    {
        var groups = lines.Split("").ToArray();

        var fields = groups[0].Select(fieldstr =>
        {
            return(fieldstr.Split(": ")[1].Split(" or ")
                   .Select(rangestr => rangestr.Split("-").Select(int.Parse).Fold((min, max) => (min: min, max: max))
                           ).ToArray());
        }).ToArray();

        var fieldNames = groups[0].Select(fieldstr =>
        {
            return(fieldstr.Split(": ")[0]);
        }).ToArray();

        //W(fields.ToDelimitedString(","));

        var myticket = groups[1].ElementAt(1).Split(",").Select(int.Parse).ToArray();

        var tickets = groups[2].Skip(1).Select(
            ticketstr => ticketstr.Split(",").Select(int.Parse).ToArray()
            ).ToArray();

        //        W(tickets.Select(t => "(" + t.ToDelimitedString(",") + ")").ToDelimitedString(","));
        W(myticket.ToDelimitedString(","));

        var validTickets = Enumerable.Append(tickets, myticket).Where(values =>
                                                                      values.All(value => fields.Any(ranges => ranges.Any(range =>
                                                                                                                          value >= range.min && value <= range.max
                                                                                                                          )))
                                                                      );

        W(validTickets.Select(t => "(" + t.ToDelimitedString(",") + ")").ToDelimitedString(","));

        int fieldCount = tickets[0].Length;
        var positionSetByFieldIndex = tickets[0].Select((x) => Enumerable.ToHashSet(Enumerable.Range(0, fieldCount))).ToArray();

        foreach (var ticket in validTickets)
        {
            for (int position = 0; position < ticket.Length; position++)
            {
                for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
                {
                    if (!fields[fieldIndex].Any(range => ticket[position] >= range.min && ticket[position] <= range.max))
                    {
                        W($"field {fieldIndex} can't be in position {position}");
                        positionSetByFieldIndex[fieldIndex].Remove(position);
                    }
                }
            }
        }

        W(positionSetByFieldIndex.Select((s, i) => $"{i}:{s.ToDelimitedString(",")}").ToDelimitedString("; "));

        while (positionSetByFieldIndex.Any(s => s.Count > 1))
        {
            for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
            {
                if (positionSetByFieldIndex[fieldIndex].Count == 1)
                {
                    int fieldPos = positionSetByFieldIndex[fieldIndex].First();
                    W($"found position for field {fieldIndex}: {fieldPos}");
                    for (int otherFieldIndex = 0; otherFieldIndex < fieldCount; otherFieldIndex++)
                    {
                        if (otherFieldIndex != fieldIndex)
                        {
                            positionSetByFieldIndex[otherFieldIndex].Remove(fieldPos);
                        }
                    }
                }
            }
        }

        W(positionSetByFieldIndex.Select((s, i) => $"{i}:{s.ToDelimitedString(",")}").ToDelimitedString("; "));

        var fieldPositions = positionSetByFieldIndex
                             .Select((s, j) => (position: s.First(), index: j))
                             .ToArray();

        var departurePos = fieldPositions
                           .Where((position, fieldIndex) => fieldNames[fieldIndex].StartsWith("departure"))
                           .Select(field => field.position);

        W($"departure pos: {departurePos.ToDelimitedString(",")}");

        var mydeparture = departurePos.Select(position => (long)myticket[position]);

        W($"my departure fields: {mydeparture.ToDelimitedString(",")}");

        return(mydeparture.Product());
    }
    private int[] Analyze(string reference)
    {
        if (!reference.IsNullOrEmpty())
        {
            reference = reference.SanitizeAndTrimEmptyLinesAndSpaces();
            int countSpaces = reference.Count(c => c == ' ');
            int countPoints = reference.Count(c => c == '.');
            if (countPoints == 0 && !reference.Any(c => char.IsNumber(c)))
            {
                return new int[] { getBookRef(reference), 1, 1 }
            }
            ;
            if (countSpaces == 0 && char.IsNumber(reference[0]))
            {
                if (countPoints == 0)
                {
                    return(Enumerable.Append(Enumerable.Append(reference.Split('.').Select(int.Parse), 1), 1).ToArray());
                }
                if (countPoints == 1)
                {
                    return(Enumerable.Append(reference.Split('.').Select(int.Parse), 1).ToArray());
                }
                if (countPoints >= 2)
                {
                    return(reference.Split('.').Select(int.Parse).Take(3).ToArray());
                }
            }
            else
            {
                try
                {
                    var itemsVerse     = new int[3];
                    var partsAllSpaced = reference.Split(' ');
                    var partVerseRef   = partsAllSpaced[partsAllSpaced.Length - 1].Split('.');
                    if (partVerseRef.Length >= 1)
                    {
                        itemsVerse[1] = int.Parse(partVerseRef[0]);
                    }
                    if (partVerseRef.Length >= 2)
                    {
                        itemsVerse[2] = int.Parse(partVerseRef[1]);
                    }
                    string book = countSpaces == 1
            ? partsAllSpaced[0]
            : partsAllSpaced[0] + " " + partsAllSpaced[1];
                    itemsVerse[0] = getBookRef(book);
                    return(itemsVerse);
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(AppTranslations.ReferenceError.GetLang(reference), ex);
                }
            }
        }
        throw new ArgumentException(AppTranslations.ReferenceError.GetLang(reference));
        //
        int getBookRef(string name)
        => ApplicationDatabase.Instance
        .Books
        .First(book => BookInfos.Transcriptions[Language.EN][(TanakBook)book.Number].RawContains(name) ||
               BookInfos.Transcriptions[Language.FR][(TanakBook)book.Number].RawContains(name) ||
               BookInfos.Common[Language.EN][(TanakBook)book.Number].RawContains(name) ||
               BookInfos.Common[Language.FR][(TanakBook)book.Number].RawContains(name)).Number;
    }
}
Ejemplo n.º 16
0
 public static IEnumerable <TSource> Append <TSource>(IEnumerable <TSource> source, TSource element) => Enumerable.Append(source, element);
Ejemplo n.º 17
0
    private static bool IsTestProgramDotsRuntimeCompatible(DotsRuntimeCSharpProgram arg)
    {
        //We need a better way of knowing which asmdefs are supposed to work on dots-runtime, and which do not.  for now use a simple heuristic of "is it called Editor or is it called Hybrid"
        var allFileNames = Enumerable.Append(arg.References.ForAny().OfType <CSharpProgram>().Select(r => r.FileName), arg.FileName).ToArray();

        if (allFileNames.Any(f => f.Contains("Editor")))
        {
            return(false);
        }
        if (allFileNames.Any(f => f.Contains("Hybrid")))
        {
            return(false);
        }
        if (allFileNames.Any(f => f.Contains("Unity.TextMeshPro")))
        {
            return(false);
        }
        if (allFileNames.Any(f => f.Contains("Unity.ugui")))
        {
            return(false);
        }
        //in theory, all tests for assemblies that are used by dotsruntime targetting programs should be dots runtime compatible
        //unfortunately we have some tests today that test dotsruntime compatible code,  but the testcode itself is not dotsruntime compatible.
        //blacklist these for now
        if (arg.FileName.Contains("Unity.Scenes.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Build.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Build.Common.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Authoring"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Serialization"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Entities.Reflection.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Properties"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Entities.Properties"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Burst.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.jobs.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Collections.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Automation.Tests"))
        {
            return(false);
        }
        if (arg.FileName.Contains(".CodeGen"))
        {
            return(false);
        }
        if (arg.FileName.Contains("Unity.Entities.Determinism.Tests"))
        {
            return(false);
        }

        return(true);
    }
Ejemplo n.º 18
0
 public static IEnumerable <Task <T> > Append <T>(this IEnumerable <Task <T> > tasks, Task <T> task) =>
 Enumerable.Append(tasks, task);