Python add block

60 Python code examples are found related to " add block". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ao_integrals.py    From orbkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
def add_MO_block_2e(self, MOrange=None, MOrangei=None, MOrangej=None, MOrangek=None, MOrangel=None):
    '''Specify block of 2-electron MO integrals to be calculated.

      **Parameters:**

      MOrangei, MOrangej : lists or range objects of integers
        Indices i, j, k and l specifing the desired block of MO integrals. If omitted, the whole range is take for the corrresponding index.
      MOrange : lists or range objects of integers
        Set same range for i, j, k and l.
    '''
    if MOrange is not None:
      MOrangei = MOrange
      MOrangej = MOrange
      MOrangek = MOrange
      MOrangel = MOrange
    if all((MOrangei is None, MOrangej is None, MOrangek is None, MOrangel is None)):
      return
    MOrangei = MOrangei if MOrangei is not None else range(self.Norb)
    MOrangej = MOrangej if MOrangej is not None else range(self.Norb)
    MOrangek = MOrangek if MOrangek is not None else range(self.Norb)
    MOrangel = MOrangel if MOrangel is not None else range(self.Norb)
    self.MO_blocks_2e.append((MOrangei, MOrangej, MOrangek, MOrangel)) 
Example 2
Source File: finalfantasyxivtimers.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def add_timer_block(response, timer_data):
    """
    :param response: The embed response to which to append the timer.
    :type response: discord.Embed
    :param timer_data: Descriptive timer data.
    :type timer_data: dict
    :return:
    :rtype: str
    """
    name = timer_data.get('name').split('>')[1].split('<')[0]
    now = arrow.utcnow()
    start = arrow.get(timer_data.get('start') / 1000)
    end = arrow.get(timer_data.get('end') / 1000)
    diff = to_delta(end) if now > start else to_delta(start)
    descriptive = f'{start.format("DD. MMM. YYYY")} - {end.format("DD. MMM. YYYY")} (In {diff})'
    response.add_field(name=f'{name}', value=descriptive, inline=False) 
Example 3
Source File: blockchain.py    From py-bitcoin with GNU General Public License v3.0 6 votes vote down vote up
def add_block(self, new_block):
        """
        添加block到链上
        :param new_block:
        :return:
        """

        # there we should mark last block hash to create a new block.
        # in the redis the l is the last block hash value key.

        pow = ProofOfWork(new_block, new_block["Nonce"])
        if pow.validate():
            # self.blocks.append(new_block)
            if not self.blocks.get(new_block["Hash"]):
                # 不存在的加入
                self.blocks.set(new_block["Hash"], new_block)
                self.blocks.set("l", new_block["Hash"]) 
Example 4
Source File: user.py    From bii-server with MIT License 6 votes vote down vote up
def add_block(self, brl, tags=None, description=""):
        '''Adds a block to the user workspace'''
        tags = tags or set()

        if brl.owner != self.ID:
            raise ForbiddenException('Can not add not own block: %s %s' % (str(brl), self.ID))
        if brl in self.blocks:
            raise DuplicateBlockException('Block %s already exist for %s')
        matching = [x for x in self.blocks if brl.lower() == x.lower()]
        if matching:
            raise BiiException("You're trying to publish block named %s. There is "
                               "already a block named %s among your blocks" % (brl, matching[0]))
        # Add tags and description
        self.blocks[brl] = [set(tags), description, 0]  # 0 bytes
        block_id = self.numeric_id + self.block_counter
        self.block_counter += 1
        return block_id 
Example 5
Source File: ResNet.py    From PANet with MIT License 6 votes vote down vote up
def add_residual_block(inplanes, outplanes, innerplanes, dilation, stride):
    """Return a residual block module, including residual connection, """
    if stride != 1 or inplanes != outplanes:
        shortcut_func = globals()[cfg.RESNETS.SHORTCUT_FUNC]
        downsample = shortcut_func(inplanes, outplanes, stride)
    else:
        downsample = None

    trans_func = globals()[cfg.RESNETS.TRANS_FUNC]
    res_block = trans_func(
        inplanes, outplanes, innerplanes, stride,
        dilation=dilation, group=cfg.RESNETS.NUM_GROUPS,
        downsample=downsample)

    return res_block


# ------------------------------------------------------------------------------
# various downsample shortcuts (may expand and may consider a new helper)
# ------------------------------------------------------------------------------ 
Example 6
Source File: world.py    From pycraft with MIT License 6 votes vote down vote up
def add_block(self, coords, block, immediate=True):
        """Add a block with the given `texture` and `position` to the world.

        Parameters
        ----------
        coords : tuple of len 3
            The (x, y, z) position of the block to add.
        block : list of len 3
            The coordinates of the texture squares. Use `tex_coords()` to
            generate.
        immediate : bool
            Whether or not to draw the block immediately.
        """
        self.area.add_block(coords, block)
        # self.sectors.setdefault(sectorize(position), []).append(position)
        if immediate:
            if self.area.exposed(coords):
                self.show_block(coords, block, immediate)
                neighbors = self.area.get_neighbors(coords)
                for element in neighbors['hide']:
                    self.hide_block(element['coords'])
                for element in neighbors['show']:
                    self.show_block(element['coords'], element['block']) 
