Esempio n. 1
0
def Chain_add_block_expect_index_of_well_formed_block():
    #Assign
    theChain = chain.Chain()
    expected_index = 1
    expected_recipient = "*****@*****.**"
    expected_nominator = "*****@*****.**"
    expected_date = datetime.date(1972, 4, 22)

    #Action
    theChain.add_block(expected_recipient, expected_nominator, expected_date)

    #Assert
    test_first.are_equal(expected_index, theChain.blocks[expected_index].index,
                         "block index")
    test_first.are_equal(expected_recipient,
                         theChain.blocks[expected_index].kudo.recipient,
                         "recipient")
    test_first.are_equal(expected_nominator,
                         theChain.blocks[expected_index].kudo.nominator,
                         "nominator")
    test_first.are_equal(expected_date,
                         theChain.blocks[expected_index].kudo.date, "date")
    test_first.are_equal(theChain.blocks[0].hash,
                         theChain.blocks[expected_index].previous_hash,
                         "previous hash matches")
Esempio n. 2
0
def mineBlock(block):
    global _chain
    global stopMining
    diff = 20
    maxNonce = 2**32
    target = 2**(256 - diff)

    while not stopMining:
        for n in range(maxNonce):
            if stopMining:
                print("Minig halted")
                return

            if int(block.hash(), 16) <= target:
                if _chain == None:
                    _chain = chain.Chain(block)
                previousBlock = _chain.getBlock()

                block.previous_hash = previousBlock.hash()
                block.blockNo = previousBlock.blockNo + 1

                _chain.add(block)
                print(block)
                msg = "MINED"
                data = pickle.dumps(msg)
                nodeServerSocket.sendall(data)

                data = pickle.dumps(_chain)
                nodeServerSocket.sendall(data)
                return
            else:
                block.nonce += 1

    data = pickle.dumps(_chain)
    nodeServerSocket.sendall(data)
Esempio n. 3
0
 def grantPermision(self,username,permissions):
     step_one = chain.Chain(self)
     try:
         """
         Do Something Here
         """
         if self.userExists(username):
             addres = self.getUserAddress
Esempio n. 4
0
def Chain_verify_no_blocks_added_expect_True():
    #Assign
    theChain = chain.Chain()

    #Action
    result = theChain.verify()

    #Assert
    test_first.are_equal(True, result)
Esempio n. 5
0
def Chain_get_list_no_blocks_expect_empty_list():
    #Assign
    theChain = chain.Chain()

    #Action
    result = theChain.get_list()

    #Assert
    test_first.are_equal(0, len(result))
Esempio n. 6
0
    def __init__(self, usage):
        Engineer.__init__(self, 'GST', usage)
        if usage[0]['url'][:3] == 'udp' and usage[0]['url'][6] != '@':
            usage[0]['url'] = 'udp://@' + usage[0]['url'][6:]
        self['pipeline'] = self['arch']['gst'].Pipeline(name='itv-channel-' +
                                                        usage[0]['chanid'])
        self['mainloop'] = self['arch']['gobj'].MainLoop()
        self['bus'] = self['pipeline'].get_bus()
        self['get_state'] = None
        self['url'] = usage[0]['url']
        self.access = usage[0]['url'][:3]

        self.ele_access_in = ''
        self.ele_typefind = ''
        self.ele_demuxer = ''
        self.ele_video_preparser = ''
        self.ele_audio_preparser = ''
        self.ele_decoder = ''
        import chain
        self.chainner = chain.Chain(usage[1])
        self['args'] = self.chainner.profile_lists

        if self.access == 'udp':
            self.ele_access_in = Gst.ElementFactory.make("udpsrc", "access")
            print(self['url'])
            self.ele_access_in.set_property('uri', self['url'])
            print(usage[0]['iface'])
            self.ele_access_in.set_property('multicast-iface',
                                            usage[0]['iface'])
            self.ele_typefind = Gst.ElementFactory.make(
                "typefind", "typefinder")
            self.ele_typefind.connect("have-type", EngineGST.__findedtype,
                                      self)
        """
		elif access_in == 'file':
			access = Gst.element_factory_make("filesrc","access")
			access.set_property('location','/media/hertz/b901d1b9-1b63-46ca-a706-86f7401fee63/hebin/4K 体验视频.mp4')
			typefind = Gst.element_factory_make("typefind","typefinder")
			#demuxer= Gst.element_factory_make("tsdemux","demuxer")
		elif access_in == 'rtsp':
			access = Gst.element_factory_make("rtspsrc","access")
			access.set_property('location','rtsp://192.168.61.26/')
			typefind = Gst.element_factory_make("typefind","typefinder")
		elif access_in == 'rtmp':
			access = Gst.element_factory_make("rtmpsrc","access")
		elif access_in == 'http':
			access = Gst.element_factory_make("httpsrc","access")
			access.set_property('location','http://192.168.61.26/')
			typefind = Gst.element_factory_make("typefind","typefinder")
			typefind.connect("have-type", findedtype, pipeline)
		"""
        for i in range(self['args']):
            profile = copy.deepcopy(self['args'][i])
        if self.ele_typefind is not None:
            self['pipeline'].add(self.ele_access_in)
            self['pipeline'].add(self.ele_typefind)
            self.ele_access_in.link(self.ele_typefind)
