Category Archives: Uncategorized

39Metatags

<title>relevant and attractive phrase </title>

<meta name="description" content="text">

<meta name="keywords" content="words">

<meta name="robots" content="selection">

<meta name="revisit-after" content="period">

<meta name="copyright" content="text">

<meta name="googlebot" content="noodp">

<meta name="language" content="English">

<meta name="reply-to" content="email address">

<meta name="web_author" content="text">

<meta http-equiv="name" content="value">

<meta name="ROBOTS" CONTENT="NOARCHIVE">

<meta name="GOOGLEBOT" CONTENT="NOSNIPPET">

meta name="identifier-URL"CONTENT="http://www.your-domain-name.com/">

<meta name="distribution" CONTENT="Global">

<meta name="note" CONTENT="place extra keywords here">

<meta name="subject" CONTENT="your website’s subject">

<meta name="copyright"CONTENT="company name">

<meta name="language" CONTENT="ES">

<meta name="version" CONTENT="MT5.1"

<meta name="generator" CONTENT="program"

<meta name="id" CONTENT="sitebuilder-software"

<meta name="rating" CONTENT="general"

<meta name="presdate" CONTENT="date"

<meta name="template" CONTENT="basisdoc.html"

<meta name="operator" CONTENT="John Smith"

<meta name="creation_date" CONTENT="date"

<meta name="host" CONTENT="www.metatags.org"

<meta name="host-admin" CONTENT="Mike Demo"

<meta name="contactName"CONTENT="Mr. E. Xample">

<meta name="contactOrganization" CONTENT="Company XYZ inc.">

<meta name="contactStreetAddress1"CONTENT="Mainstreet 123">

<meta name="contactZipcode"CONTENT="98979">

<meta name="contactCity"CONTENT="New York">

<meta name="contactCountry"CONTENT="USA">

<meta name="contactPhoneNumber" CONTENT="+1 123 6382824">

<meta name="contactFaxNumber"CONTENT="+1 123 5566779">

<meta name="contactNetworkAddress"CONTENT="your">

<meta name="linkage" CONTENT="http://www.meta-information.com/">

BuildMining rig

In March2017, the price of an Ether cryptocurrency token rose to an all-time high of around $25. This was good news for investors in Ethereum—the blockchain-based distributed computing platform that uses Ether as its currency—who had watched the cryptocurrency’s price stagnate at under $10 since its launch in July 2015. But it also had another profound effect on shaping the network: For the first time ever, it was truly profitable to mine Ether.

ADVERTISEMENT

I had been entertaining the idea of building an Ethereum mining rig for months and the price surge in May made it seem like as good a time as any to begin the process. So I sold some of my Ether, bought some computer hardware, and set to work learning about building PCs and the art of Linux.

But before I dive into the unnecessarily painful process of setting up an Ethereum mining rig as a complete n00b, let’s brush up on some Ethereum basics.

Mining is the term used to describe the process of extracting cryptocurrency tokens from a blockchain network. In the case of Ethereum, this involves having computers continuously run a hashing algorithm, which takes an arbitrarily large amount of information and condenses it to a string of letters and numbers of a fixed length. The hashing algorithm used by Ethereum— called ethash—hashes metadata from the most recent block using something called a nonce: a binary number that produces a unique hash value. For each new block in the blockchain, the network sets a target hash value and all the miners on the network try to guess the nonce that will result in that value.

Due to the way cryptographic hashing works, trying to guess the nonce that will result in the target value is practically impossible. This means that the only way of finding the correct nonce is by cycling through every possible solution until a correct one is eventually found. This is "proof-of-work," which means the computer which discovered the correct nonce must’ve actually done the work (i.e., used computing power to run the hashing algorithm) to arrive at that value. The miner that finds the correct nonce is then awarded the block, receives 5 ether, and the process then begins anew in a cycle that recurs about every 12 seconds.

