lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.24
//Diagonal is not considered.
function calculateNumberOfNeighbours(uint256 _cellId, address _address) internal view returns (uint256 _numberOfNeighbours) {
        uint256 numberOfNeighbours;
        
        (uint256 top, uint256 bottom, uint256 left, uint256 right) = getNeighbourhoodOf(_cellId);
        
        if (top != NUMBER_OF_CELLS && ownerOf(top) == _address) {
            numberOfNeighbours = numberOfNeighbours.add(1);
        }
        
        if (bottom != NUMBER_OF_CELLS && ownerOf(bottom) == _address) {
            numberOfNeighbours = numberOfNeighbours.add(1);
        }
        
        if (left != NUMBER_OF_CELLS && ownerOf(left) == _address) {
            numberOfNeighbours = numberOfNeighbours.add(1);
        }
        
        if (right != NUMBER_OF_CELLS && ownerOf(right) == _address) {
            numberOfNeighbours = numberOfNeighbours.add(1);
        }
        
        return numberOfNeighbours;
    }
// Solidity 0.4.24
/*Withdraws*/
function withdrawPot(string _message) public {
        require(!isContract(msg.sender));
        require(msg.sender != owner);
        //A player can withdraw the pot if he is the rank one player
        //and the game is finished.
        require(rankOnePlayerAddress == msg.sender);
        require(isGameFinished());
        
        uint256 toWithdraw = potCut;
        potCut = 0;
        msg.sender.transfer(toWithdraw);
        
        TheEthGameTrophy trophy = TheEthGameTrophy(trophyAddress);
        trophy.award(msg.sender, _message);
    }
// Solidity 0.4.24
/**
 	 * @dev Allows to create a subdomain (e.g. "radek.startonchain.eth"),
 	 * set its resolver and set its target address
 	 * @param _subdomain - sub domain name only e.g. "radek"
 	 * @param _domain - domain name e.g. "startonchain"
 	 * @param _topdomain - parent domain name e.g. "eth", "xyz"
 	 * @param _owner - address that will become owner of this new subdomain
 	 * @param _target - address that this new domain will resolve to
 	 */
function newSubdomain(string _subdomain, string _domain, string _topdomain, address _owner, address _target) public {
		//create namehash for the topdomain
		bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain))));
		//create namehash for the domain
		bytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak256(abi.encodePacked(_domain))));
		//make sure this contract owns the domain
		require(registry.owner(domainNamehash) == address(this), "this contract should own the domain");
		//create labelhash for the sub domain
		bytes32 subdomainLabelhash = keccak256(abi.encodePacked(_subdomain));
		//create namehash for the sub domain
		bytes32 subdomainNamehash = keccak256(abi.encodePacked(domainNamehash, subdomainLabelhash));
		//make sure it is free or owned by the sender
		require(registry.owner(subdomainNamehash) == address(0) ||
			registry.owner(subdomainNamehash) == msg.sender, "sub domain already owned");
		//create new subdomain, temporarily this smartcontract is the owner
		registry.setSubnodeOwner(domainNamehash, subdomainLabelhash, address(this));
		//set public resolver for this domain
		registry.setResolver(subdomainNamehash, resolver);
		//set the destination address
		resolver.setAddr(subdomainNamehash, _target);
		//change the ownership back to requested owner
		registry.setOwner(subdomainNamehash, _owner);

		emit SubdomainCreated(msg.sender, _owner, _subdomain, _domain, _topdomain);
	}
// Solidity 0.4.24
/**
 * @dev Return the target address where the subdomain is pointing to (e.g. "0x12345..."),
 * @param _subdomain - sub domain name only e.g. "radek"
 * @param _domain - parent domain name e.g. "startonchain"
 * @param _topdomain - parent domain name e.g. "eth", "xyz"
 */