Example 7
Source File: ChainManager.py    From QRL with MIT License 6 votes vote down vote up
def add_block(self, block: Block, check_stale=True) -> bool:
        with self.lock:
            if block.block_number <= self.re_org_limit:
                logger.debug('Skipping block #%s as beyond re-org limit', block.block_number)
                return False

            if self.get_block_is_duplicate(block):
                logger.warning("Duplicate Block found #%s", block.block_number)
                return False

            block_flag = self._add_block(block, check_stale=check_stale)
            if not block_flag:
                logger.warning("[ChainManager] Failed to Add Block #%s", block.block_number)
                return False

            logger.info('Added Block #%s %s', block.block_number, bin2hstr(block.headerhash))
            return True 
Example 8
Source File: cfg.py    From ilf with Apache License 2.0 6 votes vote down vote up
def add_block_to_method(self, method):
        method.blocks.add(self.start_idx)

        for i in range(self.start_idx, self.start_idx + self.length):
            method.insns.add(i)
            insn = self.cfg.contract.insns[i]
            method.bow[insn.op] += 1

        if self.default is not None and self.default not in method.blocks:
            self.cfg.blocks[self.default].add_block_to_method(method)

        if self.branch is not None and self.branch not in method.blocks:
            self.cfg.blocks[self.branch].add_block_to_method(method)

        for dep_default in self.dep_defaults:
            if dep_default not in method.blocks:
                self.cfg.blocks[dep_default].add_block_to_method(method)

        for dep_branch in self.dep_branches:
            if dep_branch not in method.blocks:
                self.cfg.blocks[dep_branch].add_block_to_method(method) 
Example 9
Source File: full_node_store.py    From chia-blockchain with Apache License 2.0 6 votes vote down vote up
def add_candidate_block(
        self,
        pos_hash: bytes32,
        transactions_generator: Optional[Program],
        transactions_filter: Optional[bytes],
        header: HeaderData,
        pos: ProofOfSpace,
        height: uint32 = uint32(0),
    ):
        self.candidate_blocks[pos_hash] = (
            transactions_generator,
            transactions_filter,
            header,
            pos,
            height,
        ) 
Example 10
Source File: wallet_store.py    From chia-blockchain with Apache License 2.0 6 votes vote down vote up
def add_block_record(self, block_record: BlockRecord, in_lca_path: bool):
        """
        Adds a block record to the database. This block record is assumed to be connected
        to the chain, but it may or may not be in the LCA path.
        """
        cursor = await self.db_connection.execute(
            "INSERT OR REPLACE INTO block_records VALUES(?, ?, ?, ?)",
            (
                block_record.header_hash.hex(),
                block_record.height,
                in_lca_path,
                bytes(block_record),
            ),
        )
        await cursor.close()
        await self.db_connection.commit() 
Example 11
Source File: block_store.py    From chia-blockchain with Apache License 2.0 6 votes vote down vote up
def add_block(self, block: FullBlock) -> None:
        assert block.proof_of_time is not None
        cursor_1 = await self.db.execute(
            "INSERT OR REPLACE INTO blocks VALUES(?, ?, ?)",
            (block.height, block.header_hash.hex(), bytes(block)),
        )
        await cursor_1.close()
        proof_hash = std_hash(
            block.proof_of_space.get_hash() + block.proof_of_time.output.get_hash()
        )
        cursor_2 = await self.db.execute(
            ("INSERT OR REPLACE INTO headers VALUES(?, ?, ?, ?, ?, 0, 0)"),
            (
                block.height,
                block.header_hash.hex(),
                proof_hash.hex(),
                block.proof_of_space.challenge_hash.hex(),
                bytes(block.header),
            ),
        )
        await cursor_2.close()
        await self.db.commit() 
Example 12
Source File: iptables_helper.py    From agent with MIT License 6 votes vote down vote up
def add_block_rules():
    """
    Adds rules which permit localhost and related/established connections
    (ipv4 and ipv6) and drops the rest of input traffic.
    """
    for ipv6 in (False, True):
        # -I WOTT_INPUT -i lo -j ACCEPT
        # -I WOTT_INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
        # -A WOTT_INPUT -j DROP
        iptc_helper.batch_add_rules(TABLE, [
            (INPUT_CHAIN, {
                'in-interface': 'lo',
                'target': 'ACCEPT'
            }, 1),
            (INPUT_CHAIN, {
                'conntrack': {'ctstate': 'RELATED,ESTABLISHED'},
                'target': 'ACCEPT'
            }, 2),
            (INPUT_CHAIN, {
                'target': 'DROP'
            }, 0)
        ], ipv6=ipv6) 
Example 13
Source File: chain.py    From tinycoin with MIT License 6 votes vote down vote up
def add_block(self, header, block):
        # Refactor to do this after (important for correctness)
        if self.max_height == header.height -1:
            self.max_height +=1
            self.chain.append({})
        if header.hash() in self.chain[header.height]:
            return self
        if self.max_height >= header.height:
            return self #TODO: Out of order block, deal with later elegantly
        if header.prev in self.chain[header.height-1]:
            parent = self.chain[header.height-1][h.prev]
            if header.height != parent.header.height+1:
                raise ValueError("Invalid Block Height for Parent (Internal Error)")
            try:
                new_utxoset = Chain.make_new_utxo_set(parent.utxoset, block, header)
            except ValueError as e:
                print e, "Bad Block, rejected!"
            finally:
                self.chain[header.height][header.hash()] = ChainNode(header, block, new_utxoset)
                self.max_height = max(h.height, self.max_height)
        return self 
