October 24, 2018

Solidity grammar

❑ The deployed Ethereum smart contract(DApp) is immutable.
❑ Solidity file extension.: *.sol
❑ Version pragma: It is the starting source code of a DApp, and tells you the version of Solidity.

pragma solidity ^0.4.24;


❑ Contract: The basic components of the Ethereum DApp. All variables and functions are in the Contract.

Contract HelloWorld {
}


❑ State variables are permanently stored in Contract storage.
❑ exponential operator(x^2) : x ** 2
❑ Data type : int, uint(Unsigned integer) == uint256, uint8, uint16, uint32, struct, string, array, mapping, address.
❍ uint
- Generally, uint8 uses the same storage space as uint256.
- But, uint8 in a struct uses less space than uint256.

❍ Struct struct Person { uint age; string name; }
// The continuous uint32 is packed when it stored. : struct abc2 { uint32 a; uint32 b; }
// The spaced uint32 is packed when it stored : struct abc2 { uint32 a; uint c; uint32 b; }

❍ Array uint[2] arr1; // A fixed array of uints.
string[5] arr2; // A fixed array of strings. 
Person[] people // A dynamic array of Person structs. 
uint[] arr3; // A dynamic array of uints. 
uint[] memory values = new uint[](3); // Allocate memory. 
values.push(1); // The push function returns the current length of the array. 
values.push(2); 
values.length // Length of the array.

❍ mapping : The data type of the "key => value" format.
// account => data.
mapping (address => uint) public favoriteNumber;

// The update of a mapping value.
favoriteNumber[msg.sender] = _Anumber;

// The call of a mapping value.
favoriteNumber[msg.sender]


❍ address: The datatype that stores the Ethernet address (0x~~~~~~~~~).
* The address refers to a specific user(Wallet) or smart contract.

❑ Function modifier: It is the syntax to control the function of a function.
* Generally, It is used to verify that the requirements are fulfilled before the function is executed.
* There are "Visibility modifier", "State modifier", "Custom modifier" etc.
* Several modifiers can be used together.
❑ Visibility modifier: It is the syntax that specifies where variables/functions can be called.
❍ Private [Variable | Function] : It is the Variables/functions that only functions in the Contract can call.
❍ Public [Variable | Function] : It is the Variables/functions that other Contract can call.
* If you do not specify a "visibility modifier", the Solidity function is declared public.
* When a public variable is declared, a public "getter()" function with the same name is created internally.
❍ Internal [Variable | Function] : It is "private modifier" but, It is also accessible from contracts that inherit the defined Contract.
❍ External [Variable | Function] : It is "public modifier" but, It is only accessible from outside the Contract.

// The dynamic array of Zombie structs. Other Contracts can use this array.
Zombie[] public zombies;


// The method of making a private function.
// The underbar character is used to mean a local variable/function. "_name" and "_dna" are local variables. "_createZombie" is a private function.
function _createZombie(string _name, uint _dna) private {}