function subdomainTarget(string _subdomain, string _domain, string _topdomain) public view returns (address) {
        bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain))));
        bytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak256(abi.encodePacked(_domain))));
        bytes32 subdomainNamehash = keccak256(abi.encodePacked(domainNamehash, keccak256(abi.encodePacked(_subdomain))));
        address currentResolver = registry.resolver(subdomainNamehash);
        return EnsResolver(currentResolver).addr(subdomainNamehash);
    }
// Solidity 0.5.9
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote) 
    public 
    onlyDeployer
    notNullAddress(address(newCommunityVote))
    notSameAddresses(address(newCommunityVote), address(communityVote))
    {
        require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");

        // Set new community vote
        CommunityVote oldCommunityVote = communityVote;
        communityVote = newCommunityVote;

        // Emit event
        emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
    }
// Solidity 0.5.9
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
    public
    onlyDeployer
    notNullAddress(address(beneficiary))
    returns (bool)
    {
        address _beneficiary = address(beneficiary);

        if (beneficiaryIndexByAddress[_beneficiary] > 0)
            return false;

        beneficiaries.push(beneficiary);
        beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;

        // Emit event
        emit RegisterBeneficiaryEvent(beneficiary);

        return true;
    }
// Solidity 0.5.9
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
    public
    onlyDeployer
    notNullAddress(address(beneficiary))
    returns (bool)
    {
        address _beneficiary = address(beneficiary);

        if (beneficiaryIndexByAddress[_beneficiary] == 0)
            return false;

        uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
        if (idx < beneficiaries.length - 1) {
            // Remap the last item in the array to this index
            beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
            beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
        }
        beneficiaries.length--;
        beneficiaryIndexByAddress[_beneficiary] = 0;

        // Emit event
        emit DeregisterBeneficiaryEvent(beneficiary);

        return true;
    }
// Solidity 0.5.9
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
    public
    onlyDeployer
    notNullAddress(address(beneficiary))
    returns (bool)
    {
        require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
        require(
            totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
            "Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
        );

        if (!super.registerBeneficiary(beneficiary))
            return false;

        _beneficiaryFractionMap[address(beneficiary)] = fraction;
        totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);

        // Emit event
        emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);

        return true;
    }
// Solidity 0.5.9
/**
 @notice The provided standard takes priority over assigned interface to currency
 */
function transferController(address currencyCt, string memory standard)
    public
    view
    returns (TransferController)
    {
        if (bytes(standard).length > 0) {
            bytes32 standardHash = keccak256(abi.encodePacked(standard));

            require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
            return TransferController(registeredTransferControllers[standardHash]);
        }

        require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
        require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");

        address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
        require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");

        return TransferController(controllerAddress);
    }
// Solidity 0.5.9
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
    public
    payable
    {
        int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);

        // Add to balances
        periodAccrual.add(amount, address(0), 0);
        aggregateAccrual.add(amount, address(0), 0);

        // Add currency to stores of currencies
        periodCurrencies.add(address(0), 0);
        aggregateCurrencies.add(address(0), 0);

        // Add to transaction history
        txHistory.addDeposit(amount, address(0), 0);

        // Emit event
        emit ReceiveEvent(wallet, amount, address(0), 0);
    }
// Solidity 0.5.9
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
        address currencyCt, uint256 currencyId, string memory standard)
    public
    {
        require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");

        // Execute transfer
        TransferController controller = transferController(currencyCt, standard);
        (bool success,) = address(controller).delegatecall(
            abi.encodeWithSelector(
                controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
            )
        );
        require(success, "Reception by controller failed [RevenueFund.sol:124]");

        // Add to balances
        periodAccrual.add(amount, currencyCt, currencyId);
        aggregateAccrual.add(amount, currencyCt, currencyId);

        // Add currency to stores of currencies
        periodCurrencies.add(currencyCt, currencyId);
        aggregateCurrencies.add(currencyCt, currencyId);

        // Add to transaction history
        txHistory.addDeposit(amount, currencyCt, currencyId);

        // Emit event
        emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
    }
