Grokking BlockChain basics with Python

While streaming, a brilliant visitor suggested we write a blockchain in Python.

So we did it.

Please note there is no validation or simulated voting here.

Here are the results, in package/blockchain.py:

from __future__ import annotations
# https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
from oscrypto.symmetric import aes_cbc_pkcs7_encrypt as encrypt # type: ignore


class Node:
    __slots__ = 'prior_node', 'data', 'hash'
    prior_node: Node
    data: bytes
    hash: bytes

    def __init__(self, prior_node, key, data):
        self.prior_node = prior_node
        self.data = data
        if prior_node is None:
            init_vector = bytes(16)
        else:
            init_vector = _ensure_byte_length(prior_node.hash, 16)
        key = _ensure_byte_length(key, 32)
        self.hash = encrypt(key, data, init_vector)(1)

    def __repr__(self):
        return f'Node<{self.data}n{self.hash}n{self.prior_node}>'

def _ensure_byte_length(bytes_, length):
    return bytes(bytes_.ljust(length, b'x00')(:length))

class Chain:
    __slots__ = 'nodes'
    def __init__(self, key: bytes, data: bytes):
        self.nodes = Node(None, key, data)

    def __repr__(self):
        return f'Chain:n{self.nodes}'

    def new_node(self, key, data):
        self.nodes = node = Node(self.nodes, key, data)
        return node

    def __len__(self):
        length = 0
        nodes = self.nodes
        while nodes:
            length += 1
            nodes = nodes.prior_node
        return length

def main():
    chain = Chain(b'the key', b'here is a bit of data')
    chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
    chain.new_node(b'hunter2', b'and finally here is some more')
    print(chain)


if __name__ == '__main__':
    main()

And here is a little test, tests/test_blockchain.py:

from package.blockchain import Chain


def test_blockchain():
    chain = Chain(b'the key', b'here is a bit of data')
    chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
    chain.new_node(b'hunter2', b'and finally here is some more')
    assert len(chain) == 3

Please note that we do require oscrypto and openssl to run this.

Coverage was run with pytest under Python 3.7. He ran with black and mypy too.

Python: how to convert a multivalue JSON into a data frame

How to work with json multivalue in pandas or numpy?
I have a json in the following format

  (
  "livro": "A guerra",
  "autores": {
        "Josestenne": {
            "universidade": "UNIVERSIDADE FEDERAL DO CEARÁ (UFC)",
            "departamento": "Faculdade de Economia, Administração, Atuária e Contabilidade"
        },
        "Augusto": {
            "universidade": "UNIVERSIDADE FEDERAL DO CEARÁ (UFC)",
            "departamento": "Faculdade de Economia, Administração, Atuária e Contabilidade"
        },
        "Sandra": {
            "universidade": "UNIVERSIDADE FEDERAL DO CEARÁ (UFC)",
            "departamento": "Faculdade de Economia, Administração, Atuária e Contabilidade"
        }
    }
    )

How can I transform this object into pandas so that, for example, I can count the authors of books? Or rank the best authors of all books?

python – How to use pykalman to process the trajectory of an airplane?

I am programming in Python, for a research project, I am trying to trace the trajectory of an ADS-B data based airplane which I get from opensky-network.org. Due to the nature of ADS-B data, some periodically occurring time stamps are missing. Example:

time,lat,long
2020-03-09 01:09:50,39.29488359871557,-94.729248046875
2020-03-09 01:10:00,39.28873870332362,-94.729736328125
2020-03-09 01:10:10,39.28216552734375,-94.728479800017
2020-03-09 01:10:20,39.27557373046875,-94.7266885508662
2020-03-09 01:10:30,39.268116061970346,-94.72454833984376

My goal is to estimate the condition of the aircraft (position and speed) during the period of interruption (lack of time stamp). To do that, I planned to use the Kalman filter. In kalman filter, the value of the measured parameters I have must be converted to a Cartesian format. So I manage to convert the data into Cartesian form:

