TypeError: Indexed expression has to be a type, mapping or array (is function (uint16) returns (uint256))? - mapping

Full source:https://github.com/laronlineworld/bettingMatch/blob/main/bettingMatch.sol This is a Betting Smart Contract, trying to create a mapping structure that user/wallet_address can bet on multiple matches. The problem of this betting contract is every time the user/wallet_address place a bet, the data of single mapping overwrite, how to create a mapping of value so that user/wallet_address can bet on different matches.
Place bet function:
function bet(uint16 _matchSelected, uint16 _resultSelected) public payable {
require(matchBettingActive[_matchSelected], "Betting: match voting is disabled");
//Check if the player already exist
// require(!checkIfPlayerExists(msg.sender));
//Check if the value sended by the player is higher than the min value
require(msg.value >= minimumBet);
//Set the player informations : amount of the bet, match and result selected
playerInfo[msg.sender].amountBet = msg.value;
playerInfo[msg.sender].matchSelected = _matchSelected;
playerInfo[msg.sender].resultSelected = _resultSelected;
//Add the address of the player to the players array
players.push(msg.sender);
MatchID[] storage bets = matchDetails[_matchSelected];
bets.push(MatchID(msg.sender, _matchSelected, msg.value, _resultSelected))-1;
uint16[] storage userBets = userToBets[msg.sender];
userBets.push[_matchSelected];
//Finally increment the stakes of the team selected with the player bet
if ( _resultSelected == 1){
totalBetHome[_matchSelected] += msg.value;
}
else if( _resultSelected == 2){
totalBetAway[_matchSelected] += msg.value;
}
else{
totalBetDraw[_matchSelected] += msg.value;
}
also need to sync the data in reward distribution depending of matchID distribution function:
function distributePrizes(uint16 matchFinished, uint16 teamWinner) public onlyOwner {
address[1000] memory winners;
//Temporary in memory array with fixed size. Let's choose 1000
uint256 count = 0; // This is the count for the array of winners
uint256 loserBet = 0; //This will take the value of all losers bet
uint256 winnerBet = 0; //This will take the value of all winners bet
address add;
uint256 bets;
address playerAddress;
//Check who selected the winner team
for(uint256 i = 0; i < players.length; i++){
playerAddress = players[i];
//If the player selected the winner team, we add his address to the winners array
if(playerInfo[playerAddress].matchSelected == matchFinished &&
playerInfo[playerAddress].resultSelected == teamWinner){
winners[count] = playerAddress;
count++;
}
}
//We define which bet sum is the Loser one and which one is the winner
if ( teamWinner == 1){
loserBet = totalBetAway[matchFinished] + totalBetDraw[matchFinished];
winnerBet = totalBetHome[matchFinished];
}
else if ( teamWinner == 2){
loserBet = totalBetHome[matchFinished] + totalBetDraw[matchFinished];
winnerBet = totalBetAway[matchFinished];
}
else{
loserBet = totalBetHome[matchFinished] + totalBetAway[matchFinished];
winnerBet = totalBetDraw[matchFinished];
}
//We loop through the array of winners, to give ethers to the winners
for(uint256 j = 0; j < count; j++){
//Check that the address in this fixed array is not empty
if(winners[j] != address(0))
add = winners[j];
bets = playerInfo[add].amountBet;
uint256 amountToPlayer = (bets * (10000+(loserBet*devFee/winnerBet))) / 10000;
winners[j].transfer(amountToPlayer);
}
//Reset all variables
delete playerInfo[playerAddress];
players.length = 0;
loserBet = 0;
winnerBet = 0;
//10 will be the number of matches (To improve this)
for(uint256 k = 0; k < 10; k++){
totalBetHome[k] = 0;
totalBetAway[k] = 0;
totalBetDraw[k] = 0;
}
}

Related

Is there any arithmetic formula that can test all given numbers are in row, like [ 3 5 4 ]

I m making a card game where 3 random numbers are generated..I need to check are these numbers Row numbers...
like 4 6 5 and 23,24,22. are row numbers
I have made method but I think there should be easy arithmetic formulas
I have tried this and working well, but I need simple arithmatic formula to avoid use of array and for
bool isAllInRow(int num1, int num2,int num3)
{
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
for(int x=0;x<numbers.length-1;x++)
{
if(numbers[x]-numbers[x+1]!=-1)
{
is_in_row=false;
break;
}
}
return is_in_row;
}
So you want to know if the cards form a straight, with aces both low and high.
Is the "three cards" fixed, or would you want to generalize to more cards?
Sorting should be cheap for such a short list, so that's definitely a good start. Then you just need to check the resulting sequence is increasing adjacent values.
I'd do it as:
bool isStraight(List<int> cards) {
var n = cards.length;
if (n < 2) return true;
cards.sort();
var first = cards.first;
if (first == 1 && cards[1] != 2) {
// Pretend Ace is Jack if n == 3.
// Accepts if remaining cards form a straight up to the King.
first = 14 - n;
}
for (var i = 1; i < n; i++) {
if (cards[i] != first + i) return false;
}
return true;
}
This code rejects card sets that have duplicates, or do not form a straight.
I think you are looking for Arithmetic Progression.
bool checkForAP(List<int> numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
if (numberArr[2] - numberArr[1] != diff) {
return false;
}
return true;
}
And modify your function like
bool isAllInRow(int num1, int num2,int num3) {
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
return checkForAP(numbers);
}
Note: remove sort in AP method as it is of no use. Since your numbers
list length is 3 I directly compared numbers for AP, the same can also
be written for n numbers with for.
bool checkForAp(numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
for(int i = 2; i< numberArr.length ;i++) {
if (numberArr[i] - numberArr[i - 1] != diff) {
return false;
}
}
return true;
}
You could do it like this:
bool isAllInRow(int num1, int num2,int num3) {
if (num1 == num2 || num2 == num3) return false;
var maxNum = max(num1, max(num2, num3));
var minNum = min(num1, min(num2, num3));
return (maxNum - minNum == 2) || (minNum == 1 && maxNum == 13 && num1 + num2 + num3 == 26);
}

how to track take profit and stoploss in mql4

I have the following code in mql4 and it is partially working but having an issue with order tracking.
int ticket;
void OnTick(){
... not included code, setting variables, etc ...
if(tenkan_sen < kijun_sen){
comment += "\nSHORT!";
if(OrderSelect(ticket,SELECT_BY_TICKET) && OrderType() == OP_BUY){
if(OrderClose(OrderTicket(),OrderLots(),Bid,1000,clrCrimson)){
ticket = 0;
}
}
if(ticket <= 0){
// need to set stoploss and takeprofit prices
double short_tp = current_close - (atr*6);
double short_sl = current_close + (atr*2);
ticket = OrderSend(_Symbol,OP_SELL,0.01,Bid,1000,short_sl,short_tp,"This is a sell",1,0,clrPink);
}
} else if(tenkan_sen > kijun_sen){
comment += "\nLONG!";
if(OrderSelect(ticket,SELECT_BY_TICKET) && OrderType() == OP_SELL){
if(OrderClose(OrderTicket(),OrderLots(),Ask,1000,clrPink)){
ticket = 0;
}
}
if(ticket <= 0){
// need to set stoploss and take profit prices
double long_tp = current_close + (atr*6);
double long_sl = current_close - (atr*2);
ticket = OrderSend(_Symbol,OP_BUY,0.01,Ask,1000,long_sl,long_tp,"This is a buy",1,0,clrCrimson);
}
}
}
This was previously based on the logic of closing the previous position upon opening the last position, it was working as expected before I added the sl and tp values. I am not sure how I should reset the ticket variable to 0 in the event of a sl or tp, or if there is a different way I should be handling this.

Unity 5 Saving and Loading variables

i know i can save int,float,string with PlayerPrefs, but how can i save a boolean too, like the Player has money, and he is bought an upgrade, how can i save if the player bought the upgrade and load it next time?
I have my upgrades like this:
public void Computer()
{
if(tier1 == true && Click.money >= cost)
{
Click.money -= cost;
ItemNameInfo.text = "[TIER II]Computer";
UpgradeInfo.text = "Wooaah! Upgrade Time!\n(Gives +5 CPS)";
cost = 1000;
costInfo.text = "Cost: " + cost;
Click.moneyperclick += 1;
tier1 = false;
tier2 = true;
}
else if(tier2 == true && Click.money >= cost)
{
Click.money -= cost;
ItemNameInfo.text = "[TIER III]Computer";
UpgradeInfo.text = "It's still isn't good enough\n(Gives +10 CPS)";
cost = 20000;
costInfo.text = "Cost: " + cost;
Click.moneyperclick += 5;
tier2 = false;
tier3 = true;
}
}
You cannot save bools to Player Prefs.
I tend to just use an int.
For example, let's say we have an item "item1".
To check if the player has that item unlocked:
if(PlayerPrefs.GetInt("hasItem1",0) == 1){
//player has item 1
}
to unlock item1:
PlayerPrefs.SetInt("hasItem1",1);

linkedList insertionsort

This is my implementation for an insertion sort method using linkedList. I have tried it and it works just fine the only problem that there is an index out of bounds exception caused by the J+1 line. Can anyone tell me how to get around that or how to fix it. Thnx
public static <T extends Comparable <? super T>> void insertionSort2(List<T> portion){
int i = 0;
int j = 0;
T value;
//List <T> sorted = new LinkedList<T>();
// goes through the list
for (i = 1; i < portion.size(); i++) {
// takes each value of the list
value = (T) portion.remove(i);
// the index j takes the value of I and checks the rest of the array
// from the point i
j = i - 1;
while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) {
portion.add(j+1 , portion.remove(j));//it was j+1
j--;
}
// put the value in the correct location.
portion.add(j + 1, value);
}
}
check this code out
just put it as a function in a class and try to call it
void InsertionSort()
{
int temp, out, in;
for(out=1 ; out<size ; out++)
{
temp = list[out];
in = out;
while (in > 0 && list[in-1] > temp)
{
list[in] = list[in-1];
--in;
}
list[in]= temp;
System.out.print("The list in this step became: ");
for (int t=0 ; t<size ; t++)
System.out.print(list[t]+" ");
System.out.println("");
}
}