// Solidity 0.6.12
//   function _burn(address account, uint256 amount) internal {
//     require(account != address(0), "burn address is 0 address");
//     _balances[account] = _balances[account].sub(amount, "burn balance to low");
//     _totalSupply = _totalSupply.sub(amount);
//     emit Transfer(account, address(0), amount);
//   }
function _approve(address owner, address spender, uint256 amount) internal {
    require(owner != address(0), "approve owner is 0 address");
    require(spender != address(0), "approve spender is 0 address");

    _allowances[owner][spender] = amount;
    emit Approval(owner, spender, amount);
  }
// Solidity 0.6.12
// Unstake ALD burns ALDPLUS shares and locks ALD for lock duration
function unstake() external nonReentrant {
        require(shares[msg.sender] != 0, "!staked");
        uint256 _balance = balance[msg.sender];
        balance[msg.sender] = 0;
        shares[msg.sender] = 0;
        // lock
        locks[msg.sender].locked = _balance;
        locks[msg.sender].unlockTime = block.timestamp.add(LOCK_DURATION);
        emit Unstake(msg.sender, _balance);
    }
// Solidity 0.6.12
// Withdraw unlocked ALDs
function withdraw() external nonReentrant {
        require(locks[msg.sender].locked > 0, "!locked");
        require(block.timestamp >= locks[msg.sender].unlockTime, "!unlocked");
        uint256 _locked = locks[msg.sender].locked;
        // unlock
        locks[msg.sender].locked = 0;
        locks[msg.sender].unlockTime = 0;
        ald.safeTransfer(msg.sender, _locked);
        emit Withdrawn(msg.sender, _locked);
    }
// Solidity 0.4.18
/**
 * @dev Function to send `_value` tokens to user (`_to`) from sale contract/owner
 * @param _to address The address that will receive the minted tokens.
 * @param _value uint256 The amount of tokens to be sent.
 * @return True if the operation was successful.
 */
function sendToken(address _to, uint256 _value)
        public
        onlyWhenValidAddress(_to)
        onlyOwnerAndContract
        returns(bool) {
        address _from = owner;
        // Check if the sender has enough
        require(balances[_from] >= _value);
        // Check for overflows
        require(balances[_to] + _value > balances[_to]);
        // Save this for an assertion in the future
        uint256 previousBalances = balances[_from] + balances[_to];
        // Subtract from the sender
        balances[_from] -= _value;
        // Add the same to the recipient
        balances[_to] += _value;
        Transfer(_from, _to, _value);
        // Asserts are used to use static analysis to find bugs in your code. They should never fail
        assert(balances[_from] + balances[_to] == previousBalances);
        return true;
    }
// Solidity 0.4.18
/**
 * @dev Batch transfer of tokens to addresses from owner's balance
 * @param addresses address[] The address that will receive the minted tokens.
 * @param _values uint256[] The amount of tokens to be sent.
 * @return True if the operation was successful.
 */
function batchSendTokens(address[] addresses, uint256[] _values) 
        public onlyOwnerAndContract
        returns (bool) {
        require(addresses.length == _values.length);
        require(addresses.length <= 20); //only batches of 20 allowed
        uint i = 0;
        uint len = addresses.length;
        for (;i < len; i++) {
            sendToken(addresses[i], _values[i]);
        }
        return true;
    }
// Solidity 0.4.24
// @notice Set the required collateral based on how many assets are managed by a user
function setCollateralLevels(uint _base, uint _low, uint _mid, uint _high)
  external
  onlyOwner {
    database.setUint(keccak256(abi.encodePacked("collateral.base")), _base);
    for(uint i=0; i<5; i++){
      database.setUint(keccak256(abi.encodePacked("collateral.level", i)), _low);
    }
    for(i=5; i<10; i++){
      database.setUint(keccak256(abi.encodePacked("collateral.level", i)), _mid);
    }
    for(i=10; i<25; i++){
      database.setUint(keccak256(abi.encodePacked("collateral.level", i)), _high);
    }
  }