Example 14
Source File: ResNet.py    From FPN-Pytorch with MIT License 6 votes vote down vote up
def add_residual_block(inplanes, outplanes, innerplanes, dilation, stride, deform=False):
    """Return a residual block module, including residual connection, """
    if stride != 1 or inplanes != outplanes:
        shortcut_func = globals()[cfg.RESNETS.SHORTCUT_FUNC]
        downsample = shortcut_func(inplanes, outplanes, stride)
    else:
        downsample = None

    trans_func = globals()[cfg.RESNETS.TRANS_FUNC]
    res_block = trans_func(
        inplanes, outplanes, innerplanes, stride,
        dilation=dilation, group=cfg.RESNETS.NUM_GROUPS,
        downsample=downsample, deform=deform)

    return res_block


# ------------------------------------------------------------------------------
# various downsample shortcuts (may expand and may consider a new helper)
# ------------------------------------------------------------------------------ 
Example 15
Source File: hydra_base.py    From Hydra with MIT License 6 votes vote down vote up
def add_block(self, module):
        """
        Registers a new Hydra block, automatically adds it to the
        self.blocks and the execution graph.

        Args:
          module: a `nn.Module` object

        Returns:
          a Controller object for newly added block
        """
        new_index = len(self.blocks)
        new_controller = Controller(new_index)
        self.blocks.append(module)
        self.controllers.append(new_controller)
        return new_controller 
Example 16
Source File: condensenet.py    From CondenseNet with MIT License 6 votes vote down vote up
def add_block(self, i):
        ### Check if ith is the last one
        last = (i == len(self.stages) - 1)
        block = _DenseBlock(
            num_layers=self.stages[i],
            in_channels=self.num_features,
            growth_rate=self.growth[i],
            args=self.args,
        )
        self.features.add_module('denseblock_%d' % (i + 1), block)
        self.num_features += self.stages[i] * self.growth[i]
        if not last:
            trans = _Transition(in_channels=self.num_features,
                                args=self.args)
            self.features.add_module('transition_%d' % (i + 1), trans)
        else:
            self.features.add_module('norm_last',
                                     nn.BatchNorm2d(self.num_features))
            self.features.add_module('relu_last',
                                     nn.ReLU(inplace=True))
            self.features.add_module('pool_last',
                                     nn.AvgPool2d(self.pool_size)) 
Example 17
Source File: view.py    From zulip with Apache License 2.0 6 votes vote down vote up
def add_block(block: Dict[str, Any], body: str) -> str:
    block_type = block.get("type", None)
    if block_type == "section":
        if "text" in block:
            text = block["text"]
            while type(text) == dict:  # handle stuff like block["text"]["text"]
                text = text["text"]
            body += f"\n\n{text}"

        if "accessory" in block:
            accessory = block["accessory"]
            accessory_type = accessory["type"]
            if accessory_type == "image":
                # This should become ![text](url) once proper Markdown images are supported
                body += "\n[{alt_text}]({image_url})".format(**accessory)

    return body 
Example 18
Source File: blockchain.py    From pyspv with MIT License 6 votes vote down vote up
def add_block(self, block):
        if not block.check():
            return

        block_link = self.create_block_link(hash=block.header.hash(), header=block.header)

        # __connect_block_link drops the block data after its connected to the block tree
        block_link['block'] = block

        with self.blockchain_lock:
            with closing(shelve.open(self.blockchain_db_file)) as db:
                blockchain = db['blockchain'].copy()
                changes = self.__connect_block_link(blockchain, block_link)
                db['blockchain'] = blockchain

            self.__run_changes(changes) 
Example 19
Source File: ao_integrals.py    From orbkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
def add_AO_block_1e(self, AOrange=None, AOrangei=None, AOrangej=None, shell=False):
    '''Specify block of 1-electron AO integrals to be calculated.

      **Parameters:**

      AOrangei, AOrangej : lists or range objects of integers
        Indices i and j specifing the desired block of AO integrals. If omitted, the whole range is take for the corrresponding index.
      AOrange : lists or range objects of integers
        Set same range for i and j.
      shell : boolean
        If True, indices i and j specify AO shells, instead of AO basis functions.
    '''
    if AOrange is not None:
      AOrangei = AOrange
      AOrangej = AOrange
    if all((AOrangei is None, AOrangej is None)):
      return
    if shell:
      AOrangei = list(chain(*[self._shell2ao(s) for s in AOrangei])) if AOrangei is not None else range(self.Norb)
      AOrangej = list(chain(*[self._shell2ao(s) for s in AOrangej])) if AOrangej is not None else range(self.Norb)
    else:
      AOrangei = AOrangei if AOrangei is not None else range(self.Norb)
      AOrangej = AOrangej if AOrangej is not None else range(self.Norb)
    self.AO_blocks_1e.append((AOrangei, AOrangej)) 
Example 20
Source File: block.py    From Amulet-Core with MIT License 6 votes vote down vote up
def get_add_block(self, block: Block) -> int:
        """
        Adds a Block object to the internal Block object/ID mappings. If the Block already exists in the mappings,
        then the existing ID is returned

        :param block: The Block to add to the manager
        :return: The internal ID of the Block
        """
        assert isinstance(block, Block), "BlockManager only takes Block objects."
        if block in self._block_to_index_map:
            return self._block_to_index_map[block]

        self._block_to_index_map[block] = i = len(self._block_to_index_map)
        self._index_to_block.append(block)

        return i 
