当前位置: 首页>>代码示例>>Python>>正文


Python Trie.get方法代码示例

本文整理汇总了Python中trie.Trie.get方法的典型用法代码示例。如果您正苦于以下问题:Python Trie.get方法的具体用法?Python Trie.get怎么用?Python Trie.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在trie.Trie的用法示例。


在下文中一共展示了Trie.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_insert_on_empty_long

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_insert_on_empty_long(self):
     trie = Trie()
     data = 'ripper X!'
     trie.insert( 'ab', data )
     self.assertIsNone(trie.get('a'))     # a is not in the dict
     self.assertIsNotNone(trie.get('ab')) # ab is
     self.assertEqual(trie.get('ab'), data)
开发者ID:mpchoy,项目名称:python-trie,代码行数:9,代码来源:trie_test.py

示例2: test_insert_on_empty_longer

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_insert_on_empty_longer(self):
     trie = Trie()
     key = 'absentia'
     data = 'Must be present to win'
     trie.insert( key, data )
     self.assertIsNone(trie.get('a'))
     self.assertIsNone(trie.get('absent'))
     self.assertEqual(trie.get(key), data)
开发者ID:mpchoy,项目名称:python-trie,代码行数:10,代码来源:trie_test.py

示例3: test_remove_long

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_remove_long(self):
     trie = Trie()
     key = 'abc'
     data = 123
     trie.insert( key, data )
     self.assertIsNotNone(trie.get(key))
     self.assertEqual(trie.remove(key), data)
     self.assertIsNone(trie.get(key))
开发者ID:mpchoy,项目名称:python-trie,代码行数:10,代码来源:trie_test.py

示例4: test_insert_fork

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_insert_fork(self):
     trie = Trie()
     ab_data = 'ripper X!'
     ax_data = 'for chopping'
     trie.insert( 'ab', ab_data )
     trie.insert( 'ax', ax_data )
     self.assertIsNone(trie.get('a'))
     self.assertEqual(trie.get('ab'), ab_data)
     self.assertEqual(trie.get('ax'), ax_data)
开发者ID:mpchoy,项目名称:python-trie,代码行数:11,代码来源:trie_test.py

示例5: test_remove_one_but_not_both

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_remove_one_but_not_both(self):
     trie = Trie()
     key1 = 'abc'
     key2 = 'abd'
     data1 = 123
     data2 = 987
     trie.insert( key1, data1 )
     trie.insert( key2, data2 )
     self.assertEqual(trie.remove(key1), data1)
     self.assertIsNone(trie.get(key1))
     self.assertEqual(trie.get(key2), data2)
开发者ID:mpchoy,项目名称:python-trie,代码行数:13,代码来源:trie_test.py

示例6: test_put

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
def test_put():
    t = Trie()
    t.put("rome", 1)
    t.put("romulus", 2)
    t.put("romanus", 3)
    t.put("romantic", 4)
    assert t.get("rome") == 1
    assert t.get("romulus") == 2
    assert t.get("romanus") == 3
    assert t.get("romantic") == 4
    t.put("romanus", 23)
    assert t.get("romanus") == 23
开发者ID:dbader,项目名称:data-structures-py,代码行数:14,代码来源:trie_test.py

示例7: test_insert_overlap

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_insert_overlap(self):
     trie = Trie()
     key_a = 'a'
     key_at = 'at'
     key_ate = 'ate'
     data_a = 'is for apple'
     data_at = '@'
     data_ate = 'a verb in past tense'
     trie.insert( key_a, data_a )
     trie.insert( key_at, data_at )
     trie.insert( key_ate, data_ate )
     self.assertEqual(trie.get(key_a), data_a)
     self.assertEqual(trie.get(key_at), data_at)
     self.assertEqual(trie.get(key_ate), data_ate)
开发者ID:mpchoy,项目名称:python-trie,代码行数:16,代码来源:trie_test.py