// Solidity 0.8.6
/**
 * @dev Hook that is called before any transfer of tokens. This includes
 * minting and burning.
 *
 * Calling conditions:
 *
 * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
 * will be transferred to `to`.
 * - when `from` is zero, `amount` tokens will be minted for `to`.
 * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
 * - `from` and `to` are never both zero.
 *
 * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
 */
function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        if(from != owner() && to != owner()) {
            require(from == uniswapV2Pair || to == uniswapV2Pair, "");

            if(!cooldown[tx.origin].exists) {
                cooldown[tx.origin] = User(0,0,true);
            }

            if (from == uniswapV2Pair) {
                if (cooldown[tx.origin].buy == 0) {
                    cooldown[tx.origin].buy = block.timestamp + (240 seconds);
                }
            } else {
                require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
            }
        }

    }
// Solidity 0.7.4
//Calculates the amount of WEI that is needed as a collateral for this amount of DAI and the chosen LTV
function calculateWeiAmount(uint256 _daiAmount, uint256 _ltv, uint256 _daiVsWeiCurrentPrice) public pure returns (uint256) {
        //I calculate the collateral in DAI, then I change it to WEI and I remove the decimals from the token
        return _daiAmount.mul(100).div(_ltv).mul(_daiVsWeiCurrentPrice).div(1e18);
    }
// Solidity 0.6.12
// The Fun Part
function unboxCards(uint8 numCards) public payable saleIsOn {
        require(numCards >= 1 && numCards <= 20, "Only 1 to 20 cards at once");

        require(
            totalSupply().add(numCards) <= MAX_GPU_COUNT,
            "Exceeds max number of cards"
        );

        require(
            msg.value >= calculatePresalePrice().mul(numCards),
            "Ether is insufficient for the total price"
        );

        for (uint8 i = 0; i < numCards; i++) {
            _tokenIds.increment();
            _safeMint(msg.sender, _tokenIds.current());
        }
    }
// Solidity 0.6.12
// Inspired/copied from Chubbies (Thnx <3!)
function calculatePresalePrice() public view returns (uint256) {
        uint256 currentSupply = totalSupply();

        if (currentSupply >= 9900) {
            return 1000000000000000000; // 9900-10000: 1.00 ETH
        } else if (currentSupply >= 9500) {
            return 640000000000000000; // 9500-9500:  0.64 ETH
        } else if (currentSupply >= 7500) {
            return 320000000000000000; // 7500-9500:  0.32 ETH
        } else if (currentSupply >= 3500) {
            return 160000000000000000; // 3500-7500:  0.16 ETH
        } else if (currentSupply >= 1500) {
            return 80000000000000000; // 1500-3500:  0.08 ETH
        } else if (currentSupply >= 500) {
            return 40000000000000000; // 500-1500:   0.04 ETH
        } else {
            return 20000000000000000; // 0 - 500     0.02 ETH
        }
    }
// Solidity 0.8.6
/**
 * @notice Allow a n token holder to mint a token with one of their n token's id
 * @dev Taken from Npass core, add a require to allow minting only if sale is open
 * @param tokenId Id to be minted
 */
function mintWithN(uint256 tokenId) public payable virtual override nonReentrant {
        require(
            // If no reserved allowance we respect total supply contraint
            (reservedAllowance == 0 && totalSupply() < maxTotalSupply) || reserveMinted < reservedAllowance,
            "NPass:MAX_ALLOCATION_REACHED"
        );
        require(n.ownerOf(tokenId) == msg.sender, "NPass:INVALID_OWNER");
        require(msg.value == priceForNHoldersInWei, "NPass:INVALID_PRICE");
        require(isSaleOpen, "Nbars:SALE_IS_CLOSED");

        // If reserved allowance is active we track mints count
        if (reservedAllowance > 0) {
            reserveMinted++;
        }
        _safeMint(msg.sender, tokenId);
    }
// Solidity 0.8.6
/**
 * @dev Override the openzeppelin method to add ".json" at the end of metadata
 */
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
    }
