示例#1
0
 public void setSprite(BlockList val)
 {
     GetComponent <Animator>().runtimeAnimatorController = Resources.Load <RuntimeAnimatorController>("anim_" + val);
     GetComponent <SpriteRenderer>().sprite = Resources.LoadAll <Sprite>("block_" + val)[0];
     maxHit = (int)val;
     Debug.Log(val);
 }
示例#2
0
        public override void RewriteConditional(ref BasicBlock block)
        {
            var evaluated = Context.Options.IsFeatureEnabled(Feature);

            Scanner.LogDebug(1, $"REWRITE FEATURE CONDITIONAL: {Feature} {evaluated}");


            if (evaluated)
            {
                BlockList.DeleteBlock(ref block);
                return;
            }

            Context.LogMessage(MessageImportance.High, Environment.NewLine);
            Context.LogMessage(MessageImportance.High, $"Required feature `{Feature}` not available.");
#if FIXME
            Context.Context.Tracer.Dump();
#endif
            Context.LogMessage(MessageImportance.High, Environment.NewLine);

            var pns  = Context.Context.GetType("System.PlatformNotSupportedException");
            var ctor = pns?.Methods.FirstOrDefault(m => m.Name == ".ctor");
            if (ctor == null)
            {
                throw new OptimizerAssertionException($"Can't find `System.PlatformNotSupportedException`.");
            }

            Scanner.LogDebug(1, $"REWRITE FEATURE CONDITIONAL #1: {pns} {ctor}");

            var reference = Method.DeclaringType.Module.ImportReference(ctor);

            BlockList.ReplaceInstructionAt(ref block, 0, Instruction.Create(OpCodes.Newobj, reference));
            BlockList.ReplaceInstructionAt(ref block, 1, Instruction.Create(OpCodes.Throw));
        }
示例#3
0
 /// <summary>
 /// MyProgressBar Constructor
 /// </summary>
 public BlockedProgressBar()
 {
     InitializeComponent();
     _blockList = new BlockList();
     _direction = DirectionMode.Horizontal;
     SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer, true);
 }
示例#4
0
        /// <summary>
        /// Loads the block properties from the world into the chunk properties object.
        /// </summary>
        /// <param name="properties">The chunk properties to write to.</param>
        /// <param name="blockList">The block list to reference.</param>
        /// <param name="world">The world to load from.</param>
        /// <param name="chunkPos">The target chunk.</param>
        internal static void LoadProperties(ChunkProperties properties, BlockList blockList, World world, ChunkPosition chunkPos)
        {
            GetChunkGrid(world, chunkPos);
            properties.ChunkPosition = chunkPos;

            int size         = world.ChunkSize.Value;
            int intBits      = world.ChunkSize.IntBits;
            int extendedSize = size + 2;

            for (int x = -1; x <= size; x++)
            {
                for (int y = -1; y <= size; y++)
                {
                    for (int z = -1; z <= size; z++)
                    {
                        var local = (x & world.ChunkSize.Mask) * size * size
                                    + (y & world.ChunkSize.Mask) * size
                                    + (z & world.ChunkSize.Mask);

                        var chunkIndex = ((x >> intBits) + 1) * 3 * 3
                                         + ((y >> intBits) + 1) * 3
                                         + ((z >> intBits) + 1);

                        var index = (x + 1) * extendedSize * extendedSize
                                    + (y + 1) * extendedSize
                                    + (z + 1);

                        var blockId   = m_ChunkBuffer[chunkIndex]?.Blocks[local] ?? 0;
                        var blockType = blockList.GetBlockType(blockId);
                        properties.Blocks[index] = blockType;
                    }
                }
            }
        }
示例#5
0
 internal void DumpBlocks(int level = 1)
 {
     if (DebugLevel >= level)
     {
         BlockList.Dump();
     }
 }
示例#6
0
 public ColumnList(BlockList <StructT> list, Getter getter, Setter setter)
 {
     type        = typeof(DataT);
     this.list   = list;
     this.getter = getter;
     this.setter = setter;
 }
    public List <BlockList> getBlockListAll()
    {
        List <BlockList> blockList = new List <BlockList>();
        string           UserName, Gender, DateOfBirth, Email;


        int           Id;
        string        queryStr = "SELECT * FROM Expert Order By Id";
        SqlConnection conn     = new SqlConnection(connStr);
        SqlCommand    cmd      = new SqlCommand(queryStr, conn);

        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            Id       = int.Parse(reader["Id"].ToString());
            UserName = reader["UserName"].ToString();

            Gender      = reader["Gender"].ToString();
            DateOfBirth = reader["DateOfBirth"].ToString();

            Email = reader["Email"].ToString();
            object objEnabled = reader["Enabled"];
            Enabled = (objEnabled.GetType() != typeof(DBNull)) ? Convert.ToBoolean(objEnabled) : false;

            BlockList bl = new BlockList(Id, UserName, Gender, DateOfBirth, Email, Enabled);
            blockList.Add(bl);
        }
        conn.Close();
        reader.Close();
        reader.Dispose();
        return(blockList);
    }
示例#8
0
 private bool OnBlockReceived(ErrorCode error, UInt64 height, BlockList incoming, BlockList outgoing)
 {
     //TODO Avoid event processing if subscribers do not exist
     if (error == ErrorCode.Success && incoming != null && incoming.Count > 0)
     {
         logger_.LogInformation($"New block arrived ({height}). {incoming.Count} blocks arrived.Block zero TxCount:{incoming[0].TransactionCount}");
         string blockHash;
         string coinbaseTxHash;
         string destinationAddress;
         using (var getBlockResult = executor_.Chain.FetchBlockByHeightAsync(height).Result)
         {
             Utils.CheckBitprimApiErrorCode(getBlockResult.ErrorCode, "FetchBlockByHeightAsync(" + height + ") failed");
             IBlock newBlock = getBlockResult.Result.BlockData;
             blockHash = Binary.ByteArrayToHexString(newBlock.Hash);
             ITransaction coinbaseTx = newBlock.GetNthTransaction(0);
             coinbaseTxHash     = Binary.ByteArrayToHexString(coinbaseTx.Hash);
             destinationAddress = coinbaseTx.Outputs[0].PaymentAddress(executor_.UseTestnetRules).Encoded;
         }
         var newBlocksNotification = new
         {
             eventname       = "block",
             blockhash       = blockHash,
             coinbasetxid    = coinbaseTxHash,
             destinationaddr = destinationAddress
         };
         var task = webSocketHandler_.PublishBlock(JsonConvert.SerializeObject(newBlocksNotification));
         task.Wait();
     }
     return(true);
 }
        void RewriteAsIsInst(ref BasicBlock block)
        {
            Scanner.LogDebug(1, $"REWRITE AS ISINST: {block.Count} {block}");

            var reference = Assembly.MainModule.ImportReference(InstanceType);

            int index = 1;

            BlockList.InsertInstructionAt(ref block, index++, Instruction.Create(OpCodes.Isinst, reference));
            BlockList.InsertInstructionAt(ref block, index++, Instruction.Create(OpCodes.Dup));
            BlockList.ReplaceInstructionAt(ref block, index++, Instruction.Create(OpCodes.Stloc, Variable));
            BlockList.RemoveInstructionAt(ref block, index);

            switch (block.BranchType)
            {
            case BranchType.False:
            case BranchType.True:
                break;

            case BranchType.None:
            case BranchType.Return:
                // Convert it into a bool.
                BlockList.InsertInstructionAt(ref block, index++, Instruction.Create(OpCodes.Ldnull));
                BlockList.InsertInstructionAt(ref block, index++, Instruction.Create(OpCodes.Cgt_Un));
                break;

            default:
                throw DebugHelpers.AssertFailUnexpected(Method, block, block.BranchType);
            }
        }
    protected void gvBlockList_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int         result = 0;
        BlockList   blo    = new BlockList();
        GridViewRow row    = (GridViewRow)gvBlockList.Rows[e.RowIndex];
        // int id = int.Parse(gvBlockList.SelectedRow.Cells[0].Text);
        int id = int.Parse(gvBlockList.DataKeys[e.RowIndex].Value.ToString());
        // string tid = ((TextBox)row.Cells[0].Controls[0]).Text;
        // string userName = ((TextBox)row.Cells[1].Controls[0]).Text;
        // string gender = ((TextBox)row.Cells[2].Controls[0]).Text;
        // string dateOfBirth = ((TextBox)row.Cells[3].Controls[0]).Text;
        Boolean enabled = Convert.ToBoolean(((TextBox)row.Cells[5].Controls[0]).Text);

        result = blo.BlockListUpdate(id, enabled);
        if (result > 0)
        {
            Response.Write("<script>alert('BlockList updated successfully');</script>");
        }
        else
        {
            Response.Write("<script>alert('BlockList NOT updated');</script>");
        }
        gvBlockList.EditIndex = -1;
        bind();
    }
        public async Task GetBlocks_Test()
        {
            var block = new BlockWithTransactions
            {
                Header = _osTestHelper.GenerateBlock(HashHelper.ComputeFrom("PreBlockHash"), 100).Header
            };
            var blockList = new BlockList();

            blockList.Blocks.Add(block);

            var mockClient = new Mock <PeerService.PeerServiceClient>();

            mockClient.Setup(c =>
                             c.RequestBlocksAsync(It.IsAny <BlocksRequest>(), It.IsAny <Metadata>(), null,
                                                  CancellationToken.None))
            .Returns(MockAsyncUnaryCall(blockList));
            var grpcPeer = CreatePeer(mockClient.Object);

            var result = await grpcPeer.GetBlocksAsync(block.Header.PreviousBlockHash, 1);

            result.ShouldBe(blockList.Blocks);

            var metrics = grpcPeer.GetRequestMetrics();

            metrics["GetBlocks"].Count.ShouldBe(1);
            metrics["GetBlocks"][0].MethodName.ShouldContain("GetBlocks");
            metrics["GetBlocks"][0].Info.ShouldContain("Get blocks for");
        }
