Elian  Harber

Elian Harber

1660092180

Stickers: Building Blocks for Charmbracelet/lipgloss

Stickers đŸ‘Ÿ

Is a collection of TUI elements, FlexBox and Table at the moment, its build for bubbletea using lipgloss.

Demo

Flex Box 📩

Responsive grid box insipred by CSS flexbox.
Easy to create responsive grids that scale using ratios between these elements. FlexBox Simple Demo

Table 🍰

Responsive, x/y scrollable, sortable table using FlexBox.
Tabel viewer with ability to get the content of the cell over which the cursor is placed at and sort the data by column. Sorting supports basic number and string type so number sorting is possible 🎉 Table Multi-Type Demo

TODO

  • filtering ✅
  • sorting ✅

Known issues

Table selected cell is not rendering background color correctly, will be fixed with https://github.com/charmbracelet/lipgloss/pull/69


Made with Charm.

Author: 76creates
Source Code: https://github.com/76creates/stickers 
License: MIT license

#go #golang #grid #table 

What is GEEK

Buddha Community

Stickers: Building Blocks for Charmbracelet/lipgloss
Oral  Brekke

Oral Brekke

1675381680

Create Tic Tac toe with JavaScript (Free Code)

Do you want to make a Simple Tic-Tac-Toe game using JavaScript?

In this article you will learn how to create tic tac toe game using html css and javascript. If you are a beginner in JavaScript then Tic Tac Toe Game is perfect for you. This simple javascript game will help you improve your knowledge of javascript.

Create Tic Tac Toe with JavaScript

Earlier I shared another Simple Tic-Tac-Toe JavaScript game for beginners. So I made this design in a very advanced way. Here basically we will play with the computer that is we will play with the computer.

To create this tic-tac-toe javascript first I created the basic structure by html. Then I designed it with css and finally activated this project (tic tac toe javascript code against computer) with javascript.

Tic-tac-toe Game in JavaScript

JavaScript Tic Tac Toe is a simple game where two players take turns marking a grid of 3×3 squares, typically using X and O symbols. JavaScript is a programming language that can be used to create interactive websites and games, such as a Tic Tac Toe game.

A JavaScript implementation of Tic Tac Toe would involve creating a grid of squares using HTML and CSS, and then using JavaScript to handle the logic of the game, including determining the winner and allowing players to take turns.

As you can see above this is an advanced Tic Tac Toe game that I made with javascript. Like a normal JavaScript Tic Tac Toe game, there are 9 cells and two symbols.

Here I have defined symbol “0” for user and “X” for computer. But you can change it if you want. When you click in any one of those 9 cells, another cell will automatically be filled by the computer.

Besides, I have added different types of color FF in the project (tic tac toe javascript code against computer) to make this design more modern.

How to make tic tac toe in HTML CSS and JavaScript

Now if you want to build it then you can follow the tutorial below. I have explained the complete codes step by step keeping the beginners in mind.

Hope you know the rules of this game. It is a simple javascript game where two players take turns marking the spaces in a 3×3 grid with X’s and O’s, with the goal of getting three of their marks in a row, either horizontally, vertically, or diagonally. The player who succeeds in placing three of their marks in a row is the winner.

Step 1: Basic structure of Tic Tac Toe game

First I created a basic structure of this project using the following HTML and CSS codes. Besides, I have added a heading here mainly to enhance the beauty. This heading is created by H1 tag in HTML. 

<div class="container">
  <h1>Tic-Tac-Toe</h1>

</div>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Arial, Helvetica, sans-serif;
}

.container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #eee;
}

h1 {
  font-size: 4rem;
  margin-bottom: 0.5em;
}

Basic structure of Tic Tac Toe game

Step 2: Create a place to play Tic Tac Toe games

Now create a small area for this tic tac toe javascript. Within this box are nine smaller boxes into which players can input their symbols. Also we designed this area by some css.

<div class="play-area">

</div>
.play-area {
  display: grid;
  box-shadow: 0 0 20px rgba(0,139,253,0.25);
  grid-template-columns: auto auto auto;
  background-color: #fff;
  padding: 20px;
}

Create a place to play Tic Tac Toe games

Step 3: Results of the JavaScript Tic Tac Toe game

Now another heading we need to create is within this project(How to Build Tic Tac Toe with JavaScript, HTML and CSS). This heading is mainly for showing results. 

Although this heading is currently not visible to us because there is no information in the heading. We will add this information via javascript. Results will be available automatically after Tic Tac Toe game is over.

<h2 id="winner"></h2>
h2 {
  margin-top: 1em;
  font-size: 2rem;
  margin-bottom: 0.5em;
}

