Handles new block insertion request.
547666
public function insertBlockAction()
	{
		$this->isPostRequest();
		$this->checkLock();

		$pageRequest = $this->createPageRequest();

		$blockComponentName = $this->getRequestParameter('type');

		// Generate block according the page localization type provided
		$block = Block::factory($this->getPageLocalization());
		$block->setComponentName($blockComponentName);

		$class = $block->getComponentClass();

		$blockConfiguration = $this->getBlockCollection()
				->getConfiguration($class);

		// logic/code issue
		if (! $blockConfiguration->isInsertable()) {
			throw new CmsException(null, 'This block cannot be added.');
		}

		// deny adding if block is defined as unique
		// and page block set already contains it.
		if ($blockConfiguration->isUnique()) {

			foreach ($pageRequest->getBlockSet() as $existingBlock) {

				if ($existingBlock->getComponentClass() === $class) {
					throw new CmsException(
							null,
							sprinf(
									'Only one instance of "%s" block can be added on the page.',
									$blockConfiguration->getTitle()
							)
					);
				}
			}
		}

		$placeHolderName = $this->getRequestParameter('placeholder_id');

		$placeHolder = $pageRequest->getPlaceHolderSet()
				->getFinalPlaceHolders()
				->offsetGet($placeHolderName);

		if ($placeHolder === null) {
			throw new \InvalidArgumentException(sprintf(
					'Missing placeholder [%s] in place holder set.',
					$placeHolderName
			));
		}

		$insertBeforeTargetId = $this->getRequestInput()->get('reference_id');

		if (! empty($insertBeforeTargetId)) {

			$insertBeforeTarget = null;
			
			foreach ($placeHolder->getBlocks() as $existingBlock) {
				if ($existingBlock->getId() === $insertBeforeTargetId) {
					$insertBeforeTarget = $existingBlock;
					break;
				}
			}

			if ($insertBeforeTarget === null) {
				throw new \InvalidArgumentException(sprintf(
						'Blocks collection item [%s] not found.',
						$insertBeforeTargetId
				));
			}

			$placeHolder->addBlockBefore($insertBeforeTarget, $block);

		} else {
			$placeHolder->addBlockLast($block);
		}

		$entityManager = $this->getEntityManager();

		$entityManager->persist($block);

		$entityManager->flush();

		return new SupraJsonResponse($this->getBlockData($block, true));
	}
1068832
public static void processPostSetBlock(Chunk chunk, BlockPos pos, IBlockState oldState, IBlockState newState)
	{
		postSetBlockRegistry.processCallbacks(chunk, pos, oldState, newState);
	}
140400
void add(BlockInfo block, int numReplicas) {
    synchronized (pendingReplications) {
      PendingBlockInfo found = pendingReplications.get(block);
      if (found == null) {
        pendingReplications.put(block, new PendingBlockInfo(numReplicas));
      } else {
        found.incrementReplicas(numReplicas);
        found.setTimeStamp();
      }
    }
  }
1101567
synchronized void addBlock(Block block) {
    if (!isInitialized()) {
      return;
    }
    
    BlockScanInfo info = blockMap.get(block);
    if ( info != null ) {
      LOG.warn("Adding an already existing block " + block);
      delBlockInfo(info);
    }
    
    info = new BlockScanInfo(block);    
    info.lastScanTime = getNewBlockScanTime();
    
    addBlockInfo(info);
    adjustThrottler();
  }
270998
def on_block_received(self, block_id):
        
        _libexec('chain_controller_on_block_received', self.pointer,
                 ctypes.c_char_p(block_id.encode('utf-8')))
939462
def _request_new_chunk(self):
        
        # Figure out the length of the next request
        new_len = self._bytes_left
        if new_len > _ReadRequest.MAX_DATA_LENGTH:
            new_len = _ReadRequest.MAX_DATA_LENGTH

        logger.debug('Requesting new chunk of {}bytes at 0x{:X}'.format(
            new_len, self._current_addr))

        # Request the data for the next address
        pk = CRTPPacket()
        pk.set_header(CRTPPort.MEM, CHAN_READ)
        pk.data = struct.pack('<BIB', self.mem.id, self._current_addr, new_len)
        reply = struct.unpack('<BBBBB', pk.data[:-1])
        self.cf.send_packet(pk, expected_reply=reply, timeout=1)
45805
def new_code_block(self, **kwargs):
        """"""
        proto = {'content': '',
                 'type': self.code,
                 'IO': '',
                 'attributes': ''}
        proto.update(**kwargs)
        return proto
971322
function handleHardNewlineEvent(editorState: EditorState): EditorState {
  const selection = editorState.getSelection();
  if (selection.isCollapsed()) {
    const contentState = editorState.getCurrentContent();
    const blockKey = selection.getStartKey();
    const block = contentState.getBlockForKey(blockKey);
    if (
      !isListBlock(block) &&
      block.getType() !== 'unstyled' &&
      block.getLength() === selection.getStartOffset()
    ) {
      return insertNewUnstyledBlock(editorState);
    } else if (isListBlock(block) && block.getLength() === 0) {
      const depth = block.getDepth();
      if (depth === 0) {
        return removeSelectedBlocksStyle(editorState);
      }
      if (depth > 0) {
        return changeListDepth(editorState, -1, depth);
      }
    }
  }
  return undefined;
}
75906
public function add()
    {
        $this->loadModel('Block.Blocks');
        $block = $this->Blocks->newEntity();
        $block->set('region', []);

        if ($this->request->data()) {
            $block = $this->_patchEntity($block);

            if (!$block->errors()) {
                if ($this->Blocks->save($block)) {
                    $this->Flash->success(__d('block', 'Block created.'));
                    $this->redirect(['plugin' => 'Block', 'controller' => 'manage', 'action' => 'edit', $block->id]);
                } else {
                    $this->Flash->danger(__d('block', 'Block could not be created, please check your information.'));
                }
            } else {
                $this->Flash->danger(__d('block', 'Block could not be created, please check your information.'));
            }
        }

        $this->_setLanguages();
        $this->_setRoles();
        $this->_setRegions();
        $this->set('block', $block);
        $this->title(__d('block', 'Create New Block'));
        $this->Breadcrumb
            ->push('/admin/system/structure')
            ->push(__d('block', 'Manage Blocks'), ['plugin' => 'Block', 'controller' => 'manage', 'action' => 'index'])
            ->push(__d('block', 'Create New Block'), '#');
    }