示例#12
0
    public static BlockList Serdes(int blockNumber, BlockList blockList, ISerializer s)
    {
        if (s == null)
        {
            throw new ArgumentNullException(nameof(s));
        }
        blockList ??= new BlockList();
        if (s.IsCommenting())
        {
            s.Begin(blockNumber.ToString(CultureInfo.InvariantCulture));
        }

        if (s.IsReading())
        {
            int j = 0;
            while (!s.IsComplete())
            {
                blockList.Add(Block.Serdes(j, null, s));
                j++;
            }
        }
        else
        {
            s.List(null, blockList, blockList.Count, Block.Serdes);
        }

        if (s.IsCommenting())
        {
            s.End();
        }
        return(blockList);
    }
示例#13
0
        public void RewriteConditionals()
        {
            LogDebug(1, $"REWRITE CONDITIONALS: {Method.Name}");

            DumpBlocks();

            var foundConditionals = false;

            foreach (var block in BlockList.Blocks.ToArray())
            {
                if (block.LinkerConditional == null)
                {
                    continue;
                }
                RewriteLinkerConditional(block);
                block.LinkerConditional = null;
                foundConditionals       = true;
            }

            if (!foundConditionals)
            {
                return;
            }

            BlockList.ComputeOffsets();

            DumpBlocks();

            LogDebug(1, $"DONE REWRITING CONDITIONALS: {Method.Name}");

            Context.Options.OptimizerReport.MarkAsContainingConditionals(Method);

            EliminateDeadBlocks();
        }
        /// <summary>
        /// Convert an array of blocks into a Set of integer indices
        /// </summary>
        /// <param name="blocks">the array of blocks containing the indices</param>
        /// <param name="raw_blocks">the list of blocks being managed. Unused
        /// blocks will be eliminated from the list</param>
        private void SetEntries(ListManagedBlock[] blocks,
                                BlockList raw_blocks)
        {
            int limit = BATBlock.EntriesPerBlock;

            for (int block_index = 0; block_index < blocks.Length; block_index++)
            {
                byte[] data   = blocks[block_index].Data;
                int    offset = 0;

                for (int k = 0; k < limit; k++)
                {
                    int entry = LittleEndian.GetInt(data, offset);

                    if (entry == POIFSConstants.UNUSED_BLOCK)
                    {
                        raw_blocks.Zap(_entries.Count);
                    }
                    _entries.Add(entry);
                    offset += LittleEndianConstants.INT_SIZE;
                }

                // discard block
                blocks[block_index] = null;
            }
            raw_blocks.BAT = this;
        }
示例#15
0
 public void Reset()
 {
     ItemList.Clear();
     EnemyList.Clear();
     BlockList.Clear();
     BackgroundList.Clear();
 }
示例#16
0
 internal void DumpBlock(int level, BasicBlock block)
 {
     if (DebugLevel >= level)
     {
         BlockList.Dump(block);
     }
 }
示例#17
0
        public void GetTxBlockListing()
        {
            HttpProvider client    = new HttpProvider("https://api.zilliqa.com/");
            BlockList    blockList = client.GetTxBlockListing(1).Result;

            Assert.IsNotNull(blockList);
        }
    public static async void RemotePush(BlockList blocks)
    {
        try
        {
            using (var client = new HttpClient())
            {
                try
                {
                    Console.WriteLine("Please wait.");
                    client.BaseAddress = new Uri("http://localhost:52521/Home/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var content  = JsonCompress(blocks);
                    var response = await client.PostAsync("SyncPush/", content);

                    using (var stream = await response.Content.ReadAsStreamAsync())
                    {
                        using (var streamReader = new StreamReader(stream))
                        {
                            Console.WriteLine(streamReader.ReadToEnd());
                        }
                    }
                    Console.WriteLine("Done.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
示例#19
0
        public ActionResult <BlockReadDto> Create([FromBody] BlockCreateDto request)
        {
            BlockList blockList = _blockListRepository.Get(request.BlockListId);

            if (blockList == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Block list doesn't exist."));
            }

            if (blockList.Blocks.Any(e => e.Id == request.BlockedUserId))
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "You already blocked this User."));
            }

            if (blockList.OwnerUserId == request.BlockedUserId)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "You cannot block yourself."));
            }

            if (_userRepository.Get(request.BlockedUserId) == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "User doesn't exist."));
            }

            Block newEntity = _mapper.Map <Block>(request);

            newEntity.DateTime = DateTime.UtcNow;

            newEntity = _blockRepository.Create(newEntity);

            return(StatusCode(StatusCodes.Status201Created, _mapper.Map <BlockReadDto>(newEntity)));
        }
示例#20
0
        public override object Clone()
        {
            var p = new AnalyseProject()
            {
                AnalyseEndTime      = AnalyseEndTime,
                AnalyseStartTime    = AnalyseStartTime,
                ProjectStartTime    = ProjectStartTime,
                CurrentDataSource   = CurrentDataSource.Clone() as IDataSource,
                DefaultFilterNumber = DefaultFilterNumber,
                Fine            = Fine,
                Grade           = Grade,
                Memo            = Memo,
                Name            = Name,
                TestStepDelayMS = TestStepDelayMS,
                Status          = Status
            };

            InstrumentList.ForEach(v => p.InstrumentList.Add(v.Clone() as IInstrument));
            ResultList.ForEach(v => p.ResultList.Add(v.Clone() as IInstrument));
            BlockList.ForEach(v => p.BlockList.Add(v.Clone() as IInstrument));
            ConditionList.ForEach(v => p.ConditionList.Add(v.Clone() as ICondition));
            PredicateList.ForEach(v => p.PredicateList.Add(v.Clone() as ICondition));

            return(p);
        }