Esempio n. 7
0
def Chain_verify_replace_block_expect_False():
    #Assign
    theChain = chain.Chain()
    today = datetime.date.today()
    theChain.add_block("recip1", "nom1", today)
    theChain.add_block("recip2", "nom2", today)
    theChain.add_block("recip3", "nom3", today)
    theChain.blocks.remove(theChain.blocks[2])
    alt_chain = chain.Chain()
    alt_chain.add_block("recip1", "nom1", today)
    alt_chain.add_block("recip2", "nom2", today)
    theChain.blocks.insert(2, alt_chain.blocks[2])

    #Action
    result = theChain.verify()

    #Assert
    test_first.are_equal(False, result)
Esempio n. 8
0
def Chain_count_no_kudos_expect_0():
    #Assign
    theChain = chain.Chain()

    #Action
    actual = theChain.count()

    #Assert
    test_first.are_equal(0, actual)
Esempio n. 9
0
def Chain_get_index_too_large_expect_None():
    theChain = chain.Chain()
    theChain.add_block("recip1", "nom1", datetime.date.today())

    #Action
    actual_block = theChain.get(2)

    #Assert
    test_first.are_equal(None, actual_block)
Esempio n. 10
0
 def getDataFromDataItem(self,dataItem):
     step_one = chain.Chain(self)
     if type(dataItem) is str:
         dataHex = dataItem
         return True
     else:
         vout = dataItem['vout']
         txId = dataItem['txid']
         datahex = unicode(step_one.getTxOutData(txId,vout))
         return False
Esempio n. 11
0
def Chain_get_index_1_expect_the_first_kudo():
    #Assign
    theChain = chain.Chain()
    theChain.add_block("recip1", "nom1", datetime.date.today())

    #Action
    actual_kudo = theChain.get(1)

    #Assert
    test_first.are_equal(theChain.blocks[1].kudo.__dict__,
                         actual_kudo.__dict__)
Esempio n. 12
0
 def userExists(self,username):
     step_one = chain.Chain(self)
     users_details = unicode(step_one.listStreamKeyItems('users_details', username, True, 1, -1, True))
     print "User: " + users_details
     length_of_the_user = len(users_details)
     print length_of_the_user
     if  length_of_the_user > 2:
         print 'User already exist'
         return True
     else:
         print 'User Does not Exist'
         return False
Esempio n. 13
0
def Chain_verify_add_3_blocks_expect_True():
    #Assign
    theChain = chain.Chain()
    today = datetime.date.today()
    theChain.add_block("recip1", "nom1", today)
    theChain.add_block("recip2", "nom2", today)
    theChain.add_block("recip3", "nom3", today)

    #Action
    result = theChain.verify()

    #Assert
    test_first.are_equal(True, result)
Esempio n. 14
0
def Chain_count_add_3_kudos_expect_3():
    #Assign
    theChain = chain.Chain()
    today = datetime.date.today()
    theChain.add_block("recip1", "nom1", today)
    theChain.add_block("recip2", "nom2", today)
    theChain.add_block("recip3", "nom3", today)

    #Action
    actual = theChain.count()

    #Assert
    test_first.are_equal(3, actual)
Esempio n. 15
0
def Chain_get_index_2_of_3_expect_the_second_kudo():
    #Assign
    theChain = chain.Chain()
    theChain.add_block("recip1", "nom1", datetime.date.today())
    theChain.add_block("recip2", "nom2", datetime.date.today())
    theChain.add_block("recip3", "nom3", datetime.date.today())

    #Action
    actual_kudo = theChain.get(2)

    #Assert
    test_first.are_equal(theChain.blocks[2].kudo.__dict__,
                         actual_kudo.__dict__)
Esempio n. 16
0
    def setUp(self):
        self.block = chain.Block('1')
        self.chain = chain.Chain()
        self.linkedlist = chain.LinkedList()
        self.trns = chain.LinkedList()

        self.chain.add_transaction('1')
        self.chain.add_transaction('2')
        self.chain.add_transaction('3')

        self.linkedlist.append(chain.Block('1'))
        self.linkedlist.append(chain.Block('2'))
        self.linkedlist.append('3')
        self.linkedlist.append('4')