Example 21
Source File: block_group.py    From pykit with MIT License 6 votes vote down vote up
def add_block(self, new_block, replace=False, allow_exist=False):

        if self.has(new_block) and allow_exist:
            return new_block

        bid = new_block['block_id']
        bidx = bid.block_index

        prev = self['blocks'].get(bidx)
        if not replace and prev is not None:
            raise BlockExists(
                'there is already a block at {bid}'.format(bid=bid))

        self['blocks'][bidx] = new_block

        if prev is None:
            return None
        else:
            return BlockDesc(prev) 
Example 22
Source File: ao_integrals.py    From orbkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
def add_MO_block_1e(self, MOrange=None, MOrangei=None, MOrangej=None):
    '''Specify block of 2-electron MO integrals to be calculated.

      **Parameters:**

      MOrangei, MOrangej : lists or range objects of integers
        Indices i and j specifing the desired block of MO integrals. If omitted, the whole range is take for the corrresponding index.
      MOrange : lists or range objects of integers
        Set same range for i and j.
    '''
    if MOrange is not None:
      MOrangei = MOrange
      MOrangej = MOrange
    if all((MOrangei is None, MOrangej is None)):
      return
    MOrangei = MOrangei if MOrangei is not None else range(self.Norb)
    MOrangej = MOrangej if MOrangej is not None else range(self.Norb)
    self.MO_blocks_1e.append((MOrangei, MOrangej)) 
Example 23
Source File: idf.py    From geomeppy with MIT License 6 votes vote down vote up
def add_shading_block(self, *args, **kwargs):
        # type: (*Any, **Any) -> None
        """Add a shading block to the IDF.

        :param name: A name for the block.
        :param coordinates: A list of (x, y) tuples representing the building outline.
        :param height: The height of the block roof above ground level.
        :param num_stories: The total number of stories including basement stories. Default : 1.
        :param below_ground_stories: The number of stories below ground. Default : 0.
        :param below_ground_storey_height: The height of each basement storey. Default : 2.5.

        """
        block = Block(*args, **kwargs)
        for i, wall in enumerate(block.walls[0], 1):
            if wall.area <= 0:
                continue
            s = self.newidfobject(
                "SHADING:SITE:DETAILED", Name="%s_%s" % (block.name, i)
            )
            try:
                s.setcoords(wall)
            except ZeroDivisionError:
                self.removeidfobject(s) 
Example 24
Source File: candidate_blocks.py    From loopchain with Apache License 2.0 6 votes vote down vote up
def add_block(self, block: Block, reps: Sequence[ExternalAddress]):
        if self.hash != block.header.hash:
            raise CandidateBlockSetBlock
        else:
            utils.logger.debug(f"set block({block.header.hash.hex()}) in CandidateBlock")
            self.__block = block

            self._reps = reps
            votes_class = Votes.get_block_votes_class(block.header.version)
            self.votes[0] = votes_class(self._reps, conf.VOTING_RATIO, self.height, 0, self.hash)
            for vote in self.votes_buffer:
                try:
                    if not self.votes.get(vote.round):
                        self.votes[vote.round] = \
                            votes_class(self._reps, conf.VOTING_RATIO, self.height, vote.round, self.hash)
                    self.votes[vote.round].add_vote(vote)
                except VoteError as e:
                    utils.logger.info(e)
            self.votes_buffer.clear() 
Example 25
Source File: sheet_wizard.py    From cheatsheet-maker with MIT License 6 votes vote down vote up
def add_block(self):
        """Displays block options selector"""
        print("##################################################################")
        print(self.lang_strings["BLOCK_MESSAGE"])
        options = { 1: self.lang_strings["BLOCK_OPTIONS"][1],
                    2: self.lang_strings["BLOCK_OPTIONS"][2],
                    0: self.lang_strings["BLOCK_OPTIONS"][0],
                   }
        answer = self.input_handler(options)
        if answer == "1":
            self.block_text()
        elif answer == "2":
            self.block_rows()
        elif answer == "0":
            self.end()
        else:
            print(self.lang_strings["INVALID_INPUT_MESSAGE"])
            return(self.add_block()) 
Example 26
Source File: peer.py    From simchain with The Unlicense 6 votes vote down vote up
def try_to_add_block(peer,block):  
    prev_hash = block.prev_block_hash                                                  
    height = locate_block_by_hash(peer,prev_hash)
    if not height:
        logger.info('{0}(pid={1} find a orphan {2})'.format(peer,peer.pid,block))
        peer.orphan_block.append(block)
        return False
    
    if height == peer.get_height():
        peer.blockchain.append(block)
        recieve_new_prev_hash_block(peer,block.txs)
        return True
    
    elif height == peer.get_height()-1:
        b1,b2 = peer.blockchain[-1],block
        a,b = int(b1.hash,16),int(b2.hash,16)
        if a < b:
            return False
        else:
            peer.blookchian.pop()
            peer.blockchain.append(block)
            recieve_exist_prev_hash_block(peer,block.txs)
    else:
        return False 