Six RX 470 GPUs installed in my Ethereum mining rig. Yes, those are zip ties. Image:Daniel Oberhaus/Motherboard
Okay so that’s the big picture, but what does this look like on the mining side of things? For starters, a rig is going to need some serious processing power. This is best accomplished with Graphics Processing Units (GPUs), which are generally used for 3D graphics for video games. Although it’s possible to mine with Central Processing Units, which are generally responsible for linking up all the right hardware and software in a computer, GPUs are optimized to run similar operations over and over again—which makes them perfect for hashing on the Ethereum blockchain.

This is where the problems begin. Now that the cost of electricity to mine Ethereum is far less than the worth of the Ether being mined, there has been a boom in the number of miners on the Ethereum blockchain. Until cryptocurrencies came around, GPUs were the sole purview of PC gamers, but now that they can also be used for mining, there is a complete shortage of GPUs on the market. Unless you’re trying to buy used hardware, tracking down a GPU will be difficult for the foreseeable future.

ADVERTISEMENT

Read More: Cryptocurrency Mining is Fueling a GPU Shortage

I was fortunate enough to have secured six RX 470 GPUs right as the price of Ether started skyrocketing. Still, at this point GPUs were incredibly difficult to track down and I had to settle in terms of performance. But this was better than nothing—within hours of ordering my GPUs, the site had sold out of the rest of its stock.

If you’ve somehow managed to get your paws on some graphics cards, the next task is finding a motherboard and power supply unit that can handle all of your GPUs running at once. For this task, I got an MSI Z170a motherboard and a 1200 watt Corsair power supply. Each GPU will use anywhere from 100-250 watts of power. Mine average around 120 watts apiece, which puts the total rig around 800 watts. Power supply units function optimally at around three-quarters of their total load capacity, so a 1200 watt PSU suited my needs.

You’re also going to need some powered risers since six GPUs are not going to fit directly into the PCI slots on any motherboard. These also allow you to suspend the GPUs above the motherboard in your case which helps to dissipate heat and allow air to flow through the rig.

I used a dual core Intel processor with 2.8GHz and a 4GB TForce stick for my CPU and RAM, respectively. It’s nothing fancy, but mining Ethereum doesn’t require your computer to do much multitasking so cheaper CPUs and RAM will do the trick.

The motherboard setup. On the left is the 1200 W power supply unit. Each of those blue USB cables is connected to a powered riser which links the GPUs above to the motherboard. Image: Daniel Oberhaus/Motherboard
The final element on the hardware side of things was the rig’s case. Your typical PC case isn’t going to fit six graphics cards, so a custom case is necessary. A lot of companies sell pre-made mining rig cases online, but these can cost upwards of $150 and seemed easy enough to build myself. I made mine with some aluminum angles I had cut at a local hardware store, a few wooden boards for mounting the motherboard, a few dozen self-driving screws, and a power drill.

All told, the process of making a case took about an hour and cost a little under $50. When added to the total price of the hardware for the rig, my bill came to a little over $2000.
Now that the computer is all set up and looking nice*, it’s time for the software.

(* It is said that beauty is in the eye of the beholder. Motherboard staff writer Jason Koebler saw my machine and described it as "Not Safe for Life." Motherboard news editor Emanuel Maiberg described it as "filthy." Clearly, neither of them have any taste.)

Here your options are relatively limited: you can run your rig on Windows, Linux, or ethOS. Windows has the benefit of better driver support for your graphics cards and EthOS is a plug and play solution for anyone who doesn’t know Linux and isn’t trying to learn.

But half the reason I wanted to set up an Ethereum mining rig in the first place was to give myself an excuse to learn Linux, so I decided to set up my software the hard way. First I had to download and install Xubuntu, a lightweight version of the popular Ubuntu Linux distribution, onto my motherboard. This involved writing a Linux disc image file to a 32 GB USB stick, and plugging that USB stick into the motherboard. Easy enough.