Esempio n. 17
0
def Chain_verify_change_block_expect_False():
    #Assign
    theChain = chain.Chain()
    today = datetime.date.today()
    theChain.add_block("recip1", "nom1", today)
    theChain.add_block("recip2", "nom2", today)
    theChain.add_block("recip3", "nom3", today)
    theChain.blocks[2].timestamp = datetime.datetime.utcnow()

    #Action
    result = theChain.verify()

    #Assert
    test_first.are_equal(False, result)
Esempio n. 18
0
def create_ensemble(n_res):
    # create a chain with arbitrary sequence
    c = chain.Chain('P' * n_res)
    confs = [np.array(x) for x in chain.enumerate_conf(c)]
    n_conf = len(confs)
    contacts = np.zeros((n_res, n_res, n_conf), dtype=bool)
    for n, conf in enumerate(confs):
        for i in range(n_res):
            for j in range(n_res):
                dist = np.linalg.norm(conf[i, :] - conf[j, :])
                if dist < 1.01:  # fudge factor for rounding
                    contacts[i, j, n] = True
                    contacts[j, i, n] = True
    return np.array(confs), contacts
Esempio n. 19
0
    def make_chains(self):
        self.chains = []
        self.chdic = {}
        cur_chain = None
        ch = None
        for atom in self.atoms:
            if atom.chain_id == cur_chain:
                if ch:
                    atom.chain = ch
                    ch.atoms.append(atom)
                else:
                    ch = chain.Chain()
                    cur_chain = atom.chain_id
                    ch.id = atom.chain_id
                    atom.chain = ch
                    ch.atoms.append(atom)
            else:
                if ch:
                    self.chains.append(ch)
                    ch = chain.Chain()
                    cur_chain = atom.chain_id
                    ch.id = cur_chain
                    atom.chain = ch
                    ch.atoms.append(atom)
                else:
                    ch = chain.Chain()
                    cur_chain = atom.chain_id
                    ch.id = atom.chain_id
                    atom.chain = ch
                    ch.atoms.append(atom)

        self.chains.append(ch)
        for ch in self.chains:
            ch.model = self
            idx = ch.id
            self.chdic[idx] = ch
Esempio n. 20
0
def get_nodes():
    blocks = []
    # We're assuming that the folder and at least initial block exists
    if os.path.exists(LIC_DIR):
        for filepath in glob.glob(os.path.join(LIC_DIR, '*.json')):
            with open(filepath, 'r') as block_file:
                try:
                    block_info = json.load(block_file)
                except:
                    print(filepath)
                local_block = lic_block.Block(block_info)
                blocks.append(local_block)
    blocks.sort(key=lambda block: block.index)
    local_chain = chain.Chain(blocks)
    return local_chain
Esempio n. 21
0
def Chain_verify_reorder_block_expect_False():
    #Assign
    theChain = chain.Chain()
    today = datetime.date.today()
    theChain.add_block("recip1", "nom1", today)
    theChain.add_block("recip2", "nom2", today)
    theChain.add_block("recip3", "nom3", today)
    hold_block = theChain.blocks[2]
    theChain.blocks.remove(theChain.blocks[2])
    theChain.blocks.append(hold_block)

    #Action
    result = theChain.verify()

    #Assert
    test_first.are_equal(False, result)
Esempio n. 22
0
def str_to_chain(s):
    """
    creates an chain from string generated from
    :func:`rnamake.chain.Chain.to_str`

    :param s: string containing stringifed chain
    :type s: str

    :returns: unstringifed chain object
    :rtype: chain.Chain
    """
    spl = s.split(";")
    c = chain.Chain()
    residues = []
    for r_str in spl[:-1]:
        r = str_to_residue(r_str)
        residues.append(r)
    c.residues = residues
    return c
Esempio n. 23
0
def Chain_get_list_add_3_blocks_expect_3_kudos():
    #Assign
    theChain = chain.Chain()
    today = datetime.date.today()
    expected_kudos = [
        kudo.Kudo("recip1", "nom1", today),
        kudo.Kudo("recip2", "nom2", today),
        kudo.Kudo("recip3", "nom3", today)
    ]
    for k in expected_kudos:
        theChain.add_block(k.recipient, k.nominator, k.date)

    #Action
    result = theChain.get_list()

    #Assert
    test_first.are_equal(3, len(result), "has 3 kudos")
    for i in range(0, len(result)):
        test_first.are_equal(expected_kudos[i].__dict__, result[i].__dict__,
                             expected_kudos[i].recipient)