❑ State modifier: It is the syntax that specifies how the Solidity source code interacts with the blockchain.
* "external [View | Pure]" function does not consume gas because it does not access the block.
❍ View: The read-only function. It just read stored data.
* Query occurred. No transaction occurred.
❍ Pure: The function that calculates and returns a value using a parameter. The side-effect(Changing variable's value)does not occur.

// This function returns a uint value.
// This function is a view function.
function _generateRandomDna(string _str) private view returns (uint) {}


❑ Custom modifier: It is the user-defined syntax.

// When the "setLevelUpFee()" function is called, the "onlyOwner()" modifier is executed first.
// The "onlyOwner()" modifier allows only the contract owner for use the function.
modifier onlyOwner() {
    require(msg.sender == owner);
    _; // Return to the function that called modifier.
}
function setLevelUpFee(uint _fee) external onlyOwner {
    levelUpFee = _fee;
}

// Modifier can use parameters.
modifier aboveLevel(uint _level, uint _zombieId) {
    require(zombies[_zombieId].level >= _level);
    _;
}

function changeName(uint _zombieId, string _newName) external aboveLevel(2, _zombieId) {
}


❑ Payable modifier: It is the syntax that is used in ETH coin transfer.
* The ETH that is transferred to a Contract is kept in the Contract.

[Contract]
contract OnlineStore {
    function buySomething() external payable {
        // Checking that 0.001 ETH is transmitted from the client when executing the function.
        // The data type of 0.001 ether is uint.
        require(msg.value == 0.001 ether);
    }

    // The source code for ETH withdrawals stored in the contract.
    function withdraw() external onlyOwner {
         // this.balance : The total ETH balance stored in the contract.
        owner.transfer(this.balance);
    }
}

[Client]
// The client source code written in web3.js.
// You can only send "value" to the function for which the payable modifier is set.
OnlineStore.buySomething({from: web3.eth.defaultAccount, value: web3.utils.toWei(0.001)});


❑ keccak256(): It is the SHA3-based hash function that returns a hexadecimal value of 256 bits.

// Generating a SHA-3 value.
// 6e91ec6b618bb462a4a6ee5aa2cb0e9cf30f7a052bb467b0ba58b8748c00d2e5
keccak256("aaaab");
// b1f078126895a1424524de5321b339ab00408010b7cf0e6ed451514981e58aa9
keccak256("aaaac");

// How to generate random numbers using hash values(0 to 99).
// Timestamp of current time(now), a msg.sender and the temporary value(nonce) are needed.
// Because a malicious node may try to write to a block only when the desired value comes out, this code is vulnerable.
uint randNonce = 0;
uint random = uint(keccak256(now, msg.sender, randNonce)) % 100;
randNonce++;
uint random2 = uint(keccak256(now, msg.sender, randNonce)) % 100;


❑ Typecasting

uint8 a1 = 5;
uint a2 = 6;

// uint256 → uint8
uint8 a3 = uint8(a2);


❑ Fallback function : No-name function. It is the function that is called when calling a function that does not exist in the contract. The fallback function prevents the error caused by not executing.

function () {
}


❑ event: It is the syntax that occurs logs.

// The declaring the log to be generated.
event NewZombie(uint zombieId, string name, uint dna);

// Each time the "_createZombie()" function is called, logs of "id", "_name", "_dna" values are generated.
function _createZombie(string _name, uint _dna) private {
    NewZombie(id, _name, _dna);
}


❑ msg.value: The amount of ETH sent.
❑ msg.sender: The person or the smart contract that called the current function.
❑ require: It is the syntax to raise an error message and stop execution when the condition is not true.

// Checking that "_name"'s value is the same as "abc".
// Solidity has no default string comparing function.
require(keccak256(_name) == keccak256("abc"));

// If the above condition is true, the following source code will be executed:
return "Hi!";


❑ Inheritance

contract Doge {
    function catchphrase() public returns (string) {
        return "So Wow CryptoDoge";
    }
}

// "BabyDoge" contract inherits "Doge" and "ERC721" contract.
contract BabyDoge is Doge, ERC721 {
    function anotherCatchphrase() public returns (string) {
        return "Such Moon BabyDoge";
    }
}


❑ import : The syntax to load solidity files(*.sol).

import "./someothercontract.sol";


❑ Storage: The variable that is used to store a value permanently in the blockchain.
* High cost syntax.
* [Array].push() changes the size of the array.
❑ Memory: The variable that is used to store a value temporarily.
* Low cost syntax compared to storage.
* [Array].push() doesn't change the size of the array.
❑ Without storage/memory syntax, If the storage/memory syntax doesn't exist, state variables(the Variables declared outside functions) are stored in storage, and variables in functions are stored in memory.

contract SandwichFactory {
    struct Sandwich {
        string name;
        string status;
    }

    Sandwich[] sandwiches;

    function eatSandwich(uint _index) public {

        // "mySandwich" is a pointer pointing "sandwiches [_index]".
        Sandwich storage mySandwich = sandwiches[_index];

        // This changes the storage's "status" value permanently.
        mySandwich.status = "Eaten!";

        // "anotherSandwich" copies the value of "sandwiches [_index]".
        Sandwich memory anotherSandwich = sandwiches[_index + 1];

        // This changes the "status" value of memory.
        anotherSandwich.status = "Eaten!";
    }
}


❑ Interface: The syntax to use a contract that you do not own.

// The interface declaration has the same format as a contract.
contract KittyInterface {

    // Copy the function from the name until the returns syntax and put a semicolon at the end.
    function getKitty(uint256 _id) external view returns (
        bool isGestating,
        bool isReady,
        uint256 cooldownIndex,
        uint256 nextActionAt,
        uint256 siringWithId,
        uint256 birthTime,
        uint256 matronId,
        uint256 sireId,
        uint256 generation,
        uint256 genes
    );
}


contract test {
    // The address of the smart contract to use.
    address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;

    // This initializes the interface.
    KittyInterface kittyContract = KittyInterface(ckAddress);

    // Now you can use the smart contract.
    // This stores the last of the 10 returned values in "kittyDna".
    uint kittyDna;
    (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
}


❑ Constructor: The function with the same name as the contract. It is executed once when the contract is created.

contract Ownable {
    function Ownable() public {
        owner = msg.sender;
    }
}


❑ Time(The value related in the time.)

/*
now // Returns UNIX timestamp(32 Bits uint).
seconds
minutes // Minute of the current time converted in seconds.
5 minutes // 300(60*5)
hours
1 hours // 3600(60*60)
days
weaks
years
*/

uint lastUpdated;
function updateTimestamp() public {
    lastUpdated = now;
}

// It returns "true" if it has been 5 minutes since the "updateTimestamp" function was called.
function fiveMinutesHavePassed() public view returns (bool) {
    return (now >= (lastUpdated + 5 minutes));
}


❑ For

for(uint i=0; i<10; i++) {
}


❑ If

if (var1 == var2) {
} else {
}


❑ ERC721 token
❍ function balanceOf(): It returns the number of tokens held by "_owner".

function balanceOf(address _owner) public view returns (uint256 _balance) {
    return ownerZombieCount[_owner];
}


❍ function ownerOf(): It returns the address that owns "_tokenId".

function ownerOf(uint256 _tokenId) public view returns (address _owner) {
    return zombieToOwner[_tokenId];
}


❍ function transfer(): It transfers the token from "_from" address to "_to" address.

function _transfer(address _from, address _to, uint256 _tokenId) private {
    ownerZombieCount[_to]++;
    ownerZombieCount[_from]--;
    zombieToOwner[_tokenId] = _to;

    Transfer(_from, _to, _tokenId); // The event defined by ERC721.
}

// The modifier that checks access permission to a token.
modifier onlyOwnerOf(uint _zombieId) {
    require(msg.sender == zombieToOwner[_zombieId]);
_;
}

function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
    _transfer(msg.sender, _to, _tokenId);
}


❍ function approve(): It approves tokens that is transferred.

function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
    zombieApprovals[_tokenId] = _to;
    Approval(msg.sender, _to, _tokenId); // The event defined by ERC721.
}


