## May 31, 18: #AnalyticsClub #Newsletter (Events, Tips, News & more..)

### [  COVER OF THE WEEK ]

Correlation-Causation  Source

### [ FEATURED COURSE]

Learning from data: Machine learning course

On Intelligence

### [ TIPS & TRICKS OF THE WEEK]

Data aids, not replace judgement
Data is a tool and means to help build a consensus to facilitate human decision-making but not replace it. Analysis converts data into information, information via context leads to insight. Insights lead to decision making which ultimately leads to outcomes that brings value. So, data is just the start, context and intuition plays a role.

### [ DATA SCIENCE Q&A]

Q:Given two fair dices, what is the probability of getting scores that sum to 4? to 8?
A: * Total: 36 combinations
* Of these, 3 involve a score of 4: (1,3), (3,1), (2,2)
* So: 3/36=1/12
* Considering a score of 8: (2,6), (3,5), (4,4), (6,2), (5,3)
* So: 5/36

Source

### [ VIDEO OF THE WEEK]

Discussing #InfoSec with @travturn, @hrbrmstr(@rapid7) @thebearconomist(@boozallen) @yaxa_io

### [ QUOTE OF THE WEEK]

Data matures like wine, applications like fish.  James Governor

### [ PODCAST OF THE WEEK]

@ReshanRichards on creating a learning startup for preparing for #FutureOfWork #JobsOfFuture #Podcast

Subscribe

### [ FACT OF THE WEEK]

More than 200bn HD movies  which would take a person 47m years to watch.

### Sourced from: Analytics.CLUB #WEB Newsletter

Patient experience (PX) has become an important topic for US hospitals.Â The Centers for Medicare & Medicaid Services (CMS) will be usingÂ patient feedback about their care as part of their reimbursement plan for acute care hospitalsÂ (seeÂ Hospital Value-Based Purchasing (VBP) program).Â According toÂ QualityNet, the purpoase of the VBP program is to promote better clinical outcomes for patients and improve their experience of care during hospital stays.Â Not surprisingly, hospitals are focusing on improving the patient experience to ensure they receive the maximum of their incentive payments. But what is the cost of a good patient experience? Does increased hospital spending on medical services translate into a better patient experience?

### Medicare Spending Per Beneficiary (MSPB)

Medicare tracks how much they spendÂ on each patient with Medicare who is admitted to a hospital compared to the amount Medicare spends per hospital patient nationally. Also known as “Medicare Spending per BeneficiaryÂ (MSPB)”, this measure assesses the cost of care.Â By measuring cost of care with this measure, CMS hopes to increase the transparency of care for consumers and recognize hospitals that are involved in the provision of high-quality care at lower cost to Medicare.

The MSPB measure for each hospital is calculated as the ratio of the MSPB Amount for the hospital divided by the median MSPB Amount across all hospitals. A hospital with an MSPB value of 1.o indicates that the hospital’s spending per patient is average. A hospital with an MSPB value less than 1.0 indicates that the hospital’s spending per patient is less than the average hospital. A hospital with an MSPB value greater than 1.0 indicates that the hospital’s spending per patient is greater than the average hospital.

### Patient Experience

Patient experience (PX) reflects the patients’ perceptions about their recent inpatient experience. PX isÂ collected by a survey known asÂ HCAHPSÂ (Hospital Consumer Assessment of Healthcare Providers and Systems).Â HCAHPS (pronounced “H-caps“)Â is a national, standardized survey of hospital patients and was developed by a partnership of public and private organizations andÂ was created to publicly report the patientâs perspective of hospital care.

The survey asks a random sample of recently discharged patients about important aspects of their hospital experience.Â The data set includes patient survey results for over 3800 US hospitalsÂ onÂ ten measures of patients’ perspectives of careÂ (e.g., nurse communication, pain well controlled). I combined two general questions (Overall hospital rating and recommend) to create a patient advocacy metric. Thus, a total of 9 PX metrics were used.Â Across all 9 metrics, hospital scores can range from 0 (bad) to 100 (good).Â You can see the PX measures for different US hospitalÂ here.