Example 27
Source File: Blockchain.py    From neo-python with MIT License 6 votes vote down vote up
def AddBlock(self, block):
        if not block.Hash.ToBytes() in self._block_cache:
            self._block_cache[block.Hash.ToBytes()] = block

        header_len = len(self._header_index)

        if block.Index - 1 >= header_len:
            return False

        if block.Index == header_len:

            if self._verify_blocks and not block.Verify():
                return False
            elif len(block.Transactions) < 1:
                return False
            self.AddHeader(block.Header)

        return True 
Example 28
Source File: CaffeUNet_3D.py    From peters-stuff with GNU General Public License v3.0 6 votes vote down vote up
def add_expansion_block(self, input, block_number):

        l = L.Deconvolution(input, convolution_param=dict(num_output=self.base_n_filters * pow(2, block_number), group=self.base_n_filters * pow(2, block_number), kernel_size=2, stride=2, weight_filler=dict(type='constant', value=1), bias_term=False), param=dict(lr_mult=0, decay_mult=0))
        setattr(self.net_spec, 'upscale_' + str(block_number), l)

        l = L.Concat(l, getattr(self.net_spec, 'contr_' + str(block_number) + '_2'), axis=1)
        setattr(self.net_spec, 'concat_' + str(block_number), l)

        if self.use_batchnorm:
            l = self.add_batchnormscale(name='expand_' + str(block_number) + '_1', input=L.ReLU(L.Convolution(l, pad=self.pad, kernel_size=self.kernel_size, num_output=self.base_n_filters * pow(2, block_number - 1), weight_filler=self.weight_filler, bias_filler=self.bias_filler, param=self.param), in_place=True))
            l = self.add_batchnormscale(name='expand_' + str(block_number) + '_2', input=L.ReLU(L.Convolution(l, pad=self.pad, kernel_size=self.kernel_size, num_output=self.base_n_filters * pow(2, block_number - 1), weight_filler=self.weight_filler, bias_filler=self.bias_filler, param=self.param), in_place=True))
        else:
            l = self.add_conv(input=l, name='expand_' + str(block_number) + '_1', filter_mult=block_number - 1)
            l = self.add_conv(input=l, name='expand_' + str(block_number) + '_2', filter_mult=block_number - 1)

        return l 
Example 29
Source File: ledger.py    From neo-python with MIT License 6 votes vote down vote up
def add_block(self, raw_block: bytes) -> bool:
        # return await self.controller.add_block(block)
        block = IOHelper.AsSerializableWithType(raw_block, 'neo.Core.Block.Block')  # type: Block

        if block is None:
            return False
        else:
            self.ledger.AddHeader(block.Header)

            success, reason = await self.ledger.TryPersist(block)
            if not success:
                logger.debug(f"Failed to Persist block. Reason: {reason}")
                return False

            try:
                self.ledger.OnPersistCompleted(block)
            except Exception as e:
                traceback.print_exc()
                logger.debug(f"Failed to broadcast OnPersistCompleted event, reason: {e}")

        return True 
Example 30
Source File: Viewer.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def AddNewBlock(self, bbox, wire=None):
        dialog = FBDBlockDialog(self.ParentWindow, self.Controler, self.TagName)
        dialog.SetPreviewFont(self.GetFont())
        dialog.SetMinElementSize((bbox.width, bbox.height))
        if dialog.ShowModal() == wx.ID_OK:
            id = self.GetNewId()
            values = dialog.GetValues()
            values.setdefault("name", "")
            block = FBD_Block(
                self, values["type"], values["name"], id,
                values["extension"], values["inputs"],
                executionControl=values["executionControl"],
                executionOrder=values["executionOrder"])
            self.Controler.AddEditedElementBlock(self.TagName, id, values["type"], values.get("name", None))
            connector = None
            if wire is not None:
                for input_connector in block.GetConnectors()["inputs"]:
                    if input_connector.IsCompatible(
                            wire.GetStartConnectedType()):
                        connector = input_connector
                        break
            self.AddNewElement(block, bbox, wire, connector)
            self.RefreshVariablePanel()
            self.ParentWindow.RefreshPouInstanceVariablesPanel()
        dialog.Destroy() 
Example 31
Source File: Viewer.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def AddBlockPinMenuItems(self, menu, connector):
        no_modifier = self.AppendItem(menu,  _(u'No modifier'), self.OnNoModifierMenu, kind=wx.ITEM_RADIO)
        negated = self.AppendItem(menu,  _(u'Negated'), self.OnNegatedMenu, kind=wx.ITEM_RADIO)
        rising_edge = self.AppendItem(menu,  _(u'Rising Edge'), self.OnRisingEdgeMenu, kind=wx.ITEM_RADIO)
        falling_edge = self.AppendItem(menu,  _(u'Falling Edge'), self.OnFallingEdgeMenu, kind=wx.ITEM_RADIO)

        not_a_function = self.Controler.GetEditedElementType(
            self.TagName, self.Debug) != "function"
        rising_edge.Enable(not_a_function)
        falling_edge.Enable(not_a_function)

        if connector.IsNegated():
            negated.Check(True)
        elif connector.GetEdge() == "rising":
            rising_edge.Check(True)
        elif connector.GetEdge() == "falling":
            falling_edge.Check(True)
        else:
            no_modifier.Check(True)

    # Add Alignment Menu items to the given menu 