Step 4: Create the game's restart button

Now we have to create a button in this simple Tic-Tac-Toe game. This button will basically work as a reset button. When you click on this button, the game will restart from a new state.

<button onclick="reset_board()">RESET</button>
button {
  outline: none;
  background: rgb(8, 88, 208);
  padding: 12px 40px;
  font-size: 1rem;
  font-weight: bold;
  color: #fff;
  border: none;
  transition: all 0.2s ease-in-out;
}

button:hover {
  cursor: pointer;
  background: green;
  color: white;
}

Results of the JavaScript Tic Tac Toe game

Step 5: Activate Simple Tic-Tac-Toe with JavaScript

Above we have designed this project(How to create a tic tac toe grid in JavaScript?). Now it’s time to make it work using JavaScript. We have used quite a bit of JavaScript code to make this game work. But don’t worry I will tell you all the codes step by step.

const player = "O";
const computer = "X";

let board_full = false;
let play_board = ["", "", "", "", "", "", "", "", ""];

const board_container = document.querySelector(".play-area");
const winner_statement = document.getElementById("winner");

With these variables, you’ve defined the player and computer as “O” and “X” respectively, and created an empty board to play on. The board_full variable will be used to check if the board is full and the game is over, and the play_board array will hold the state of the game. 

The board_container variable is used to select the element on the page where the Tic Tac Toe board will be rendered, and the winner_statement variable is used to select the element where the winner statement will be displayed.

check_board_complete = () => {
  let flag = true;
  play_board.forEach(element => {
    if (element != player && element != computer) {
      flag = false;
    }
  });
  board_full = flag;
};

The function is using the forEach() method to iterate over the play_board array, and it checks if each element is not equal to the player or computer. If any element is not equal to the player or computer, it sets the flag variable to false and breaks out of the loop. 

If the loop completes and the flag variable is still true, it means that all the elements are equal to the player or computer, and the board is full. Then the board_full variable is updated to reflect that the board is full.

You can use this function at the end of the player’s turn and computer’s turn, to check if the board is full and the game is over.

const check_line = (a, b, c) => {
  return (
    play_board[a] == play_board[b] &&
    play_board[b] == play_board[c] &&
    (play_board[a] == player || play_board[a] == computer)
  );
};

The function takes in 3 arguments, a, b, c, which represent the indices of the 3 cells on the board that need to be checked for a winning line.

The function uses the ternary operator to check if the values at the indices a, b, c in the play_board array are the same and not empty. If the values are the same and not empty, the function returns true, otherwise it returns false.

You can use this function in a larger function that checks for all the possible winning combinations on the board.

const check_match = () => {
  for (i = 0; i < 9; i += 3) {
    if (check_line(i, i + 1, i + 2)) {
      document.querySelector(`#block_${i}`).classList.add("win");
      document.querySelector(`#block_${i + 1}`).classList.add("win");
      document.querySelector(`#block_${i + 2}`).classList.add("win");
      return play_board[i];
    }
  }
  for (i = 0; i < 3; i++) {
    if (check_line(i, i + 3, i + 6)) {
      document.querySelector(`#block_${i}`).classList.add("win");
      document.querySelector(`#block_${i + 3}`).classList.add("win");
      document.querySelector(`#block_${i + 6}`).classList.add("win");
      return play_board[i];
    }
  }
  if (check_line(0, 4, 8)) {
    document.querySelector("#block_0").classList.add("win");
    document.querySelector("#block_4").classList.add("win");
    document.querySelector("#block_8").classList.add("win");
    return play_board[0];
  }
  if (check_line(2, 4, 6)) {
    document.querySelector("#block_2").classList.add("win");
    document.querySelector("#block_4").classList.add("win");
    document.querySelector("#block_6").classList.add("win");
    return play_board[2];
  }
  return "";
};

The check_match() function uses two for loops to check for all the possible winning combinations on the board, both horizontally and vertically. It also includes two if statements to check for the two diagonal winning combinations.

The function uses the check_line function you created earlier to check if a line is a winning line. If a winning line is found, the function highlights the winning cells by adding the “win” class to them. This class can be used in your CSS to change the appearance of the winning cells, for example by adding a different background color.

The function also returns the value of the first cell in the winning line, which should be either “X” or “O” depending on who won the game.

You can use this function in another function that checks for a win or a draw and updates the UI accordingly.