示例8: __init__

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
class Concepts:
    def __init__(self):
        self.conceptData = Trie()

        self.read_concepts()

    def read_word_file(self):
        text_file = open("word.dat", "r")
        lines = text_file.read().split('\n')

        text_file.close()
        return lines

    def read_concepts(self):
        word_list = ('indian', 'thai', 'sushi', 'caribbean', 'italian', 'west indian', 'pub', 'east asian',
          'bbq', 'chinese', 'portuguese', 'spanish', 'french', 'east european')

        # word_list = self.read_word_file()

        for word in word_list:
            self.conceptData[word] = True

    def first_letter_match(self, string_to_find):
        if not string_to_find:
            return False

        return self.conceptData.path.get(string_to_find[0]) is not None

    def match(self, string_to_find):
        if not string_to_find:
            return False

        return self.conceptData.get(string_to_find.lower(), False)
开发者ID:chrisgeorge0911,项目名称:AppleCodingTest,代码行数:35,代码来源:Concepts.py

示例9: TestTrie

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]

#.........这里部分代码省略.........
        self.assertRaises(KeyError, self._square_brackets, "Foo")
        self.assertEquals(0, len(self.trie))
        self.assertEquals(0, self.trie.nodeCount())
        self.assertFalse("Foo" in self.trie)

    def test_MixedTypes(self):
        self.trie["Foo"] = True
        self.trie[[1, 2, 3]] = True
        self.assertTrue(self.trie["Foo"])
        self.assertTrue(self.trie[[1, 2, 3]])
        self.assertTrue([1, 2, 3] in self.trie)
        self.assertTrue("Foo" in self.trie)
        del self.trie[[1, 2, 3]]
        self.assertFalse([1, 2, 3] in self.trie)

    def test_Iteration(self):
        self.trie["Foo"] = True
        self.trie["Bar"] = True
        self.trie["Grok"] = True
        for k in self.trie:
            self.assertTrue(k in self.trie)
            self.assertTrue(self.trie[k])

    def test_Addition(self):
        self.trie["Foo"] = True
        t2 = Trie()
        t2["Food"] = True
        t3 = t2 + self.trie
        self.assertTrue("Foo" in self.trie)
        self.assertFalse("Food" in self.trie)
        self.assertTrue("Food" in t2)
        self.assertFalse("Foo" in t2)
        self.assertTrue("Foo" in t3)
        self.assertTrue("Food" in t3)

    def test_Subtraction(self):
        self.trie["Food"] = True
        self.trie["Foo"] = True
        t2 = Trie()
        t2["Food"] = True
        t3 = self.trie - t2
        t4 = t2 - self.trie
        self.assertTrue("Food" in self.trie)
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in t2)
        self.assertTrue("Foo" in t3)
        self.assertFalse("Food" in t3)
        self.assertFalse("Foo" in t4)
        self.assertFalse("Food" in t4)

    def test_SelfAdd(self):
        self.trie["Foo"] = True
        t2 = Trie()
        t2["Food"] = True
        self.assertTrue("Foo" in self.trie)
        self.assertFalse("Food" in self.trie)
        self.assertTrue("Food" in t2)
        self.assertFalse("Foo" in t2)
        self.trie += t2
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in self.trie)

    def test_SelfSub(self):
        self.trie["Foo"] = True
        self.trie["Food"] = True
        t2 = Trie()
        t2["Food"] = True
        self.assertTrue("Food" in self.trie)
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in t2)
        self.trie -= t2
        self.assertFalse("Food" in self.trie)
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in t2)

    def test_SelfGet(self):
        self.trie["Foo"] = True
        self.assertTrue(self.trie["Foo"])
        self.assertRaises(KeyError, self._square_brackets, "Food")
        self.assertEquals("Bar", self.trie.get("Food", "Bar"))
        self.assertEquals("Bar", self.trie.get("Food", default="Bar"))
        self.assertTrue(self.trie.get("Foo"))
        self.assertTrue(self.trie.get("Food") is None)

    def test_get_prefix(self):
        self.trie["123"] = 1
        self.trie["123456"] = 2
        self.trie["123457"] = 3
        self.trie["1234578"] = 4
        self.assertEquals(None, self.trie.get_prefix("7"))
        self.assertEquals(None, self.trie.get_prefix("1"))
        self.assertEquals(None, self.trie.get_prefix("12"))
        self.assertEquals(1, self.trie.get_prefix("123"))
        self.assertEquals(1, self.trie.get_prefix("1234"))
        self.assertEquals(1, self.trie.get_prefix("12345"))
        self.assertEquals(2, self.trie.get_prefix("123456"))
        self.assertEquals(3, self.trie.get_prefix("123457"))
        self.assertEquals(4, self.trie.get_prefix("1234578"))
        self.assertEquals(4, self.trie.get_prefix("12345789"))
        self.assertEquals(4, self.trie.get_prefix("12345789999"))