Example 32
Source File: slave.py    From pyquarkchain with MIT License 6 votes vote down vote up
def handle_add_minor_block_request(self, req):
        """ For local miner to submit mined blocks through master """
        try:
            block = MinorBlock.deserialize(req.minor_block_data)
        except Exception:
            return AddMinorBlockResponse(error_code=errno.EBADMSG)
        shard = self.shards.get(block.header.branch, None)
        if not shard:
            return AddMinorBlockResponse(error_code=errno.EBADMSG)

        if block.header.hash_prev_minor_block != shard.state.header_tip.get_hash():
            # Tip changed, don't bother creating a fork
            Logger.info(
                "[{}] dropped stale block {} mined locally".format(
                    block.header.branch.to_str(), block.header.height
                )
            )
            return AddMinorBlockResponse(error_code=0)

        success = await shard.add_block(block)
        return AddMinorBlockResponse(error_code=0 if success else errno.EFAULT) 
Example 33
Source File: blocks.py    From ether_sql with Apache License 2.0 6 votes vote down vote up
def add_block(cls, block_data, iso_timestamp):
        """
        Creates a new block object from data received from JSON-RPC call
        eth_getBlockByNumber.

        :param dict block_data: data received from the JSON RPC call
        :param datetime iso_timestamp: timestamp when the block was mined
        """
        block = cls(block_hash=to_hex(block_data['hash']),
                    parent_hash=to_hex(block_data['parentHash']),
                    difficulty=to_int(block_data['difficulty']),
                    block_number=to_int(block_data['number']),
                    gas_used=to_int(block_data['gasUsed']),
                    miner=to_checksum_address(block_data['miner']),
                    timestamp=iso_timestamp,
                    sha3uncles=to_hex(block_data['sha3Uncles']),
                    extra_data=to_hex(block_data['extraData']),
                    gas_limit=to_int(block_data['gasLimit']),
                    transaction_count=len(block_data['transactions']),
                    uncle_count=len(block_data['uncles']))

        return block 
Example 34
Source File: world.py    From TerraCraft with GNU General Public License v3.0 6 votes vote down vote up
def add_block(self, position, block):
        """Add a block to this chunk only if the `position` is part of this chunk."""
        if not self.contains(position):
            return

        self.blocks[position] = block
        if self.exposed(position):
            self.visible.add(position)
        self.check_neighbors(position)

        for axis in range(3):
            if position[axis] == self.min_block[axis]:
                self.outline.add(position)
                face = [0] * 3
                face[axis] = -1
                face = tuple(face)
                if self.check_face_full(face):
                    self.face_full_cache.add(face)
            elif position[axis] == self.max_block[axis] - 1:
                self.outline.add(position)
                face = [0] * 3
                face[axis] = 1
                face = tuple(face)
                if self.check_face_full(face):
                    self.face_full_cache.add(face) 
Example 35
Source File: debug.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def AddScriptBlock(self, codeBlock):
		# If we dont have debugging support, dont bother.
		cc = DebugCodeBlockContainer(codeBlock, self.scriptSiteDebug)
		if self.IsSimpleHost():
			document = documents.DebugDocumentText(cc)
			document = _wrap(document, axdebug.IID_IDebugDocument)
			provider = documents.DebugDocumentProvider(document)
			provider = _wrap(provider, axdebug.IID_IDebugDocumentProvider)
			cc.debugDocument = document
			newNode = self.debugApplication.CreateApplicationNode()
			newNode.SetDocumentProvider(provider)
			newNode.Attach(self.rootNode)
		else:
			newNode = None # Managed by smart host.
			self.codeContainers[cc.sourceContext] = cc
		self.ccProvider.AddCodeContainer(cc, newNode) 
Example 36
Source File: BlockInstanceCollector.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def AddBlockInstance(self, context, *args):
        specific_values_tuple, specific_values_translation = \
            _SpecificValuesTuples.get(args[0][0], _BlockSpecificValues)

        if args[0][0] == "step" and len(self.SpecificValues) < 3 or \
           args[0][0] == "transition" and len(self.SpecificValues) < 4:
            self.SpecificValues.append([None])
        elif args[0][0] == "actionBlock" and len(self.SpecificValues) < 1:
            self.SpecificValues.append([[]])
        specific_values = specific_values_tuple(*_translate_args(
            specific_values_translation, self.SpecificValues))
        self.SpecificValues = None

        self.CurrentInstance = _BlockInstanceInfos(
            *(_translate_args([_StringValue, int] + [float] * 4, args) +
              [specific_values, [], []]))

        self.BlockInstances[self.CurrentInstance.id] = self.CurrentInstance 
Example 37
Source File: Viewer.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def AddVariableBlock(self, x, y, scaling, var_class, var_name, var_type):
        id = self.GetNewId()
        variable = FBD_Variable(self, var_class, var_name, var_type, id)
        width, height = variable.GetMinSize()
        if scaling is not None:
            x = round(x / scaling[0]) * scaling[0]
            y = round(y / scaling[1]) * scaling[1]
            width = round(width / scaling[0] + 0.5) * scaling[0]
            height = round(height / scaling[1] + 0.5) * scaling[1]
        variable.SetPosition(x, y)
        variable.SetSize(width, height)
        self.AddBlock(variable)
        self.Controler.AddEditedElementVariable(self.GetTagName(), id, var_class)
        self.RefreshVariableModel(variable)
        self.RefreshBuffer()
        self.RefreshScrollBars()
        self.RefreshVisibleElements()
        self.Editor.Refresh(False)

    # -------------------------------------------------------------------------------
    #                          Model adding functions
    # ------------------------------------------------------------------------------- 