const check_for_winner = () => {
  let res = check_match()
  if (res == player) {
    winner.innerText = "Winner is player!!";
    winner.classList.add("playerWin");
    board_full = true
  } else if (res == computer) {
    winner.innerText = "Winner is computer";
    winner.classList.add("computerWin");
    board_full = true
  } else if (board_full) {
    winner.innerText = "Draw!";
    winner.classList.add("draw");
  }
};

This code looks like it’s checking for a winner in a javascript Tic Tac Toe game. The check_line function takes in 3 indices of the play_board array and checks if the values at those indices are equal to each other and if they are equal to either the player or computer. 

The check_match function uses the check_line function to check for a winner across the rows, columns, and diagonals of the Tic Tac Toe board. If a winning line is found, the check_match function adds a “win” class to the corresponding HTML elements of the Tic Tac Toe board and returns the winning player. 

The check_for_winner function calls the check_match function and checks the returned value. If the returned value is the player, it sets the winner statement to “Winner is player!!” and adds playerWin class.

const render_board = () => {
  board_container.innerHTML = ""
  play_board.forEach((e, i) => {
    board_container.innerHTML += `<div id="block_${i}" class="block" onclick="addPlayerMove(${i})">${play_board[i]}</div>`
    if (e == player || e == computer) {
      document.querySelector(`#block_${i}`).classList.add("occupied");
    }
  });
};

The render_board() function creates a grid of divs in the HTML, each one representing a cell in the Tic-Tac-Toe board. The addPlayerMove() function allows the player to make a move by clicking on a cell in the grid. 

The check_board_complete() function checks if the board is full and the check_for_winner() function checks for a winner or draw. It also uses the check_match() function to check if any winning combination is formed.

const game_loop = () => {
  render_board();
  check_board_complete();
  check_for_winner();
}

The game_loop function combines all of these functions together to create the game loop that updates the game state and renders the game board to the user. 

It calls the render_board function to render the current state of the game board to the user, check_board_complete to check if the board is full and check_for_winner which checks if there is a winner or a draw, and updates the UI accordingly.

const addPlayerMove = e => {
  if (!board_full && play_board[e] == "") {
    play_board[e] = player;
    game_loop();
    addComputerMove();
  }
};

The above code defines a Tic Tac Toe game in JavaScript that uses HTML and CSS for the game board and styling. The game’s state is maintained in the play_board array, and the game_loop function updates the state of the game, renders the board, and checks for a winner. 

The addPlayerMove function allows players to make a move by clicking on a block on the board, and the addComputerMove function allows the computer to make a move. The check_match, check_for_winner, render_board functions are also defined and used in the game loop to check for a winner or a draw, render the board and check if the game is complete.

const addComputerMove = () => {
  if (!board_full) {
    do {
      selected = Math.floor(Math.random() * 9);
    } while (play_board[selected] != "");
    play_board[selected] = computer;
    game_loop();
  }
};

Great! Your code is now complete and should be able to run a game of javascript Tic-Tac-Toe between a player and the computer. The player can make moves by clicking on the blocks on the game board, and the computer will randomly select an available space to make its move. The code also checks for a winner or a draw after each move, and updates the game board and the winner statement accordingly.

const reset_board = () => {
  play_board = ["", "", "", "", "", "", "", "", ""];
  board_full = false;
  winner.classList.remove("playerWin");
  winner.classList.remove("computerWin");
  winner.classList.remove("draw");
  winner.innerText = "";
  render_board();
};

This code defines a function called “reset_board” that sets the play_board array back to an empty array, sets the board_full variable to false, removes any classes related to winning or drawing from the winner element, sets the inner text of the winner element to an empty string, and then calls the render_board function to update the display. This function is likely intended to be used as a way to clear the game board and start a new game.

//initial render
render_board();

That’s it, you have created a complete Tic-Tac-Toe game using JavaScript. To start the game, the player can click on any of the empty blocks on the board and the computer will automatically make its move. 

The game checks for a winner or a draw after each move and updates the board accordingly. The game can also be reset by calling the reset_board() function.

Step 6: Basic design of simple Tic-Tac-Toe game with CSS

Above we enabled Tic-tac-toe in JavaScript by JavaScript. Now we need to design it with some more CSS. We know there are 9 small boxes in this game that are currently too small for us to see. So a fixed size must be defined for each box.

.block {
  display: flex;
  width: 100px;
  height: 100px;
  align-items: center;
  justify-content: center;
  font-size: 3rem;
  font-weight: bold;
  border: 3px solid black;
  transition: background 0.2s ease-in-out;
}

.block:hover {
  cursor: pointer;
  background: #0ff30f;
}

.occupied:hover {
  background: #ff3a3a;
}

.win {
  background: #0ff30f;
}