Next, I had to download the graphics drivers for my AMD GPUs so that they could communicate with the motherboard and do parallel processing. These drivers are free on AMD’s website and their installation is easy enough using a few commands in the Ubuntu terminal. Finally, it was time to download Geth, which is program used to implement commands on my Ethereum node. After downloading the blockchain and pointing my rig to a wallet I had already set up on Mist, it was time to start mining.

Out of the box, my 6 GPUs had a total hashing power of around 120 MH/s—that’s 120 million hashing operations per second. By tweaking the settings for my GPUs, I hope to increase this to between 125 and 130 MH/s, but that’s about as good as I’ll get with these cards. This may sound like a lot, but the total Ethereum network has a hashrate of around 39.1 TH/s at the time of writing. That’s 39 trillion hashing operations per second, which makes my rig just a drop in this ocean of computing power.

Since Ether is rewarded based on discovering the correct nonce, the odds of this happening increase the more hashing operations you are able to work through each block. If I were to try to do this on my own using my rig, it could be months before I ‘won’ a single block.

Most other miners are in the same boat as I am and don’t have access to huge mining farms like Genesis. So to increase their odds, small miners band together in mining pools, which combine each individual miner’s computing power to hash blocks. With combined computing power, mining pools are able to solve a block every few minutes, and the reward of this block is distributed to the miners in that pool in proportion to the work they did to help solve it. This means you might make only a few thousandths of an Ether each day, but over time this adds up—especially if the price of Ether keeps increasing.

Each pool has different requirements and fees for joining. Although I am only contributing 120 MH/s to the pool I joined, this will result in about 35 Ether per year for my rig. Based on the mining difficulty and price of Ether at the time of writing, this should be nearly $8,000 per year after electricity costs.

So there you have it—a total Linux n00b with no previous PC building experience was able to get an Ethereum mining rig up and running with minimal difficulty (aside from some faulty hardware). So maybe building a PC isn’t so hard after all.

Showtimes at Regal Prince Kuhio 9 Wed, Dec 20 All times are in HST

Star Wars: The Last Jedi
Standard
12:00 PM
3:30 PM
7:00 PM
10:30 PM
3D
12:30 PM
4:00 PM
7:30 PM
Jumanji: Welcome to the Jungle
Standard
11:00 AM
1:50 PM
4:40 PM
7:30 PM
3D
10:20 PM
The Greatest Showman
Standard
11:20 AM
2:00 PM
4:40 PM
7:20 PM
10:00 PM
Ferdinand
Standard
11:05 AM
2:00 PM
4:30 PM
7:25 PM
9:55 PM
Coco
Standard
11:10 AM
1:40 PM
4:20 PM
7:10 PM
9:40 PM
Wonder
Standard
11:05 AM
1:45 PM
4:30 PM
7:15 PM
9:55 PM
Justice League
Standard
11:10 AM
1:40 PM
4:35 PM
7:05 PM
10:05 PM
Thor: Ragnarok
Standard
12:20 PM
3:40 PM
7:00 PM
10:00 PM

USA jails 1 of every 100

NO COUNTRY imprisons a larger share of its people than America. Its incarceration rate—693 of every 100,000—is nearly five times Britain’s, six times Canada’s and 15 times Japan’s. And that rate masks huge variations: Washington, DC, Louisiana and Georgia each lock up more than one in every 100 residents. Why?

“Blind Injustice” tries to answer that complex question from an unusual perspective. The author, Mark Godsey, used to be a federal prosecutor in New York. He went on to co-found the Ohio Innocence Project, which works to free the wrongly convicted. His book is about how his career change also changed his outlook, by showing up “problems in the system that I, as a prosecutor, should have seen, but about which I had simply been in denial”.