### The Relationship Between Medicare Spend and Patient Loyalty/Experience

Hospitals were divided into 10 groups based on their MSPB score. Figure 1 contains the plot of patient advocacy for each of the 10 MSPB levels. Figure 2 contains the plot of patient experience ratings for each of the 10 MSPB levels.

There were statistically significant differences across the 10 segments.Â Â Although these differences were statistically significant, the differences were not substantial. Specifically, the MSPB segments accounted for about 4.5% of the variance in patient metrics.

We might expect hospitals that spend more on medical services per patient would receive higher patient experience ratings. The patients are, after all, receiving more resources directed toward them compared to hospitals who spend less on medical services. If anything, we see that as the cost of care goes up, patient experience actually decreases (however slightly).

### Improving Patient Loyalty and the Patient Experience

Improving patient loyalty and the patient experience clearly does not start with medical spend. The results show that hospitals who spend less on medical services compared to other hospitals who spend more on medical services receive comparable marks on their patient experience and patient loyalty scores.

One possible approach to understand patient experience/loyalty differences across hospitals is to understand how hospitals build their patient experience (PX) programs. How mature is their PX program? Do they even have a PX program? In other industries, we know thatÂ loyalty leading companiesÂ structure their customer experience programs differently than loyalty lagging companies (see Figure 3). Specifically, loyalty leaders: 1) have top executive support of the customer program, 2) communicate all aspects of the program throughout the company and 3) integrate their customer feedback with other business data for deep dive customer research. I suspect these same processes (or something similar) are key to a successful PX program (e.g., high patient loyalty and patient experience) in the hospital setting. But that is an empirical question.

Research on the role of PX programs in hospitals would help hospitals better understand the necessary ingredients they need to improve the patient experience. Many hospitals receive very low marks on their HCAHPS ratings, suggesting they will be penalized on their Medicare payments. This PX program research needs to identifyÂ best practices. Findings could help individual hospitals improve their HCAHPS score by adopting/incorporating best practices into their PX programs. Additionally, findings could help the healthcare industry overall by sharing best practices across all hospitals that would remove inefficienciesÂ in healthcare delivery while improving patient satisfaction with their care.

## May 24, 18: #AnalyticsClub #Newsletter (Events, Tips, News & more..)

### [  COVER OF THE WEEK ]

Data Accuracy  Source

### [ FEATURED COURSE]

Statistical Thinking and Data Analysis

Rise of the Robots: Technology and the Threat of a Jobless Future

### [ TIPS & TRICKS OF THE WEEK]

Data Analytics Success Starts with Empowerment
Being Data Driven is not as much of a tech challenge as it is an adoption challenge. Adoption has it’s root in cultural DNA of any organization. Great data driven organizations rungs the data driven culture into the corporate DNA. A culture of connection, interactions, sharing and collaboration is what it takes to be data driven. Its about being empowered more than its about being educated.

### [ DATA SCIENCE Q&A]

Q:Name a few famous APIs (for instance GoogleSearch)
Source

### [ VIDEO OF THE WEEK]

#BigData @AnalyticsWeek #FutureOfData with Jon Gibs(@jonathangibs) @L2_Digital

### [ QUOTE OF THE WEEK]

If we have data, let’s look at data. If all we have are opinions, let’s go with mine.  Jim Barksdale

### [ PODCAST OF THE WEEK]

#FutureOfData with @theClaymethod, @TiVo discussing running analytics in media industry

Subscribe

### [ FACT OF THE WEEK]

Poor data can cost businesses 20%35% of their operating revenue.

## NSA to crunch big data in AWS C2S

WASHINGTON, D.C. – The National Security Agency is moving some of its IT operations to Amazon’s cloud.

The National Security Agency (NSA) was represented by Alex Voultepsis, chief of the engineering and planning process for the NSA’s Intelligence Community Special Operations Group, at a session during the AWS Public Sector Symposium here this week. Voultepsis said during a panel discussion the agency plans to migrate some of its infrastructure to Amazon Web Services (AWS).

