How to limit MultiAutoCompleteTextView items/inputs - multiautocompletetextview

I have MultiAutoCompleteTextView use for selecting multiple recipient in a messaging app but I just want to limit it only to two recipient or 3. User should not be able to add more recipient once the limit is reached. Any hints how to do that?
final MultiAutoCompleteTextView mtv = (MultiAutoCompleteTextView) this
.findViewById(R.id.to);
final MobilePhoneAdapter mpa = new MobilePhoneAdapter(this);
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(this);
MobilePhoneAdapter.setMobileNumbersOnly(p.getBoolean(
PreferencesActivity.PREFS_MOBILE_ONLY, false));
mtv.setThreshold(2);
mtv.setAdapter(mpa);
((MultiAutoCompleteTextView) mtv).setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
mtv.setText(to);

Related

Create USDT Wallet on ERC20 Dart

I want to understand for myself how to generate USDT ERC20 wallet in dart language. I found the web3dart library. But what does it take to generate a koschel using the 12-word phrase provided by the bip39 library? And I don’t understand, is it necessary to write a smart contract? I would like to see a small code example of how to generate a wallet. Many thanks.
Update:
I seem to have managed to generate a wallet. But how to make exactly USDT on ERC20?
var random = Random.secure();
var mnemonic = 'obvious width mechanic wheat cargo toe bike seek spirit jungle enlist thumb';
String mnemonicToSeedHex = bip39.mnemonicToSeedHex(mnemonic);
EthPrivateKey credentials = EthPrivateKey.fromHex(mnemonicToSeedHex);
Wallet wallet = Wallet.createNew(credentials, mnemonic, random);
var address = await credentials.extractAddress();
dev.log(address.hex);
Since USDT is an erc-20 token, you can use the erc-20 abi for contract interactions.
final _erc20ContractAbi = web3.ContractAbi.fromJson(
'[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]',
'Erc20');
Now write a class to interact with each functions in the abi. You need to pass the contract address, web3client (infura or any other) and chainID (1 for ethereum mainnet)
class ERC20 extends web3.GeneratedContract {
ERC20({
required web3.EthereumAddress address,
required web3.Web3Client client,
int? chainId,
}) : super(web3.DeployedContract(_erc20ContractAbi, address), client,
chainId);
Now you can get the balance of your USDT by writing a balanceOf method inside the class like this,
Future<BigInt> balanceOf(
web3.EthereumAddress account, {
web3.BlockNum? atBlock,
}) async {
final function = self.abi.functions[2];
assert(checkSignature(function, '70a08231'));
final params = [account];
final response = await read(function, params, atBlock);
return (response[0] as BigInt);
}
Function to Transafer USDT tokens,
Future<String> transfer(
web3.EthereumAddress recipient,
BigInt amount, {
required web3.Credentials credentials,
web3.Transaction? transaction,
}) async {
final function = self.abi.functions[7];
assert(checkSignature(function, 'a9059cbb'));
final params = [recipient, amount];
return write(credentials, transaction, function, params);
}
Check out my article on Medium , Crypto-wallet app using flutter to get an idea on how to build your own erc-20 token and use flutter mobile application to build a wallet that can transfer the coins.

How to get AutoRefreshingAuthClient from AuthClient without any service account (Google Auth)

I need an AutoRefreshingAuthClient to use gsheet to play with authenticated users Google Sheet. I can get AuthClient using google_sign_in package.
So, How can I get AutoRefreshingAuthClient from AuthClient in a flutter application without any service account?
The reason I don't want to use a Service Account is,
If I use a Service Account, all files are saved into this Service Account. But, I want to read, write and use Google Sheet from the authenticated user's account.
I ended up using googleapis instead. Seems like gsheets was made to work specifically with Service Accounts so even if you create a valid AutoRefreshingAuthClient it'll check to see if it's a Service Account.
Here's how I did it with the SheetsApi (The GoogleAuthClient class was found after a lot of searching on GitHub and multiple users had the same thing):
import 'package:http/http.dart' as http;
class GoogleAuthClient extends http.BaseClient {
final Map<String, String> _headers;
final http.Client _client = new http.Client();
GoogleAuthClient(this._headers);
Future<http.StreamedResponse> send(http.BaseRequest request) {
return _client.send(request..headers.addAll(_headers));
}
}
final client = GoogleAuthClient((await _googleSignIn.currentUser.authHeaders));
_SheetApi = sheets.SheetsApi(client);
There is as decent amount of overhead on our side with SheetsApi compared to GSheets. Like appending rows or simply naming your Spreadsheet requires more lines of code and/or objects:
// Sheet creation
sheets.Spreadsheet request = sheets.Spreadsheet.fromJson({
'properties': {
'title': "$title",
},
});
sheets.Spreadsheet sh = getSheetApi().spreadsheets.create(request));
// Add first row
List<String> row = [...];
getSheetApi().spreadsheets.values.append(createSheetRows([columns]), sh.spreadsheetId, "Sheet1!$startLetter:$endLetter",
valueInputOption: 'USER_ENTERED');
...
static sheets.ValueRange createSheetRows(List<List<String>> row){
return sheets.ValueRange.fromJson({
"values": row,
"majorDimension": "ROWS"
});
}
static sheets.ValueRange createSheetRow(List<String> row){
return createSheetRows([row]);
}