And it is about the police and prosecutors who uphold that system—the “normal, regular people…who would help an old man cross the road, or who would shovel the snow from a sick neighbour’s driveway, [but who] go back to their offices and commit acts of heartbreaking, callous injustice…because they are operating under a bureaucratic fog of denial.” Each of Mr Godsey’s six central chapters centres on a different systemic flaw: denial, ambition, bias, memory, intuition and tunnel vision.

People in all fields, of course, commit these deeply human sins. Tunnel vision, conformity born of a desire to please bosses and not to rock the boat, answering difficult questions not by trying to work out the right answer but by determining what is best for your team: such behaviour is not unique to America’s criminal-justice system. But for police and prosecutors, it can deprive people of their liberty and lives. Last month, for instance, Wilbert Jones left a prison in Baton Rouge, Louisiana, after almost 46 years. A judge threw out his conviction for rape because the prosecution failed to turn over to the defence evidence that might have helped his case (the state is appealing). Mr Jones entered prison at 19; he is now 65.

Mr Godsey’s work is memorable because he is able to show precisely how these flaws work in action. He describes prosecutors routinely denying requests to give inmates DNA tests, even though these could help free them. Prosecutors think of themselves as the good guys and, therefore, their opponents as bad. This leads to routine dehumanisation, such as when prosecutors in Chicago competed in a “two-ton contest” to see who could be the first to indict 4,000lb of human flesh (which led prosecutors to be especially hard on overweight defendants).

He is particularly—and with good reason—tough on elected judges, who know that being “tough on crime” will always win more votes than promises of sober fairness and probity; and on forensic science, a contributing factor in nearly half of all wrongful convictions (second only to false eyewitness accounts). He ends the book on a hopeful note, though. States across the country are implementing some of the changes he recommends. These include recording interrogations, standardising eyewitness-identification procedures, expanding access to post-conviction DNA testing and, perhaps most important, opening conviction-review boards inside prosecutors’ offices, to investigate post-conviction claims of innocence.

If Mr Godsey focuses on how people are unjustly jailed, Lauren-Brooke Eisen, a former lawyer now at New York University, has written a deeply researched, scrupulously fair book about private prisons, which house 126,000 people in America, or 7% of state inmates and almost 18% of federal prisoners. They are opaque in a way that state prisons are not; despite the book’s title, Ms Eisen barely manages to get inside a private prison.

Some liberals cast private prisons as a driver of mass incarceration. Their business model is built around it and, as Ms Eisen notes, they have lobbied for policies that have helped them. Some feel that profiting from other people’s incarceration is inherently immoral, or that it violates constitutional protections against involuntary servitude and cruel and unusual punishment.

But Ms Eisen convincingly argues that they are a symptom, rather than a cause, of America’s over-punitive, carceral state. Private prisons took off because governments could not build prisons quickly enough to hold all the people they sentenced. Now private-prison firms are diversifying with the times by building treatment centres and electronic-monitoring services as America’s justice system explores alternatives to imprisonment. Some may find it depressing that these firms are simply looking for another way to profit from society’s unfortunates. But it also shows that these companies respond to political demand, and that the best way to do away with private prisons is to lock up fewer people.

Beat worry

….

1. Ask yourself, “What’s the worst that can happen?”

There’s a simple three-step technique that can help when you’re besieged by personal or professional worries.

First, ask yourself what’s the worst that could possibly happen. Second, prepare to accept the worst. Finally, figure out how to improve upon the worst, should it come to pass.

This technique is based on an anecdote from Willis Carrier, founder of the modern air-conditioning industry. While working for the Buffalo Forge Company as a young man, Carrier found that a new gas-cleaning service his company provided wasn’t as effective as he’d hoped.

Carrier realized that the worst that could happen was that his company would lose $20,000. He then accepted it: The company could qualify the loss as the cost of researching a new strategy. Finally, he figured out how to improve the situation: If the company bought $5,000 worth of new equipment, they could resolve the issue. Ultimately, that’s exactly what they did, and they ended up making $15,000.