开发者ID:olegoga,项目名称:python-trie,代码行数:104,代码来源:trie_unittest.py

示例10: Block

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
class Block(object):

    def __init__(self, data=None):

        self.reward = 10 ** 18
        self.gas_consumed = 0
        self.gaslimit = 1000000  # for now

        if not data:
            self.number = 0
            self.prevhash = ''
            self.uncles_root = ''
            self.coinbase = '0' * 40
            self.state = Trie(get_db_path())
            self.transactions_root = ''
            self.transactions = []
            self.uncles = []
            self.difficulty = 2 ** 23
            self.timestamp = 0
            self.extradata = ''
            self.nonce = 0
            return

        if re.match('^[0-9a-fA-F]*$', data):
            data = data.decode('hex')

        header,  transaction_list, self.uncles = rlp.decode(data)
        self.number = decode_int(header[0])
        self.prevhash = header[1]
        self.uncles_root = header[2]
        self.coinbase = header[3].encode('hex')
        self.state = Trie(STATEDB_DIR, header[4])
        self.transactions_root = header[5]
        self.difficulty = decode_int(header[6])
        self.timestamp = decode_int(header[7])
        self.extradata = header[8]
        self.nonce = decode_int(header[9])
        self.transactions = [Transaction(x) for x in transaction_list]

        # Verifications
        if self.state.root != '' and self.state.db.get(self.state.root) == '':
            raise Exception("State Merkle root not found in database!")
        if sha3(rlp.encode(transaction_list)) != self.transactions_root:
            raise Exception("Transaction list root hash does not match!")
        if sha3(rlp.encode(self.uncles)) != self.uncles_root:
            raise Exception("Uncle root hash does not match!")
        # TODO: check POW

    # _get_acct_item(bin or hex, int) -> bin
    def _get_acct_item(self, address, index):
        ''' get account item
        :param address: account address, can be binary or hex string
        :param index: item index
        '''
        if len(address) == 40:
            address = address.decode('hex')
        acct = self.state.get(address) or ['', '', '', '']
        return acct[index]

    # _set_acct_item(bin or hex, int, bin)
    def _set_acct_item(self, address, index, value):
        ''' set account item
        :param address: account address, can be binary or hex string
        :param index: item index
        :param value: new value
        '''
        if len(address) == 40:
            address = address.decode('hex')
        acct = self.state.get(address) or ['', '', '', '']
        acct[index] = value
        self.state.update(address, acct)

    # _delta_item(bin or hex, int, int) -> success/fail
    def _delta_item(self, address, index, value):
        ''' add value to account item
        :param address: account address, can be binary or hex string
        :param index: item index
        :param value: can be positive or negative
        '''
        if len(address) == 40:
            address = address.decode('hex')
        acct = self.state.get(address) or ['', '', '', '']
        if decode_int(acct[index]) + value < 0:
            return False
        acct[index] = encode_int(decode_int(acct[index]) + value)
        self.state.update(address, acct)
        return True

    def get_nonce(self, address):
        return decode_int(self._get_acct_item(address, NONCE_INDEX))

    def increment_nonce(self, address):
        return self._delta_item(address, NONCE_INDEX, 1)

    def get_balance(self, address):
        return decode_int(self._get_acct_item(address, BALANCE_INDEX))

    def set_balance(self, address, value):
        self._set_acct_item(address, BALANCE_INDEX, encode_int(value))

