How to get all friends - TweetSharp - wpf

I'm using the ListFriends() method of TweetSharp library to get all friends of my user (My user has 500 friends).
TwitterCursorList<TwitterUser> friendsList = service.ListFriends(new ListFriendsOptions { Cursor=-1,SkipStatus=true});
while (friendsList.NextCursor != null)
{
foreach (var item in friendsList)
{
count++;
}
TwitterCursorList<TwitterUser> friendsList = service.ListFriends(new ListFriendsOptions { Cursor = friendsList.NextCursor, SkipStatus = true });
}
The above code is working well but it gives me only 300 friends because ListFriends() method has rate limit of 15 per 15 mins and when I'm trying to get more friends its rate limits get over.
How to get all friends in one attempt coz my requirement is to show all friends.

friends/ids will give you the id's of your friends (5.000 max/request). After that you can do a users/show to get the details for the userid's. I don't know what TweetSharp methods you need to use, but I think you can find that in the documentation.

You have one mistake in your code. You cant define friendsList again inside your loop. Thus the last line of code should looks like:
friendsList = service.ListFriends(new ListFriendsOptions { Cursor = friendsList.NextCursor, SkipStatus = true });

Related

Save the for-loop index for certain values to be used later

I'm trying to create two spreadsheets: one tracks student attendance at school, the other tracks their attendance at Track practice. The goal is to write a function, that I can set up as a button, that I can click that will automatically send emails to several people if the student is present at school but is absent for sports without getting excused.
Right now, the whole thing is working pretty well, but I have one issue. I have a column that will read "Good" or "Bad" depending on whether the student meets the above condition. The function turns these into an array. I would like to use the index of the "Bad"'s to find the necessary email addresses, which are stored at the same index point in another array that I make from the spreadsheet. I'm not sure how to save this index point and use it to reference the email addresses. Code below.
function sendEmailsMonday() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TrackAttendance");
var dataRange = sheet.getRange("D2:D30");
var data = dataRange.getValues();// Gets array of "Good" and "Bad"
for (i in data) {
if(i = "Bad") {
var place = data.indexOf(i);
var dataRange2 = sheet.getRange("M2:M30");// Gets array of email addresses
var data2 = dataRange2.getValues();
var emailAddress = data2[place];
var message = "This is an automated email informing you that your child/advisee ____ was present at school today, but missed Track without being excused. Feel free to email Mr. # with any questions.";
var subject = "___ missed Track Practice";
MailApp.sendEmail(emailAddress, subject, message);
return;
}
}
}
So, the issue comes in with the index lines. If I get rid of
var place = data.indexOf(i);
and replace
var emailAddress = data[place];
with
var emailAddress = data[28];
or any other number, it will grab the email address and send it. But then it has nothing to do with the values in the other column.
Seems like this should be an easy fix but I'm bad at this.
Very late responding now. I think you are almost there.
Your IF statement should read:
if(i == "Bad") {
And then replace 'place' with i:
var emailAddress = data2[i];
It should work as expected now.

Unable to cast object of type [TweetSharp.TwitterUser]' to type 'TweetSharp.TwitterCursorList`1[TweetSharp.TwitterUser]'

hi i want to get follower list via tweetsharp but i have a exception this = Unable to cast object of type 'System.Collections.Generic.List1[TweetSharp.TwitterUser]' to type 'TweetSharp.TwitterCursorList1[TweetSharp.TwitterUser]'.
help me please HOW CAN I GET FOLLOWERLIST?
my code like this
string aranan = "anilsarii";
var AramaAyari = new SearchForUserOptions { Q = aranan, Count = 25 };
var users = ts.SearchForUser(AramaAyari); //Get list of users by query
//...
//var asd=ts.FollowList(new FollowListOptions{ OwnerId= 2603023494});
var followers = ts.ListFollowers(new ListFollowersOptions { Cursor = -1 });
while (followers.NextCursor != null)
{
followers = ts.ListFollowers(new ListFollowersOptions { followers.NextCursor });
}
You may just need to change this line;
followers = ts.ListFollowers(new ListFollowersOptions { followers.NextCursor });
to
followers = ts.ListFollowers(new ListFollowersOptions { Cursor = followers.NextCursor });
If that doesn't work, it's likely a problem in TweetSharp itself. TweetSharp has been abandoned by the original authors and is no longer maintained. As a result, there are a number of problems using it with the current Twitter API, due to changes on Twitter's end in the last few years. However there are several forks of TweetSharp that are current.
I tried your code with the one line modified above using TweetMoaSharp (a fork, available on Nuget, or on github here; https://github.com/Yortw/tweetmoasharp) and it worked fine.
Full disclosure: TweetMoaSharp is a fork primarily maintained by me. If you search Nuget for 'TweetSharp' you should find several others.

Parse.com-FindAsync doesn't work.Not able to get Top 10 score

I work in unity and I am using parse.com to save my game score.But I'm getting a problem that I'm not able to get top ten score. Here the following code I'm using,
var query = ParseObject.GetQuery ("GameScore").OrderByDescending("score").Limit(5);
query.FindAsync().ContinueWith(t =>
{
IEnumerable<ParseObject> comments = t.Result;
foreach (var obj in comments) {
int score = obj.Get<int>("score");
Debug.Log(score);
string playerName = obj.Get<string>("playerName");
Debug.Log(playerName);
bool cheatMode = obj.Get<bool>("cheatMode");
Debug.Log("cheatmode"+cheatMode);
}
});
when I run this code the "foreach" loop runs only once, But I have save six rows in my class(over the parse.com server side).
I don't know why it is not responding. Please help me.
Thanks

cakephp - using create() not working as expected

I have a product controller and when I'm saving a new product I want to save some records to another related controller to make a record of what categories the product is associated with.
My code I'm using is:
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$newProductId = $this->Product->getInsertID();
//associate products with categories
foreach($categoriesToSave as $key=>$value) {
$saveArray['CategoriesProduct'] = array('category_id'=>$value, 'product_id'=>$newProductId);
$this->Product->CategoriesProduct->create();
$this->Product->CategoriesProduct->save($saveArray);
$this->Product->CategoriesProduct->clear();
}
}
For some reason though, even if $categoriesToSave has 10 items in it, only the very last one is being saved. So it's obviuosly creating only the one new CategoriesProduct item and saving each record over the top of the last instead of create()-ing a new one.
Can anyone explain what I'm doing wrong and how I can make this work?
The way I would do it would be like this:
//Add a counter
$c = 0
foreach($categoriesToSave as $key=>$value) {
$saveArray[$c]['CategoriesProduct']['category_id'] = $value;
$saveArray[$c]['CategoriesProduct']['product_id'] = $newProductId;
$c++;
}
$this->Product->CategoriesProduct->saveMany($saveArray);
I don't think that is the only way to do it but that should work just fine.
Good luck!

In Firebase, is there a way to get the number of children of a node without loading all the node data?

You can get the child count via
firebase_node.once('value', function(snapshot) { alert('Count: ' + snapshot.numChildren()); });
But I believe this fetches the entire sub-tree of that node from the server. For huge lists, that seems RAM and latency intensive. Is there a way of getting the count (and/or a list of child names) without fetching the whole thing?
The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.
Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.
For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
For more info, see https://www.firebase.com/docs/transactions.html
UPDATE:
Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.
If you want to count upvotes for example, you should create a structure similar to this one:
{
"posts" : {
"-JRHTHaIs-jNPLXOQivY" : {
"upvotes_count":5,
"upvotes" : {
"userX" : true,
"userY" : true,
"userZ" : true,
...
}
}
}
}
And then write a javascript function to increase the upvotes_count when there is a new write to the upvotes node.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});
You can read the Documentation to know how to Get Started with Cloud Functions.
Also, another example of counting posts is here:
https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js
Update January 2018
The firebase docs have changed so instead of event we now have change and context.
The given example throws an error complaining that event.data is undefined. This pattern seems to work better:
exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
const data = change.after.val();
const count = Object.keys(data).length;
return change.after.ref.child('_count').set(count);
});
```
This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.
This hinges on the fact that the Firebase REST API offers a shallow=true parameter.
Assume you have a post object and each one can have a number of comments:
{
"posts": {
"$postKey": {
"comments": {
...
}
}
}
}
You obviously don't want to fetch all of the comments, just the number of comments.
Assuming you have the key for a post, you can send a GET request to
https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.
This will return an object of key-value pairs, where each key is the key of a comment and its value is true:
{
"comment1key": true,
"comment2key": true,
...,
"comment9999key": true
}
The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).
This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.
Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).
The 'trick' here is to use the node priority to as the vote count...
The data is:
vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount
vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote
,"vote": {
".read" : true
,".write" : true
,"$issue" : {
"user" : {
"$user" : {
".validate" : "!data.exists() &&
newData.val()==data.parent().parent().child('count').getPriority()+1 &&
newData.val()==newData.GetPriority()"
user can only vote once && count must be one higher than current count && data value must be same as priority.
}
}
,"count" : {
".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
newData.getPriority()==data.getPriority()+1 "
}
count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.
}
}
Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.
<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
window.fb = new Firebase('https:...vote/iss1/');
window.fb.child('count').once('value', function (dss) {
votes = dss.getPriority();
for (var i=1;i<10;i++) vote(dss,i+votes);
} );
function vote(dss,count)
{
var user='user/zz' + count; // replace with auth.id or whatever
window.fb.child(user).setWithPriority(count,count);
window.fb.child('count').setWithPriority(user,count);
}
</script>
The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)
The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).
write a cloud function to and update the node count.
// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.userscount = functions.database.ref('/users/')
.onWrite(event => {
console.log('users number : ', event.data.numChildren());
return event.data.ref.parent.child('count/users').set(event.data.numChildren());
});
Refer :https://firebase.google.com/docs/functions/database-events
root--|
|-users ( this node contains all users list)
|
|-count
|-userscount :
(this node added dynamically by cloud function with the user count)

Resources