2. Gather all the facts in an objective way

As Herbert E. Hawkes, former dean of Columbia College, told Carnegie, “If a man will devote his time to securing facts in an impartial, objective way, his worries will usually evaporate in light of knowledge.”

two ways to go about collecting facts objectively. You can pretend that you’re gathering this data for someone else, so you’re less emotionally invested in what you find.

Or you can pretend that you’re a lawyer who is preparing to argue the other side of the issue — so you gather all the facts against yourself. Write down the facts on both sides of the case and you’ll generally get a clearer picture of the truth.

3. Generate potential solutions to the problem

Leon Shimkin, then general manager at Simon and Schuster (he later became the owner), figured out a way to cut the time he spent in meetings by 75%.

He told his associates that every time they wanted to present a problem at a meeting, they had to first submit a memorandum answering four questions: What is the problem? What is the cause of the problem? What are all possible solutions of the problem? What solution do you suggest?

According to Shimkin, once he instituted this new system, his associates rarely came to him with their concerns.

“They have discovered that in order to answer those four questions they have to get all the facts and think their problems through,” he told Carnegie. Once they did that, they typically found that “the proper solution has popped out like a piece of bread popping out from an electric toaster.”

In other words, action replaced worrying and talking.

4. Remember the law of averages

The law of averages refers to the probability of a specific event occurring — and you should consult the law to find out if it’s worth fretting. Chances are good that whatever you’re worried about isn’t likely to transpire.

Carnegie writes that the U.S. Navy employed the law of averages in order to boost sailors’ morale. Sailors who were assigned to high-octane tankers were initially worried that they would be blown up when the tank exploded. So the Navy provided them with exact figures: Of the 100 tanks that were hit by torpedoes, 60 stayed afloat and only five sank in less than 10 minutes, leaving time to get off the ship.

5. Place stop-loss orders on your worries

This strategy is based on a principle in stock trading. One investor said he set a stop-loss order on every market commitment he made. Here’s how it works: Say you buy a stock that sells for 100 dollars a share and set a stop-loss order for 90 dollars a share. As soon as that stock dips to 90 dollars a share, you sell it — no questions asked.

You can use this principle in everyday life. For example, Carnegie once wanted to be a novelist, but after two years of toiling away without much success, he decided to cut his losses and go back to teaching and nonfiction writing.

Isis

Why ISIS is dwindling in Iraq and Syria
The U.S. military estimates the terror group now controls just 3 percent of Iraq and only 5 percent of Syria after the fall of Raqqa.

BAGHDAD – Hundreds of ISIS fighters had just been chased out of a northern Syrian city and were fleeing through the desert in long convoys, presenting an easy target to U.S. A-10 "warthogs."

But the orders to bomb the black-clad jihadists never came, and the terrorists melted into their caliphate — living to fight another day. The events came in August 2016, even as then-Republican presidential nominee Donald Trump was vowing on the campaign trail to let generals in his administration crush the organization that, under President Obama, had grown from the “jayvee team” to the world’s most feared terrorist organization.

U.S. Air Force Brig. Gen. Andrew Croft said the Trump administration has put a strong leadership team in place.
“I will…quickly and decisively bomb the hell out of ISIS,” Trump, who would name legendary Marine Corps Gen. James Mattis as secretary of defense, promised. “We will not have to listen to the politicians who are losing the war on terrorism."

ISIS CURSED, MOCKED IN MOSUL, WHERE OLD CITY REMAINS A HAUNTED WASTELAND

Just over a year later, ISIS has been routed from Iraq and Syria with an ease and speed that’s surprised even the men and women who carried out the mission. Experts say it’s a prime example of a campaign promise kept. President Trump scrapped his predecessor’s rules of engagement, which critics say hamstrung the military, and let battlefield decisions be made by the generals in the theater, and not bureaucrats in Washington.

"I felt quite liberated because we had a clear mandate and there was no questioning that.”