示例#21
0
        public object Load(BinaryReader br, long streamLength, string name, AssetInfo config)
        {
            var bl = new BlockList();

            bl.Width  = br.ReadByte();
            bl.Height = br.ReadByte();
            if (bl.Width == 0 && bl.Height == 0)
            {
                return(null);
            }

            for (int j = 0; j < bl.Height; j++)
            {
                for (int i = 0; i < bl.Width; i++)
                {
                    var ble = new BlockList.BlockListEntry();
                    ble.b1 = br.ReadByte();
                    ble.b2 = br.ReadByte();
                    ble.b3 = br.ReadByte();
                    bl.Entries.Add(ble);
                }
            }

            return(bl);
        }
示例#22
0
        /// <summary>
        /// Occurs when the tag field has been changed.
        /// </summary>
        /// <param name="e">An <see cref="EventArgs"/> that contains the event data.</param>
        protected override void OnTagFieldChanged(EventArgs e)
        {
            //Reinitialize List
            BlockList.Clear();
            foreach (ITagBlock tagBlock in TagField.BlockList)
            {
                BlockList.Add(new TagBlockModel()
                {
                    Owner = Owner, TagBlock = tagBlock
                });
            }

            //Check
            if (BlockList.Count > 0)
            {
                SelectedBlockIndex = 0;
            }
            else
            {
                SelectedBlockIndex = -1;
            }

            //Notify
            Expanded = BlockList.Count > 0;
            NotifyPropertyChanged(nameof(HasBlocks));

            //Base procedures
            base.OnTagFieldChanged(e);
        }
示例#23
0
        // 한 줄이 다 채워지면 라인을 없앤다.
        public void DestroyCheck()
        {
            for (int y = BlockList.Count - 1; y >= 0; y--)
            {
                bool IsDestroy = true;
                for (int x = 0; x < BlockList[y].Count; x++)
                {
                    // 만약 한 라인에 공백이 있다면 부술 필요가 없다.
                    if (BlockList[y][x] == "□")
                    {
                        IsDestroy = false;
                    }
                }

                // 만약 부술 라인이 있다면
                if (IsDestroy)
                {
                    // 새로운 라인을 생성한다.
                    List <string> newLine = new List <string>();

                    // 공백을 넣는다.
                    for (int i = 0; i < X; i++)
                    {
                        newLine.Add("□");
                    }

                    // 맨 뒤를 날리고 다시 넣는다.
                    BlockList.RemoveAt(BlockList.Count - 1);
                    BlockList.Insert(0, newLine);

                    // 내려 앉았으니 다시 검색한다.
                    y = BlockList.Count - 1;
                }
            }
        }
示例#24
0
        private void AddBlock()
        {
            //Count
            int count = BlockList.Count;

            //Add
            Block tagBlock = TagField.Add(out bool success);

            if (success)
            {
                //Add
                BlockList.Add(new TagBlockModel()
                {
                    Owner = Owner, TagBlock = tagBlock
                });

                //Notify Changes
                if (count == 0)
                {
                    NotifyPropertyChanged(nameof(HasBlocks));
                }

                //Set
                SelectedBlockIndex = TagField.BlockList.IndexOf(tagBlock);
                NotifyValueChanged();
            }
        }
示例#25
0
        public string GenerateCode()
        {
            _text            = new StringBuilder(1024);
            _generatedBlocks = new List <GeneratedBlockInfo>();

            foreach (var block in BlockList.OrderBy(it => it.InputNodes.Count))
            {
                AddBlock(block);
            }
            AppendClassDeclarationCode();

            _text.AppendLine(Ident(3) + "//Declaring the blocks");
            foreach (var blockInfo in _generatedBlocks)
            {
                GenerateDeclarationCode(blockInfo);
            }
            _text.AppendLine();

            _text.AppendLine(Ident(3) + "//Connecting the blocks");
            foreach (var blockInfo in _generatedBlocks)
            {
                GenerateConnectionCode(blockInfo);
            }
            _text.AppendLine();

            _text.AppendLine(Ident(3) + "//Appending the blocks to a block list and execute all");
            _text.AppendLine(Ident(3) + "var blockList = new BlockList();");
            foreach (var blockInfo in _generatedBlocks)
            {
                _text.AppendLine(Ident(3) + "blockList.Add(" + blockInfo.VariableName + ");");
            }
            _text.AppendLine(Ident(3) + "blockList.ExecuteAll();");
            AppendClassEndCode();
            return(_text.ToString());
        }
示例#26
0
 public GameState()
 {
     Blocks = new BlockList();
     Effects = new EffectList();
     Units = new UnitList();
     Projectiles = new ProjectileList();
 }
示例#27
0
        private void RemoveBlock(GameObject pGameObject)
        {
            if (!blockUse.ContainsKey(pGameObject))
            {
                return;
            }

            ActionBlock actionBlock = dictionaryBlock[blockUse[pGameObject].type];


            if (actionBlock.prefabGame == blockUse[pGameObject].prefabGame)
            {
                actionBlock.nbLeft++;
                blockUse.Remove(pGameObject);
                Destroy(pGameObject);
                Destroy(selector);

                if (listBlockEmpty.Contains(currentBlock))
                {
                    listBlockEmpty.Remove(currentBlock);
                }

                currentBlock = actionBlock.type;

                if (OnInventoryChange != null)
                {
                    OnInventoryChange(dictionaryBlock, currentBlock);
                }

                SelectBlock();
            }
        }
示例#28
0
    public GameWorld(int width, int height, ContentManager Content)
    {
        screenWidth = width;
        screenHeight = height;
        random = new Random();
        gameState = GameState.Menu;
        inputHelper = new InputHelper();
        block = Content.Load<Texture2D>("block");
        reset = Content.Load<Texture2D>("reset");
        font = Content.Load<SpriteFont>("SpelFont");
        font2 = Content.Load<SpriteFont>("SpriteFont1");
        font3 = Content.Load<SpriteFont>("SpriteFont2");
        playButton = Content.Load<Texture2D>("Play");
        optionsButton = Content.Load<Texture2D>("Options");
        backButton = Content.Load<Texture2D>("Back");
        polytris = Content.Load<Texture2D>("Polytris");
        grid = new TetrisGrid(block);
        level = 1;
        levelspeed = 1;
        score = 0;
        i = (int)random.Next(7) + 1;
        i2 = (int)random.Next(7) + 1;
        blockcounter = 1;

        blocks = new BlockList(block, Content);          //Voegen de verschillende blockobjecten toe aan de lijst
        block1 = new Block1(block, Content);
        blocks.Add(block1, 1);
        block2 = new Block2(block, Content);
        blocks.Add(block2, 2);
        block3 = new Block3(block, Content);
        blocks.Add(block3, 3);
        block4 = new Block4(block, Content);
        blocks.Add(block4, 4);
        block5 = new Block5(block, Content);
        blocks.Add(block5, 5);
        block6 = new Block6(block, Content);
        blocks.Add(block6, 6);
        block7 = new Block7(block, Content);
        blocks.Add(block7, 7);

        //Voegen de verschillende blockobjecten toe aan een tweede lijst voor het tekenen van het volgende blokje
        block1res = new Block1(block, Content);
        blocks.AddToReserve(block1res, 1);
        block2res = new Block2(block, Content);
        blocks.AddToReserve(block2res, 2);
        block3res = new Block3(block, Content);
        blocks.AddToReserve(block3res, 3);
        block4res = new Block4(block, Content);
        blocks.AddToReserve(block4res, 4);
        block5res = new Block5(block, Content);
        blocks.AddToReserve(block5res, 5);
        block6res = new Block6(block, Content);
        blocks.AddToReserve(block6res, 6);
        block7res = new Block7(block, Content);
        blocks.AddToReserve(block7res, 7);

        options = new Options(block, reset, backButton, width, height, font, blocks);
        menu = new Menu(playButton, optionsButton, polytris, width, height);
        gameOver = new GameOver(backButton, width, height);
    }