.win:hover {
  background: #0ff30f;
}

Activate Simple Tic-Tac-Toe with JavaScript

As we can see in the above image there are 9 boxes created. But we want to hide some borders here. We will use the following CSS to hide those borders.

#block_0,
#block_1,
#block_2 {
  border-top: none;
}

#block_0,
#block_3,
#block_6 {
  border-left: none;
}

#block_6,
#block_7,
#block_8 {
  border-bottom: none;
}

#block_2,
#block_5,
#block_8 {
  border-right: none;
}
.playerWin {
  color: green;
}

.computerWin {
  color: red;
}

.draw {
  color: orangered;
}

We’ll make this project(Create a Tic-Tac-Toe with HTML and JavaScript) responsive  using a small amount of our own code. Here for Responsive only headings have been resized or reduced.

@media only screen and (max-width: 600px) {

  h1 {
    font-size: 3rem;
    margin-bottom: 0.5em;
  }

  h2 {
    margin-top: 1em;
    font-size: 1.3rem;
  }
}

Create Tic Tac Toe with JavaScript

Hope from this tutorial you got to know how I made this Simple Tic-Tac-Toe JavaScript game.

Not only this but earlier I have shared more advanced game tutorials. Earlier I shared another JavaScript Tic-Tac-Toe which is basically made by Simple Code. Where you can play with two users rather than with the computer. Be sure to comment how you like this project(How to Recreate Tic-Tac-Toe in Vanilla JavaScript).

Original article source at: https://foolishdeveloper.com/

#javascript 

The Best Way to Build a Chatbot in 2021

A useful tool several businesses implement for answering questions that potential customers may have is a chatbot. Many programming languages give web designers several ways on how to make a chatbot for their websites. They are capable of answering basic questions for visitors and offer innovation for businesses.

With the help of programming languages, it is possible to create a chatbot from the ground up to satisfy someone’s needs.

Plan Out the Chatbot’s Purpose

Before building a chatbot, it is ideal for web designers to determine how it will function on a website. Several chatbot duties center around fulfilling customers’ needs and questions or compiling and optimizing data via transactions.

Some benefits of implementing chatbots include:

  • Generating leads for marketing products and services
  • Improve work capacity when employees cannot answer questions or during non-business hours
  • Reducing errors while providing accurate information to customers or visitors
  • Meeting customer demands through instant communication
  • Alerting customers about their online transactions

Some programmers may choose to design a chatbox to function through predefined answers based on the questions customers may input or function by adapting and learning via human input.

#chatbots #latest news #the best way to build a chatbot in 2021 #build #build a chatbot #best way to build a chatbot

Riyad Amin

Riyad Amin

1571046022

Build Your Own Cryptocurrency Blockchain in Python

Cryptocurrency is a decentralized digital currency that uses encryption techniques to regulate the generation of currency units and to verify the transfer of funds. Anonymity, decentralization, and security are among its main features. Cryptocurrency is not regulated or tracked by any centralized authority, government, or bank.

Blockchain, a decentralized peer-to-peer (P2P) network, which is comprised of data blocks, is an integral part of cryptocurrency. These blocks chronologically store information about transactions and adhere to a protocol for inter-node communication and validating new blocks. The data recorded in blocks cannot be altered without the alteration of all subsequent blocks.

In this article, we are going to explain how you can create a simple blockchain using the Python programming language.

Here is the basic blueprint of the Python class we’ll use for creating the blockchain:

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Now, let’s explain how the blockchain class works.

Initial Structure of the Block Class

Here is the code for our initial block class:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

As you can see above, the class constructor or initiation method ( init()) above takes the following parameters:

self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.

index — it’s used to track the position of a block within the blockchain.

previous_hash — it used to reference the hash of the previous block within the blockchain.

data—it gives details of the transactions done, for example, the amount bought.

timestamp—it inserts a timestamp for all the transactions performed.

The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.

As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.

Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.

So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.

Building the Chain

The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.

It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.

Let’s talk about the helper methods.

Adding the Constructor Method

Here is the code:

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

The init() constructor method is what instantiates the blockchain.

Here are the roles of its attributes:

self.chain — this variable stores all the blocks.

self.current_data — this variable stores information about the transactions in the block.

self.build_genesis() — this method is used to create the initial block in the chain.

Building the Genesis Block

The build_genesis() method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.

To create it, we’ll call the build_block() method and give it some default values. The parameters proof_number and previous_hash are both given a value of zero, though you can give them any value you desire.

Here is the code:

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirming Validity of the Blockchain

The confirm_validity method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.

As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.