❍ function takeOwnership(): It calls "_transfer()" after ensuring that the "msg.sender" is approved to have a token.

function takeOwnership(uint256 _tokenId) public {
    require(zombieApprovals[_tokenId] == msg.sender);
    address owner = ownerOf(_tokenId);

    // Since msg.sender calls this function, it becomes a recipient.
    _transfer(owner, msg.sender, _tokenId);
}


❑ The Library is a special kind of contract In Solidity.
❑ Library SafeMath

library SafeMath {

    // Be careful not to input any values other than uint256(e.g. uint16, uint32 etc.).
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;

        // Check overflow..
        // "require()" and "assert()" are equivalent in that they return an error when the condition is not satisfied.
        // "require()" returns the remaining gas when the condition is not satisfied, but "assert()" doesn't return the remaining gas.
        assert(c >= a);
        return c;
    }
}

contract abc {
    // This applies the SafeMath library to the data type.
    using SafeMath for uint;

    uint a = 5;
    // The variable "a" is entered as the first argument of "add()".
    uint b = a.add(3); // 5 + 3 = 8
    uint c = a.mul(2); // 5 * 2 = 10
}


❑ Comment: Natspec comment is the standard comment format in Solidity.
❍ // @title: The title of a comment.
❍ // @autor: The author of a comment.
❍ // @notice: The description of a source code.
❍ // @dev: The description for developers.
❍ // @param: The parameter used by the function..
❍ // @return: The value returned by the function.