time,X_position,Y_position,Z_position,Velocity,velocity_x,velocity_y,velocity_z,Acceleration,acceleration_x,acceleration_y,acceleration_z,Delta_time
2020-03-09 01:09:50,-407542.7557490199,-4926243.355891898,4018043.497980225,70.7561572258253,-68.93549599999999,-15.947764000000017,16.90624,0.0,0.0,0.0,0.0,0.0
2020-03-09 01:10:00,-407631.54840079864,-4926805.655733497,4017626.447953463,70.05699827516962,-69.964384,3.6011080000000137,13.32992,-0.06991589506556864,0.0698234673266738,-0.003593854935931754,-0.35763200000000006,10.0
2020-03-09 01:10:10,-407567.9161406082,-4927351.560671127,4017124.268793508,75.46737426866473,-74.07993599999999,14.404431999999998,9.10336,0.5410375993495109,-0.5310908339108239,0.10326766214932687,-0.4226559999999999,10.0
2020-03-09 01:10:20,-407458.85953741614,-4927908.400397506,4016625.242964065,81.02288852983754,-79.22437599999999,16.976652000000023,11.70432,0.5555514261172817,-0.5432195256016256,0.11640418405749135,0.2600959999999999,10.0
2020-03-09 01:10:30,-407324.27388949855,-4928522.438497869,4016046.8880836726,87.22215588451971,-84.88325999999999,20.06331600000003,6.1772800000000005,0.6199267354682163,-0.6033031600063801,0.14259892872878097,-0.5527039999999999,10.0

Based on what I learned from kalmanfilter.net, I need to determine several equations:

From what I find, this calculation can be solved using the pykalman library, but I'm actually lost on how I should apply it to my code. On the website, there is an indication that I could enter the other matrix variable that I need to calculate the Kalman filter equation. However, there is no other explanation on how I can adjust the code.

My question is how should I adjust the code so that my calculation agrees with the Kalman filter equation

Grocking BlockChain basics with Python

While streaming, a brilliant visitor suggested we write a blockchain in Python.

So we did it.

Please note there is no validation or simulated voting here.

Here are the results, in package/blockchain.py:

from __future__ import annotations
# https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
from oscrypto.symmetric import aes_cbc_pkcs7_encrypt as encrypt # type: ignore


class Node:
    __slots__ = 'prior_node', 'data', 'hash'
    prior_node: Node
    data: bytes
    hash: bytes

    def __init__(self, prior_node, key, data):
        self.prior_node = prior_node
        self.data = data
        if prior_node is None:
            init_vector = bytes(16)
        else:
            init_vector = _ensure_byte_length(prior_node.hash, 16)
        key = _ensure_byte_length(key, 32)
        self.hash = encrypt(key, data, init_vector)(1)

    def __repr__(self):
        return f'Node<{self.data}n{self.hash}n{self.prior_node}>'

def _ensure_byte_length(bytes_, length):
    return bytes(bytes_.ljust(length, b'x00')(:length))

class Chain:
    __slots__ = 'nodes'
    def __init__(self, key: bytes, data: bytes):
        self.nodes = Node(None, key, data)

    def __repr__(self):
        return f'Chain:n{self.nodes}'

    def new_node(self, key, data):
        self.nodes = node = Node(self.nodes, key, data)
        return node

    def __len__(self):
        length = 0
        nodes = self.nodes
        while nodes:
            length += 1
            nodes = nodes.prior_node
        return length

def main():
    chain = Chain(b'the key', b'here is a bit of data')
    chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
    chain.new_node(b'hunter2', b'and finally here is some more')
    print(chain)


if __name__ == '__main__':
    main()

And here is a little test, tests/test_blockchain.py:

from package.blockchain import Chain


def test_blockchain():
    chain = Chain(b'the key', b'here is a bit of data')
    chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
    chain.new_node(b'hunter2', b'and finally here is some more')
    assert len(chain) == 3

Please note that we do require oscrypto and openssl to run this.

Coverage was run with pytest under Python 3.7. He ran with black and mypy too.

Assigning a class to a user [Python]

I have a wizard and warrior class and I want them to be assigned to the user when they choose what class they are, how can I do that?

Here is my code, I don't know how much you need, so I send everything.

from abc import ABC
from typing import List
from Story import Backstory

