public async Task LoadBlocks()
        {
            IsBusy        = true;
            IsGridVisible = false;

            try
            {
                var blocks = await Task.Run(() => _blockRepository.LoadBlocks());

                Blocks.Clear();
                foreach (var block in blocks)
                {
                    Blocks.Add(CreateBlockViewModel(block));
                }

                IsGridVisible = true;
            }
            catch (Exception)
            {
                MessageBox.Show(Resources.ErrorLoadingBlocks, Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                Blocks.Clear();
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #2
0
        public object AddMessage(Message message, User user, object textObject)
        {
            Action <Message, User, Paragraph> handler;

            if (!_handlers.TryGetValue(message.Type, out handler))
            {
                return(null);
            }
            var paragraph = new Paragraph {
                Margin = new Thickness(0)
            };

            handler(message, user, paragraph);

            var after = textObject as Paragraph;

            if (after != null)
            {
                Blocks.InsertAfter(after, paragraph);
            }
            else
            {
                Blocks.Add(paragraph);
            }

            return(paragraph);
        }
Example #3
0
        public void Load()
        {
            if (_load)
            {
                return;
            }

            _load = true;
            Blocks.Clear();
            TorchBase.Instance.Invoke(() =>
            {
                foreach (var block in Grid.GetFatBlocks().Where(b => b is IMyTerminalBlock))
                {
                    Blocks.Add(new BlockViewModel((IMyTerminalBlock)block, Tree));
                }

                Grid.OnBlockAdded   += Grid_OnBlockAdded;
                Grid.OnBlockRemoved += Grid_OnBlockRemoved;

                Tree.ControlDispatcher.BeginInvoke(() =>
                {
                    Blocks.Sort(b => b.Block.CustomName);
                });
            });
        }
Example #4
0
 private void GetBlocks(XElement curNode)
 {
     if (curNode.Name.Equals(Xns + "img"))
     {
         int        id     = ImageBlocks.Count;
         ImageBlock iBlock = new ImageBlock(id, curNode, this);
         ImageBlocks.Add(iBlock);
         curNode.SetAttributeValue("id", iBlock.B_ID);
         Blocks.Add(iBlock);
     }
     foreach (XNode childNode in curNode.Nodes())
     {
         if (childNode is XText)
         {
             XText        textNode = childNode as XText;
             int          id       = ContentBlocks.Count;
             String       text     = textNode.Value;
             ContentBlock cBlock   = new ContentBlock(id, text, this);
             ContentBlocks.Add(cBlock);
             textNode.Value = cBlock.B_ID;
             Blocks.Add(cBlock);
         }
         else if (childNode is XElement)
         {
             GetBlocks(childNode as XElement);
         }
     }
 }
Example #5
0
        void ResetBlocks()
        {
            var first = Blocks.First();

            Blocks.Clear();
            Blocks.Add(first);
        }
Example #6
0
        public Block TryLoadBlock(ByteString id, byte[] data)
        {
            // Data should not exceed the maximum size.
            if (data.Length > MaximumBlockSize)
            {
                throw new ArgumentException(nameof(data));
            }

            // Integrity check.
            var computedId = BlockchainUtil.ComputeBlockId(data);

            if (!ByteString.CopyFrom(computedId).Equals(id))
            {
                throw new ArgumentException(nameof(id));
            }

            // Try to deserialize the data for format validity check.
            var block = BlockchainUtil.DeserializeBlock(data);

            lock (Blocks)
            {
                if (Blocks.ContainsKey(id))
                {
                    return(null);
                }
                Blocks.Add(id, data);
            }

            // Schedule the block for execution.
            Executor.ProcessBlock(block);

            return(block);
        }
Example #7
0
        protected override void SetMasterElementValue(ulong id, ulong size)
        {
            switch (id)
            {
            case ElementID.SilentTracks:
                SilentTracks = new SilentTracks
                {
                    Stream = this.Stream,
                    Offset = this.Stream.Position,
                    Size   = size
                };
                SilentTracks.LoadChildren();
                break;

            case ElementID.SimpleBlock:
                Blocks.Add(new SimpleBlock
                {
                    Stream = this.Stream,
                    Offset = this.Stream.Position,
                    Size   = size
                });
                Stream.Seek((long)size, System.IO.SeekOrigin.Current);
                break;

            case ElementID.BlockGroup:
                Blocks.Add(new BlockGroup
                {
                    Stream = this.Stream,
                    Offset = this.Stream.Position,
                    Size   = size
                });
                Stream.Seek((long)size, System.IO.SeekOrigin.Current);
                break;
            }
        }
Example #8
0
 private void LoopRestBlocks(bool[,] matrix)
 {
     for (int i = 0; i < Rows; i++)
     {
         for (int j = 0; j < Columns; j++)
         {
             if (matrix[i, j])
             {
                 continue;
             }
             var lartestSize = LargestSizeAt(i, j, matrix);
             var size        = rnd.Next(1, lartestSize + 1);
             Blocks.Add(new Block {
                 X = j, Y = i, Size = size
             });
             for (int r = i; r < i + size; r++)
             {
                 for (int c = j; c < j + size; c++)
                 {
                     matrix[r, c] = true;
                 }
             }
         }
     }
 }
Example #9
0
        public void InitializeGrid(int rows = 10, int cols = 18)
        {
            containerGrid.Children.Clear();
            containerGrid.RowDefinitions.Clear();
            containerGrid.ColumnDefinitions.Clear();
            Rows    = rows;
            Columns = cols;

            for (int i = 0; i < Rows; i++)
            {
                containerGrid.RowDefinitions.Add(new RowDefinition {
                    Height = new GridLength(GridLength)
                });
            }
            for (int i = 0; i < Columns; i++)
            {
                containerGrid.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(GridLength)
                });
            }

            Blocks.Clear();

            var matrix = new bool[Rows, Columns];
            var areas  = Depart(Rows, Columns);

            foreach (var area in areas)
            {
                FindLargestBlock(area, matrix, out var block);
                Blocks.Add(block);
            }

            LoopRestBlocks(matrix);
        }
Example #10
0
        public void AddBlock(String label, TimeSpan time)
        {
            if (HasStarted)
            {
                return;
            }

            var interval = new IntervalBlock();

            interval.CenterText  = label;
            interval.CurrentTime = time;
            interval.OnFinished += delegate(object o, EventArgs args)
            {
                _elapsedTime = _elapsedTime.Add(interval.OriginalTime);
                if (Blocks.Count == Blocks.Count(b => b.HasFinished))
                {
                    Stop();
                    HasFinished = true;
                    var oldBlock = CurrentBlock;
                    Blocks.RemoveAt(0);
                    Blocks.Add(oldBlock);
                }
                else
                {
                    StartNextBlock();
                }

                Common.PlaySound(Common.AlertSound1);
            };
            RemainingTime = RemainingTime.Add(interval.CurrentTime);
            _orignalTime  = RemainingTime; // keep the original time in memory so we can substract when running
            Blocks.Add(interval);
        }
Example #11
0
        /// <summary>
        /// Добавить блок
        /// </summary>
        /// <param name="data"></param>
        /// <param name="user"></param>

        public void Add(string data, string user)
        {
            var block = new Block(data, user, Last);

            Blocks.Add(block);
            Last = block;
        }
Example #12
0
        private void AddReturnDetails(List <Block> parsedBlocks)
        {
            TypeRef returnTypeRef = _method.GetReturnType();

            if (returnTypeRef == WellKnownTypeDef.Void)
            {
                return;
            }

            Blocks.Add(new Header3("Returns"));

            (EntryKey typeKey, string typeName) = CreateEntryKey(returnTypeRef);

            // build the page output
            Inline type = new Run(typeName);

            if (typeKey != null)
            {
                type = new Hyperlink(new Run(typeName));
                ((Hyperlink)type).Tag    = typeKey;
                ((Hyperlink)type).Click += new System.Windows.RoutedEventHandler(LinkHelper.Resolve);
            }

            Blocks.Add(new Paragraph(type));

            if (parsedBlocks != null)
            {
                Block found = parsedBlocks.Find(currentBlock => currentBlock is Returns);
                if (found != null)
                {
                    Blocks.Add(found);
                }
            }
        }
        public IWorksheetBlock <T> CreateBlock <T>()
        {
            var block = new WorksheetBlock <T>();

            Blocks.Add(block);
            return(block);
        }
Example #14
0
        public void Add(Block block)
        {
            var lastBlock = Blocks.Last();

            block.PreviousHash = lastBlock.Hash;
            Blocks.Add(block);
        }
Example #15
0
 public void AddBlock(PocBlock newBlock)
 {
     newBlock.PreviousHash = GetLatestBlock().Hash;
     newBlock.Index        = Blocks.Count;
     newBlock.MineBlock(Difficulty);
     Blocks.Add(newBlock);
 }
Example #16
0
        public bool MineBlock(int proof, ulong nodeId)
        {
            if (!ValidateProof(Blocks.Last(), proof))
            {
                return(false);
            }

            CurrentTransactions.Add(new Transaction
            {
                Amount = 1,
                From   = 0,
                To     = nodeId
            });

            var lastBlock = Blocks.Last();

            var block = new Block
            {
                Index         = lastBlock.Index + 1,
                Transactions  = CurrentTransactions.ToArray(),
                Proof         = proof,
                LastBlockHash = Hash(lastBlock),
                TimeStamp     = DateTime.UtcNow
            };

            Blocks.Add(block);
            CurrentTransactions = new List <Transaction>();

            return(true);
        }
Example #17
0
        private void ParseText(string[] lines)
        {
            INIBlock block = new INIBlock();

            block.Name = "";
            foreach (string lineCR in lines)
            {
                string line = lineCR.TrimEnd('\r');
                if (line.StartsWith("["))
                {
                    block      = new INIBlock();
                    block.Name = line;
                    if (!Blocks.ContainsKey(block.Name))
                    {
                        Blocks.Add(block.Name, block);
                    }
                    else
                    {
                        block = Blocks[block.Name];
                    }
                }
                else if (!line.StartsWith(";") && !line.StartsWith("#") && line.Contains("="))
                {
                    block.SetValue(line);
                }
            }
        }
Example #18
0
        public void Ops(CorrectVerifyValOps ops)
        {
            if (ops == CorrectVerifyValOps.AndOp)
            {
                return;
            }

            if (ops == CorrectVerifyValOps.AndOpWithNewScope)
            {
                var block = new CorrectVerifyValBlock();
                WorkingBlock.AddBlock(block, true);
                WorkingBlock = block;
            }

            if (ops == CorrectVerifyValOps.OrOp)
            {
                var block = new CorrectVerifyValBlock();
                Blocks.Add(block);
                WorkingBlock = block;
            }

            if (ops == CorrectVerifyValOps.OrOpWithSameScope)
            {
                var block = new CorrectVerifyValBlock();
                WorkingBlock.AddBlock(block, false);
                WorkingBlock = block;
            }
        }
Example #19
0
        /// <summary>
        ///
        /// </summary>
        public void Load()
        {
            updateHistoryStruct(POSTFIX_FILE_DUMP);
            lock (syncLock)
            {
                foreach (var itemHist in HistoryStruct)
                {
                    var filename = itemHist.Filename;// getFileNameDump(itemHist.Filename);
                    if (File.Exists(filename))
                    {
                        CandlesBlock block  = null;
                        bool         isLoad = false;

                        block = CandlesBlock.Load(filename);
                        if (block.NotIsNull())
                        {
                            var existBlock = Blocks.FirstOrDefault(b => b.IdTime == block.IdTime);
                            if (existBlock.IsNull())
                            {
                                Blocks.Add(block);
                                isLoad = true;
                            }
                        }
                        if (isLoad)
                        {
                            updateMergeCollection();
                            return;
                        }
                    }
                }
            }
        }
Example #20
0
 ///<summary>МЕТОД Инициализация отчета</summary>
 /// <param name="pNodes">Ветка</param>
 public override VirtualOtchet MET_Inizial(VirtualNodes pNodes)
 {
     // Если нужно формировать отчет
     if (PROP_NewCreate)
     {
         base.MET_Inizial(pNodes);
         PROP_Prefix = "kdl";
         // Ветка
         PROP_Nodes = pNodes;
         // Чистим блок
         Blocks.Clear();
         // Если есть заполенный протокол
         if (PROP_Nodes.PROP_shaPresenceProtokol)
         {
             MET_Otchet();                                               // Формируем отчет
         }
         else
         {
             MET_NoOtchet();                                             // Отчет не заполен
         }
         // Добавляем последний параграф в блок
         Blocks.Add(PRO_Paragraph);
         // Помечаем, что больше его формировать не надо
         PROP_NewCreate = false;
     }
     // Фон
     MET_Background();
     return(this);
 }
Example #21
0
        /// <summary>
        /// Occurs when <see cref="TokensSource"/> property changes.
        /// </summary>
        protected virtual async void OnTokensSourceChanged(string Value)
        {
            if (!TokensChangeHandled)
            {
                TextChangeHandled = true;

                await Dispatcher.BeginInvoke(() =>
                {
                    var d = TokenDelimiter.ToString();

                    //Check to see if delimiter occurs more than once in any one place.
                    var Temp = Regex.Replace(Value, d + "+", d);

                    //If so, correct it
                    if (Temp != Value)
                    {
                        TokensChangeHandled = true;
                        TokensSource        = Temp;
                        TokensChangeHandled = false;
                    }

                    Tokens.Clear();
                    Blocks.Clear();

                    if (Value?.ToString().IsEmpty() == false)
                    {
                        var p = new Paragraph();
                        Tokenizer?.Tokenize(Value, TokenDelimiter)?.ForEach(Token => p.Inlines.Add(GenerateInline(Token)));
                        Blocks.Add(p);
                    }
                });

                TextChangeHandled = false;
            }
        }
Example #22
0
        private void DoRead(int numBytes, Action <byte[], int, int> reader)
        {
            while (true)
            {
                if (Offset + numBytes < BlockSize)
                {
                    if (numBytes > 0)
                    {
                        reader(Blocks[CurrentBlock], Offset, numBytes);
                        Offset += numBytes;
                    }

                    return;
                }

                var firstLen  = BlockSize - Offset;
                var secondLen = numBytes - firstLen;
                reader(Blocks[CurrentBlock], Offset, firstLen);
                Offset        = 0;
                CurrentBlock += 1;
                if (Blocks.Count <= CurrentBlock)
                {
                    Blocks.Add(new byte[BlockSize]);
                }

                // Read remaining parts
                numBytes = secondLen;
            }
        }
Example #23
0
        public void initBlocks()
        {
            int currentBlock = 1;

            for (int r = 1; r <= 9; r++)
            {
                SquareContainer block = new SquareContainer(r, "block");
                Blocks.Add(block);
            }
            foreach (Square s in Squares)
            {
                int index = s.Index;
                if (index % 27 == 0)
                {
                    AddToBlock(currentBlock, s);
                    currentBlock++;
                }
                else if (index % 9 == 0)
                {
                    AddToBlock(currentBlock, s);
                    currentBlock -= 2;
                }
                else if (index % 3 == 0)
                {
                    AddToBlock(currentBlock, s);
                    currentBlock++;
                }
                else
                {
                    AddToBlock(currentBlock, s);
                }
            }
        }
Example #24
0
 /// <summary>
 /// Получает блок по свечам-объемам
 /// </summary>
 /// <param name="time"></param>
 /// <returns></returns>
 protected override HVolumeBlock getBlock(DateTime time)
 {
     lock (syncLock)
     {
         BlockTime timeBlock = BlockTime.ConvertForDay(time);
         if (lastUseBlock.NotIsNull())
         {
             if (lastUseBlock.IdTime == timeBlock)
             {
                 return(lastUseBlock);
             }
             lastUseBlock = null;
         }
         if (Blocks.Count > 0)
         {
             var block = Blocks.FirstOrDefault(b => b.IdTime == timeBlock);
             if (block.NotIsNull() && block.IdTime == timeBlock)
             {
                 lastUseBlock = block;
                 return(block);
             }
         }
         if (lastUseBlock.IsNull())
         {
             HVolumeBlock newBlock = loadByIdTime(timeBlock, POSTFIX_FILE_DUMP);
             if (newBlock.IsNull())
             {
                 newBlock = new HVolumeBlock(periodTimeFrame, timeBlock);
             }
             Blocks.Add(newBlock);
             lastUseBlock = newBlock;
         }
         return(lastUseBlock);
     }
 }
Example #25
0
        private void BuildLanguageBlockCollection()
        {
            var tokenizer = new MdTokenizer();
            var tokens    = tokenizer.Tokenize(TextBuffer.CurrentSnapshot.GetText());

            var rCodeTokens = tokens.Where(t => {
                var mct = t as MarkdownCodeToken;
                return(mct != null && mct.LeadingSeparatorLength > 1);
            });

            // TODO: incremental updates
            Blocks.Clear();
            _separators.Clear();

            foreach (MarkdownCodeToken t in rCodeTokens)
            {
                // Verify that code block is properly terminated.
                // If not, it ends at the end of the buffer.
                var text = t.GetText(TextBuffer.CurrentSnapshot);

                _separators.Add(new TextRange(t.Start, t.LeadingSeparatorLength)); // ```r{ or `r
                if (t.IsWellFormed)
                {
                    // Count backticks
                    Blocks.Add(TextRange.FromBounds(t.Start + t.LeadingSeparatorLength, t.End - t.TrailingSeparatorLength));
                    _separators.Add(new TextRange(t.End - t.TrailingSeparatorLength, t.TrailingSeparatorLength));
                }
                else
                {
                    Blocks.Add(TextRange.FromBounds(t.Start + t.LeadingSeparatorLength, t.End));
                }
            }
        }
Example #26
0
        private void BuildLanguageBlockCollection()
        {
            var tokenizer = new MdTokenizer();
            var tokens    = tokenizer.Tokenize(TextBuffer.CurrentSnapshot.GetText());

            var rCodeTokens = tokens.Where(t => t.TokenType == MarkdownTokenType.Code);

            // TODO: incremental updates
            Blocks.Clear();
            _separators.Clear();

            foreach (var t in rCodeTokens)
            {
                // Verify that code block is properly terminated.
                // If not, it ends at the end of the buffer.
                _separators.Add(new TextRange(t.Start, 5));
                if (t.IsWellFormed)
                {
                    Blocks.Add(TextRange.FromBounds(t.Start + 3, t.End - 3));
                    _separators.Add(new TextRange(t.End - 3, 3));
                }
                else
                {
                    Blocks.Add(TextRange.FromBounds(t.Start + 3, t.End));
                }
            }
        }
Example #27
0
 ///<summary>МЕТОД Инициализация отчета</summary>
 /// <param name="pNodes">Ветка</param>
 public override VirtualOtchet MET_Inizial(VirtualNodes pNodes)
 {
     // Если нужно формировать отчет
     if (PROP_NewCreate)
     {
         base.MET_Inizial(pNodes);
         // Список элементов
         PRO_PoleHistory = new Queue();
         // Чистим
         Blocks.Clear();
         // Формируем отчет
         MET_Otchet();
         // Добавляем последний параграф в блок
         Blocks.Add(PRO_Paragraph);
         // Помечаем, что больше его формировать не надо
         PROP_NewCreate = false;
         // Если всего один отчет, то сразу же его показываем
         if (PRO_PoleHistory.Count == 1)
         {
             UserPole_History _Pole = (UserPole_History)PRO_PoleHistory.Peek();
             // Окрываем эспандер
             _Pole.PROP_IsExpanded = true;
         }
     }
     return(this);
 }
Example #28
0
        public void Update(BlockColumnMeta update)
        {
            var pos = update.Position;

            if (!Position.GetBlockBounds().Contains(pos))
            {
                Log.InfoFormat("Region {0} with bounds {1} doesn't contain block {2}", Position, Position.GetBlockBounds(), pos);
                return;
            }

            var x = pos.X % Size;
            var z = pos.Z % Size;

            x = x < 0 ? Size + x : x;
            z = z < 0 ? Size + z : z;

            lock (_ioSync)
            {
                //Log.InfoFormat("Updating block {0},{1} @ {2}", x, z, update.Position);
                if (!Blocks.ContainsKey(x))
                {
                    Blocks.Add(x, new Dictionary <int, BlockColumnMeta>());
                }

                Blocks[x][z] = update;
                _isDirty     = true;
            }
        }
Example #29
0
        public MainWindow()
        {
            DataContext = this;

            foreach (var line in File.ReadAllLines("blocks.txt"))
            {
                var split = line.Split(' ');
                Blocks.Add(new Block {
                    Id = split[1], Name = split[0]
                });
            }

            foreach (var line in File.ReadAllLines("biomes.txt"))
            {
                var split = line.Split(' ');
                Biomes.Add(new Biome {
                    Id = split[1], Name = split[0]
                });
            }
            Builder = new ConfigBuilder();

            InitializeComponent();

            SelectedBlocks = new ReorderableList <Block>(selectedBlockList, "TString");
            UpdateString();
        }
Example #30
0
 private void GenerateMemory()
 {
     for (var i = 0; i < MemorySize; i++)
     {
         Blocks.Add(CpuBinary.Zero);
     }
 }