Thus, the confirm_validity method utilizes a series of if statements to assess whether the hash of each block has been compromised.

Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.

Here is the code:

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Declaring Data of Transactions

The get_data method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.

Here is the code:

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True

Effecting the Proof of Work

In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.

For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.

This way, it discourages spamming and compromising the integrity of the network.

In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.

Finalizing With the Last Block

Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.

Here is the code:

def latest_block(self):
        return self.chain[-1]

Implementing Blockchain Mining

Now, this is the most exciting section!

Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.

If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.

Here is the mining method in this simple cryptocurrency blockchain project:

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)

Summary

Here is the whole code for our crypto blockchain class in Python:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Now, let’s try to run our code to see if we can generate some digital coins


Wow, it worked!

Conclusion

That is it!

We hope that this article has assisted you to understand the underlying technology that powers cryptocurrencies such as Bitcoin and Ethereum.

We just illustrated the basic ideas for making your feet wet in the innovative blockchain technology. The project above can still be enhanced by incorporating other features to make it more useful and robust.

Learn More

Thanks for reading !

Do you have any comments or questions? Please share them below.

#python #cryptocurrency

Crypto Like

Crypto Like

1612506216

What is BUILD Finance (BUILD) | What is BUILD Finance token | What is BUILD token

BUILD Finance DAO

The document is non-binding. Some information may be outdated as we keep evolving.

BUILD Philosophy

BUILD Finance is a decentralised autonomous venture builder, owned and controlled by the community. BUILD Finance produces, funds, and manages community-owned DeFi products.

There are five core activities in which the venture BUILDers engage:

  1. Identifying business ideas,
  2. Organising teams,
  3. Sourcing capital,
  4. Helping govern the product entities, and
  5. Providing shared services.

BUILD operates a shared capabilities model, where the DAO provides the backbone support and ensures inter-entity synergies so that the product companies can focus on their own outcomes.

BUILD takes care of all organisational, hiring, back/mid office functions, and the product companies focus on what they can do best, until such time where any individual product outgrows the DAO and becomes fully self-sustainable. At that point, the chick is strong enough to leave the nest and live its own life. The survival of the fittest. No product entity is held within DAO by force.

Along the way, BUILD utilises the investment banking model, which, in its essence, is a process of creating assets, gearing them up, and then flipping them into a fund or setting them as income-generating business systems, all this while taking fees along the way at each step. BUILD heavily focuses on integrating each asset/product with each other to boost productive yield and revenues. For example, BUILD’s OTC Market may be integrated with Metric Exchange to connect the liquidity pools with the trading traffic. The net result – pure synergy that benefits each party involved, acting in a self-reinforcing manner.

El EspĂ­ritu de la Colmena (The Spirit of the Beehive)

BUILD is a hive and is always alive. While some members may appear more active than others, there’s no central source of control or “core teams” as such. BUILD is work in progress where everyone is encouraged to contribute.

Following the natural free market forces, BUILD only works on those products that members are wanting to work on themselves and that they believe have economic value. Effectively, every builder is also a user of BUILD’s products. We are DeFi users that fill the gaps in the ecosystem. Any member can contribute from both purely altruistic or ultra-mercantile intentions – it’s up to the wider community to decide what is deemed valuable and what product to support. The BUILD community is a sovereign individual that votes with their money and feet.

BUILD members = BUILD users. It’s that simple.

$BUILD TOKEN

Tokenomics

$BUILD token is used as a governance token for the DAO. It also represents a pro-rata claim of ownership on all DAO’s assets and liabilities (e.g. BUILD Treasury and $bCRED debt token).

The token was distributed via liquidity mining with no pre-sale and zero founder/private allocation. The farming event lasted for 7 days around mid-Sep 2020. At the time, BUILD didn’t have any products and held no value. Arguably, $BUILD has still zero value as it is not a legal instrument and does not guarantee or promise any returns to anyone. See the launch announcement here https://medium.com/@BUILD_Finance/announcing-build-finance-dc08df585e57​

Initial supply was 100,000 $BUILD with 100% distributed via fair launch. Subsequently, the DAO unanimously voted to approve minting of extra 30,000 $BUILD and allocate them as:

  • 15,000 $BUILD (11.5%) to the founding member of the DAO (@0xdev0) with 1-year gradual vesting, and
  • 15,000 $BUILD (11.5%) to the DAO treasury as development funds.

For the proposal of the above see: https://forum.letsbuild.finance/t/proposal-2-fund-the-development-of-defi-lending-platform/24​