class Class(ABC):
    def Attack1(self):
    pass

    def Attack2(self):
        pass

    def AttackSpecial(self):
        pass

    def Defense(self):
        pass


class Mage(Class):
    def Attack1(self):
        pass

    def Attack2(self):
        pass

    def AttackSpecial(self):
        pass

    def Defense(self):
        pass


class Warrior(Class):
    def Attack1(self):
        pass

    def Attack2(self):
        pass

    def AttackSpecial(self):
        pass

    def Defense(self):
        pass


class Archer(Class):
    def Attack1(self):
        pass

    def Attack2(self):
        pass

    def AttackSpecial(self):
        pass

    def Defense(self):
        pass


Mage_Warrior_Archer: List(str) = ('Mage', 'Warrior', 'Archer')

yes_no: List(str) = ('yes', 'no')

Name = input("What is your character's name? ")
print("Nice to meet ya" + Name + "!")
Role = input("Please choose your class, Mage, Warrior, or Archer : ")
while Role not in Mage_Warrior_Archer:
    Role = input("Please choose a class")

if Role in Mage_Warrior_Archer:
    print("Congratulations" + Role + Name + "!")

Username = Role + Name

Beginning = ''
while Beginning not in yes_no :
    print("Please pick yes or no")
    Beginning = input(Username + ", are you ready to begin your journey?")
if Beginning in yes_no :
    print('Well then, ' + Username + ', we shall begin')

django – python cgi + openldap x framework

Hi everyone

I have been using python (cgi) + html5 + jquery + css3 and many ways to insert / show / change an openldap base.

Now I try to change this using bootstrap to make my life easier … 80)

I've been looking at jar and django, but I'm not sure if it's the best option …

I cannot change openldap as a database because I have a lot of software that depends on it.

Any help will be greatly appreciated.

Thanks in advance

tensorflow: I get an error creating helper GAN model for CSV dataset in Python

I am trying to build a generator and a discriminator for the CSV dataset.
Where I am trying to build the Generative Auxiliary Adversary Network (GAN) model
But I get some error coding it.
Please help to resolve these errors.
I am open to suggestions from everyone. Thanks in advance for reviewing my problem

Generator

def create_generator():
    generator=Sequential()
    generator.add(Dense(units=64,input_dim=10))
    generator.add(LeakyReLU(0.2))

    generator.add(Dense(units=128))
    generator.add(LeakyReLU(0.2))

    generator.add(Dense(units=256))
    generator.add(LeakyReLU(0.2))


    generator.add(Dense(units=44, activation='tanh'))

    generator.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.001, beta_1=0.5))
    return generator

Discriminated against

def create_discriminator():

    discriminator = Sequential()
    discriminator.add(Dense(units = 256,input_dim = 44))
    discriminator.add(LeakyReLU(0.2))
    discriminator.add(Dropout(0.3))


    discriminator.add(Dense(units=128))
    discriminator.add(LeakyReLU(0.2))
    discriminator.add(Dropout(0.3))


    discriminator.add(Dense(units=64))
    discriminator.add(LeakyReLU(0.2))
    discriminator.add(Dropout(0.3))

#     inpu = Input(shape=(44,))

    value = discriminator(Input(shape=(44,)))



#     discriminator.add(Dense(units=1, activation='sigmoid'))
    discriminator_fake = Dense(units=1, activation='sigmoid')(value)
    discriminator_predict = Dense(units=2, activation='softmax')(value)

    model = Model(inputs = Input(shape=(44,)), outputs=(discriminator_fake,discriminator_predict))
#     discriminator.compile(loss='binary_crossentropy', optimizer='adam')

    model.compile(loss=('binary_crossentropy', 'sparse_categorical_crossentropy'), optimizer=Adam(lr=0.001, beta_1=0.5))
    return model

>
ERROR


 ValueError                                Traceback (most recent call last)
 in 
----> 1 d = create_discriminator()
      2 d.summary()

 in create_discriminator()
     26     discriminator_predict = Dense(units=2, activation='softmax')(value)
     27 