August 15, 2018

What is Block chain

[Block chain]

❑ Blockchain : The computer using P2P based distributed DB. Or the technology to make up this computer.
* P2P based distributed data storage creates data(blocks) and interconnects them using a consensus algorithm.
* Four major functions : Cryptocurrency, Smart Contract, Smart Asset, DAO.
❑ Side chain : A technology that allows trading of assets that exist in different block chains.
❑ On chain : Using Blockchain.
❑ Off chain : Not using Blockchain.
❑ Lightning Network(LN) : The technology allows sending and receiving cryptocurrencies immediately without mining.
* If a payment channel is written to a block, a transaction is not required to be written to the block because the off-chain verification method is used.
❑ Raiden network : It means Etherium's lightning network.
❑ A block is a storage. The gathered blocks are called distributed DB..
❑ The cryptocurrency issuance is made by recording in a block according to a specific format created by a dedicated program.
❑ Crypt wallet is a dedicated program.
❑ the data types of the bitcoin blockchain and the Ethereum blockchain are different. So each network's data is not compatible.
❑ The condition for data integrity in a blockchain.
❍ The format of the recorded data is correct.
❍ It is equal if comparing my data to data of other blocks.
❑ The member of the blockchain network.
❍ Node(miner) : A server in the blockchain network. Run DAPP. Create blocks(Transaction approval, distributed consensus, Storing transaction history.).
* Master node : The node that performs additional functions(anonymization, governance participation, etc.).
❍ Client(user) : Server users(Transaction creation, transaction history verification.).
❑ If a client creates a transaction, nodes share and execute the transaction through a distributed consensus.
❑ The blockchain node has two DBs.
❍ Transaction DB.
❍ Application(Smart contract) DB : It stores the latest state (variables) of the smart contract.
❑ Smart contract : Software. Application. DApp.
❑ The state of a smart contract : A variable used in a smart contract.
❑ Interface for using smart contracts.
❍ Transaction : Write, Modify. Delete. It is recorded in transaction DB. It changes the state of a smart contract.
❍ Query : Read.  It is not recorded in transaction DB. It reads the state of a smart contract.
At present, Transaction is slower than regular DB, but Query can be faster than regular DB.
❑ If the miner succeeds in mining, the miner receives transaction fee and compensation for the block issuance and.
❑ The miner creates a block first by processing a transaction that has a higher fee to increase mining compensation.
❑ A simple calculation has small fee, and a complex calculation has high fee.
❑ Transaction is a signed data package.
❑ Fork : Version update of a blockchain software.
* Miners update mining software and users update user software(wallet etc.).
❑ Hard fork : Creating a new main net.
❍ At a specific time, it copies blocks applied the old rule and connects the blocks to which the new rule is applied for constructing a new blockchain network.
❍ All miners/users should update their software.
❍ Service is not available during the update.
❑ Soft fork
❍ At a specific time, it connects the blocks applied the new rule to blocks which the old rule is applied.
❍ miners should update their software, but users don't need that.
❍ Service is available during the update.
❑ Test net : A blockchain network for testing before launching the main net..
❑ Main net : A block-chain network with an independent environment that is platform/transaction/wallet etc.
❑ Private blockchain : A closed blockchain network(Intranet).
❑ Public blockchain : A opened blockchain network(Internet).
❑ Token : A cryptocurrency application implemented in an existing main net.
* The tokens on Ethereum network are implemented in Solidity language.
❑ Coin : A cryptocurrency application implemented in its independent main net.
* Ethereum coin was implemented in languages other than Solidity(C++, GO).
❑ ICO(Initial Coin Offering) : Supporting the fund by appealing the blockchain technology. It is similar to IPO in that it distributes tokens to sponsors.
❑ ICO is usually implemented using Ethereum smart contract.
In "etherscan.io", you can find the corresponding ICO DApp by searching with the address.
* Investments and token distributions are made transparent and real time.
❑ Typical blockchain network building process.
1. Issue tokens in existing blockchain network.
* e.g. Issue ERC-20 tokens in Ethereum network.
2. Raise the fund through ICO and distributes tokens to participants.
3. Launch the test net for preparing the main net.
* In general, development status is disclosed to GitHub.
4. Launch the main net and issue coins.
5. Exchange the issued tokens and the coins.
❑ PoW(Proof Of Work) : Being the node by solving the hash problem.
❑ PoS(Proof Of Stake) : Being the node by having coins(stake).
❑ DPoS(Delegated Proof Of Stake) : It is the same as PoS but nodes are selected by electing.
The nodes of the DPoS are called delegated node or witness etc.