示例#29
0
 public async Task SaveBlockList(BlockList data)
 {
     await _queryService
     .CreateMySqlFactory()
     .FromTable(TableName)
     .InsertAsync(data);
 }
示例#30
0
        public void Delete(int id)
        {
            BlockList block = GetOne(id);

            CyclepathDbContext.Blocks.Remove(block);
            CyclepathDbContext.SaveChanges();
        }
        private static void AssertBlock(BlockBase block)
        {
            var blockList = new BlockList {
                block
            };

            foreach (var inputNode in block.InputNodes)
            {
                var signalBlock = new GenerateSignalBlock
                {
                    TemplateName     = "Binary",
                    Start            = 0,
                    Finish           = 4,
                    SamplingRate     = 1,
                    IgnoreLastSample = true
                };
                signalBlock.OutputNodes[0].ConnectTo(inputNode);
                blockList.Add(signalBlock);
            }
            blockList.ExecuteAll();
            var clone = block.CloneWithLinks();

            foreach (var outputNode in clone.OutputNodes)
            {
                Assert.IsNotNull(outputNode.Object[0].Samples);
            }

            Assert.IsNotNull(block.Name);
            Assert.IsNotNull(block.Description);
            Assert.IsNotNull(block.ProcessingType);
        }
示例#32
0
        public override async Task <BlockList> RequestBlocks(BlocksRequest request, ServerCallContext context)
        {
            if (request == null || request.PreviousBlockHash == null || _syncStateService.SyncState != SyncState.Finished)
            {
                return(new BlockList());
            }

            Logger.LogDebug($"Peer {context.GetPeerInfo()} requested {request.Count} blocks from {request.PreviousBlockHash}.");

            var blockList = new BlockList();

            var blocks = await _blockchainService.GetBlocksWithTransactions(request.PreviousBlockHash, request.Count);

            if (blocks == null)
            {
                return(blockList);
            }

            blockList.Blocks.AddRange(blocks);

            if (blockList.Blocks.Count != request.Count)
            {
                Logger.LogTrace($"Replied with {blockList.Blocks.Count} blocks for request {request}");
            }

            if (NetworkOptions.CompressBlocksOnRequest)
            {
                var headers = new Metadata {
                    new Metadata.Entry(GrpcConstants.GrpcRequestCompressKey, GrpcConstants.GrpcGzipConst)
                };
                await context.WriteResponseHeadersAsync(headers);
            }

            return(blockList);
        }
示例#33
0
        public override void ClearData()
        {
            if (WordList != null)
            {
                WordList.Clear();
                WordList = null;
            }

            if (Blocks != null)
            {
                Blocks.DeleteRawData();
                Blocks = null;
            }
        }
示例#34
0
		public virtual void TestGet()
		{
			BlockList<string> list = new BlockList<string>(4);
			string b;
			try
			{
				b = list[-1];
			}
			catch (IndexOutOfRangeException badIndex)
			{
				NUnit.Framework.Assert.AreEqual((-1).ToString(), badIndex.Message);
			}
			try
			{
				b = list[0];
			}
			catch (IndexOutOfRangeException badIndex)
			{
				NUnit.Framework.Assert.AreEqual(0.ToString(), badIndex.Message);
			}
			try
			{
				b = list[4];
			}
			catch (IndexOutOfRangeException badIndex)
			{
				NUnit.Framework.Assert.AreEqual(4.ToString(), badIndex.Message);
			}
			string fooStr = "foo";
			string barStr = "bar";
			string foobarStr = "foobar";
			list.AddItem(fooStr);
			list.AddItem(barStr);
			list.AddItem(foobarStr);
			NUnit.Framework.Assert.AreSame(fooStr, list[0]);
			NUnit.Framework.Assert.AreSame(barStr, list[1]);
			NUnit.Framework.Assert.AreSame(foobarStr, list[2]);
			try
			{
				b = list[3];
			}
			catch (IndexOutOfRangeException badIndex)
			{
				NUnit.Framework.Assert.AreEqual(3.ToString(), badIndex.Message);
			}
		}
示例#35
0
 public Options(Texture2D blockSprite, Texture2D resetSprite, Texture2D backSprite, int screenWidth, int screenHeight, SpriteFont spriteFont, BlockList blocks)
 {
     block = blockSprite;
     reset = resetSprite;
     back = backSprite;
     this.screenWidth = screenWidth;
     this.screenHeight = screenHeight;
     this.blocks = blocks;
     block1 = blocks.Find(1);
     block2 = blocks.Find(2);
     block3 = blocks.Find(3);
     block4 = blocks.Find(4);
     block5 = blocks.Find(5);
     block6 = blocks.Find(6);
     block7 = blocks.Find(7);
     font = spriteFont;
     backRect = new Rectangle(screenWidth / 2 - backSprite.Width / 2, screenHeight - backSprite.Height - 100, backSprite.Width, backSprite.Height);
 }
示例#36
0
		public virtual void TestEmptyList()
		{
			BlockList<string> empty;
			empty = new BlockList<string>();
			NUnit.Framework.Assert.AreEqual(0, empty.Count);
			NUnit.Framework.Assert.IsTrue(empty.IsEmpty());
			NUnit.Framework.Assert.IsFalse(empty.Iterator().HasNext());
			empty = new BlockList<string>(0);
			NUnit.Framework.Assert.AreEqual(0, empty.Count);
			NUnit.Framework.Assert.IsTrue(empty.IsEmpty());
			NUnit.Framework.Assert.IsFalse(empty.Iterator().HasNext());
			empty = new BlockList<string>(1);
			NUnit.Framework.Assert.AreEqual(0, empty.Count);
			NUnit.Framework.Assert.IsTrue(empty.IsEmpty());
			NUnit.Framework.Assert.IsFalse(empty.Iterator().HasNext());
			empty = new BlockList<string>(64);
			NUnit.Framework.Assert.AreEqual(0, empty.Count);
			NUnit.Framework.Assert.IsTrue(empty.IsEmpty());
			NUnit.Framework.Assert.IsFalse(empty.Iterator().HasNext());
		}
示例#37
0
        public double Run(double[] data, int detailLevel)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i]);
                if (i < data.Length - 1) sb.Append(",");
            }

            string datastring = sb.ToString();

            var textBlock = new ImportFromTextBlock
            {
                Text = datastring,
                ColumnSeparator = ",",
                SignalStart = 0,
                SignalNameInFirstColumn = false
            };

            var dwtBlock = new DWTBlock
            {
                WaveletName = "db10",
                Level = detailLevel,
                ExtensionMode = SignalExtension.ExtensionMode.ZeroPadding
            };


            var b = new BlockList();
            b.Add(textBlock);
            b.Add(dwtBlock);

            textBlock.ConnectTo(dwtBlock);

            b.ExecuteAll();

            int length = dwtBlock.OutputNodes[dwtBlock.OutputNodes.Count-1].Object[detailLevel - 1].Samples.Length;

            double val = dwtBlock.OutputNodes[dwtBlock.OutputNodes.Count-1].Object[detailLevel - 1].Samples[length - 1];

            return val;
        }
示例#38
0
 public static List<double> FFTTransform(List<double> serie)
 {
     //Declaring the blocks
     var inputSeriesBlock = new InputSeriesBlock();
     inputSeriesBlock.SetSeries(serie);
     var outputSeriesBlock = new OutputSeriesBlock();
     var fFTBlock = new FFTBlock
     {
         Mode = ManagedFFTModeEnum.UseLookupTable
     };
     //Connecting the blocks
     inputSeriesBlock.OutputNodes[0].ConnectTo(fFTBlock.InputNodes[0]);
     fFTBlock.OutputNodes[1].ConnectTo(outputSeriesBlock.InputNodes[0]);
     //Appending the blocks to a block list and execute all
     var blockList = new BlockList();
     blockList.Add(inputSeriesBlock);
     blockList.Add(fFTBlock);
     blockList.Add(outputSeriesBlock);
     blockList.ExecuteAll();
     return outputSeriesBlock.GetSeries();
 }