– U.S. Marine Col. Seth Folsom
At its peak, ISIS held land in Iraq and Syria that equaled the size of West Virginia, ruled over as many as 8 million people, controlled oilfields and refineries, agriculture, smuggling routes and vast arsenals. It ran a brutal, oppressive government, even printing its own currency.

Lt. Col. Seth Folsom credits the cooperation between Iraqi Security Forces and the U.S-led coalition for the military defeat of ISIS in Iraq. (Courtesy U.S Army)

The terror organization now controls just 3 percent of Iraq and less than 5 percent of Syria. Its self-styled "caliph," Abu Bakr al-Baghdadi, is believed to be injured and holed up somewhere along the lawless border of Syria and Iraq.

ISIS remains a danger, as members who once ruled cities and villages like a quasi-government now live secretly among civilian populations in the region, in Europe and possibly in the U.S. These cells will likely present a terrorist threat for years. In addition, the terrorist organization is attempting to regroup in places such as the Philippines, Libya and the Sinai Peninsula.

But the military’s job — to take back the land ISIS claimed as its caliphate and liberate cities like Mosul, in Iraq, and Raqqa, in Syria, as well as countless smaller cities and villages, is largely done. And it has taken less than a year.

Mattis, a US Marine Corps general, said there would be no White House micromanaging on his watch (Associated Press)

“The leadership team that is in place right now has certainly enabled us to succeed,” Brig. Gen. Andrew Croft, the ranking U.S. Air Force officer in Iraq, told Fox News. “I couldn’t ask for a better leadership team to work for, to enable the military to do what it does best.”

President Trump gave a free hand to Mattis, who in May stressed military commanders were no longer being slowed by Washington “decision cycles,” or by the White House micromanaging that existed President Obama. As a result of the new approach, the fall of ISIS in Iraq came even more swiftly than hardened U.S. military leaders expected.

“It moved more quickly than at least I had anticipated,” Croft said. “We and the Iraqi Security Forces were able to hunt down and target ISIS leadership, target their command and control.”

U.S. Marine Corps Brig. Gen. Robert Sofge said the military now has a clear mandate.)

IRAQI KURDS STILL LOVE US DESPITE ITS OPPOSITION TO KURDISH INDEPENDENCE, SAYS KURDISH LEADER

After the battle to liberate Mosul – ISIS’ Iraqi headquarters – was completed in July — the U.S.-led coalition retook Tel Afar in August, Hawija in early October and Rawa in Anbar province in November.

Marine Col. Seth Folsom, who oversaw fighting in Al Qaim near the Syrian border, agreed. He wasn’t expecting his part of the campaign against ISIS to get going until next spring and figured even then, it would then "take six months or more."

Instead, ISIS was routed in Al Qaim in just a few days.

Mosul, and several other cities liberated by ISIS, were largely destroyed in the fighting. (Fox News/Hollie McKay)

“We really had one mandate and that was enable the Iraqi Security Forces to defeat ISIS militarily here in Anbar. I feel that we have achieved that mission,” Folsom said. “I never felt constrained. In a lot of ways, I felt quite liberated because we had a clear mandate and there was no questioning that.”

Brig. Gen. Robert “G-Man” Sofge, the top U.S. Marine in Iraq, told Fox News his commanders have “enjoyed not having to deal with too many distractions and there was no question about what the mission here in Iraq was.”

Iraqi Brig. Gen. Yahya Rasool was skeptical of Trump at first, but says success on the ground has been swift (Fox News/Hollie McKay )

“We were able to focus on what our job was without distraction and I think that goes a long way in what we are trying to accomplish here,” he said.

Sofge said while some had implied that there had been a "loosening of the rules," he insisted that such a suggestion is “absolutely not true.”

Col. Ryan Dillon. Combined Joint Task Force – Inherent Resolve Spokesman (Photo by CJTFOIR)