[Bitcoin]

❑ nBits : Filling the left side of the hash value with zeros. It affects mining difficulty because, If the miner's hash value is smaller than the hash value adjusted by nBits, mining will be achieved.
❑ Bitcoin script
❍ The first smart contract.
❍ Loop cannot be used(If a loop is allowed, the infinite loop occurs.).
❑ In the bitcoin network, the decentralized application called bitcoin is the main application.




[Ethereum]

❑ A block chain platform specialized in smart contract.
* Ethereum smart contract is written in Solidity language and becomes EVM Bytecode after being compiled.
❑ Solidity : The object-oriented programming language capable of developing Ethereum DAPP..
❑ Web3.js : The JavaScript library that interacts with an Ethereum smart contract.
❑ All cryptocurrency(token) issued on the Ethereum network are smart contracts.
* EOS token and crypto kitty are all just DApp.
❑ Ethereum combines transaction DB and smart contract DB for high compression ratio.
❑ Examples of Etherium's most famous smart contract is DAO(Decentralized Autonomous Organization)
* DAO tokens enable the company to make decisions.
* DAO smart contracts were attacked by hackers because of vulnerabilities.
❑ EVM(Ethereum Virtual Machine) : The node drives EVM and can run EVM Bytecode.
❑ GAS : The fee incurred when EVM Bytecode is executed.
* Unlike Ethereum coin, it maintains a constant price.
* Ethereum coin is used for GAS payments.
* The miner can determine the gas quantity to reject the transaction of the lower fee.
* Max fee : GAS limit * GAS price.
❍ GAS Limit : The max gas quantity that transaction generates.
* As a result of transactions, it is possible to use less gas than GAS Limit("GAS Used By Txn" displays this.).
❍ GAS Price(unit : wei).
* 1 Wei = 1/10^18 ETH
* 1 Kwei = 1/10^15 ETH
* 1 Mwei = 1/10^12 ETH
* 1 Gwei = 1/10^9 ETH
❑ Ethereum uses a node search protocol based on the Kadelima protocol.
❑ DApp distribution.
❍ TestRPC(Ganache) : Virtual environment. ETH can be issued without mining. The smart contract distributed can be deleted.
❍ TestNet : Ethereum network for testing. The difficulty of mining is low.
❍ MainNet : The actual Ethereum network that consumes gas when a transaction occurs.
❑ Ethereum's smart contract/wallet address length is 20 Bytes.
❑ ERC(Ethereum Request for Comment) : The standard recommended for cryptocurrency DApp of Etereum network.
❍ ERC-20(https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md)
❍ ERC-721(https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md)
- Each token cannot be split into decimal points.
- Each token has an ID.