The voting took place at a later retired web-page https://vote.letsbuild.finance. The governance has since moved to Snapshot (link below). The results of the old proposals are not visible there, however, on-chain voting contract can be see here: https://etherscan.io/address/0xa8621477645f76b06a41c9393ddaf79ddee63daf#readContract​

$Build Token Repartition

Vesting Schedule

Minting keys are not burnt = $BUILD supply is not fixed as token holders can vote on minting new tokens for specific reasons determined by the token holders. For example, the DAO may mint additional tokens to incentivise usage of its products, which would, in turn, increase the value flow or TVL. Dilution is not in the economic benefit of the token holders, hence any such events has to be considered carefully.

Access to minting function is available via on-chain governance. A safe buffer is established in a form of the contract-enforced 24 hour delay, which should provide a sufficient time for the community to flag. Meaning that before such a transaction could be executed, everyone would be able to act in advance by withdrawing their funds / exiting from BUILD. Any malicious minting would, theoretically, result in an immediate market sell-off of $BUILD, making it economically detrimental to do such an action. This makes it highly improbable that any malicious minting would be performed_._

GOVERNANCE

All components of the BUILD DAO and the control over its have been decentralised:

  • All contracts (incl. the Treasury and Basis Gold) can be operated by $BUILD holders with on-chain proposals (see https://docs.build.finance/build-knowledge-base/on-chain-voting);
  • All social accounts (Discord, Telegram, and Twitter) are managed by multiple moderators;
  • All frontends (Metric Exchange, Basis Gold, and the BUILD homepage) are auto-deployed and managed by multiple devs.

TREASURY & DEVELOPMENT

BUILD DAO Treasury

The BUILD treasury has over $400k that can be managed by on-chain proposals and used in whichever way the community desires. For example, to hire developers. Having a functioning product, enough funds in the treasury and a fully decentralised governance has been a long-term goal since the inception in September 2020, and now it’s finally here.

Current holdings are (might be outdated):

  • Capital budget (dev / incentives fund) - 11,025 $BUILD (~$94k);
  • Operational budget (product development) - 204,300 $aDAI;
  • Ownership stake - 200,000 $METRIC (~$84k);
  • Ownership stake - 199,900 $UPDOWN(~$62k);
  • Ownership stake - 5,400 $HYPE (~$1.3k);
  • Ownership stake - 2% of $BSGS supply.
  • TOTAL: ~$445k

Funding of the Development

In an early stage, the development will be funded by an allocation of bCRED debt tokens for development expenses. After the first product was built (i.e. Metric Exchange), the DAO sold 5,000 $BUILD for 203,849 $DAI which will now be used for funding of other products or a combination of revenue + a smaller token allocation. This is up to the community to decide.

Smart Contract Audit

Contracts are not audited. It’s up to the BUILD community governance to decide how to spend our funds. If the community wants to spend any amount for auditing, a voting proposal can be initiated. As with any decisions and proposals, the cost-benefit analysis must be employed in regards to the economical sense of spending any funds on audit vs developing more products and expanding our revenue streams.

DAO Liabilities and $bCRED

$bCRED is a token that allowed the DAO to reward members for work before the DAO source sufficient funds. Effectively, $bCRED is a promissory note or an IOU to give back $DAI at 1:1 ratio, when the DAO starts generating revenues. Read more about $bCRED here: https://medium.com/@BUILD_Finance/what-is-bcred-b97e4cc75f8c.

“BUILDER” User Role in Discord

Since Discord is our primary coordination mechanism, we need to make effort to keep it focused on producing value. During the launch of METRIC, we’ve doubled our total number of users! This made it very difficult for existing users to explain what BUILD is about to new users and created a lot of confusion.

To help improve the quality of conversations, we’ve introduced a new user role called BUILDer. BUILDers will have write-access to product development channels while everyone else will only be able to read them. This should keep those product changes focused on actual productive conversations and make them more informative.

“GUARDIAN” Role in Discord

To increase our collective output as a community, a governance vote introduced an incentivisation mechanism for community contribution, tipping, and other small projects using our unique bCRED token (but may change in the future as required). These tokens are stewarded by active community members — “guardians’’ — who are free to allocate these funds to tip people for proactive work. Current guardians are @Son of Ishtar and @0xdev0, although anyone can propose the tip for anyone else. For more details see Proposal #15.

Hence, Guardians are defined as members of the DAO who are entrusted with a community budget for tipping other members for performing various small tasks.

PRODUCT SUITE & ROADMAP

  • Metric Exchange - is a DEX aggregator that allows for limit orders trading for any ERC-20 token via 0x relayer. Development continues with the product owner SHA_2048 and inputs from vfat. Live at metric.exchange.
  • Basis Gold - a synthetic, algorythmically-adjusted token pegged to the price of gold (sXAU) with elastic supply. Live at https://basis.gold/.
  • Updown Finance - binary options for volatility trading instrument (alpha is live at updown.finance).
  • Vortex - a lending & borrowing platform, which will target the long tail of assets that are currently not served by the existing DeFi money markets. Aiming to launch by March’2021.

The other immediate focus right now will be to make good use of our newly available funding and hire several product managers for other projects.

Please note that nothing is here set in stone. Just like any other start-up, we’ll keep experimenting, learning, and evolving. What’s listed here is just our current trajectory but it might change at any point.

SOCIAL MEDIA

Would you like to earn BUILD right now! ☞ CLICK HERE

Top exchanges for token-coin trading. Follow instructions and make unlimited money

☞ Binance ☞ Bittrex ☞ Poloniex ☞ Bitfinex ☞ Huobi

Thank you for reading!

#blockchain #cryptocurrency #build finance #build

Construisez votre propre blockchain de crypto-monnaie en Python

La crypto-monnaie est une monnaie numérique décentralisée qui utilise des techniques de cryptage pour réguler la génération d'unités monétaires et vérifier le transfert de fonds. L'anonymat, la décentralisation et la sécurité font partie de ses principales caractéristiques. La crypto-monnaie n'est réglementée ou suivie par aucune autorité centralisée, gouvernement ou banque.

Blockchain, un rĂ©seau peer-to-peer dĂ©centralisĂ© (P2P), composĂ© de blocs de donnĂ©es, fait partie intĂ©grante de la crypto-monnaie. Ces blocs stockent chronologiquement des informations sur les transactions et adhĂšrent Ă  un protocole de communication inter-nƓuds et de validation de nouveaux blocs. Les donnĂ©es enregistrĂ©es dans les blocs ne peuvent pas ĂȘtre modifiĂ©es sans la modification de tous les blocs suivants.

Dans cet article, nous allons expliquer comment créer une blockchain simple à l'aide du langage de programmation Python.

Voici le plan de base de la classe Python que nous utiliserons pour crĂ©er la blockchain :

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Maintenant, expliquons comment fonctionne la classe blockchain.

Structure initiale de la classe Block

Voici le code de notre classe de bloc initiale :

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

Comme vous pouvez le voir ci-dessus, le constructeur de classe ou la méthode d'initiation ( init ()) ci-dessus prend les paramÚtres suivants :

self— comme toute autre classe Python, ce paramĂštre est utilisĂ© pour faire rĂ©fĂ©rence Ă  la classe elle-mĂȘme. Toute variable associĂ©e Ă  la classe est accessible en l'utilisant.

index - il est utilisé pour suivre la position d'un bloc dans la blockchain.

previous_hash — il faisait rĂ©fĂ©rence au hachage du bloc prĂ©cĂ©dent dans la blockchain.

data—it donne des dĂ©tails sur les transactions effectuĂ©es, par exemple, le montant achetĂ©.

timestamp—it insĂšre un horodatage pour toutes les transactions effectuĂ©es.

La deuxiÚme méthode de la classe, compute_hash , est utilisée pour produire le hachage cryptographique de chaque bloc en fonction des valeurs ci-dessus.

Comme vous pouvez le voir, nous avons importé l'algorithme SHA-256 dans le projet de blockchain de crypto-monnaie pour aider à obtenir les hachages des blocs.

Une fois les valeurs placées dans le module de hachage, l'algorithme renvoie une chaßne de 256 bits indiquant le contenu du bloc.

C'est donc ce qui donne Ă  la blockchain l'immuabilitĂ©. Étant donnĂ© que chaque bloc sera reprĂ©sentĂ© par un hachage, qui sera calculĂ© Ă  partir du hachage du bloc prĂ©cĂ©dent, la corruption de n'importe quel bloc de la chaĂźne fera que les autres blocs auront des hachages invalides, entraĂźnant la rupture de l'ensemble du rĂ©seau blockchain.

Construire la chaĂźne

Tout le concept d'une blockchain est basĂ© sur le fait que les blocs sont « enchaĂźnĂ©s Â» les uns aux autres. Maintenant, nous allons crĂ©er une classe blockchain qui jouera le rĂŽle essentiel de gestion de l'ensemble de la chaĂźne.

Il conservera les données des transactions et inclura d'autres méthodes d'assistance pour remplir divers rÎles, tels que l'ajout de nouveaux blocs.

Parlons des méthodes d'aide.

Ajout de la méthode constructeur

Voici le code :

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

La méthode constructeur init () est ce qui instancie la blockchain.

Voici les rĂŽles de ses attributs :

self.chain — cette variable stocke tous les blocs.

self.current_data — cette variable stocke des informations sur les transactions dans le bloc.

self.build_genesis() — cette mĂ©thode est utilisĂ©e pour crĂ©er le bloc initial de la chaĂźne.

Construire le bloc Genesis

La build_genesis()méthode est utilisée pour créer le bloc initial dans la chaßne, c'est-à-dire un bloc sans aucun prédécesseur. Le bloc de genÚse est ce qui représente le début de la blockchain.

Pour le créer, nous appellerons la build_block()méthode et lui donnerons des valeurs par défaut. Les paramÚtres proof_numberet previous_hashreçoivent tous deux une valeur de zéro, bien que vous puissiez leur donner la valeur que vous désirez.

Voici le code :

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirmation de la validité de la blockchain

La confirm_validityméthode est essentielle pour examiner l'intégrité de la blockchain et s'assurer qu'il n'y a pas d'incohérences.

Comme expliqué précédemment, les hachages sont essentiels pour assurer la sécurité de la blockchain de crypto-monnaie, car toute légÚre modification d'un objet entraßnera la création d'un hachage entiÚrement différent.

Ainsi, le confirm_validityprocédé utilise une série d'instructions if pour évaluer si le hachage de chaque bloc a été compromis.

De plus, il compare Ă©galement les valeurs de hachage de tous les deux blocs successifs pour identifier toute anomalie. Si la chaĂźne fonctionne correctement, elle renvoie true ; sinon, il retourne faux.

Voici le code :

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Déclaration des données des transactions

La get_dataméthode est importante pour déclarer les données des transactions sur un bloc. Cette méthode prend trois paramÚtres (informations de l'expéditeur, informations du destinataire et montant) et ajoute les données de transaction à la liste self.current_data.

Voici le code :

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True

Effectuer la preuve de travail

Dans la technologie blockchain, la preuve de travail (PoW) fait référence à la complexité impliquée dans l'extraction ou la génération de nouveaux blocs sur la blockchain.

Par exemple, le PoW peut ĂȘtre mis en Ɠuvre en identifiant un numĂ©ro qui rĂ©sout un problĂšme chaque fois qu'un utilisateur effectue un travail informatique. Toute personne sur le rĂ©seau blockchain devrait trouver le numĂ©ro complexe Ă  identifier mais facile Ă  vĂ©rifier - c'est le concept principal de PoW.

De cette façon, cela décourage le spam et compromet l'intégrité du réseau.

Dans cet article, nous allons illustrer comment inclure un algorithme de preuve de travail dans un projet de crypto-monnaie blockchain.

Finaliser avec le dernier bloc

Enfin, la méthode helper last_block() est utilisée pour récupérer le dernier bloc sur le réseau, qui est en fait le bloc actuel.

Voici le code :

def latest_block(self):
        return self.chain[-1]

Mise en Ɠuvre du minage de la blockchain

Maintenant, c'est la section la plus excitante!

Initialement, les transactions sont conservĂ©es dans une liste de transactions non vĂ©rifiĂ©es. Le minage fait rĂ©fĂ©rence au processus consistant Ă  placer les transactions non vĂ©rifiĂ©es dans un bloc et Ă  rĂ©soudre le problĂšme de PoW. Il peut ĂȘtre appelĂ© le travail informatique impliquĂ© dans la vĂ©rification des transactions.

Si tout a été compris correctement, un bloc est créé ou extrait et joint aux autres dans la blockchain. Si les utilisateurs ont réussi à exploiter un bloc, ils sont souvent récompensés pour avoir utilisé leurs ressources informatiques pour résoudre le problÚme de PoW.

Voici la mĂ©thode de minage dans ce projet simple de blockchain de crypto-monnaie :

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)

Sommaire

Voici le code complet de notre classe crypto blockchain en Python :

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Maintenant, essayons d'exécuter notre code pour voir si nous pouvons générer des piÚces numériques


Waouh, ça a marché !

Conclusion

C'est ça!

Nous espérons que cet article vous a aidé à comprendre la technologie sous-jacente qui alimente les crypto-monnaies telles que Bitcoin et Ethereum.

Nous venons d'illustrer les idĂ©es de base pour se mouiller les pieds dans la technologie innovante de la blockchain. Le projet ci-dessus peut encore ĂȘtre amĂ©liorĂ© en incorporant d'autres fonctionnalitĂ©s pour le rendre plus utile et robuste.