QnA Maker: How to count a specific answer in a session?

I have QnA Maker chatbot. I want to do that: If bot gives the DefaultNoAnswer 3 times in a session, I want to show different DefaultNoAnswer. How can I count the DefaultNoAnswers in QnAMakerBaseDialog ?
ex:
Client: asdaaasd
Bot: Sorry, Could you phrase your question differently?
Client: dsjhdsgjdsa
Bot:Sorry, Could you phrase your question differently?
Client: aasdjhajds
Bot: Sorry, I couldn't get the question. Send an email for detailed information.
I find the best way to handle this is with a conversation state variable. I have my default message set up in my helper (i.e. I have a helper file that makes the call to QnA Maker, checks the confidence, and sends a default message in case of low confidence or no answer). If you are using a similar case, you can increment your state variable there. If you are using QnA Maker's default answer directly, you still need to do some check on every result before sending the response to user. I haven't used that method, but I would probably just check the result for the default answer and increment the variable accordingly.
Here is a sample for the first case. I am assuming here that you are already familiar with managing user and conversation state.
var qnaResult = await QnAServiceHelper.queryQnaService(query, oldState);
if (qnaResult[0].score > MINIMUM_SCORE) {
const conversationData = await this.dialogState.get(step.context, {});
conversationData.defaultAnswerCounter = 0;
await this.conversationState.saveChanges(step.context);
var outputActivity = MessageFactory.text(qnaResult[0].answer);
} else {
const conversationData = await this.dialogState.get(step.context, {});
conversationData.defaultAnswerCounter += 1;
if (conversationData.defaultAnswerCounter <= 2) {
var outputActivity = defaultAnswer;
} else {
var outputActivity = escalationAnswer;
}
await this.conversationState.saveChanges(step.context);
}

Bot not detecting server members (Discord.py)

I have a command that I made to choose a random member for the server, but for some reason, whenever I run it, it only mentions itself.. As if it cannot detect that there are other members in the server besides itself. Here is the code:
ok
client = commands.Bot(command_prefix=['%', "v", "V"],
case_insensitive=True,
help_command=None)
intents = discord.Intents().all()
intents = True
#client.event
async def on_ready():
print('Bot is Online! ;)')
servers = len(client.guilds)
members = 0
for guild in client.guilds:
members += guild.member_count - 1
await client.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching,
name=f'{servers} servers and {members} members | %help'))
#client.command()
async def choosemem(ctx):
guild = ctx.guild
await ctx.send(f"{random.choice(guild.members).mention} has been chosen")
This Is the full code, including the status, and the intents.
You need to add the intents value in client= commands.Bot as well
intents = discord.Intents().all()
client = commands.Bot(command_prefix=['%', "v", "V"],
case_insensitive=True,
help_command=None,
intents = intents)

Smack - get entry starts with specific letter

I'm using Smack to build simple XMPP android client, I need to retrieve users only starts with letter "a" I've tried to use roster and UserSearchManager both need specific user id I couldn't use wild card for e.g.
UserSearch userSearch = new UserSearch();
answerForm.setAnswer("user", "a*");
or
RosterEntry entry = roster.getEntry("a*");
Any help?
This is a working snippet:
public static List<Row> searchOnServerForUsers(String searchString, XmppManager xmppManager) throws Exception
{
UserSearchManager usersearchManager = new UserSearchManager(abstractXMPPConnection.getConnection());
String searchServiceName = XmppConstants.USER_SERVICE_NAME_PREFIX + abstractXMPPConnection.getConnection().getServiceName();
Form form = usersearchManager.getSearchForm( searchServiceName );
Form answers = form.createAnswerForm();
answers.setAnswer("Name", false);
answers.setAnswer("Email", false);
answers.setAnswer("Username", true);
// answers.setAnswer("search", "*"); //search for all registered users
answers.setAnswer("search", "a*"); //your search string
ReportedData data = usersearchManager.getSearchResults(answers, searchServiceName);
List<Row> rows = data.getRows();
return rows;
}
So you have to use UserSearch,
on each column (like Username, pay attention to case!)
you have to set if search (true) or to not search (false)
your search string (in your usecase: "a*")
Don't use smack version 4.4.0 alpha1 it has some bugs. After reverting it to 4.1.1 . I got all the users. from UserSearchManager