示例#39
0
 public virtual void TestAddRejectsBadIndexes()
 {
     BlockList<int> list = new BlockList<int>(4);
     list.AddItem(Sharpen.Extensions.ValueOf(41));
     try
     {
         list.Add(-1, Sharpen.Extensions.ValueOf(42));
     }
     catch (IndexOutOfRangeException badIndex)
     {
         NUnit.Framework.Assert.AreEqual((-1).ToString(), badIndex.Message);
     }
     try
     {
         list.Add(4, Sharpen.Extensions.ValueOf(42));
     }
     catch (IndexOutOfRangeException badIndex)
     {
         NUnit.Framework.Assert.AreEqual(4.ToString(), badIndex.Message);
     }
 }
示例#40
0
		/// <summary>Parse the pack stream.</summary>
		/// <remarks>Parse the pack stream.</remarks>
		/// <param name="receiving">
		/// receives progress feedback during the initial receiving
		/// objects phase. If null,
		/// <see cref="NGit.NullProgressMonitor">NGit.NullProgressMonitor</see>
		/// will be
		/// used.
		/// </param>
		/// <param name="resolving">receives progress feedback during the resolving objects phase.
		/// 	</param>
		/// <returns>
		/// the pack lock, if one was requested by setting
		/// <see cref="SetLockMessage(string)">SetLockMessage(string)</see>
		/// .
		/// </returns>
		/// <exception cref="System.IO.IOException">the stream is malformed, or contains corrupt objects.
		/// 	</exception>
		public virtual PackLock Parse(ProgressMonitor receiving, ProgressMonitor resolving
			)
		{
			if (receiving == null)
			{
				receiving = NullProgressMonitor.INSTANCE;
			}
			if (resolving == null)
			{
				resolving = NullProgressMonitor.INSTANCE;
			}
			if (receiving == resolving)
			{
				receiving.Start(2);
			}
			try
			{
				ReadPackHeader();
				entries = new PackedObjectInfo[(int)objectCount];
				baseById = new ObjectIdOwnerMap<PackParser.DeltaChain>();
				baseByPos = new LongMap<PackParser.UnresolvedDelta>();
				deferredCheckBlobs = new BlockList<PackedObjectInfo>();
				receiving.BeginTask(JGitText.Get().receivingObjects, (int)objectCount);
				try
				{
					for (int done = 0; done < objectCount; done++)
					{
						IndexOneObject();
						receiving.Update(1);
						if (receiving.IsCancelled())
						{
							throw new IOException(JGitText.Get().downloadCancelled);
						}
					}
					ReadPackFooter();
					EndInput();
				}
				finally
				{
					receiving.EndTask();
				}
				if (!deferredCheckBlobs.IsEmpty())
				{
					DoDeferredCheckBlobs();
				}
				if (deltaCount > 0)
				{
					if (resolving is BatchingProgressMonitor)
					{
						((BatchingProgressMonitor)resolving).SetDelayStart(1000, TimeUnit.MILLISECONDS);
					}
					resolving.BeginTask(JGitText.Get().resolvingDeltas, deltaCount);
					ResolveDeltas(resolving);
					if (entryCount < objectCount)
					{
						if (!IsAllowThin())
						{
							throw new IOException(MessageFormat.Format(JGitText.Get().packHasUnresolvedDeltas
								, Sharpen.Extensions.ValueOf(objectCount - entryCount)));
						}
						ResolveDeltasWithExternalBases(resolving);
						if (entryCount < objectCount)
						{
							throw new IOException(MessageFormat.Format(JGitText.Get().packHasUnresolvedDeltas
								, Sharpen.Extensions.ValueOf(objectCount - entryCount)));
						}
					}
					resolving.EndTask();
				}
				packDigest = null;
				baseById = null;
				baseByPos = null;
			}
			finally
			{
				try
				{
					if (readCurs != null)
					{
						readCurs.Release();
					}
				}
				finally
				{
					readCurs = null;
				}
				try
				{
					inflater.Release();
				}
				finally
				{
					inflater = null;
				}
			}
			return null;
		}
示例#41
0
        private void ProcessProperties(BlockList small_blocks,
                                       BlockList big_blocks,
                                       IEnumerator properties,
                                       DirectoryNode dir,
                                       int headerPropertiesStartAt)
        {
            while (properties.MoveNext())
            {
                Property      property = ( Property ) properties.Current;
                String        name     = property.Name;
                DirectoryNode parent   = (dir == null)
                                         ? (( DirectoryNode ) this.Root)
                                         : dir;

                if (property.IsDirectory)
                {
                    DirectoryNode new_dir =
                        ( DirectoryNode ) parent.CreateDirectory(name);

                    new_dir.StorageClsid=property.StorageClsid ;

                    ProcessProperties(
                        small_blocks, big_blocks,
                        ((DirectoryProperty)property).Children, new_dir, headerPropertiesStartAt);
                }
                else
                {
                    int           startBlock = property.StartBlock;
                    int           size       = property.Size;
                    POIFSDocument document   = null;

                    if (property.ShouldUseSmallBlocks)
                    {
                        document =
                            new POIFSDocument(name, small_blocks
                                .FetchBlocks(startBlock, headerPropertiesStartAt), size);
                    }
                    else
                    {
                        document =
                            new POIFSDocument(name,
                                              big_blocks.FetchBlocks(startBlock,headerPropertiesStartAt),
                                              size);
                    }
                    parent.CreateDocument(document);
                }
            }
        }
示例#42
0
        /// <summary>
        /// Processes the properties.
        /// </summary>
        /// <param name="small_blocks">The small_blocks.</param>
        /// <param name="big_blocks">The big_blocks.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        private List<DocumentDescriptor> ProcessProperties(BlockList small_blocks,
                                       BlockList big_blocks,
                                       IEnumerator properties,
                                       POIFSDocumentPath path)
        {
            List<DocumentDescriptor> documents =
                new List<DocumentDescriptor>();

            while (properties.MoveNext())
            {
                Property property = (Property)properties.Current;
                String name = property.Name;

                if (property.IsDirectory)
                {
                    POIFSDocumentPath new_path = new POIFSDocumentPath(path,
                                                     new String[]
                {
                    name
                });

                    ProcessProperties(
                        small_blocks, big_blocks,
                        ((DirectoryProperty)property).Children, new_path);
                }
                else
                {
                    int startBlock = property.StartBlock;
                    IEnumerator listeners = registry.GetListeners(path, name);
                    POIFSDocument document = null;
                    if (listeners.MoveNext())
                    {
                        listeners.Reset();
                        int size = property.Size;
                        

                        if (property.ShouldUseSmallBlocks)
                        {
                            document =
                                new POIFSDocument(name, small_blocks
                                    .FetchBlocks(startBlock, -1), size);
                        }
                        else
                        {
                            document =
                                new POIFSDocument(name, big_blocks
                                    .FetchBlocks(startBlock, -1), size);
                        }
                        //POIFSReaderListener listener =
                        //        (POIFSReaderListener)listeners.Current;
                        //listener.ProcessPOIFSReaderEvent(
                        //        new POIFSReaderEvent(
                        //            new DocumentInputStream(document), path,
                        //            name));
                        while (listeners.MoveNext())
                        {
                            POIFSReaderListener listener =
                                (POIFSReaderListener)listeners.Current;
                            listener.ProcessPOIFSReaderEvent(
                                new POIFSReaderEvent(
                                    new DocumentInputStream(document), path,
                                    name));
                        }
                    }
                    else
                    {
                        // consume the document's data and discard it
                        if (property.ShouldUseSmallBlocks)
                        {
                            small_blocks.FetchBlocks(startBlock, -1);
                        }
                        else
                        {
                            big_blocks.FetchBlocks(startBlock, -1);
                        }
                        //documents.Add(
                        //        new DocumentDescriptor(path, name));
                        //fire event
                        //OnStreamReaded(new POIFSReaderEventArgs(name, path, document));
                    }
                }
            }
            return documents;
        }