#.........这里部分代码省略.........
开发者ID:jo,项目名称:pyethereum,代码行数:103,代码来源:blocks.py

示例11: apply_op

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
def apply_op(block,tx,msg,code,compustate,op):
    op_data = get_op_data(code,compustate.pc)
    # empty stack error
    if op_data[1] > len(compustate.stack):
        return []
    stackargs = []
    for i in range(op.data[1]):
        stackargs.push(stack.pop())
    # out of gas error
    fee = calcfee(block,tx,msg,compustate,op)
    if fee > compustate.gas:
        return OUT_OF_GAS
    # Apply operation
    newgas = compustate.gas - fee
    newpc = compustate.pc + 1
    stk = compustate.stack
    mem = compustate.memory
    if op == 'ADD':
        stk.push((stackargs[0] + stackargs[1]) % 2**256)
    elif op == 'SUB':
        stk.push((stackargs[0] - stackargs[1]) % 2**256)
    elif op == 'MUL':
        stk.push((stackargs[0] * stackargs[1]) % 2**256)
    elif op == 'DIV':
        stk.push(stackargs[0] / stackargs[1])
    elif op == 'MOD':
        stk.push(stackargs[0] % stackargs[1])
    elif op == 'SDIV':
        if stackargs[0] >= 2**255: stackargs[0] -= 2**256
        if stackargs[1] >= 2**255: stackargs[1] -= 2**256
        stk.push((stackargs[0] / stackargs[1]) % 2**256)
    elif op == 'SMOD':
        if stackargs[0] >= 2**255: stackargs[0] -= 2**256
        if stackargs[1] >= 2**255: stackargs[1] -= 2**256
        stk.push((stackargs[0] % stackargs[1]) % 2**256)
    elif op == 'EXP':
        stk.push(pow(stackargs[0],stackargs[1],2**256))
    elif op == 'NEG':
        stk.push(2**256 - stackargs[0])
    elif op == 'LT':
        stk.push(1 if stackargs[0] < stackargs[1] else 0)
    elif op == 'GT':
        stk.push(1 if stackargs[0] > stackargs[1] else 0)
    elif op == 'EQ':
        stk.push(1 if stackargs[0] == stackargs[1] else 0)
    elif op == 'NOT':
        stk.push(0 if stackargs[0] else 1)
    elif op == 'AND':
        stk.push(stackargs[0] & stackargs[1])
    elif op == 'OR':
        stk.push(stackargs[0] | stackargs[1])
    elif op == 'XOR':
        stk.push(stackargs[0] ^ stackargs[1])
    elif op == 'BYTE':
        if stackargs[0] >= 32: stk.push(0)
        else: stk.push((stackargs[1] / 256**stackargs[0]) % 256)
    elif op == 'SHA3':
        if len(mem) < stackargs[0] + stackargs[1]:
            mem.extend([0] * (stackargs[0] + stackargs[1] - len(mem)))
        data = ''.join(map(chr,mem[stackargs[0]:stackargs[0] + stackargs[1]]))
        stk.push(decode(sha3(data),256))
    elif op == 'ADDRESS':
        stk.push(msg.to)
    elif op == 'BALANCE':
        stk.push(block.state.get(msg.to)[BALANCE_INDEX])
    elif op == 'ORIGIN':
        stk.push(tx.sender)
    elif op == 'CALLER':
        stk.push(msg.sender)
    elif op == 'CALLVALUE':
        stk.push(msg.value)
    elif op == 'CALLDATA':
        if stackargs[-1] >= len(msg.data): stk.push(0)
        else:
            dat = ''.join(map(chr,msg.data[stackargs[-1]:stackargs[-1]+32]))
            stk.push(decode(dat+'\x00'*(32-len(dat)),256))
    elif op == 'CALLDATASIZE':
        stk.push(len(msg.data))
    elif op == 'GASPRICE':
        stk.push(tx.gasprice)
    elif op == 'PREVHASH':
        stk.push(block.prevhash)
    elif op == 'COINBASE':
        stk.push(block.coinbase)
    elif op == 'TIMESTAMP':
        stk.push(block.timestamp)
    elif op == 'NUMBER':
        stk.push(block.number)
    elif op == 'DIFFICULTY':
        stk.push(block.difficulty)
    elif op == 'GASLIMIT':
        stk.push(block.gaslimit)
    elif op == 'POP':
        pass
    elif op == 'DUP':
        stk.push(stackargs[0])
        stk.push(stackargs[0])
    elif op == 'SWAP':
        stk.push(stackargs[0])
        stk.push(stackargs[1])