July 02, 2018

Javascript grammar

[Example 1]
<div id="box" style="border: 1px solid #000;">
    <p>
        pageX : <span id="x"></span>
    </p>
    <p>
        pageY : <span id="y"></span>
    </p>
</div>

<script>
window.onload = function (){
    var box = document.getElementById("box");
    var pageX = document.getElementById("x");
    var pageY = document.getElementById("y");

    box.addEventListener("mousemove", function(){
        pageX.innerText = event.pageX;
        pageY.innerText = event.pageY;
    });
}
</script>



[Example 1 : Result]
pageX :
pageY :

window.onload = function() {} : The code for executing after all loading has finished. If it is used more than once, an error can occur without an error message.
❑ document.getElementById("[ID]") : Select an element using the [ID].
❑ [Element].addEventListener("mousemove", function() {}) : Register an [Element]'s event to event listener.
❑ event.pageX : The x-coordinate of the mouse.
event.pageY : The y-coordinate of the mouse.
[Element].innerText = [Plain text] : Insert a [Plain text] to the [Element].
[Element].innerHTML = [HTML text] : Insert a [HTML text] to the [Element].




[Example 2]
<p class="pClass">
    <b><span class="ft">Test1</span></b>
</p>
<p class="pClass">
    <b><span class="ft">Test2</span></b>
</p>

<input id="btn1" type="button" value="one"/>
<input id="btn2" type="button" value="two"/>
<input id="btn3" type="button" value="clear"/>

<br/><br/>
[Result]
<div id="rst"></div>


<script>
    document.querySelector("#btn1").addEventListener("click", function(){
        var spanFirst = document.querySelector("b span.ft");

        spanFirst.style.color="#FF0000";
        document.querySelector("#rst").innerHTML += spanFirst.style.color + "<br/>";
        spanFirst.setAttribute("onclick", "javascript:alert('One clicked!!')");
        var tmpStr = spanFirst.getAttribute("onclick");
        document.querySelector("#rst").innerHTML += tmpStr + "(Type : "+ typeof(tmpStr) + ")" + "<br/>";
    });

    document.querySelector("#btn2").addEventListener("click", function(){
        var pAll = document.querySelectorAll(".pClass");

        pAll[1].style.color="#00FF00";
        document.querySelector("#rst").innerHTML += pAll[1].style.color + "<br/>";
        pAll[1].setAttribute("onclick", "javascript:alert('Two clicked!!')");
        var tmpStr = pAll[1].getAttribute("onclick");
        document.querySelector("#rst").innerHTML += tmpStr + "(Type : "+ typeof(tmpStr) + ")" + "<br/>";
    });

    document.querySelector("#btn3").addEventListener("click", function(){
        var spanFirst = document.querySelector("b span.ft");
        spanFirst.style.color="";
        spanFirst.setAttribute("onclick", "");

        var pAll = document.querySelectorAll(".pClass");
        pAll[1].style.color="";
        pAll[1].setAttribute("onclick", "");
        document.querySelector("#rst").innerHTML = "";
    });
</script>


[Example 2 : Result]
Test1
Test2


[Result]

❑ document.querySelector("b span.ft") : Select one of the children of the "b" element that is a "span" element and has the attribute class "ft".
document.querySelector("#rst") : Select the element that has the attribute id is "rst".
❑ document.querySelectorAll(".pClass") : Select all elements that have the attribute class is "pClass"(Type : NodeList).
❑ [Element].style.color="#FF0000" : Set the [Element] to a red color style.
[Element].innerHTML += "[HTML code]"Append the [HTML code] to [Element].
❑ [Element].setAttribute("onclick", "javascript:alert('One clicked!!')") : Set the [Element]'s "onclick" attribute to the javascript code.
❑ [Element].getAttribute("onclick") : Return the value of the [Element]'s "onclick" attribute.
❑ typeof([Variable]) : Return [Variable]'s data format such as string, integer etc.
await [Promise] : Return the value of the disaggregated [Promise] object.