Esempio n. 24
0
 def makeChain(self):
     try:
         f = open(self.file, 'r')
         lines = f.read()
         lines = re.sub(r'\n', r' ', lines)
         lineArr = lines.split(' ')
         lineArr = [x for x in lineArr if x != '']
         corpus = {}
         for x in range(0, len(lineArr) - 2):
             x0 = lineArr[x]
             x1 = lineArr[x + 1]
             x2 = lineArr[x + 2]
             try:
                 corpus[(x0, x1)].append(x2)
             except KeyError:
                 corpus[(x0, x1)] = [x2]
         self.chain = mark.Chain(corpus, list(corpus.keys())[0])
     except Exception:
         raise
     finally:
         f.close()
Esempio n. 25
0
    def _build_structure(self):
        starts = []

        for n in self.chain_graph.nodes:
            if n.available_pos(0):
                starts.append(n)

        chains = []
        for n in starts:
            res = []
            cur = n
            while cur is not None:
                res.extend(cur.data.included_res())
                if cur.available_pos(1):
                    cur = None
                else:
                    con = cur.connections[1]
                    cur = con.partner(cur.index)

            c = chain.Chain(res)
            chains.append(c)

        self.rna_structure.structure.chains = chains
        res = self.rna_structure.residues()
        uuids = [r.uuid for r in res]

        current_bps = []
        for bp in self.all_bps.values():
            if bp.res1.uuid in uuids and bp.res2.uuid in uuids:
                current_bps.append(bp)

        self.rna_structure.basepairs = current_bps
        self.rna_structure.ends = rna_structure.ends_from_basepairs(
            self.rna_structure.structure, current_bps)

        self.rebuild_structure = 0
Esempio n. 26
0
from __future__ import print_function
import Pyro4.core
import Pyro4.naming
import chain

this_node = "B"
next_node = "C"

servername = "example.chain." + this_node

with Pyro4.core.Daemon() as daemon:
    obj = chain.Chain(this_node, next_node)
    uri = daemon.register(obj)
    with Pyro4.naming.locateNS() as ns:
        ns.register(servername, uri)

    # enter the service loop.
    print("Server started %s" % this_node)
    daemon.requestLoop()
Esempio n. 27
0
from __future__ import print_function
import Pyro4
import chain

this = "B"
next = "C"

servername = "example.chain." + this

daemon = Pyro4.core.Daemon()
obj = chain.Chain(this, next)
uri = daemon.register(obj)
ns = Pyro4.naming.locateNS()
ns.register(servername, uri)

# enter the service loop.
print("Server started %s" % this)
daemon.requestLoop()
Esempio n. 28
0
print y.data.shape

# train test
x = np.random.normal(scale=1, size=(128, 28 * 28)).astype(np.float32)
x = Variable(x)

seq = Sequential(weight_initializer="GlorotNormal", weight_init_std=0.05)
seq.add(link.Linear(28 * 28, 500, use_weightnorm=True))
seq.add(link.BatchNormalization(500))
seq.add(function.Activation("relu"))
seq.add(link.Linear(None, 500, use_weightnorm=True))
seq.add(link.BatchNormalization(500))
seq.add(function.Activation("relu"))
seq.add(link.Linear(500, 28 * 28, use_weightnorm=True))
seq.build()

chain = chain.Chain()
chain.add_sequence(seq)
chain.setup_optimizers("adam",
                       0.001,
                       momentum=0.9,
                       weight_decay=0.000001,
                       gradient_clipping=10)

for i in xrange(100):
    y = chain(x)
    loss = F.mean_squared_error(x, y)
    chain.backprop(loss)
    print float(loss.data)

chain.save("model")
Esempio n. 29
0
 def on_message(self, message):
     newchain = chain.Chain(chain=message)
     if _chain.replaceChain(newchain.chain):
         update_chain.update_cache(str(newchain))
         update_chain.send_updates(str(newchain))
Esempio n. 30
0
class update_chain(chainbase):
    def open(self):
        update_chain.waiters.add(self)

    def on_close(self):
        update_chain.waiters.remove(self)

    def on_message(self, message):
        newchain = chain.Chain(chain=message)
        if _chain.replaceChain(newchain.chain):
            update_chain.update_cache(str(newchain))
            update_chain.send_updates(str(newchain))


if __name__ == '__main__':
    _chain = chain.Chain(db_path='chain.json')
    if sys.argv[1] == 'node':
        define("port", default=8989, help="run on the given port", type=int)
        tornado.options.parse_command_line()
        app = Application()
        app.listen(options.port)
        tornado.ioloop.IOLoop.current().start()
    elif sys.argv[1] == "server":
        app = Flask(__name__)

        @app.route('/')
        def hello():
            return "hello"

        @app.route("/blocks")
        def get_blocks():