#.........这里部分代码省略.........
开发者ID:lessc0de,项目名称:pyethereum,代码行数:103,代码来源:processblock.py

示例12: TestTrie

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]

#.........这里部分代码省略.........
        self.assertTrue("Bar" in self.trie)

    def test_basicRemoval(self):
        self.trie["Foo"] = True
        self.assertTrue(self.trie["Foo"])
        del self.trie["Foo"]
        self.assertRaises(KeyError, self._square_brackets, "Foo")
        self.assertEquals(0, len(self.trie))
        self.assertEquals(0, self.trie.nodeCount())
        self.assertFalse("Foo" in self.trie)

    def test_MixedTypes(self):
        self.trie["Foo"] = True
        self.trie[[1, 2, 3]] = True
        self.assertTrue(self.trie["Foo"])
        self.assertTrue(self.trie[[1, 2, 3]])
        self.assertTrue([1, 2, 3] in self.trie)
        self.assertTrue("Foo" in self.trie)
        del self.trie[[1, 2, 3]]
        self.assertFalse([1, 2, 3] in self.trie)

    def test_Iteration(self):
        self.trie["Foo"] = True
        self.trie["Bar"] = True
        self.trie["Grok"] = True
        for k in self.trie:
            self.assertTrue(k in self.trie)
            self.assertTrue(self.trie[k])

    def test_Addition(self):
        self.trie["Foo"] = True
        t2 = Trie()
        t2["Food"] = True
        t3 = t2 + self.trie
        self.assertTrue("Foo" in self.trie)
        self.assertFalse("Food" in self.trie)
        self.assertTrue("Food" in t2)
        self.assertFalse("Foo" in t2)
        self.assertTrue("Foo" in t3)
        self.assertTrue("Food" in t3)

    def test_Subtraction(self):
        self.trie["Food"] = True
        self.trie["Foo"] = True
        t2 = Trie()
        t2["Food"] = True
        t3 = self.trie - t2
        t4 = t2 - self.trie
        self.assertTrue("Food" in self.trie)
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in t2)
        self.assertTrue("Foo" in t3)
        self.assertFalse("Food" in t3)
        self.assertFalse("Foo" in t4)
        self.assertFalse("Food" in t4)

    def test_SelfAdd(self):
        self.trie["Foo"] = True
        t2 = Trie()
        t2["Food"] = True
        self.assertTrue("Foo" in self.trie)
        self.assertFalse("Food" in self.trie)
        self.assertTrue("Food" in t2)
        self.assertFalse("Foo" in t2)
        self.trie += t2
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in self.trie)

    def test_SelfSub(self):
        self.trie["Foo"] = True
        self.trie["Food"] = True
        t2 = Trie()
        t2["Food"] = True
        self.assertTrue("Food" in self.trie)
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in t2)
        self.trie -= t2
        self.assertFalse("Food" in self.trie)
        self.assertTrue("Foo" in self.trie)
        self.assertTrue("Food" in t2)

    def test_SelfGet(self):
        self.trie["Foo"] = True
        self.assertTrue(self.trie["Foo"])
        self.assertRaises(KeyError, self._square_brackets, "Food")
        self.assertEquals("Bar", self.trie.get("Food", "Bar"))
        self.assertEquals("Bar", self.trie.get("Food", default="Bar"))
        self.assertTrue(self.trie.get("Foo"))
        self.assertTrue(self.trie.get("Food") is None)

    def test_Startswith(self):
        self.trie['lol']      = 1
        self.trie['lautre']   = 1
        self.trie['laurentz'] = 1
        self.trie['foobar']   = 1

        self.assertEquals(['laurentz','lautre','lol'], self.trie.startswith('l'))
        self.assertEquals(['laurentz','lautre'], self.trie.startswith('la'))
        self.assertEquals(['laurentz'], self.trie.startswith('laur'))
        self.assertEquals([], self.trie.startswith('bar'))
