Github API: Get number of contributions on a day by day basis - github

I want to GET from the Github API, the number of contributions per day. I'm making a webapp that compares the number of github contributions to the number of Dota 2 matches I play.
This picture should explain things more clearly.
http://i.stack.imgur.com/cZ1XK.png
I have scoured the Github API and the internet looking for a simple solution and some of the answers I've seen weren't what I was looking for. This Github API get last year of commit activity blurb is the closest I've gotten to finding a solution, but using it would involve making the API call for ALL repos in my account and concatenating the data into one JSON. If there are no solutions to this I would like to know it so I can abandon ship.
Thanks!

You can use the svg calendar data with the url :
https://github.com/users/USER/contributions?to=2016-12-25
You can set the to query param to your target day and then parse the svg result to get the last data in the output calendar.
For the web integration part, you can use a proxy like urlreq. An example :
const user = 'bertrandmartel';
const day = "2016-12-25";
fetch('https://urlreq.appspot.com/req?method=GET&url=https%3A%2F%2Fgithub.com%2Fusers%2F' + user + '%2Fcontributions%3Fto%3D' + day)
.then(function(response) {
return response.text();
})
.then(function(text) {
xmlDoc = new DOMParser().parseFromString(text, 'text/xml');
var nodes = xmlDoc.getElementsByTagName('rect');
var dayContributions = nodes[nodes.length-1].getAttribute('data-count');
console.log('contributions count for ' + day + ' : ' + dayContributions);
})
.catch(function(error) {
console.log('Request failed', error)
});

Related

Check and compare times of messages in Firebase Swift

what I am trying to do is I have a messages app made in Swift and I'm using Firebase as my database. What I'm trying to do is to have the functionality of disappearing messages like in Snapchat; however, I'm not exactly sure how I should to that. I have a timestamp on the message in the database, but I'm not sure how to use it. This is what I'm trying to do, I just don't know the exact code for it.
Here is a picture of what my database structure looks like. Let me know if you need any more information. Thank you
I would suggest managing your timestamps in Firebase by the metric of milliseconds since January 1st, 1970, by using NSDate().timeIntervalSince1970 * 1000 in Swift and then Date().getTime(); in your cron job written in JavaScript. You can store let date = Int64(NSDate().timeIntervalSince1970 * 1000) under your date node in firebase for each of your posts when they are created. Then you can create a cron job using Firebase Functions and Google Cloud that runs every hour that queries the posts and deletes posts with date timestamps more than a day old.
Here is a great tutorial on how get started with cron: https://firebase.googleblog.com/2017/03/how-to-schedule-cron-jobs-with-cloud.html
Your cron job will need to be coded in node.js and will look something like this:
// example cron job after setting everything up in the tutorial
exports.hourly_job =
functions.pubsub.topic('hourly-tick').onPublish((event) => {
// get current date and time
var currentDate = new Date();
console.log("Hourly Deletion Ran at: " + currentDate);
var currentNumMilliseconds = currentDate.getTime();
// remove a days worth of time
var oneDayAgo = currentNumMilliseconds - (3 * 24 * 60 * 1000);
var cutoffDate = new Date(oneDayAgo);
console.log("Query start at date: " + oneDayAgo);
// the firebase database ref where your posts are stored
const ref = admin.database().ref('posts');
// query all posts more than a day old
ref.orderByChild('date').startAt(oneDayAgo).once('value').then(function (snapshot) {
// for each snapshot returned from the query that is older than one day, delete
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var postObject = childSnapshot.val();
ref.child('key').remove();
});
});
});

right way to query calendar items via ews managed api?