❑ setInterval(function() {}, 2000): Execute the anonymous function every 2 seconds.
window.setTimeout(function() {}, 2000) : Execute the anonymous function after 2 seconds.
Math.random() : Return the value of 0<=x<1.
Math.floor(Math.random()*3+1) : Return the value of 1<=x<=3.
❑ let css1 = document.createElement('link');
css1.href = "[URL]";
css1.rel = "stylesheet";
css1.onload = [Function name to execute after the load is completed];
document.querySelector('head').appendChild(css1);
: Import an external css file.

Example to use Inline-assembly in C language

The method using assembly code in C language is called Inline-assembly.


[Example 1]
#include<stdio.h>

int main() {

    int a = 0;
    int b = 0;
    int c = 0;

    printf("Hello world\n");

    __asm__ __volatile__(
        "mov $2, %%eax;"
        "mov %%eax, %0;"
        "mov $10, %%ebx;"
        "mov %%ebx, %1"
        : "=m" (a), "=m" (c)
    );


    __asm__ __volatile__(
        "mov $5, %%ebx;"
        "mov %%ebx, %0"
        : "=m" (b)
    );

    printf("Result(a) : %d\n", a);
    printf("Result(c) : %d\n", c);
    printf("Result(b) : %d\n", b);


    int src = 3;
    int dst = 5;
    __asm__ volatile (
        "mov %1, %%eax;"
        "add $1, %%eax;"
        "mov %%eax, %0;"
        : "=m" (dst)
        : "m" (src)
    );

    printf("Result(add) : %d\n", dst);

    system("pause");
    return 0;
}

[Example 1 : result]
Hello world
Result(a) : 2
Result(c) : 10
Result(b) : 5
Result(add) : 4

❑ : "=m" (dst) → The result is output to the dst using memory.
❑ : "=r" (dst) → The result is output to the dst using a register. 
❑ : "m" (src) → The src value is input using memory.
❑ : "=m" (dst) : "m" (src)  %0 points to the dst and %1 points to the src.
❑ __volatile__ → The assembly code is executed where it is located and doesn't move for reasons such as optimization.


June 19, 2018

Python class examples

<Code1.py>
class Car(object):
    __w = 4
    __d= 2

    def __init__(self, v1, v2):
        print "__init__() is called"
        self.v1 = v1
        self.v2 = v2

    def func1(self):
        print "w_ => {}".format(self.__w)
        print "d_ => {}".format(self.__d)
   
    def __del__(self):
        print "__del__() is called"


# Instance object
car_object = Car(2, 3)
car_object2 = Car(2, 3)

print "address(Car) => {0:#x}".format(id(Car))
print "address(Car_object) => {0:#x}".format(id(car_object))


print id(car_object.v1), id(car_object2.v1)


car_object.func1()


if (isinstance(car_object, Car) == True):
    print "yes"
else:
    print "no"

class_of_car_object = car_object.__class__
class_of_car_ojbect2 = car_object2.__class__

print class_of_car_object, class_of_car_ojbect2

print car_object2.__w


<Code1.py result>
__init__() is called
__init__() is called
address(Car) => 0x60014f4f0
address(Car_object) => 0x6ffffe60d90
25770367776 25770367776
w_ => 4
d_ => 2
yes
<class '__main__.Car'> <class '__main__.Car'>
Traceback (most recent call last):
  File "C:\Users\user\Desktop\tmp\test.py", line 43, in <module>
    print car_object2.__w
AttributeError: 'Car' object has no attribute '__w'
__del__() is called
__del__() is called