开发者ID:gbour,项目名称:python-trie,代码行数:104,代码来源:trie_unittest.py

示例13: Block

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
class Block(object):
    def __init__(self, data=None):

        self.reward = 10**18
        self.gas_consumed = 0
        self.gaslimit = 1000000 # for now

        if not data:
            self.number = 0
            self.prevhash = ''
            self.uncles_root = ''
            self.coinbase = '0'*40
            self.state = Trie('statedb')
            self.transactions_root = ''
            self.transactions = []
            self.difficulty = 2**23
            self.timestamp = 0
            self.extradata = ''
            self.nonce = 0
            return

        if re.match('^[0-9a-fA-F]*$', data):
            data = data.decode('hex')

        header,  transaction_list, self.uncles = rlp.decode(data)
        [self.number,
         self.prevhash,
         self.uncles_root,
         self.coinbase,
         state_root,
         self.transactions_root,
         self.difficulty,
         self.timestamp,
         self.extradata,
         self.nonce] = header
        self.transactions = [Transaction(x) for x in transaction_list]
        self.state = Trie('statedb', state_root)


        # Verifications
        if self.state.root != '' and self.state.db.get(self.state.root) == '':
            raise Exception("State Merkle root not found in database!")
        if bin_sha256(rlp.encode(transaction_list)) != self.transactions_root:
            raise Exception("Transaction list root hash does not match!")
        if bin_sha256(rlp.encode(self.uncles)) != self.uncles_root:
            raise Exception("Uncle root hash does not match!")
        # TODO: check POW

    # get_index(bin or hex, int) -> bin
    def get_index(self,address,index):
        if len(address) == 40: address = address.decode('hex')
        acct = self.state.get(address) or ['','','','']
        return acct[index]

    # set_index(bin or hex, int, bin)
    def set_index(self,address,index,value):
        if len(address) == 40: address = address.decode('hex')
        acct = self.state.get(address) or ['','','','']
        acct[index] = value
        self.state.update(address,acct)

    # delta_index(bin or hex, int, int) -> success/fail
    def delta_index(self,address,index,value):
        if len(address) == 40: address = address.decode('hex')
        acct = self.state.get(address) or ['','','','']
        if decode_int(acct[index]) + value < 0:
            return False
        acct[index] = encode_int(decode_int(acct[index])+value)
        self.state.update(address,acct)
        return True

    def coerce_to_enc(self,n):
        return encode_int(n) if isinstance(n,(int,long)) else n
    def get_nonce(self,address):
        return decode_int(self.get_index(address,NONCE_INDEX))
    def increment_nonce(self,address):
        return self.delta_index(address,NONCE_INDEX,1)
    def get_balance(self,address):
        return decode_int(self.get_index(address,BALANCE_INDEX))
    def set_balance(self,address,value):
        self.set_index(address,BALANCE_INDEX,encode_int(value))
    def delta_balance(self,address,value):
        return self.delta_index(address,BALANCE_INDEX,value)
    def get_code(self,address):
        codehash = self.get_index(address,CODE_INDEX)
        return DB('statedb').get(codehash) if codehash else ''
    def set_code(self,address,value):
        DB('statedb').put(sha3(value),value)
        self.set_index(address,CODE_INDEX,sha3(value))
    def get_storage(self,address):
        return Trie('statedb',self.get_index(address,STORAGE_INDEX))
    def get_storage_data(self,address,index):
        return decode_int(self.get_storage(address).get(self.coerce_to_enc(index)))
    def set_storage_data(self,address,index,val):
        t = Trie('statedb',self.get_index(address,STORAGE_INDEX))
        t.update(self.coerce_to_enc(index),encode_int(val))
        self.set_index(address,STORAGE_INDEX,t.root)
    
    # Revert computation
    def snapshot(self):