示例#43
0
 public virtual BlockList VisitBlockList(BlockList blockList1, BlockList blockList2)
 {
     if (blockList1 == null) return null;
     for (int i = 0, n = blockList1.Count, m = blockList2 == null ? 0 : blockList2.Count; i < n; i++)
     {
         //^ assert blockList2 != null;
         if (i >= m)
             blockList1[i] = this.VisitBlock(blockList1[i], null);
         else
             blockList1[i] = this.VisitBlock(blockList1[i], blockList2[i]);
     }
     return blockList1;
 }
示例#44
0
 public virtual BlockList VisitBlockList(BlockList blockList, BlockList changes, BlockList deletions, BlockList insertions){
   if (changes == null || deletions == null || insertions == null) return blockList;
   int n = blockList == null ? 0 : blockList.Count;
   if (n > changes.Count){Debug.Assert(false); n = changes.Count;}
   if (n > deletions.Count){Debug.Assert(false); n = deletions.Count;}
   if (n > insertions.Count){Debug.Assert(false); n = insertions.Count;}
   if (blockList != null)
     for (int i = 0; i < n; i++)
       blockList[i] = this.VisitBlock(blockList[i], changes[i], deletions[i], insertions[i]);
   BlockList result = new BlockList(insertions.Count-n);
   for (int i = n, m = insertions.Count; i < m; i++)
     result.Add(insertions[i]);
   return result;
 }
        /// <summary>
        /// Convert an array of blocks into a Set of integer indices
        /// </summary>
        /// <param name="blocks">the array of blocks containing the indices</param>
        /// <param name="raw_blocks">the list of blocks being managed. Unused
        /// blocks will be eliminated from the list</param>
        private void SetEntries(ListManagedBlock[] blocks,
                                BlockList raw_blocks)
        {

            int limit = bigBlockSize.GetBATEntriesPerBlock();

            for (int block_index = 0; block_index < blocks.Length; block_index++)
            {
                byte[] data = blocks[block_index].Data;
                int offset = 0;

                for (int k = 0; k < limit; k++)
                {
                    int entry = LittleEndian.GetInt(data, offset);

                    if (entry == POIFSConstants.UNUSED_BLOCK)
                    {
                        raw_blocks.Zap(_entries.Count);
                    }
                    _entries.Add(entry);
                    offset += LittleEndianConsts.INT_SIZE;
                }

                // discard block
                blocks[block_index] = null;
            }
            raw_blocks.BAT = this;
        }
 /// <summary>
 /// create a BlockAllocationTableReader from an array of raw data blocks
 /// </summary>
 /// <param name="bigBlockSize"></param>
 /// <param name="blocks">the raw data</param>
 /// <param name="raw_block_list">the list holding the managed blocks</param>
 public BlockAllocationTableReader(POIFSBigBlockSize bigBlockSize, ListManagedBlock[] blocks,  
                            BlockList raw_block_list)
     : this(bigBlockSize)
 {
     SetEntries(blocks, raw_block_list);
 }
 protected override object VisitSwitch(Variable selector, BlockList targets, Statement stat, object arg) {
   return arg;
 }
        /// <summary>
        /// create a BlockAllocationTableReader for an existing filesystem. Side
        /// effect: when this method finishes, the BAT blocks will have
        /// been Removed from the raw block list, and any blocks labeled as
        /// 'unused' in the block allocation table will also have been
        /// Removed from the raw block list. </summary>
        /// <param name="block_count">the number of BAT blocks making up the block allocation table</param>
        /// <param name="block_array">the array of BAT block indices from the
        /// filesystem's header</param>
        /// <param name="xbat_count">the number of XBAT blocks</param>
        /// <param name="xbat_index">the index of the first XBAT block</param>
        /// <param name="raw_block_list">the list of RawDataBlocks</param>
        public BlockAllocationTableReader(int block_count,
                                          int[] block_array,
                                          int xbat_count,
                                          int xbat_index,
                                          BlockList raw_block_list)
            : this()
        {

            if (block_count <= 0)
            {
                throw new IOException(
                    "Illegal block count; minimum count is 1, got " + block_count
                    + " instead");
            }

            // acquire raw data blocks containing the BAT block data
            RawDataBlock[] blocks = new RawDataBlock[block_count];
            int limit = Math.Min(block_count, block_array.Length);
            int block_index;

            for (block_index = 0; block_index < limit; block_index++)
            {
                blocks[block_index] =
                    (RawDataBlock)raw_block_list
                        .Remove(block_array[block_index]);
            }
            if (block_index < block_count)
            {

                // must have extended blocks
                if (xbat_index < 0)
                {
                    throw new IOException(
                        "BAT count exceeds limit, yet XBAT index indicates no valid entries");
                }
                int chain_index = xbat_index;
                int max_entries_per_block = BATBlock.EntriesPerXBATBlock;
                int chain_index_offset = BATBlock.XBATChainOffset;

                for (int j = 0; j < xbat_count; j++)
                {
                    limit = Math.Min(block_count - block_index,
                                     max_entries_per_block);
                    byte[] data = raw_block_list.Remove(chain_index).Data;
                    int offset = 0;

                    for (int k = 0; k < limit; k++)
                    {
                        blocks[block_index++] =
                            (RawDataBlock)raw_block_list
                                .Remove(LittleEndian.GetInt(data, offset));
                        offset += LittleEndianConstants.INT_SIZE;
                    }
                    chain_index = LittleEndian.GetInt(data, chain_index_offset);
                    if (chain_index == POIFSConstants.END_OF_CHAIN)
                    {
                        break;
                    }
                }
            }
            if (block_index != block_count)
            {
                throw new IOException("Could not find all blocks");
            }

            // now that we have all of the raw data blocks, go through and
            // create the indices
            SetEntries((ListManagedBlock[])blocks, raw_block_list);
        }
        /// <summary>
        /// walk the entries from a specified point and return the
        /// associated blocks. The associated blocks are Removed from the block list
        /// </summary>
        /// <param name="startBlock">the first block in the chain</param>
        /// <param name="blockList">the raw data block list</param>
        /// <returns>array of ListManagedBlocks, in their correct order</returns>
        public ListManagedBlock[] FetchBlocks(int startBlock,
                                        BlockList blockList)
        {
            IList blocks = new ArrayList();
            int currentBlock = startBlock;

            while (currentBlock != POIFSConstants.END_OF_CHAIN)
            {
                blocks.Add(blockList.Remove(currentBlock));
                currentBlock = _entries[currentBlock];
            }
            ListManagedBlock[] array = new ListManagedBlock[blocks.Count];
            blocks.CopyTo(array, 0);

            return (array);
        }
 /// <summary>
 /// create a BlockAllocationTableReader from an array of raw data blocks
 /// </summary>
 /// <param name="blocks">the raw data</param>
 /// <param name="raw_block_list">the list holding the managed blocks</param>
 public BlockAllocationTableReader(ListManagedBlock[] blocks,
                            BlockList raw_block_list)
     : this()
 {
     SetEntries(blocks, raw_block_list);
 }
示例#51
0
		/// <summary>
		/// switch selector,targets -- branch to target block indexed by selector
		/// <p>
		/// Description:
		/// <br/>
    /// if <c>selector</c> is between <c>0</c> and <c>targets.Length-1</c>c>
    /// then branch to targets[selector]. Otherwise, fall through.
		/// </p>
		/// </summary>
		/// <param name="selector">Selector variable.</param>
		/// <param name="targets">List of targets.</param>
		protected virtual object VisitSwitch (Variable selector, BlockList targets, Statement stat, object arg)
		{
			return DefaultVisit(stat, arg);
		}
 protected override object VisitSwitch(Variable selector, BlockList targets, Statement stat, object arg) {
   ExposureState estate=(ExposureState)arg;
   foreach (CfgBlock target in ExposureChecker.currBlock.NormalSuccessors)
     ExposureChecker.PushState(ExposureChecker.currBlock,target,estate);
   return null;
 }
 protected override object VisitSwitch(Variable selector, BlockList targets, Statement stat, object arg) {
   InitializedVariables iv=(InitializedVariables)arg;
   CheckUse(iv, selector, stat);
   return arg;
 }