---> 28     model = Model(inputs = Input(shape=(44,)), outputs=(discriminator_fake,discriminator_predict))
     29 #     discriminator.compile(loss='binary_crossentropy', optimizer='adam')
     30 

e:gan autofilllibsite-packagestensorflow_corepythonkerasenginetraining.py in __init__(self, *args, **kwargs)
    145 
    146   def __init__(self, *args, **kwargs):
--> 147     super(Model, self).__init__(*args, **kwargs)
    148     _keras_api_gauge.get_cell('model').set(True)
    149     # initializing _distribution_strategy here since it is possible to call

e:gan autofilllibsite-packagestensorflow_corepythonkerasenginenetwork.py in __init__(self, *args, **kwargs)
    162         'inputs' in kwargs and 'outputs' in kwargs):
    163       # Graph network
--> 164       self._init_graph_network(*args, **kwargs)
    165     else:
    166       # Subclassed network

e:gan autofilllibsite-packagestensorflow_corepythontrainingtrackingbase.py in _method_wrapper(self, *args, **kwargs)
    455     self._self_setattr_tracking = False  # pylint: disable=protected-access
    456     try:
--> 457       result = method(self, *args, **kwargs)
    458     finally:
    459       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

e:gan autofilllibsite-packagestensorflow_corepythonkerasenginenetwork.py in _init_graph_network(self, inputs, outputs, name, **kwargs)
    315     # Keep track of the network's nodes and layers.
    316     nodes, nodes_by_depth, layers, _ = _map_graph_network(
--> 317         self.inputs, self.outputs)
    318     self._network_nodes = nodes
    319     self._nodes_by_depth = nodes_by_depth

e:gan autofilllibsite-packagestensorflow_corepythonkerasenginenetwork.py in _map_graph_network(inputs, outputs)
   1819                              'The following previous layers '
   1820                              'were accessed without issue: ' +
-> 1821                              str(layers_with_complete_input))
   1822         for x in nest.flatten(node.output_tensors):
   1823           computable_tensors.add(x)

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_21:0", shape=(?, 44), dtype=float32) at layer "input_21". The following previous layers were accessed without issue: ()

ERROR

python – Clean Sockets – Stack Overflow in Spanish

I have a problem. Make a client in python, but I don't know if it is problem receiving, printing and closing the socket. My doubt comes to that I do not know if it is the socket or the buffer, but it prints things from another socket.

def cliente_TCP(host,puerto):
    cliente = socket(AF_INET, SOCK_STREAM)
    cliente.connect((host, puerto))
    msg = metodo_recibir_msg(cliente)
    msg = msg1.split()
    ....
    cliente.send(msg.encode()) 
    msg = cliente.recv(1024)
    print(msg.decode())
    cliente.close()

def cliente_TCP2(host,puerto):
    cliente = socket(AF_INET, SOCK_STREAM)
    cliente.connect((host, puerto))
    msg = metodo_recibir_msg(cliente)
        ....
    cliente.send(msg.encode()) 
    msg = cliente.recv(1024)
    print(msg.decode())
    cliente.close()

Maybe it's the fault of using the same variable, but being local, there should be no problem with that, I also tried to put a different name to the variables, but the same thing happens to me. How can I clean the socket once I have closed it? or the buffer.

And I have another question, if I do .decode (), what I get is a string? Why did I try to perform a .lstr () to remove and it gave me this error.

a bytes-like object is required, not 'str'

Can I pass bytes to string?

python: why is my program "not responding" when i run it?

Quickly looking at a hello world with pygame, I came to this page.

Here is the code they use:

import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

Your program needs to be "alive", this means you need to have a main loop that will handle at least The events that the operating system sends, Windows in your case.