Example 38
Source File: tadam.py    From am3 with Apache License 2.0 6 votes vote down vote up
def add_dense_block(h, block_depth, growth_rate, flags, beta=None, gamma=None, is_training=False, reuse=None,
                    scope='dense_block'):
    conv2d_arg_scope, dropout_arg_scope = _get_scope(is_training, flags)
    activation_fn = ACTIVATION_MAP[flags.activation]
    with tf.variable_scope(scope, reuse=reuse):
        with conv2d_arg_scope, dropout_arg_scope:
            for i in range(block_depth):
                h_previous = h
                h = slim.conv2d(h, num_outputs=4 * growth_rate, kernel_size=1, stride=1,
                                scope='conv_1x1' + str(i), padding='SAME')
                if flags.conv_dropout:
                    h = slim.dropout(h, scope='conv_1x1dropout' + str(i), keep_prob=1.0 - flags.conv_dropout)
                h = slim.conv2d(h, num_outputs=growth_rate, kernel_size=3, stride=1,
                                activation_fn=None,  # normalizer_fn=None, biases_initializer=None,
                                scope='conv_3x3' + str(i), padding='SAME')
                # conditional batch norm
                if beta is not None and gamma is not None:
                    with tf.variable_scope('conditional_batch_norm' + str(i), reuse=reuse):
                        h = get_cbn_layer(h, beta=beta[i], gamma=gamma[i])
                # activation
                h = activation_fn(h, name='activation_' + str(i))
                if flags.conv_dropout:
                    h = slim.dropout(h, scope='conv_3x3dropout' + str(i), keep_prob=1.0 - flags.conv_dropout)
                h = tf.concat([h_previous, h], name='concat_features' + str(i), axis=-1)
    return h 
Example 39
Source File: esbtc.py    From blockchain-elasticsearch with Apache License 2.0 6 votes vote down vote up
def add_block(self, block, force_add=False):
        "Add a block. Do nothing if the block already exists"

        read_index = "btc-blocks-*"
        the_index = "btc-blocks"

        exists = False
        try:
            #self.es.get(index=the_index, doc_type="doc", id=block['hash'])
            self.es.get(index=read_index, id=block['hash'])
            exists = True
        except NotFoundError:
            # We need to add this block
            exists = False

        if exists is False or force_add is True:
            #self.es.update(id=block['hash'], index=the_index, doc_type='doc', body={'doc' :block, 'doc_as_upsert': True}, request_timeout=30)
            self.es.update(id=block['hash'], index=the_index, body={'doc' :block, 'doc_as_upsert': True}, request_timeout=30) 
Example 40
Source File: shard_state.py    From pyquarkchain with MIT License 6 votes vote down vote up
def add_cross_shard_tx_list_by_minor_block_hash(
        self, h, tx_list: CrossShardTransactionList
    ):
        """ Add a cross shard tx list from remote shard
        The list should be validated by remote shard, however,
        it is better to diagnose some bugs in peer shard if we could check
        - x-shard gas limit exceeded
        - it is a neighor of current shard following our routing rule
        """
        self.db.put_minor_block_xshard_tx_list(h, tx_list)
        tx_hashes = [
            tx.tx_hash + tx.from_address.full_shard_key.to_bytes(4, byteorder="big")
            for tx in tx_list.tx_list
        ]
        asyncio.ensure_future(
            self.subscription_manager.notify_new_pending_tx(tx_hashes)
        ) 
Example 41
Source File: pieces.py    From Katastrophe with MIT License 6 votes vote down vote up
def addBlock(self, offset, data):
        if offset == 0:
            index = 0
        else:
            index = offset/BLOCK_SIZE

        if not self.blockTracker[index]:
            self.blocks[index] = data
            self.blockTracker[index] = True
            self.blocksSoFar += 1

        self.finished = all(self.blockTracker)

        if self.finished:
            return self.checkHash()

        return True 
Example 42
Source File: bridge_client.py    From dtella with GNU General Public License v2.0 6 votes vote down vote up
def addDataBlock(self, bhash, data):
        # Return True if the block was accepted, False otherwise

        if bhash not in self.blocks:
            return False

        # If we're requesting blocks, then mark this one off
        # and possibly ask for more.
        
        if bhash in self.req_blocks:
            self.req_blocks.discard(bhash)
            self.scheduleRequestBlocks()

        # Record the block data, and check if it's time to assemble
        # all the blocks together.

        if self.blocks[bhash] is None:
            self.blocks[bhash] = data
            self.assembleBlocks()

        return True 