264725
def replace_blocks(self, blocks):
        """"""
        start = 0
        bulk_insert = self.bulk_insert
        blocks_len = len(blocks)
        row = '(%s,%s,%s,%s,%s)'
        query = 'REPLACE INTO gauged_data (namespace, offset, `key`, ' \
            'data, flags) VALUES '
        execute = self.cursor.execute
        to_buffer = self.to_buffer
        while start < blocks_len:
            rows = blocks[start:start+bulk_insert]
            params = []
            for namespace, offset, key, data, flags in rows:
                params.extend((namespace, offset, key, to_buffer(data), flags))
            insert = (row + ',') * (len(rows) - 1) + row
            execute(query + insert, params)
            start += bulk_insert
185603
function replaceBlock( block, newBlock ) {
		// Block is to be removed, create a temp element to
		// save contents.
		var removeBlock = !newBlock;
		if ( removeBlock ) {
			newBlock = block.getDocument().createElement( 'div' );
			block.copyAttributes( newBlock );
		}

		var newBlockIsPre = newBlock && newBlock.is( 'pre' ),
			blockIsPre = block.is( 'pre' ),
			isToPre = newBlockIsPre && !blockIsPre,
			isFromPre = !newBlockIsPre && blockIsPre;

		if ( isToPre )
			newBlock = toPre( block, newBlock );
		else if ( isFromPre )
			// Split big <pre> into pieces before start to convert.
			newBlock = fromPres( removeBlock ? [ block.getHtml() ] : splitIntoPres( block ), newBlock );
		else
			block.moveChildren( newBlock );

		newBlock.replace( block );

		if ( newBlockIsPre ) {
			// Merge previous <pre> blocks.
			mergePre( newBlock );
		} else if ( removeBlock ) {
			removeNoAttribsElement( newBlock );
		}
	}
1014800
void assignToBlock(BlockId blk) {
		internalLock.writeLock().lock();
		try {
			flush();
			this.blk = blk;
			contents.read(blk);
			pins = 0;
			lastLsn = LogSeqNum.readFromPage(contents, LAST_LSN_OFFSET);
		} finally {
			internalLock.writeLock().unlock();
		}
	}
1054738
public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
    {
        $this->setBlockSetting($block_id, 'days', $request->get('days', self::DEFAULT_DAYS));
        $this->setBlockSetting($block_id, 'filter', $request->get('filter', ''));
        $this->setBlockSetting($block_id, 'infoStyle', $request->get('infoStyle', self::DEFAULT_STYLE));
        $this->setBlockSetting($block_id, 'sortStyle', $request->get('sortStyle', self::DEFAULT_SORT));
        $this->setBlockSetting($block_id, 'events', implode(',', (array) $request->get('events')));
    }
95415
def insert(index, middleware, *args, &block)
      index = self.index(index) unless index.is_a?(Integer)
      raise "no such middleware to insert before: #{index.inspect}" unless index
      stack.insert(index, [middleware, args, block])
    end
1108088
def insert(index, *args, &block)
      raise_if_locked
      index = assert_index(index)
      handler = self.class::Handler.new(*args, &block)
      @handlers.insert(index, handler)
    end
574171
private int insertInCurrOnly(Object caller, int version, bbBlock curr, int pos, int len)
    {
        assert mutation_in_progress(caller, version);
        // the space we need is available right in the block
        assert curr.unusedBlockCapacity() >= len;
        System.arraycopy(curr._buffer, curr.blockOffsetFromAbsolute(pos)
                         ,curr._buffer, curr.blockOffsetFromAbsolute(pos) + len, curr.bytesAvailableToRead(pos));
        curr._limit += len;
        this.adjustOffsets(curr._idx, len, 0);
        notifyInsert(pos, len);
        return len;
    }
92195
public function reorderBlocksAction()
	{
		$this->isPostRequest();
		$this->checkLock();

		$placeHolderName = $this->getRequestParameter('place_holder_id');

		$pageRequest = $this->createPageRequest();

		$placeHolder = $pageRequest->getPlaceHolderSet()
				->getFinalPlaceHolders()
				->offsetGet($placeHolderName);

		if ($placeHolder === null) {
			throw new \InvalidArgumentException(sprintf(
					'Placeholder [%s] not found in placeholders set.',
					$placeHolderName
			));
		}

		$blockSet = $pageRequest->getBlockSet()
				->getPlaceHolderBlockSet($placeHolder);

		$blockPositionMap = array_values($this->getRequestParameter('order', array()));

		if ($blockSet->count() !== count($blockPositionMap)) {
			// JS error or data spoofing
			throw new \UnexpectedValueException('Ordered elements and actual blocks count does not match.');
		}

		foreach ($blockPositionMap as $position => $id) {
			
			$block = $blockSet->findById($id);
			
			if ($block === null) {
				throw new \UnexpectedValueException(sprintf('Block [%s] not found.'));
			}

			$block->setPosition($position);
		}

		$this->getEntityManager()
				->flush();

		return new SupraJsonResponse();
	}