Voultepsis’s unit within the NSA will use Commercial Cloud Services (C2S), the Amazon cloud region established by the Central Intelligence Agency for classified data, which is open to all 17 federal intelligence agencies, according to Amazon officials interviewed after the panel session.

“The capabilities are there to meet our specialized needs for confidentiality, integrity and availability [of data],” Voultepsis said. “We can shift our focus from commodity things to mission-focused customer-facing things.”

The NSA as a whole also operates a private cloud called GovCloud, but for Voultepsis’s unit, C2S offers better value.

“The infrastructure as a service which Amazon provides has shown us significant IT efficiencies,” Voultepsis said, estimating that the savings on infrastructure costs alone will be between 50-55%.

While it was unclear how much of the NSA’s data center had moved already, Voultepsis said the ultimate goal is to be ‘all-in’ and close private data centers.

“It’s a seismic shift in the way we do business,” he said. “We’ve moved away from the concept of putting our big toe in the water with hybrid cloud, because from an efficiencies perspective, if you don’t go all-in and turn off your old [assets], you never gain the efficienciesâ¦of intelligence integration and an enhanced security posture.”

Asked how he imagined the deployment looking in three to five years, Voultepsis said the agency is most looking forward to analyzing big data in AWS.

“The big data concept will come to fruition more broadly than it hasâ¦being able to ask questionsâ¦that you couldn’t ask in the past,” he said. “Federated, old-style dogpile type searches go away, and you’re asking complex questions against a broad corpus of data Â — complex questions that you couldn’t even dream of asking in the past.”

Other federal agencies in the intelligence community have also moved to C2S for new projects. The National Geospatial-Intelligence Agency (NGA) was also represented on the panel by Jason Hess, cloud security manager for the office of the chief information officer.

“We’ve embraced the director of national intelligence’sâ¦vision of providing intelligence integration,” Hess said. “We cannot continue to operate in the silo mentality of each agency not talking to each otherâ¦we’re leveraging this initiative to start working together.”

Hess and Kristine A Guisewite, information system security engineer from Raytheon working for the National Reconnaissance Office (NRO), agreed using C2S makes it easier for them to work together. It’s also easier for developers to do research on the platform with the wealth of knowledge available online, then execute specific projects inside the agencies. Having a consistent operating system image deployed to an entire agency also improves security over having to maintain different versions, Guisewite said.

However, there are still some issues with moving to the cloud. Auto Scaling, for example, has been difficult for the NRO to take advantage of, because of security concerns with machines spinning up and down, the security of external interfaces that require an opening in the firewall, and resources which aren’t always operating from the same IP address, according to Guisewite.

Unlike the NSA, the NGA is not ‘all-in,’ according to Hess. The NGA built a new building and state-of-the-art data center just three years ago that many in the agency are loath to abandon.

“It’s a coalition of the willing right now,” Hess said. “We’re in the bottom of the first [inning] in our cloud migration.”

## Healthcare Analytics Tips for Business Minded Doctors

The promise of data is huge â enormous clinical and financial rewards, less work, quantifying patient health habits and some form of IBMâs revered Watson supercomputer in every practice.

The 2012 U.S. Hospital Health Data Analytics Market report revealed that 50% of U.S. hospitals are expected to have implemented health data analytics tools by 2016, which represents an annual compound growth rate of 37.9%. In an ever-changing healthcare sector, itâs not wise for the private practice to be left behind.

Still, the industry faces serious technical and strategic challenges. Health data is diverse, complicated and unstructured across a range of criteria, making it very difficult for, say, a small practice doctor to penetrate â especially if he/she has limited experience operating in the tech sphere.

Below are some healthcare analytics tips for more business-minded physicians, no prior experience required.

Choose the right system for reporting. If youâre going to use analytics to better organize your business, donât choose an inefficient one thatâll further complicate matters. A recent KLAS report titled Business Intelligence: Making Cents of Performance outlines some helpful features that providers searching for (or currently using) analytics tools should keep in mind. These include:

• Quick implementation
• Easy-to-use interface
• Customizable to suit unique organizational needs
• Ability to develop personalized dashboards for users
• Flexibility to accommodate other parties like pharmacies, health plans, government entities, financial institutions, etc.

Integrate analytics with training. Practices should teach analytics to new hires, from staff members to doctors. This will help every member of the office understand how analytics data helps both patients and the execution of his/her daily tasks, to the point where seeing through data goggles becomes second nature.

Use dashboards for doctors at your practice to visualize data. As analytics move platforms closer to real-time processing and reporting â at the point of care, even â your practice should focus on updating processes and developing capabilities to enable analytics tool use, namely on the topic of real-time clinical decision support.

Use Google Analytics for online marketing efforts. Make sure your Google configuration is up to date and set up metrics goals for your website, e.g., conversion on opt-in forms, and engagement in the form of time on site and page depth.

Spot barriers to analytics adoption. According to an IBM study, titled âThe Value of Analytics in Healthcare,â many healthcare executives have a difficult time differentiating bad and good data.

If this is not the case, other common barriers include lack of data-driven culture, lack of connecting the power of analytics to business improvement tactics, lack of management bandwidth or a perception that costs outweigh benefits.

Adopt an EHR that provides business data. Some people are huge fans of 2-in-1 shampoo/conditioners combos. While this is a more a serious investment, purchasing an EHR system with a built-in analytics platform may be the right choice for practices that donât have the time or budget to seek solo solutions.

Humanize the data. While this may seem obvious, making the data accessible and friendly to humans â who will, after all, be employing, analyzing and making full use of it â is essential. In this case, usability may be the most crucial element of an effective analytics system because you and your staff simply will not use a tool that makes their jobs more difficult.

Source by analyticsweekpick

## May 17, 18: #AnalyticsClub #Newsletter (Events, Tips, News & more..)

### [  COVER OF THE WEEK ]

Data security  Source

### [ FEATURED COURSE]

Artificial Intelligence

Research Design: Qualitative, Quantitative, and Mixed Methods Approaches, 4th Edition

### [ TIPS & TRICKS OF THE WEEK]

Fix the Culture, spread awareness to get awareness
Adoption of analytics tools and capabilities has not yet caught up to industry standards. Talent has always been the bottleneck towards achieving the comparative enterprise adoption. One of the primal reason is lack of understanding and knowledge within the stakeholders. To facilitate wider adoption, data analytics leaders, users, and community members needs to step up to create awareness within the organization. An aware organization goes a long way in helping get quick buy-ins and better funding which ultimately leads to faster adoption. So be the voice that you want to hear from leadership.

### [ DATA SCIENCE Q&A]

Q:Give examples of data that does not have a Gaussian distribution, nor log-normal?
A: * Allocation of wealth among individuals
* Values of oil reserves among oil fields (many small ones, a small number of large ones)

Source

### [ VIDEO OF THE WEEK]

Understanding #Customer Buying Journey with #BigData

### [ QUOTE OF THE WEEK]

Hiding within those mounds of data is knowledge that could change the life of a patient, or change the world.  Atul Butte, Stanford

### [ PODCAST OF THE WEEK]

#BigData @AnalyticsWeek #FutureOfData #Podcast with @MichOConnell, @Tibco

Subscribe

### [ FACT OF THE WEEK]

Every second we create new data. For example, we perform 40,000 search queries every second (on Google alone), which makes it 3.5 searches per day and 1.2 trillion searches per year.In Aug 2015, over 1 billion people used Facebook FB +0.54% in a single day.

## How to Win Business using Marketing Data [infographics]

A marketer’s job is to win the hearts and minds of customers and prospects. Even though priority is to clearly accounts for the intricacies of customerâs intellects and emotions, often major of it is in using intellectual triggers and minor of it is in connecting with them emotionally. It has consistently been overlooked. The fact that, when wielded correctly, emotion is a much more potent persuasive force in forging connections than intellect. Following infographic explains how various channels are being utilized and how they are acting to make the business successful.

Source