示例#54
0
 public virtual BlockList VisitBlockList(BlockList blockList)
 {
     if (blockList == null) return null;
     for (int i = 0, n = blockList.Count; i < n; i++)
         blockList[i] = this.VisitBlock(blockList[i]);
     return blockList;
 }
        /// <summary>
        /// walk the entries from a specified point and return the
        /// associated blocks. The associated blocks are Removed from the block list
        /// </summary>
        /// <param name="startBlock">the first block in the chain</param>
        /// <param name="headerPropertiesStartBlock"></param>
        /// <param name="blockList">the raw data block list</param>
        /// <returns>array of ListManagedBlocks, in their correct order</returns>
        public ListManagedBlock[] FetchBlocks(int startBlock, int headerPropertiesStartBlock,
                                        BlockList blockList)
        {
            List<ListManagedBlock> blocks = new List<ListManagedBlock>();
            int currentBlock = startBlock;
            bool firstPass = true;
            ListManagedBlock dataBlock = null;

            while (currentBlock != POIFSConstants.END_OF_CHAIN)
            {
                try
                {
                    dataBlock = blockList.Remove(currentBlock);
                    blocks.Add(dataBlock);
                    currentBlock = _entries[currentBlock];
                    firstPass = false;
                }
                catch(Exception)
                {
                    if (currentBlock == headerPropertiesStartBlock)
                    {
                        // Special case where things are in the wrong order
                        _logger.Log(POILogger.WARN, "Warning, header block comes after data blocks in POIFS block listing");
                        currentBlock = POIFSConstants.END_OF_CHAIN;
                    }
                    else if (currentBlock == 0 && firstPass)
                    {
                        // Special case where the termination isn't done right
                        //  on an empty set
                        _logger.Log(POILogger.WARN, "Warning, incorrectly terminated empty data blocks in POIFS block listing (should end at -2, ended at 0)");
                        currentBlock = POIFSConstants.END_OF_CHAIN;
                    }
                    else
                    {
                        // Ripple up
                        throw;
                    }
                }
            }
            ListManagedBlock[] array = blocks.ToArray();
            return (array);
        }
示例#56
0
 public virtual Block GetClosestMatch(Block/*!*/ nd1, BlockList/*!*/ list1, BlockList list2, int list1pos, ref int list2start,
   TrivialHashtable/*!*/ matchedNodes, out Differences closestDifferences, out int list2pos) {
   closestDifferences = null; list2pos = -1;
   if (list2 == null) return null;
   if (nd1 == null || list1 == null || matchedNodes == null || list1pos < 0 || list1pos >= list1.Count || list2start < 0 || list2start >= list2.Count) {
     Debug.Assert(false); return null;
   }
   Block closest = null;
   Differences winnerSoFar = null;
   for (int j = list2start, m = list2.Count; j < m; j++){
     Block nd2 = list2[j];
     if (list2start == j) list2start++;
     if (nd2 == null) continue;
     if (matchedNodes[nd2.UniqueKey] != null) continue;
     Differences diff = this.GetDifferences(nd1, nd2);
     if (diff == null){Debug.Assert(false); continue;}
     if (diff.Similarity <= 0.5){
       //Not a good enough match
       if (list2start == j+1) list2start--; //The next call to GetClosestMatch will start looking at list2start, so this node will be considered then
       continue; //ignore it for the rest of this call
     }
     if (winnerSoFar != null && winnerSoFar.Similarity >= diff.Similarity) continue;
     winnerSoFar = closestDifferences = diff;
     closest = nd2;
     list2pos = j;
     if (diff.NumberOfDifferences == 0) return closest; //Perfect match, no need to look for other matches
   }
   if (closest != null){
     //^ assert winnerSoFar != null;
     //closest is closer to nd1 than any other node in list2, but this is no good if some other node in list1 has a better claim on closest
     for (int i = list1pos+1, n = list1.Count; i < n; i++){
       Block nd1alt = list1[i];
       if (nd1alt == null) continue;
       if (matchedNodes[nd1alt.UniqueKey] != null) continue;
       Differences diff = this.GetDifferences(nd1alt, closest);
       if (diff == null){Debug.Assert(false); continue;}
       if (diff.Similarity <= winnerSoFar.Similarity) continue;
       //nd1alt has a better claim on closest. See if it wants closest.
       Differences diff2;
       int j, k = list2start;
       Block nd2alt = this.GetClosestMatch(nd1alt, list1, list2, i, ref k,  matchedNodes, out diff2, out j);
       if (nd2alt != closest){
         Debug.Assert(nd2alt != null && diff2 != null && diff2.Similarity >= diff.Similarity);
         continue; //nd1alt prefers nd2alt to closest, so closest is still available
       }
       //nd1alt wants closest, take it out of the running
       matchedNodes[closest.UniqueKey] = nd1alt;
       //Now that closest is out of the running, try again
       k = list2start;
       Block newClosest = this.GetClosestMatch(nd1, list1, list2, i, ref k, matchedNodes, out winnerSoFar, out list2pos);
       //put closest back in the running so that the next call to this routine will pick it up
       matchedNodes[closest.UniqueKey] = closest;
       closest = newClosest;
       break;
     }
   }
   closestDifferences = winnerSoFar;
   return closest;
 }
        /// <summary>
        /// create a BlockAllocationTableReader for an existing filesystem. Side
        /// effect: when this method finishes, the BAT blocks will have
        /// been Removed from the raw block list, and any blocks labeled as
        /// 'unused' in the block allocation table will also have been
        /// Removed from the raw block list. </summary>
        /// <param name="bigBlockSizse">the poifs bigBlockSize</param>
        /// <param name="block_count">the number of BAT blocks making up the block allocation table</param>
        /// <param name="block_array">the array of BAT block indices from the
        /// filesystem's header</param>
        /// <param name="xbat_count">the number of XBAT blocks</param>
        /// <param name="xbat_index">the index of the first XBAT block</param>
        /// <param name="raw_block_list">the list of RawDataBlocks</param>
        public BlockAllocationTableReader(POIFSBigBlockSize bigBlockSizse,
                                          int block_count,
                                          int[] block_array,
                                          int xbat_count,
                                          int xbat_index,
                                          BlockList raw_block_list)
            : this(bigBlockSizse)
        {
            SanityCheckBlockCount(block_count);

            RawDataBlock[] blocks = new RawDataBlock[block_count];
            int limit = Math.Min(block_count, block_array.Length);
            int block_index;

            for (block_index = 0; block_index < limit; block_index++)
            {
                int nextOffset = block_array[block_index];
                if (nextOffset > raw_block_list.BlockCount())
                {
                    throw new IOException("Your file contains " + raw_block_list.BlockCount() +
                                           " sectors, but the initial DIFAT array at index " + block_index +
                                           " referenced block # " + nextOffset + ". This isn't allowed and " +
                                           " your file is corrupt");
                }

                blocks[block_index] = (RawDataBlock)raw_block_list.Remove(nextOffset);
            }
            if (block_index < block_count)
            {

                // must have extended blocks
                if (xbat_index < 0)
                {
                    throw new IOException(
                        "BAT count exceeds limit, yet XBAT index indicates no valid entries");
                }
                int chain_index = xbat_index;
                int max_entries_per_block = BATBlock.EntriesPerXBATBlock;
                int chain_index_offset = BATBlock.XBATChainOffset;

                // Each XBAT block contains either:
                //  (maximum number of sector indexes) + index of next XBAT
                //  some sector indexes + FREE sectors to max # + EndOfChain
                for (int j = 0; j < xbat_count; j++)
                {
                    limit = Math.Min(block_count - block_index,
                                     max_entries_per_block);
                    byte[] data = raw_block_list.Remove(chain_index).Data;
                    int offset = 0;

                    for (int k = 0; k < limit; k++)
                    {
                        blocks[block_index++] =
                            (RawDataBlock)raw_block_list.Remove(LittleEndian.GetInt(data, offset));
                        offset += LittleEndianConsts.INT_SIZE;
                    }
                    chain_index = LittleEndian.GetInt(data, chain_index_offset);
                    if (chain_index == POIFSConstants.END_OF_CHAIN)
                    {
                        break;
                    }
                }
            }
            if (block_index != block_count)
            {
                throw new IOException("Could not find all blocks");
            }

            // now that we have all of the raw data blocks, go through and
            // create the indices
            SetEntries((ListManagedBlock[])blocks, raw_block_list);
        }