If you don't process these events, Windows will know this and think the program is frozen (i.e. does not respond) You'll also want to make sure you draw something (that's with the last line in the example).

python – Pygame TypeError: The join () argument must be str, bytes, or os.PathLike, not & # 39; Surface & # 39;

I've only been learning Python for a couple of weeks now and this problem has me stumped. I am trying to create a simple tower defense style game using Pygame. I've been Googling and researching for over 4 hours (Pygame Docs website is down at press time, relying on a cached version). I'm sure it will end up being trivially easy to fix, but I have no ideas.

I have the Tower class in one file and the main loop of the game in a different file. The image files are stored in a folder called "assets" which is located in the same directory as the tower class and the main loop of the game. When I try to create a new tower, specifically upload the tower image, I get the error that appears in the title.

I understand that somehow I'm passing a "Surface" as a parameter, but for the life of me I can't figure out where it is. I ask the player to select the type of tower he is building using the 1 or 2 keys, then find the corresponding image for that keystroke, then place the tower where they click on the screen. The print statement immediately after the mouse click pygame event correctly lists "elf_tower.png" as the file name, but the print statement in the class in that He says "". The class works normally if I encode the image filename, but I doubt it's the best solution. I also tried setting a variable to be "assets /" + tower_type but similarly it said it couldn't concatenate a Surface into a str.

Main file:

"""Homebrew tower defense game using pygame and object oriented programming.
This is a learning project"""
import pygame
from tower import Tower
from scaling import get_scaling_info

get_scaling_info()

def run_game():
    """Runs the game"""
    pygame.init()
    get_scaling_info()
    width, height = get_scaling_info()(1:)
    screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 32)
    pygame.display.set_caption("Tower Defense")
    game_surface = screen.copy()

    def toggle_fullscreen():
        """Toggles between fullscreen and windowed mode"""
        if screen.get_flags() & pygame.FULLSCREEN:
            return pygame.display.set_mode((800, 600), pygame.RESIZABLE)
        return pygame.display.set_mode((width, height), pygame.FULLSCREEN)

    def update_display():
        """Update the game display"""
        scaling_info = get_scaling_info()(0)
        screen.fill((0, 0, 0))
        for tower in Tower.towers:
            tower.draw()
        screen.blit(pygame.transform.scale(
            game_surface, (scaling_info.current_w, scaling_info.current_h)), (0, 0))
        pygame.display.update()

    run = True
    tower_type = 0
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = False
                if event.key == pygame.K_F11:
                    toggle_fullscreen()
                if event.key == pygame.K_1 or event.key == pygame.K_2:
                    tower_type = Tower.selection_dict(event.key)
            if event.type == pygame.MOUSEBUTTONDOWN and tower_type != 0: #to prevent game from breaking if no tower selected.
                print(tower_type) #returns elf_tower.png which is the expected result
                mouse_x, mouse_y = pygame.mouse.get_pos()
                Tower(tower_type, mouse_x, mouse_y).create_tower()

        update_display()

    pygame.quit()

run_game()

Tower class file:

"""Contains the class used to generate towers"""
import os
import pygame
from scaling import get_scaling_info

get_scaling_info()

class Tower:
    """Tower information"""
    selection_dict = {49:"elf_tower.png", 50:"dwarf_tower.png"} #pygame keypress of 1 corresponds to value 49, 2 to 50.
    towers = ()
    def __init__(self, img, x, y, display_surface="game_surface"):
        x_scale, y_scale = get_scaling_info()(1:)
        self.img = pygame.image.load(os.path.join('assets', img))
        print(self.img) # returns 
        self.x_coord = x * x_scale
        self.y_coord = y * y_scale
        self.display_surface = display_surface

    def create_tower(self):
        """Creates a tower of the selected type and scales to the correct size"""
        Tower.towers.append(Tower(self.img, self.x_coord, self.y_coord))
        print(Tower.towers)

    def draw(self):
        """Draws the tower on the screen using the specified image at coordinates x and y"""
        pygame.transform.scale(self.img, (32, 32))
        self.display_surface.blit(self.img, (self.x_coord, self.y_coord))
        print(self.img)

 #   def attack(self):
 #       """Causes the tower to attack enemies in range
 #       Not yet written"""

Image Scale File

"""Gets the scaling info used in the other modules of the game"""
import pygame

def get_scaling_info():
    """Gathers display info for scaling elements of the game"""
    pygame.init()
    display_info = pygame.display.Info()
    scaling_info = pygame.display.Info()
    x_ratio = display_info.current_w/scaling_info.current_w
    y_ratio = display_info.current_h/scaling_info.current_h
    return scaling_info, x_ratio, y_ratio