Example 43
Source File: srez_model.py    From srez with MIT License 6 votes vote down vote up
def add_residual_block(self, num_units, mapsize=3, num_layers=2, stddev_factor=1e-3):
        """Adds a residual block as per Arxiv 1512.03385, Figure 3"""

        assert len(self.get_output().get_shape()) == 4 and "Previous layer must be 4-dimensional (batch, width, height, channels)"

        # Add projection in series if needed prior to shortcut
        if num_units != int(self.get_output().get_shape()[3]):
            self.add_conv2d(num_units, mapsize=1, stride=1, stddev_factor=1.)

        bypass = self.get_output()

        # Residual block
        for _ in range(num_layers):
            self.add_batch_norm()
            self.add_relu()
            self.add_conv2d(num_units, mapsize=mapsize, stride=1, stddev_factor=stddev_factor)

        self.add_sum(bypass)

        return self 
Example 44
Source File: base.py    From keras-rtst with MIT License 5 votes vote down vote up
def add_seq_conv_block(net, filters, filter_size, activation='relu', subsample=(1, 1), input_shape=None):
    if input_shape:
        kwargs = dict(input_shape=input_shape)
    else:
        kwargs = dict()
    net.add(Convolution2D(
        filters, filter_size, filter_size, subsample=subsample, border_mode='same', **kwargs))
    net.add(BatchNormalization(mode=0, axis=1))
    if isinstance(activation, six.string_types):
        if activation != 'linear':
            net.add(Activation(activation))
    else:
        net.add(activation()) 
Example 45
Source File: blockchain.py    From Foundations-of-Blockchain with MIT License 5 votes vote down vote up
def add_block(self, new_block):

        if self.is_valid_new_block(new_block, self.get_latest_block()):

            transactions = new_block.data if isinstance(new_block.data, list) else [new_block.data]
            ret_val = process_transactions([transaction_object(transaction) for transaction in transactions], self.get_unspent_tx_outs(), new_block.index)

            if ret_val is None:
                print('block is not valid in terms of transactions')
                return False
            else:
                self._blockchain.append(new_block)
                self.set_unspent_tx_outs(ret_val)
                update_transaction_pool(self.get_unspent_tx_outs())
                return True 
Example 46
Source File: base.py    From keras-rtst with MIT License 5 votes vote down vote up
def add_conv_block(net, name, input_name, filters, filter_size, activation='relu', subsample=(1, 1)):
    net.add_node(Convolution2D(filters, filter_size, filter_size, subsample=subsample, border_mode='same'),
        name + '_conv', input_name)
    net.add_node(BatchNormalization(mode=0, axis=1), name + '_bn',  name + '_conv')
    if isinstance(activation, six.string_types):
        net.add_node(Activation(activation), name,  name + '_bn')
    else:
        net.add_node(activation(), name, name + '_bn') 
Example 47
Source File: __init__.py    From LT-code with MIT License 5 votes vote down vote up
def add_block(self, nodes, data):
        """Adds a new check node and edges between that node and all
        source nodes it connects, resolving all message passes that
        become possible as a result.
        """

        # We can eliminate this source node
        if len(nodes) == 1:
            to_eliminate = list(self.eliminate(next(iter(nodes)), data))

            # Recursively eliminate all nodes that can now be resolved
            while len(to_eliminate):
                other, check = to_eliminate.pop()
                to_eliminate.extend(self.eliminate(other, check))
        else:

            # Pass messages from already-resolved source nodes
            for node in list(nodes):
                if node in self.eliminated:
                    nodes.remove(node)
                    data ^= self.eliminated[node]

            # Resolve if we are left with a single non-resolved source node
            if len(nodes) == 1:
                return self.add_block(nodes, data)
            else:

                # Add edges for all remaining nodes to this check
                check = CheckNode(nodes, data)
                for node in nodes:
                    self.checks[node].append(check)

        # Are we done yet?
        return len(self.eliminated) >= self.num_blocks 
Example 48
Source File: LDViewer.py    From OpenPLC_Editor with GNU General Public License v3.0 5 votes vote down vote up
def AddLadderBlock(self):
        message = wx.MessageDialog(self, _("This option isn't available yet!"), _("Warning"), wx.OK | wx.ICON_EXCLAMATION)
        message.ShowModal()
        message.Destroy()

    # -------------------------------------------------------------------------------
    #                          Delete element functions
    # ------------------------------------------------------------------------------- 
Example 49
Source File: mainwindow.py    From Turing with MIT License 5 votes vote down vote up
def add_if_block():
    from forms import alg_if
    dlg = alg_if.AlgoIfStmt(GuiState.window)
    if dlg.run():
        append_line(IfStmt(dlg.expr, [])) 
Example 50
Source File: OLVPrinter.py    From bookhub with MIT License 5 votes vote down vote up
def AddBlock(self, block):
        """
        Add the given block at the current insertion point
        """
        self.blocks.insert(self.blockInsertionIndex, block)
        self.blockInsertionIndex += 1
        block.engine = self 
Example 51
Source File: mainwindow.py    From Turing with MIT License 5 votes vote down vote up
def add_block(block: BlockStmt, current, add=False):
    current.append(0)

    for child in block.children:
        add_line(current, child, add=add)

        if isinstance(child, BlockStmt):
            add_block(child, current, add)

        current[-1] += 1

    current.pop() 
Example 52
Source File: mgbdis.py    From mgbdis with MIT License 5 votes vote down vote up
def add_block(self, bank, address, block_type, length, arguments = None):
        memory_base_address = 0x0000 if bank == 0 else 0x4000

        if address >= memory_base_address:
            blocks = self.get_blocks(bank)
            blocks[address] = {
                'type': block_type,
                'length': length,
                'arguments': arguments
            }