Using #upstash/redis node client (https://www.npmjs.com/package/#upstash/redis) im trying to run the scan command (that should be supported, according to docs), but im not able to set the options:
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_RO_REST_TOKEN,
});
const result = await redis.scan(0);
This way it works, but when i try to add MATCH or COUNT (it says it is ScanCommandOptions type) i get no results. I tried several ways
const result = await redis.scan(0, MATCH, 'title*');
const result = await redis.scan(0, (MATCH, 'title*'));
const result = await redis.scan(0, {MATCH:'title*'});
but it looks these are not the correct way, i cant find any example, any suggestion?
Thank you
scan(cursor: number, opts: {
match?: string
count?: number
type?: string
})
For more details, see this Github Issue
Related
Whats a good way to find all users to execute a kick on them if they all contained a phrase in their name like "ihatemelons" for example.
let server = message.guild.id
//grab all discord names
let list = client.guilds.cache.get(server)
console.log(`All Users In Guild: ${list}`)
list.members.cache.forEach(member => console.log(member.user.username));
//Regex term to search
let re = (/_/ig)
//Search all of them
let usersFound = list.members.cache.forEach.match(re)(member => console.log(member.user.username))
list.members.cache.forEach(usersFound => console.log(member.user.username));
//What to do with the users that have the phrase in their name
message.reply(`Found:${usersFound}`)
Except I am stuck on where I search because
let usersFound = list.members.cache.forEach.match(re)(member => console.log(member.user.username)) doesnt work
Well you can use a regex to find the phrases you don't like, for example if you don't like the word creepy in username, you can simply do this:
let regex = /creepy/ig
regex.test("creepyUsername"); // Outputs true
for more info about regex:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
message.guild.members.cache.filter(member => member.user.username.includes('ihatemelons'))
Since GuildMemberManager.cache returns a Collection, you can utilise the methods provided by Collection and Map. Collection.filter() acts like Array.filter(), but returns a Collection instead.
Edit
This works for me:
const members = await message.guild.members.fetch();
let usersFound = members.filter(member => member.user.username.includes('ihatemelons'));
// OR: case-insensitive:
let usersFound = members.filter(member => /ihatemelons/i.test(member.user.username));
// OR
let usersFound = members.filter(member => member.user.username.toLowerCase().includes('ihatemelons'));
usersFound.forEach(member => console.log(member.user.username));
Make sure you have enabled the privileged intent for receiving full member lists in the Discord Developer Portal.
I developing a simple chat applicaiton for my website using firebase firestore. where every chat session has an id
provided i have an array of ids
chat_sessions = ["q93XhadA9QQLu6X8yfZB", "YXEYISEI8b2iixCcP3VO", "GXrSZbtrmN5NcrtvjFYp"]
I want to get all document whose id is equal to any of the id's in the chat_sessions object using the code below.
return this.afs
.collection('chats', ref => ref.where('uid','in_array',chat_sessions)).snapshotChanges...
but I am not getting any results.
I come from a PHP/MYSQL background
the PHP equivalent of what i am trying to achieve will be sth like this in PHP
if(in_array(uid,chat_sessions)){
get(doc/uid)
}
can anyone help with the right query where we check for document id against a list of ids in an array? Thank You!
Thank you #frank van Puffelen. You were almost right. I should have used in instead of in_array
ref.where(firebase.firestore.FieldPath.documentId(),'in_array',chat_sessions)
did not work. Instead I replaced in_array with in :
ref.where(firebase.firestore.FieldPath.documentId(),'in',chat_sessions)
This worked! Thank you
Your query is:
ref.where('uid','in_array',chat_sessions)
This checks a field called uid in each document against the values of the chat_sessions.
It seems that instead you want to the check the ID of each document against the array, which you can do with:
ref.where(firebase.firestore.FieldPath.documentId(),'in_array',chat_sessions)
I found something else on firestore i.e "array-contains-any" for this case.
Maybe it's updated now.
UPDATE
Hi, firebase did some update recently, so for do it I found out this method
`
const [products, setProduct] = useState([]);
const ids = ['H11LlJsh3sObwORZhA0b','om9m0lU9HYWyOJZKvEdi','1AoHyHuSFcF01zoyXyTD','6xoBlxsRXUoyzBUcWl0F',
'GJqthlmBGZaFAJqtC2jK','QNT3PxMfhNGg1RZnuqcq','RZgGoFZHyDAYaVZJWxGk','g4UO5P0EgtEqJnawwhXX','gyrZm8p0cEgJdDvTuB1g','mrscldfeYlkaSF151MpI',]
useEffect(() => {
const saveFirebaseTodos = [];
ids.forEach((element) => {
fetchMyAPI()
async function fetchMyAPI() {
const q = query(collection(db, "a"), where('__name__', '==', element));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
saveFirebaseTodos.push(({id: doc.id, ...doc.data()}));
/*console.log(doc.id, " => ", doc.data());*/
if (ids.length == saveFirebaseTodos.length) {
setProduct(saveFirebaseTodos)
}
});
}})
}, [])`
In this way, you can check how many element in arrays you want (bypassing 10 elements limit of firebase).
Hope can help anyone :D
I'm trying to use a regular expression to filter the name column in a csv file that has be put into an object array. Everything works fine if I type the exact value.
values I want "king" to match are below:
kingkong, king kong, king-kong, king_kong, king11, kongking, kong-king, kong_king, kong king, 11king
I've tried using filter and find methods but I want to use filter to return multiple values if they exist. I have tried the following regex but can't figure out the proper sytax if it is even correct.
const CSVToJSON = require('csvtojson');
const user = "king";
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter(function(v, i){
return ((v["name"]== /\bking.*/g));
})
You can use the following approach.
const CSVToJSON = require('csvtojson');
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter(function(v, i){
return ((v["name"].match(/king/g)));
});
return statement could be something like
return ((/king/g).test(v["name"]));
OR
return ((v["name"].match(/king/g)));
Both should work
However, your sample patterns show that king might stand either at the beginning or at the end of the target (bot can't have both prefix and suffix). If I am right, that means you don't need regex for that.
const CSVToJSON = require('csvtojson');
const user = "king";
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter((v, i) => v.startsWith(user) || v.endsWith(user))
/*rest of the code */
});
If king can stand anywhere, you can simply use includes instead.
This is what worked, I'm totally new to JavaScript:
const user = args;
var regex = new RegExp(user, "g");
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter(function(v, i){
return ((v["name"].match(regex)));
})
I am developing angular blockchain application using hyperledger composer tool.When i query the historian i got a response like in the below.
{
transactionType:"org.hyperledger.composer.system.AddParticipant"
}
I display the transaction type using follwing code snippet.
<div class="col-md-6">
{{participant.transactionType}}
</div>
The displayed part like this.
org.hyperledger.composer.system.AddParticipant
but I only want to display the 'AddParticipant' part in the response without 'org.hyperledger.composer.system.' part. How can I fix it?
For that just do little string manipulation. Make use of JS .split() method which splits string by argument character/string.
let arr = this.participant.transactionType.split(".");
then arr[arr.length-1] is your required string part which you can bind to view. Like use below {{txTyepe}} in template binding
this.txType = arr[arr.length-1];
you can use "substr" to pick a word from string but you need position of your word in your string first so :
const str = 'org.hyperledger.composer.system.AddParticipant'
let getPosition = str.indexOf('AddParticipant'); // get the position of AddParticipant
let getWord = str.substr(getPosition,13);
the length of AddParticipant is 13 also you can change the code above for better and cleaner and multi use code
const splitWord = (index)=>{
const str = 'org.hyperledger.composer.system.AddParticipant'
let strArray = str.split('.')
let getPosition = str.indexOf('AddParticipant'); // get the position of AddParticipant
let getWord = str.substr(getPosition,strArray[index].lenght); //you just need to change the number
return getWord;
}
console.log(splitWord(4));
You can also get the last "word" with regular expression :
<div class="col-md-6">
{{participant.transactionType.match(/\w+$/i)}}
</div>
When you see your historian data it'll look something like this
'$namespace': 'org.hyperledger.composer.system',
'$type': 'HistorianRecord',
'$identifier': '6e43b959c39bdd0c15fe45587a8dc866f1fa854d9fea8498536e84b45e281b31',
'$validator': ResourceValidator { options: {} },
transactionId: '6e43b959c39bdd0c15fe45587a8dc866f1fa854d9fea8498536e84b45e281b31',
transactionType: 'org.hyperledger.composer.system.IssueIdentity',
transactionInvoked:
Relationship {
'$modelManager': [Object],
'$classDeclaration': [Object],
'$namespace': 'org.hyperledger.composer.system',
'$type': 'IssueIdentity',
'$identifier': '6e43b959c39bdd0c15fe45587a8dc866f1fa854d9fea8498536e84b45e281b31',
'$class': 'Relationship' },
So, instead of taking transactionType you can use the transactionInvoked object. And then you can get whatever information you want from that object.
Finally your code should be like this
<div class="col-md-6">
{{participant.transactionInvoked.$type}}
</div>
In my case it will give me transaction type as just 'IssueIdentity'.
Not entirely sure how I word the question but my problem is Im doing an api call that returns a bunch of messages that have a creation time, now what I want to do is only return the latest creationTime for the messages with the same date so say If I have 30 messages on the 15/03/2018 I want to grab the latest time, and discard the rest.. and do that for each set of messages with the same date
So what Ive done so far is..
using lodash I have gotten all the messages, filtered out all the ones with a certain type, and I have ordered them by creationTime so the latest being at the top and going down.. now my question is how can I then make an array of the latest times for each date??
this._activityServiceProxy.getAllItems(start, end).subscribe(result => {
// this.messages = result;
// console.log(result);
let loginUnfiltered = _.filter(result, {'title': 'LOGIN'});
let loginFiltered = _.orderBy(loginUnfiltered, {'creationTime': 'desc'});
console.log(loginFiltered);
});
any help would be appreciated!
Thanks
Use .map(...) to get at array of only the latest creationTime:
this._activityServiceProxy.getAllItems(start, end).subscribe(result => {
// this.messages = result;
// console.log(result);
let loginUnfiltered = _.filter(result, {'title': 'LOGIN'});
let loginFiltered = _.orderBy(loginUnfiltered, {'creationTime': 'desc'});
const creationTimes = loginFiltered.map(l => l.creationTime);
console.log(creationTimes);
const latestTime = creationTimes[0];
console.log(latestTime);
});
You can use Underscore's groupBy function to achieve this:
const groups = _.groupBy(loginFiltered, (login) => {
const asDate = new Date(login.creationTime);
asDate.setHours(0, 0, 0, 0);
return asDate;
});
Object.keys(groups).forEach((key) => {
console.log(groups[key][0]);
});
You group by the creationDate property but remove the time component so all days get grouped together. You then loop through the result and just take the first entry per day.
Note that this assumes your creationTime property is a string, as it came from an API. If it's already a date, you don't need the new Date line.