## May 10, 18: #AnalyticsClub #Newsletter (Events, Tips, News & more..)

### [  COVER OF THE WEEK ]

Data security  Source

### [ FEATURED COURSE]

Probability & Statistics

Data Science for Business: What You Need to Know about Data Mining and Data-Analytic Thinking

### [ TIPS & TRICKS OF THE WEEK]

Analytics Strategy that is Startup Compliant
With right tools, capturing data is easy but not being able to handle data could lead to chaos. One of the most reliable startup strategy for adopting data analytics is TUM or The Ultimate Metric. This is the metric that matters the most to your startup. Some advantages of TUM: It answers the most important business question, it cleans up your goals, it inspires innovation and helps you understand the entire quantified business.

### [ DATA SCIENCE Q&A]

Q:What are feature vectors?
A: * n-dimensional vector of numerical features that represent some object
* term occurrences frequencies, pixels of an image etc.
* Feature space: vector space associated with these vectors

Source

### [ VIDEO OF THE WEEK]

Understanding #BigData #BigOpportunity in Big HR by @MarcRind #FutureOfData #Podcast

### [ QUOTE OF THE WEEK]

In God we trust. All others must bring data.  W. Edwards Deming

### [ PODCAST OF THE WEEK]

#BigData @AnalyticsWeek #FutureOfData #Podcast with @MPFlowersNYC, @enigma_data

Subscribe

### [ FACT OF THE WEEK]

And one of my favourite facts: At the moment less than 0.5% of all data is ever analysed and used, just imagine the potential here.

## A Super Scary Halloween Story for Data Scientists and other Change Agents

As the mistÂ swirled and parted,Â the SeerÂ suddenly appeared before me. He was barely recognizable as human. His skin wasÂ deeplyÂ etched fromÂ aÂ hundred winters spent roaming theÂ barren peaksÂ and cragsÂ of Mount Olympus. He regarded me with his one good eye, and croaked words that chilled the air around us… “Hey, wassup? What can I do you for? And make it snappy, ’cause I’ve gotÂ baklava in the oven. You know how easy it is to burn baklava?”

“Oh, Seer, I’ve come a long way to ask you something that’s been troubling my soul for a very long time. I’ve been involved in many projects where a centralized Data ScienceÂ team triesÂ to help internal customers from a business unit leverage analytics in some way. I’ve seenÂ mixed results. What’s the secret to a successful analytics engagement with internal business customers? How can I get them to cooperate with me, to take my findings seriously, and above all to actually implement changes to business processes based on my findings?

The SeerÂ smiled. Or was it a sneer? “Can you handle the truth?” he said.

That sounded vaguely familiar… “Didn’tÂ Jack Nicholson say that in…”

“JackÂ got it from me!” the Seer snapped. “Can you handle the truth?”

“I… think so…”, I sputtered. “Yes! Give it to me straight!”

The contempt-o-meter

“Here’s the thing.” said the Seer,Â sniffing the air for the slightestÂ hintÂ of burning baklava. “As soon as you start having feelings of contempt for your internal customers – let’s call them your clientsÂ for short – you’re done. Cash in your chips. Go home. It’s over. Humans are exquisitely fine-tunedÂ to sense the feelingsÂ of others. It’s simply impossible toÂ hide your feelings of contempt from your clients. And nobody wants to workÂ with some pretentious jackassÂ who they sense isÂ always looking down on them .”

“Well, no problem there!” I preened. “I pride myself on always being professional and respectful towards my clients.”

Oh, really?” he said, his smile-sneer growing wider.

“Clients can sense how you feel about them. Ever sat in a meetingÂ with your clients,Â and thought to yourselfÂ that you’reÂ surrounded by mouth breathing knuckle draggers?”

“Well… ”

“I…. ”

“TheyÂ canÂ sense how you feel about them. Ever… ”

“Okay, okay, I get it. I can see how thinking about myÂ clients like that is not going to win me their cooperation or help me beÂ anÂ effective Data Scientist, which isÂ all about changing a company’s behavior in some way, whether big or small. But exactly how canÂ I silenceÂ myÂ judgmentalÂ internal dialog?”