I've got the following code:
var startProp = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Meeting, "DTSTART", MapiPropertyType.String);
var endProp = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Meeting, "DTEND", MapiPropertyType.String);
var cond1 = new SearchFilter.IsEqualTo(startProp, StartDate);
var cond2 = new SearchFilter.IsEqualTo(endProp, EndDate);
var filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, cond1, cond2);
var items = svc.FindItems(WellKnownFolderName.Calendar, filter, view);
I am trying to run this query on an exchange room mailbox. (This is not apparent in the code above however). It may have reservation with the exact start/end time. Hence if there is one reservation matching that criteria, I should get at least one item.
The background to this: think of a meeting room and people are trying to block it for a meeting. On exchange, this is just another mailbox, similar to a user mailbox. So on successful reservation, this mailbox gets an email with the calendar details (iCalendar format (*.ics).
I am stuck on two different counts...
items don't return anything in the code above. The TotalCount is zero. Maybe I am doing something wrong with the api. I am unable to figure this.
I am actually confused with what I am trying to query. I don't understand exchange's resolution in this matter. This is described further below.
So you've email items in a room mailbox. Each email has the calendar embedded with it usually with some base64 encoding. The calendar has a specific schema - we are only interested in the data you find in between VEVENTS (i.e BEGIN:VEVENT and END:VEVENT). The issue here is that there can be multiple VEVENTS sometimes. So how does exchange really do it? Does it run through all the VEVENTS, match the criteria; if it matches successfully, does it return that "email" (with the calendar attached/embedded)? Or it is some other mechanism?
Hence I am unsure of the semantic I've written in the code above. So please advise on this.
Found the answer to the first part:
static void Find(DateTime Start, DateTime End, ExchangeService svc)
{
var filter1 = new SearchFilter.IsGreaterThanOrEqualTo(MeetingRequestSchema.Start, Start);
var filter2 = new SearchFilter.IsLessThanOrEqualTo(MeetingRequestSchema.End, End);
var filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filter1, filter2);
var vw = new ItemView(99);
var items = svc.FindItems(WellKnownFolderName.Calendar, filter, vw);
Console.WriteLine("Count: {0}", items.TotalCount);
}

How to get active users of a specific page by Google analytics API?

I use rt:activeUsers metric to get active users on website for realtime data.
I want to get active users in real time for a specific page (path or url), not the whole website. Is there a way to implement it? I went through API Explorer but gain no success.
For anybody else looking for this below is an example of how I accomplished this in javascript.
I started with the sample at: https://ga-dev-tools.appspot.com/embed-api/third-party-visualizations/
That sample uses a extension to the embed api to get active users: active-users.js
I didn't know where to get that active-users.js file so I just used the developer tools in Chrome and grabbed it that way. Saved it locally and linked to it in my page. If anyone knows a official location to get that please comment below. Thx.
If you look at the source to that file, I modifed the pollActiveUsers function to add a filters parameter like so:
pollActiveUsers_: function () {
var t = this.get(),
i = 1e3 * (t.pollingInterval || 5);
if (isNaN(i) || i < 5e3)
throw new Error("Frequency must be 5 seconds or more.");
this.polling_ = !0,
gapi.client.analytics.data.realtime.get({
ids: t.ids,
metrics: "rt:activeUsers",
filters: t.filters
}).then(function (t) {
var e = t.result,
s = e.totalResults ? +e.rows[0][0] : 0,
n = this.activeUsers;
this.emit("success", {
activeUsers: this.activeUsers
}),
s != n && (this.activeUsers = s, this.onChange_(s - n)),
1 == this.polling_ && (this.timeout_ = setTimeout(this.pollActiveUsers_.bind(this), i))
}
.bind(this))
},
Now in my page javascript I can call it like so:
var activeUsers = new gapi.analytics.ext.ActiveUsers({
container: 'active-users-container',
pollingInterval: 5,
filters: "rt:pagePath==/somepath/somepage/",
ids: "ga:<yourviewid>"
});
Hope that helps somebody.
While the Real-time API is very limited it does allow you to use filters. Filters are a kind of where clause.
The real-time documentation is also very limited but you can look at the documentation for filters on the core reporting API it works the same
filters=ga:browser%3D~%5EFirefox
I think you should check out the dimension rt:pagePath its probably what you are looking for.

Limit of 100 items for graph statuses?

I'm working on a console application to download statuses and such from my own account -- nothing production or public. I'm finding that I can only get the last 100 statuses, but I was hoping to at least go a couple of years back.
I'm using the C# API, with something like:
dynamic response = Client.Get(string.Format("{0}/statuses", Secrets.FacebookUserName));
while (response.data.Count > 0)
{
foreach (dynamic status in response.data)
{
// do stuff
}
response = Client.Get(response.paging.next);
}
This works fine, but stops after 100 records.
I see the same thing when trying to use FQL:
dynamic x = Client.Get("fql", new { q = "select message from status where uid=me() limit 1000" });
Do I need to go down the road of exploring the batch API?

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.