Hash of a cell text in Google Spreadsheet

How can I compute a MD5 or SHA1 hash of text in a specific cell and set it to another cell in Google Spreadsheet?
Is there a formula like =ComputeMD5(A1) or =ComputeSHA1(A1)?
Or is it possible to write custom formula for this? How?
Open Tools > Script Editor then paste the following code:
function MD5 (input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
return txtHash;
}
Save the script after that and then use the MD5() function in your spreadsheet while referencing a cell.
This script is based on Utilities.computeDigest() function.
Thanks to gabhubert for the code.
This is the SHA1 version of that code (very simple change)
function GetSHA1(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, input);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
Ok, got it,
Need to create custom function as explained in
http://code.google.com/googleapps/appsscript/articles/custom_function.html
And then use the apis as explained in
http://code.google.com/googleapps/appsscript/service_utilities.html
I need to handtype the complete function name so that I can see the result in the cell.
Following is the sample of the code that gave base 64 encoded hash of the text
function getBase64EncodedMD5(text)
{
return Utilities.base64Encode( Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, text));
}
The difference between this solution and the others is:
It fixes an issue some of the above solution have with offsetting the output of Utilities.computeDigest (it offsets by 128 instead of 256)
It fixes an issue that causes some other solutions to produce the same hash for different inputs by calling JSON.stringify() on input before passing it to Utilities.computeDigest()
function MD5(input) {
var result = "";
var byteArray = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, JSON.stringify(input));
for (i=0; i < byteArray.length; i++) {
result += (byteArray[i] + 128).toString(16) + "-";
}
result = result.substring(result, result.length - 1); // remove trailing dash
return result;
}
to get hashes for a range of cells, add this next to gabhubert's function:
function RangeGetMD5Hash(input) {
if (input.map) { // Test whether input is an array.
return input.map(GetMD5Hash); // Recurse over array if so.
} else {
return GetMD5Hash(input)
}
}
and use it in cell this way:
=RangeGetMD5Hash(A5:X25)
It returns range of same dimensions as source one, values will spread down and right from cell with formulae.
It's universal single-value-function to range-func conversion method (ref), and it's way faster than separate formuleas for each cell; in this form, it also works for single cell, so maybe it's worth to rewrite source function this way.
Based on #gabhubert but using array operations to get the hexadecimal representation
function sha(str){
return Utilities
.computeDigest(Utilities.DigestAlgorithm.SHA_1, str) // string to digested array of integers
.map(function(val) {return val<0? val+256 : val}) // correct the offset
.map(function(val) {return ("00" + val.toString(16)).slice(-2)}) // add padding and enconde
.join(''); // join in a single string
}
Using #gabhubert answer, you could do this, if you want to get the results from a whole row. From the script editor.
function GetMD5Hash(value) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, value);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
function straightToText() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var r = 1;
var n_rows = 9999;
var n_cols = 1;
var column = 1;
var sheet = ss[0].getRange(r, column, n_rows, ncols).getValues(); // get first sheet, a1:a9999
var results = [];
for (var i = 0; i < sheet.length; i++) {
var hashmd5= GetMD5Hash(sheet[i][0]);
results.push(hashmd5);
}
var dest_col = 3;
for (var j = 0; j < results.length; j++) {
var row = j+1;
ss[0].getRange(row, dest_col).setValue(results[j]); // write output to c1:c9999 as text
}
}
And then, from the Run menu, just run the function straightToText() so you can get your result, and elude the too many calls to a function error.
I was looking for an option that would provide a shorter result. What do you think about this? It only returns 4 characters. The unfortunate part is that it uses i's and o's which can be confused for L's and 0's respectively; with the right font and in caps it wouldn't matter much.
function getShortMD5Hash(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (j = 0; j < 16; j += 8) {
hashVal = (rawHash[j] + rawHash[j+1] + rawHash[j+2] + rawHash[j+3]) ^ (rawHash[j+4] + rawHash[j+5] + rawHash[j+6] + rawHash[j+7])
if (hashVal < 0)
hashVal += 1024;
if (hashVal.toString(36).length == 1)
txtHash += "0";
txtHash += hashVal.toString(36);
}
return txtHash.toUpperCase();
}
I needed to get a hash across a range of cells, so I run it like this:
function RangeSHA256(input)
{
return Array.isArray(input) ?
input.map(row => row.map(cell => SHA256(cell))) :
SHA256(input);
}

Resources