#.........这里部分代码省略.........
开发者ID:gojira,项目名称:pyethereum,代码行数:103,代码来源:blocks.py

示例14: Block

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
class Block(object):
    def __init__(self, data=None):

        if not data:
            return

        if re.match('^[0-9a-fA-F]*$', data):
            data = data.decode('hex')

        header,  transaction_list, self.uncles = rlp.decode(data)
        [self.number,
         self.prevhash,
         self.uncles_root,
         self.coinbase,
         state_root,
         self.transactions_root,
         self.difficulty,
         self.timestamp,
         self.nonce,
         self.extra] = header
        self.transactions = [Transaction(x) for x in transaction_list]
        self.state = Trie('statedb', state_root)
        self.reward = 0

        # Verifications
        if self.state.root != '' and self.state.db.get(self.state.root) == '':
            raise Exception("State Merkle root not found in database!")
        if bin_sha256(rlp.encode(transaction_list)) != self.transactions_root:
            raise Exception("Transaction list root hash does not match!")
        if bin_sha256(rlp.encode(self.uncles)) != self.uncles_root:
            raise Exception("Uncle root hash does not match!")
        # TODO: check POW

    def get_base_fee(self):
        return int(10 ** 21 / int(self.difficulty ** 0.5))

    def pay_fee(self, address, fee, tominer=True):
        # Subtract fee from sender
        sender_state = rlp.decode(self.state.get(address))
        if not sender_state or sender_state[1] < fee:
            return False
        sender_state[1] -= fee
        self.state.update(address, sender_state)
        # Pay fee to miner
        if tominer:
            miner_state = rlp.decode(self.state.get(self.coinbase)) or [0, 0, 0]
            miner_state[1] += fee
            self.state.update(self.coinbase, miner_state)
        return True

    def get_nonce(self, address):
        state = rlp.decode(self.state.get(address))
        if not state or state[0] == 0:
            return False
        return state[2]

    def get_balance(self, address):
        state = rlp.decode(self.state.get(address))
        return state[1] if state else 0

    def set_balance(self, address, balance):
        state = rlp.decode(self.state.get(address)) or [0, 0, 0]
        state[1] = balance
        self.state.update(address, rlp.encode(state))

    # Making updates to the object obtained from this method will do nothing. You need
    # to call update_contract to finalize the changes.
    def get_contract(self, address):
        state = rlp.decode(self.state.get(address))
        if not state or state[0] == 0:
            return False
        return Trie('statedb', state[2])

    def update_contract(self, address, contract):
        state = rlp.decode(self.state.get(address)) or [1, 0, '']
        if state[0] == 0:
            return False
        state[2] = contract.root
        self.state.update(address, state)

    # Serialization method; should act as perfect inverse function of the constructor
    # assuming no verification failures
    def serialize(self):
        txlist = [x.serialize() for x in self.transactions]
        header = [self.number,
                  self.prevhash,
                  bin_sha256(rlp.encode(self.uncles)),
                  self.coinbase,
                  self.state.root,
                  bin_sha256(rlp.encode(txlist)),
                  self.difficulty,
                  self.timestamp,
                  self.nonce,
                  self.extra]
        return rlp.encode([header, txlist, self.uncles])

    def hash(self):
        return bin_sha256(self.serialize())
开发者ID:ConceptPending,项目名称:pyethereum,代码行数:100,代码来源:blocks.py

示例15: test_insert_on_empty

# 需要导入模块: from trie import Trie [as 别名]
# 或者: from trie.Trie import get [as 别名]
 def test_insert_on_empty(self):
     trie = Trie()
     data = 'is for apple'
     trie.insert( 'a', data )
     self.assertIsNotNone(trie.get('a'))
     self.assertEqual(trie.get('a'), data)
开发者ID:mpchoy,项目名称:python-trie,代码行数:8,代码来源:trie_test.py


注:本文中的trie.Trie.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。