First things first

“Build empathy for your clients. Empathy… AÂ good, solid Greek word if there ever was one. And empathy in the context of cross-organizationalÂ relationships is not about moral virtue. It’s about getting thingsÂ done that are good forÂ the business, and good for your career at the same time. Oh, and you can’t fake empathy. The contempt radar that I mentioned earlier? Yeah, it also detects insincerity.”

A piece of the Seer’s ear fell off, but it didn’t seem to bother him.

“But before we get into my specific adviceÂ for increasing your empathyÂ for internal customers,” he said, “you have to be honest with yourself. Do you really giving a rat’s ass about their happiness? Really? If yes, then continue. If not, then go back to raising your goats, or practicing your lute, or weaving your baskets from found human hair to sell on Etsy. Building empathy is very hard work. But it’s also the only path I’ve found to delivering happiness to internal customers, which turns out to be the golden roadÂ to effectiveness as you’ve defined it. So, do you have a heartfelt desire to make your clientsÂ happy?”

I nodded.

You’re wrong. You’re just wrong.

“What if I told you that everything you know is a lie?” quizzed the Seer. I was expecting him to launch into the whole red-pill blue-pill thing, but he skipped it.

Beginner’s mind

The SeerÂ took another whiff of air, like an Irish Setter on the scent.

“Here’s one idea forÂ cultivating authentic empathy. Two mountains over there are these Buddhists. They’re an absolute riot at my fondue parties, by the way… Anyhow, they talk about the importance of having aÂ beginner’s mind. It means that, regardless ofÂ how many decades you’ve been practicingÂ meditation, you should approach each new meditation session as if it were your firstÂ time meditating. You should approach it with anticipation, curiosity, and an openness to being surprised.”

“What if you took the same kind of approach to your internal customers?”

On notÂ peeing into the wind

“For example: What if you took them toÂ lunch, and asked them questions that helped you to deeply understand what makes them tick at work:

1) What brings them joy in their job?
3) What are their career aspirations?
4) What makes their boss praise them?
5) What makes their boss yell at them?
6)Â What must they do to achieveÂ their jobÂ goals (and hence their bonus)?

“You were expecting project-related questions, right?” the Seer sneer-smiled.

“The truth is, nobody gives a sh*t about your equations and graphs, per se. But they deeply give a sh*tÂ about how your equations and graphs mightÂ impact them along those personal dimensions, both positively and negatively. They’ll never say so, but they do. They might not even consciously realize it, but they do.”

“So, what I’m saying is, as you think about how you are going to get your Brilliant Data Science Idea implemented, deconstructÂ those personal dimensions of your clients, and thenÂ explain the benefits of your Brilliant Data Science Idea to them in ways thatÂ addressÂ those personal dimensions.”

“But isn’t that manipulative?, you ask. Only if it’sÂ done with malice, I answer.”

“Here’sÂ an analogy. You are outÂ sailing on the wine dark sea, and you wantÂ to get your little boatÂ from point A to point B, because you’ve heard that the feta is amazing at point B. Isn’t it wise to considerÂ where the winds are blowing, and where the shoals are lurking, and to get aligned with the great forces of nature, rather than be willfully ignorantÂ of them?Â Â Isn’t it better to leverageÂ those forces, rather than to fight them? Where is the manipulation and malice in that?”

“Look, I don’t expect you to just take my word for it. Try it for yourself. Experiment with it. Play with it. Then come back and tell me how it went.”

Baklava’s done

The sweet smell of freshly baked baklava was now competing with the Seer’s formidable stench. “I love the smell of baklava in the morning!” said the Seer.

“Thanks for the advice,” I said. But it sounds like very hard work. Interpersonal skills… Change managementÂ strategies…. TheseÂ are not exactly part of the standard Data Science repertoire.”

“True dat,” said the Seer, winking at me with his one good eye.

“But luckily you don’t have to be perfect at it. Because you know what they say… In the land of the blind, the one-eyed man is…”

And with that, the SeerÂ was gone.