❑ [Object].__class__ : Returns the class to which the [Object] belongs.
❑ Error occurs because __w is a variable that is set to private by the underscore(__).
* [Information hiding]
__name == private
_name == protected
name == public
❑ The constructor and The Destructor are called automatically at the beginning and end.




<Code2.py>
class P:
  v=100

class C(P): #Inheritance
  pass

class Np:
vv=15
__w = "This is __w"
_wp = "This is _wp"

def __f(self):
print "This is private method"

def wFunc(self):
print self.__w


objectC = C()
print objectC.v

print issubclass(C, P)
print issubclass(C, C)
print issubclass(C, Np)
print issubclass(C, object) #True in Python 3.x

print C.__bases__
print P.__bases__
print Np.__bases__ # An Object is displayed in Python 3.x



class CC(P, Np): # Multiple inheritance
pass

objectCC = CC()

print objectCC.vv
# print CC.__w
# print CC.__f() # The private member variables/functions are not inherited.
print objectCC._wp
objectCC.wFunc()

<Code2.py result>
100
True
True
False
False
(<class __main__.P at 0x6ffffe56598>,)
()
()
15
This is _wp
This is __w

❑ A class's subclass includes itself.
❑ In Python 3.x, the object class is the parent class of all classes.
❑ [Class].__bases__ : Check the parent class of the [Class].
❑ Private member variables/functions are not inherited, but protected member variables/functions are inherited.
❑ The protected member variable/function can only be called in inheritance.




<Code3.py>
class Pp:
    v = 0x12
 
class C2(Pp):
    pass
 
objectC2= C2()
objectC2_2= C2()
objectC2.w = 10 
#The new member variable "w" is created in the objectC2.
print objectC2.w

print hex(id(objectC2.v))
print hex(id(objectC2_2.v))
print hex(id(C2.v))

objectC2.v = 55
print hex(id(objectC2.v))
print hex(id(objectC2_2.v))
print hex(id(C2.v))

C2.kVal = 150
print objectC2.kVal
print objectC2_2.kVal



class P10(object):
    def f(self):
        print "Parent f()"
     
class P11(P10):
    def f(self):    #Redefine
        print "Child f()"
    pass
 
objectP11 = P11()
objectP11.f()

<Code3.py result>
10
0x6000899a0
0x6000899a0
0x6000899a0
0x600089df0
0x6000899a0
0x6000899a0
150
150
Child f()

❑ If a member variable/function is redefined, the variable/function of the child object is used.

June 18, 2018

XML special characters

❑ &#nn : Decimal format.
❑ &#xhh : Hexadecimal format.


Character Numeric
character
Name

&#09;Horizontal tab

&#10;Line feed

&#13;Carriage Return

&#32;Space
!&#33;Exclamation mark
"&#34;Quotation mark
#&#35;Number sign
$&#36;Dollar sign
%&#37;Percent sign
&&#38;Ampersand
'&#39;Apostrophe
(&#40;Left parenthesis
)&#41;Right parenthesis
*&#42;Asterisk
+&#43;Plus sign
,&#44;Comma
-&#45;Hyphen
.&#46;Period
/&#47;Slash
:&#58;Colon
;&#59;Semi-colon
<&#60;Less than
=&#61;Equals sign
>&#62;Greater than
?&#63;Question mark
@&#64;At
[&#91;Left square bracket
\&#92;Bbackslash
]&#93;Right square bracket
^&#94;Caret
_&#95;Underscore
`&#96;Acute accent
{&#123;Left curly brace
|&#124;Vertical bar
}&#125;Right curly brace
~&#126;Tilde

June 12, 2018

Exit status

exit status test example

❑ Exit status : The returned value when a program exits. This can only be used if the program supports exit status.

❑ "$?" has the exit status.
* 0 : Successfully executed.
* 1~255(Non-zero) : An error occurred.



In above image, the "vi" program doesn't support the exit status. It always has the 0 exit status.

On the other hand, the "ls" program support the exit status. the below image is the manual of the "ls" program. the exit status can be checked.

checking the ls exit status