示例#58
0
 public virtual Differences VisitBlockList(BlockList list1, BlockList list2,
   out BlockList changes, out BlockList deletions, out BlockList insertions){
   changes = list1 == null ? null : list1.Clone();
   deletions = list1 == null ? null : list1.Clone();
   insertions = list1 == null ? new BlockList() : list1.Clone();
   //^ assert insertions != null;
   Differences differences = new Differences();
   for (int j = 0, n = list2 == null ? 0 : list2.Count; j < n; j++){
     //^ assert list2 != null;
     Block nd2 = list2[j];
     if (nd2 == null) continue;
     insertions.Add(null);
   }
   TrivialHashtable savedDifferencesMapFor = this.differencesMapFor;
   this.differencesMapFor = null;
   TrivialHashtable matchedNodes = new TrivialHashtable();
   for (int i = 0, k = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
     //^ assert list1 != null && changes != null && deletions != null;
     Block nd1 = list1[i]; 
     if (nd1 == null) continue;
     Differences diff;
     int j;
     Block nd2 = this.GetClosestMatch(nd1, list1, list2, i, ref k, matchedNodes, out diff, out j);
     if (nd2 == null || diff == null){Debug.Assert(nd2 == null && diff == null); continue;}
     matchedNodes[nd1.UniqueKey] = nd1;
     matchedNodes[nd2.UniqueKey] = nd2;
     changes[i] = diff.Changes as Block;
     deletions[i] = diff.Deletions as Block;
     insertions[i] = diff.Insertions as Block;
     insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation
     Debug.Assert(diff.Changes == changes[i] && diff.Deletions == deletions[i] && diff.Insertions == insertions[i]);
     differences.NumberOfDifferences += diff.NumberOfDifferences;
     differences.NumberOfSimilarities += diff.NumberOfSimilarities;
   }
   //Find deletions
   for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){
     //^ assert list1 != null && changes != null && deletions != null;
     Block nd1 = list1[i]; 
     if (nd1 == null) continue;
     if (matchedNodes[nd1.UniqueKey] != null) continue;
     changes[i] = null;
     deletions[i] = nd1;
     insertions[i] = null;
     differences.NumberOfDifferences += 1;
   }
   //Find insertions
   for (int j = 0, n = list1 == null ? 0 : list1.Count, m = list2 == null ? 0 : list2.Count; j < m; j++){
     //^ assert list2 != null;
     Block nd2 = list2[j]; 
     if (nd2 == null) continue;
     if (matchedNodes[nd2.UniqueKey] != null) continue;
     insertions[n+j] = nd2;  //Records nd2 as an insertion into list1, along with its position in list2
     differences.NumberOfDifferences += 1; //REVIEW: put the size of the tree here?
   }
   if (differences.NumberOfDifferences == 0){
     changes = null;
     deletions = null;
     insertions = null;
   }
   this.differencesMapFor = savedDifferencesMapFor;
   return differences;
 }
示例#59
0
		protected override object VisitSwitch (Variable selector, BlockList Targets, Statement stat, object arg)
		{
			return "SWITCH (" + CciHelper.Name(selector) + ")";
		}
示例#60
0
 protected virtual Expression CoerceFromTypeUnion(Expression source, TypeUnion sourceType, TypeNode targetType, bool explicitCoercion, TypeNode originalTargetType, TypeViewer typeViewer){
   if (source == null || sourceType == null || targetType == null) return null;
   if (targetType == SystemTypes.Object) return this.CoerceTypeUnionToObject(source, typeViewer);
   int cErrors = (this.Errors != null) ? this.Errors.Count : 0;
   if (explicitCoercion){
     Method coercion = this.UserDefinedExplicitCoercionMethod(source, sourceType, targetType, false, originalTargetType, typeViewer);
     if (coercion != null && coercion.ReturnType == targetType && coercion.Parameters != null && coercion.Parameters[0] != null &&
       this.ImplicitCoercionFromTo(sourceType, coercion.Parameters[0].Type, typeViewer))
       return this.ImplicitCoercion(new MethodCall(new MemberBinding(null, coercion), new ExpressionList(source), NodeType.Call, coercion.ReturnType),
         targetType, typeViewer);
   }
   Method getTag = TypeViewer.GetTypeView(typeViewer, sourceType).GetMethod(StandardIds.GetTag);
   if (getTag == null) return null;
   Method getValue = TypeViewer.GetTypeView(typeViewer, sourceType).GetMethod(StandardIds.GetValue);
   if (getValue == null) return null;
   Local src = new Local(sourceType);
   Local srcOb = new Local(SystemTypes.Object, source.SourceContext);
   Local tgt = new Local(targetType);
   Expression callGetTag = new MethodCall(new MemberBinding(new UnaryExpression(src, NodeType.AddressOf), getTag), null);
   Expression callGetValue = new MethodCall(new MemberBinding(new UnaryExpression(src, NodeType.AddressOf), getValue), null);
   TypeNodeList types = sourceType.Types;
   int n = types == null ? 0 : types.Count;
   Block endOfSwitch = new Block();
   StatementList statements = new StatementList(5+n);
   statements.Add(new AssignmentStatement(src, source));
   statements.Add(new AssignmentStatement(srcOb, callGetValue));
   BlockList cases = new BlockList(n);
   statements.Add(new SwitchInstruction(callGetTag, cases));
   bool hadCoercion = false;
   Block eb = new Block(new StatementList(1));
   Construct c = new Construct(new MemberBinding(null, SystemTypes.InvalidCastException.GetConstructor()), null, SystemTypes.InvalidCastException);
   eb.Statements.Add(new Throw(c));
   for (int i = 0; i < n; i++){
     TypeNode t = types[i];
     if (t == null) continue;
     if (!explicitCoercion && !this.ImplicitCoercionFromTo(t, targetType, typeViewer)) return null;
     Expression expr = this.ExplicitCoercion(srcOb, t, typeViewer);
     if (expr == null) return null;
     expr = this.ExplicitCoercion(expr, targetType, typeViewer);
     if (expr == null) {
       cases.Add(eb);
       statements.Add(eb);
     }
     else {
       Block b = new Block(new StatementList(2));
       hadCoercion = true;
       expr.SourceContext = srcOb.SourceContext;
       b.Statements.Add(new AssignmentStatement(tgt, expr));
       b.Statements.Add(new Branch(null, endOfSwitch));
       cases.Add(b);
       statements.Add(b);
     }
   }
   if (this.Errors != null) {
     for (int ie = cErrors, ne = this.Errors.Count; ie < ne; ie++) {
       this.Errors[ie] = null;
     }
   }
   if (!hadCoercion) return null;
   statements.Add(endOfSwitch);
   statements.Add(new ExpressionStatement(tgt));
   return new BlockExpression(new Block(statements));
   //TODO: wrap this in a CoerceTypeUnion node so that source code can be reconstructed easily
 }