“We used precision strikes, and completely in accordance with international standards,” he said. “We didn’t lower that standard, not one little bit. But we were able to exercise that precision capability without distraction and I think the results speak for themselves.”

The U.S.-led coalition said this week the Coalition Civilian Casualty Assessment Team has added 30 new staffers to travel throughout the region. It said military leaders continue to “hold themselves accountable for actions that may have caused unintentional injury or death to civilians.”

The coalition also said dozens of reports of civilian casualties have been determined to be “non-credible,” and just .35 percent of the almost 57,000 separate engagement carried out between August 2014 and October 2017 resulted in a credible report of a civilian casualty.

In addition to air support, the U.S.-led strategy also includes training and equipping Iraqi troops on the ground.

While the Trump administration’s success is often underplayed in the U.S. media, it is obvious on the ground in Iraq, according to a spokesman for Iraq’s Ministry of Defense, Yahya Rasool.

“I was not optimistic when Trump first came to the office,” Rasool said. “But after a while I started to see a new approach, the way the U.S. was dealing with arming and training. I saw how the coalition forces were all moving faster to help the Iraq side more than before. There seemed to be a lot of support, under Obama we did not get this.”

Al-Baghdadi, who once ruled a caliphate the size of California, is now inn hiding and likely badly injured

Despite the victories on the battlefield, U.S. officials cautioned much work remains to be done.

“ISIS is very adaptive,” noted Col. Ryan Dillon, the U.S.-led coalition spokesman. “We are already seeing smaller cells and pockets that take more of an insurgent guerrilla type approach as opposed to an Islamic army or conventional type force. So we have got to be prepared for that.”

He said as a result the coalition is “adjusting some training efforts” so the Iraqi forces — upwards of 150,000 have already undergone training — are equipped to address such threats and ensure long-term stability.

Folsom said “the worst thing we could do” is not finish the job.

“If a country becomes a failed state, if it becomes a lawless region, you begin to set the conditions for what happened in the years before 9/11,” he said. “In those ungoverned spaces where we don’t know what is going on, that is where those seeds of extremism begin to blossom.”

@holliesmckay

60 lines of code to handle the flow between FB messenger and api.ai

import requests
import json
from flask import Flask, request
import apiai

# FB messenger credentials
ACCESS_TOKEN = "EAAKsKOJ37rUBAKVZAQ21bn…UsZCXx6UWqQ6XuQr7OHnBYL3xD3Sy5u1ZAZCwip0XnTAHq25CsIpxRsbxZALRHOOguKm2unY7I06LRAZDZD"

# api.ai credentials
CLIENT_ACCESS_TOKEN = "78c0e0…d9404a2"
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

app = Flask(__name__)

@app.route(‘/’, methods=['GET'])
def verify():
# our endpoint echos back the ‘hub.challenge’ value specified when we setup the webhook
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == ‘foo’:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200

return ‘Hello World (from Flask!)’, 200

def reply(user_id, msg):
data = {
"recipient": {"id": user_id},
"message": {"text": msg}
}
resp = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token=" + ACCESS_TOKEN, json=data)
print(resp.content)

@app.route(‘/’, methods=['POST'])
def handle_incoming_messages():
data = request.json
sender = data['entry'][0]['messaging'][0]['sender']['id']
message = data['entry'][0]['messaging'][0]['message']['text']

# prepare API.ai request
req = ai.text_request()
req.lang = ‘en’ # optional, default value equal ‘en’
req.query = message

# get response from API.ai
api_response = req.getresponse()
responsestr = api_response.read().decode(‘utf-8’)
response_obj = json.loads(responsestr)
if ‘result’ in response_obj:
response = response_obj["result"]["fulfillment"]["speech"]
reply(sender, response)

return "ok"

if __name__ == ‘__main__’:
app.run(debug=True)
view rawFlaskFBmAPI.ai rig hosted with ❤ by GitHub