<commit_before>#!/usr/bin/env python
#coding:utf-8
import urllib
import json
import os
import requests
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

from flask import Flask
from flask import request
from flask import make_response

import logging

import mysql.connector
#from mysql.connector import errorcode

mysql_config = config = {
  'user': 'root',
  'password': 'password',
  'host': 'mysql.cii5tvbuf3ji.us-west-1.rds.amazonaws.com',
  'database': 'RestaurantsRecommendation'
}

class Mysql(object):

	def connect(self, config):
		try:
		  self.cnx = mysql.connector.connect(**config)
		  return None
		except err:
			print err
			self.cnx = None
			return err
		else:
		  self.cnx.close()
		  self.cnx = None
		  return 0

	def close(self):
		if self.cnx: self.cnx.close(); self.cnx=None;

	def query(self, query,schema=None):
		cursor = self.cnx.cursor()

		cursor.execute(query)
		result = []
		for i, row in enumerate(cursor):
			if schema == None:
				result.append(row)
			else:
				dict = {}
				for j, column in enumerate(row):
					print j
					print column
					if j >= len(schema):
						break
					if isinstance(column, unicode):
						dict[schema[j]] = column.encode('utf-8')
					else:
						dict[schema[j]] = column
				result.append(dict)
		print result
		# for (first_name, last_name, hire_date) in cursor:
		#   print("{}, {} was hired on {:%d %b %Y}".format(
		#     last_name, first_name, hire_date))

		cursor.close()
		return result
	def __del__(self):
		if self.cnx: self.cnx.close(); self.cnx=None;


# Flask app should start in global layout
app = Flask(__name__)
print ('嘿嘿')

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

@app.route('/smarthome', methods=['POST'])
def smarthome():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeResponse(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

@app.route('/restaurantsRec', methods=['POST'])
def restaurantsRec():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeResponse2(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeResponse2(req):
	action = req.get("result").get("action")
	result = req.get("result")
	facebook_userId = str(req.get("sessionId"))
	parameters = result.get("parameters")
	res = {}
	speech = '出错啦！！！'
	if action == 'query.restaurants':
		speech = "你喜欢什么类型的菜？"
	if action == 'query.restaurants.location':
		speech = "能把你的位置发送给我嘛？"
	if action == 'query.restaurants.taste':
		speech = "正在寻找中，请稍等！"
	if action == 'query.restaurants.unknownLocation':
		mysql = Mysql()
		if(mysql.connect(mysql_config) == None):
			speech = 'Success'
			schema = ['id', 'name_en', 'name_cn', 'rating', 'type']
			results = mysql.query("SELECT * FROM Restaurants", schema)
			mysql.close()
			speech = "我们给你推荐" + results[0]['name_cn']
		else:
			speech = 'Database Error'

		#speech = result.get('resolvedQuery')

	print("Response:" + str(speech))
	res["speech"] = speech
	res["displayText"] = speech
	res["source"] = "shokse-restaurants-recommendation"

	return res;<commit_msg>Improve<commit_after>#!/usr/bin/env python
#coding:utf-8
import urllib
import json
import os
import requests
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

import random
from flask import Flask
from flask import request
from flask import make_response

import logging

import mysql.connector
#from mysql.connector import errorcode

mysql_config = config = {
  'user': 'root',
  'password': 'password',
  'host': 'mysql.cii5tvbuf3ji.us-west-1.rds.amazonaws.com',
  'database': 'RestaurantsRecommendation'
}

answers_query_restaurants = ['你喜欢哪种口味的菜？', '你喜欢哪种风格的菜？']
answers_query_restaurants_location = ['好的，请稍等！正在搜寻中！']
answers_query_restaurants_taste = ['好的，%s是个很棒的选择哦。那你能告诉我你的位置么？这\
样我好帮你寻找符合条件的餐馆。你可以直接打你所在的地址，也可以发送你当前位置。']
answers_query_restaurants_unknownLocation = ['请问是%d嘛？']

class Mysql(object):

	def connect(self, config):
		try:
		  self.cnx = mysql.connector.connect(**config)
		  return None
		except err:
			print err
			self.cnx = None
			return err
		else:
		  self.cnx.close()
		  self.cnx = None
		  return 0

	def close(self):
		if self.cnx: self.cnx.close(); self.cnx=None;

	def query(self, query,schema=None):
		cursor = self.cnx.cursor()

		cursor.execute(query)
		result = []
		for i, row in enumerate(cursor):
			if schema == None:
				result.append(row)
			else:
				dict = {}
				for j, column in enumerate(row):
					print j
					print column
					if j >= len(schema):
						break
					if isinstance(column, unicode):
						dict[schema[j]] = column.encode('utf-8')
					else:
						dict[schema[j]] = column
				result.append(dict)
		print result
		# for (first_name, last_name, hire_date) in cursor:
		#   print("{}, {} was hired on {:%d %b %Y}".format(
		#     last_name, first_name, hire_date))

		cursor.close()
		return result
	def __del__(self):
		if self.cnx: self.cnx.close(); self.cnx=None;


# Flask app should start in global layout
app = Flask(__name__)
print ('嘿嘿')

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

@app.route('/smarthome', methods=['POST'])
def smarthome():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeResponse(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

@app.route('/restaurantsRec', methods=['POST'])
def restaurantsRec():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeResponse2(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def makeResponse2(req):
	action = req.get("result").get("action")
	result = req.get("result")
	facebook_userId = str(req.get("sessionId"))
	parameters = result.get("parameters")
	res = {}
	print action
	speech = '出错啦！！！'

	if action == 'query.restaurants':
		speech = answers_query_restaurants[randint(0, len(answers_query_restaurants))]
		print '123'

	if action == 'query.restaurants.location':
		speech = answers_query_restaurants_location[0]

	if action == 'query.restaurants.taste':
		speech = answers_query_restaurants_taste[0] % (parameters.get('taste'),)

	if action == 'query.restaurants.unknownLocation':
		print 'big error'
		speech = answers_query_restaurants_unknownLocation[0] % (result.get('resolvedQuery'),)
		print 'big error2'
		res["contextOut"] = [
      	{
        "name": "user_asks4_restaurants_withUnknownLocation",
        "parameters": {
          "location.original": result.get('resolvedQuery'),
        },
        "lifespan": 3
      	}]
      	print 'bigerror 3'

	if action == 'query.restaurants.show':
		mysql = Mysql()
		if(mysql.connect(mysql_config) == None):
			schema = ['id', 'name_en', 'name_cn', 'rating', 'type', 'signature', 'price_average', 'address']
			results = mysql.query("SELECT * FROM Restaurants", schema)
			mysql.close()
			speech = "我们给你推荐" + results[0]['name_cn'] + "。它在这里" + results[0]['address']
		else:
			speech = '哎呀！数据库出了点小问题！等我下！'
		

		#speech = result.get('resolvedQuery')

	print("Response:" + str(speech))
	res["speech"] = speech
	res["displayText"] = speech
	res["source"] = "shokse-restaurants-recommendation"

	return res;
{'fraction_non_alphanumeric': 0.1530475143520215, 'fraction_numerical': 0.005374374007572982, 'mean_word_length': 3.917717717717718, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2899889', 'n_tokens_mistral': 3264, 'n_tokens_neox': 2998, 'n_words': 618}