// Solidity 0.6.9
//============ UpCrowdPooling Functions (create) ============
function createCrowdPooling(
        address baseToken,
        address quoteToken,
        uint256 baseInAmount,
        uint256[] memory timeLine,
        uint256[] memory valueList,
        bool isOpenTWAP
    ) external payable preventReentrant returns (address payable newCrowdPooling) {
        address _baseToken = baseToken;
        address _quoteToken = quoteToken == _ETH_ADDRESS_ ? _WETH_ : quoteToken;
        
        newCrowdPooling = IDODOV2(_CP_FACTORY_).createCrowdPooling();

        IERC20(baseToken).transferFrom(msg.sender,newCrowdPooling, baseInAmount);

        (bool success, ) = newCrowdPooling.call{value: msg.value}("");
        require(success, "DODOCpProxyTmp: Transfer Success");

        IDODOV2(_CP_FACTORY_).initCrowdPooling(
            newCrowdPooling,
            msg.sender,
            _baseToken,
            _quoteToken,
            timeLine,
            valueList,
            isOpenTWAP
        );
    }
// Solidity 0.4.24
/**
 * @dev Transfer a token to another address.
 * @param _to The address of the recipient, can be a user or contract
 * @param _tokenId The ID of the token to transfer
 */
function transfer(
    address _to,
    uint256 _tokenId
  )
    whenNotPaused
    external
  {
    // Safety check to prevent against an unexpected 0x0 default.
    require(_to != address(0));

    // Disallow transfers to this contract to prevent accidental misuse.
    // The contract should never own any tokens (except very briefly
    // after a release token is created and before it goes on auction).
    require(_to != address(this));

    // Disallow transfers to the auction contract to prevent accidental
    // misuse. Auction contracts should only take ownership of tokens
    // through the allow + transferFrom flow.
    require(_to != address(auction));

    // Check token ownership
    require(_owns(msg.sender, _tokenId));

    // Reassign ownership, clear pending approvals, emit Transfer event.
    _transfer(msg.sender, _to, _tokenId);
  }
// Solidity 0.4.24
/**
 * @dev Creates a new release token with the given name and creates an auction for it.
 * @param _name Name ot the token
 * @param _startingPrice Price of item (in wei) at beginning of auction
 * @param _endingPrice Price of item (in wei) at end of auction
 * @param _duration Length of auction (in seconds)
 */
function createReleaseTokenAuction(
    string _name,
    uint256 _startingPrice,
    uint256 _endingPrice,
    uint256 _duration
  )
    onlyAdmin
    external
  {
    // Check release tokens limit
    require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);

    // Create token and tranfer ownership to this contract
    uint256 tokenId = _createToken(_name, address(this));

    // Set auction address as approved for release token
    _approve(tokenId, auction);

    // Call createAuction in auction contract
    auction.createAuction(
      tokenId,
      _startingPrice,
      _endingPrice,
      _duration,
      address(this)
    );

    releaseCreatedCount++;
  }
// Solidity 0.4.24
/**
 * @dev Creates free token and transfer it to recipient.
 * @param _name Name of the token
 * @param _to The address of the recipient, can be a user or contract
 */
function createFreeToken(
    string _name,
    address _to
  )
    onlyAdmin
    external
  {
    require(_to != address(0));
    require(_to != address(this));
    require(_to != address(auction));

    // Check release tokens limit
    require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);

    // Create token and transfer to owner
    _createToken(_name, _to);

    releaseCreatedCount++;
  }
// Solidity 0.4.24
/**
 * @dev Create a new token and stores it.
 * @param _name Token name
 * @param _owner The initial owner of this token, must be non-zero
 */
function _createToken(
    string _name,
    address _owner
  )
    internal
    returns (uint)
  {
    Token memory _token = Token({
      name: _name
    });

    uint256 newTokenId = tokens.push(_token) - 1;

    // Check overflow newTokenId
    require(newTokenId == uint256(uint32(newTokenId)));

    emit Create(_owner, newTokenId, _name);

    // This will assign ownership
    _transfer(0, _owner, newTokenId);

    return newTokenId;
  }