Before we begin, here’s a working example of this quick Facebook app on my Github 🙂

There are a few (or a lot, depending on your excitement) cool things you can do with the Facebook Graph API.

First of all, what is the Graph API?

1. In short, it’s our way ofÂ gettingÂ Facebook goodies like posts, pictures, status updates, friends list, all that good stuff. We can alsoÂ post data (AKA update our status) using the Graph API.

For this mini blog tutorial, I’m going to cover theÂ gettingÂ part.

#### In particular, I’ll be demonstrating how toÂ find:

I’ll be using JavaScript and Python for this tutorial. No worries if these languages aren’t your go-to; the concepts I cover in this tutorial are constant across all languages.

Let’s roll.

## 1.Â Boilerplate (boring stuff) out of the way

First, let’s set up a very simple JavaScript SDK so we can talk to Facebook using JavaScript.

I didn’t want to waste precious code space with boilerplate code, so check it out my Github

## 2. Basic GET request

Let’s do a basic GET request. Let’s get all my posts, messages, stories along with the likes and comments associated with each post.

```function getPosts() {
function(response) {
passPosts(JSON.stringify(response))
});
}
```

Ignore the passPosts() function for now

This returns a JSON response as such:

```{
"data": [
{
"story": "Nikhil Bhaskar updated his profile picture.",
"id": "[id of post]",
"likes": {
"data": [
{
"id": "[id of liker]"
"name": "[name of liker]"
},
],
"summary": {
"total_count": [num of likes],
"can_like": true,
"has_liked": false
}
},
....{}, {}, {}
],
"paging": {
"previous": "[url]",
"next": "[url]"
}
}
```

Notice how our result has beenÂ paginated. In other words, to actually get all of our posts, we need to run an API call again, on the “paging”:”next”:Â url.

We shouldÂ avoid multiple API calls whenever necessary, so let’s slightly modify our basic GET request.

```'me/posts/?limit=5000&fields=comments.summary(true),likes.summary(true).fields(name), message,  story'
```

Notice how now, we include a limit of 5000 posts. It seems to me that this is the max limit we can set (I’m not sure; it was more trial & error here). This way, we get as many posts as we can in one API call. Consequently, we greatly reduce the number of API calls we make.

#### Learner’s check:

1. Our ‘response’ object is a JavaScript object. In order for us to easily pass it around we convert it to a string with JSON.stringify()

## 3. AJAX call to Python

Let’s pass our JSON response to our Python backend so we can further process it.

```function passPosts(userPosts){
\$.ajax({
method: "POST",
data: {
"user_posts": userPosts
}
})
.success(function(data) {
//handle results
});
}
```

#### Learner’s check

1. We call our AJAX function (POST) to the url route ‘fb_login’, with our userPosts

## 4. Python ~ Get the AJAX POST data

Side note: I am using Django. You can use whatever framework (or no framework) you want

InÂ views.py,Â let’s get our Facebook API response:

```def fb_login(request):
if request.method == 'POST':

all_posts_dict = get_all_posts_dict(request.POST['user_posts'])

'''Ignore rest of function for now
all_posts_dict['data'] = remove_dicts_from_list_based_on_key(all_posts_dict, 'likes')

my_most_liked_post = sort_posts_dict_by_likes(all_posts_dict)[0]
print my_most_liked_post
'''
```

#### What does ‘get_all_posts_dict(arg)’ do?

```def get_all_posts_dict(response):
```

#### As you can see, it calls 2 functions. So it does 2 tasks:

1. Convert our response to a Python dictionary
2. Call a function on this dictionary to get all of our posts (remember, the JSON response we got was paginated)

Here, we achieve task 1 with our string_to_dict function:

```def string_to_dict(json_string):
```

And here, we call a recursive function tornado_all_posts_dict to achieve task 2:

```def tornado_all_posts_dict(response_dict, master_posts = None ):
master_posts = {'data':[]} if master_posts is None else master_posts
posts = response_dict['data']
master_posts['data'] = master_posts['data'] + posts
if 'paging' in response_dict and 'next' in response_dict['paging']:
r = requests.get(response_dict['paging']['next']).json()
return master_posts
```

## 5. Find your most liked posts

We gotta do a little clean up, first.Â As you’ve noticed, the all_posts_dict is a Python dictionaryÂ with a “data” property.

“data” is a list of several dictionaries. Each dictionary in “data” is basically a post/message/story, etc. The problem is that some of these dictionaries don’t have a “likes” property.

Example:

```{
"id": "[id]"
}, ...
```

These are probably just occurrences when you change your cover photo to a photo you’ve already used before, for example. Although there are “likes” associated with your cover photo, there are no “likes” associated with the act of updating your cover photoÂ back to this old picture. Make sense?

So, let’s remove all the dictionaries in “data” that have no “likes” property

```def remove_dicts_from_list_based_on_key(response_dict, key):
the_list = response_dict['data']
return [dicti for dicti in the_list if key in dicti]
```

```all_posts_dict['data'] = remove_dicts_from_list_based_on_key(all_posts_dict, 'likes')
```

Now, we can sort our all_posts_dict by “likes”:

```def sort_posts_dict_by_likes(response_dict):
list_of_user_post_objects = response_dict['data']
list_of_user_post_objects = sorted(list_of_user_post_objects, key=lambda k: -k['likes']['summary']['total_count'])
return list_of_user_post_objects
```

#### Learner’s check

1. “likes” has a “summary” property, which in turn has a “total_count property”
2. “total_count” is the number we care about here
3. -k because are sorting in descending order

Now, in views.py, the def fb_login function should look like this:

```def fb_login(request):
if request.method == 'POST':

all_posts_dict = get_all_posts_dict(request.POST['user_posts'])
all_posts_dict['data'] = remove_dicts_from_list_based_on_key(all_posts_dict, 'likes')

my_most_liked_post = sort_posts_dict_by_likes(all_posts_dict)[0]
print my_most_liked_post

```

Our response:

```{u'message': u'AHAHAHAHHA', u'id': u'1090366184360236_310878925642303', u'comments': {u'data': [], u'summary': {u'total_count': 171, u'can_comment': True, u'order': u'chronological'}}, u'likes': {u'data': [], u'summary': {u'total_count': 1643, u'has_liked': False, u'can_like': True}}}
```

This was a post I shared a long time ago. Got over a 1000Â likes, haha

Obviously, our actual result is justÂ a Python dictionary. But you can use its id to get everything associated with this post.

Let’s move on..

## 6. Find your biggest fans

First, let’s put every single friend who liked your posts into a list of tuples. This tuple will contain the id and name of your friend

```def liker_ids_tornado(response, like_ids_list = None):
like_ids_list = [] if like_ids_list is None else like_ids_list
data_list = response['data']

for post_message_story in data_list:
if 'likes' in post_message_story:
for liker in post_message_story['likes']['data']:
like_ids_list.append((liker['id'], liker['name']))
if 'paging' in response and 'next' in response['paging']:
r = requests.get(response['paging']['next']).json()
return like_ids_list
```

Now, let’s use the convenient Counter() function from the ‘collections’ module

```def get_most_likers(like_ids_list):
id_results_dict = Counter(like_ids_list)
return id_results_dict
```

Here’s what our def fb_login function looks like now:

```def fb_login(request):
if request.method == 'POST':

all_posts_dict = get_all_posts_dict(request.POST['user_posts'])
all_posts_dict['data'] = remove_dicts_from_list_based_on_key(all_posts_dict, 'likes')

my_biggest_fans = get_most_likers(like_ids_list)
print my_biggest_fans

```

Our response:

```Counter({(u'id', u'Name'): 101, (u'id2', u'Name2'):97...})
```

The result is a Counter, which is a subclass of a Dictionary. So, my ‘biggest fan’ (who I won’t disclose here) has given me a total of 101 likes.

There you have it. A little Facebook insight for ya.

Enjoy 🙂

Once again, here’s a working example of this quick Facebook app on my Github 🙂