def execute_cmd(cmd): try: manage_user() method = get_attr(cmd) # check if method is whitelisted if frappe.session['user'] == 'Guest' and (method not in frappe.guest_methods): return get_response(message="Not Allowed", args={"http_status_code": 403}) elif not method in frappe.whitelisted: return get_response(message="Not Allowed", args={"http_status_code": 403}) else: args = get_json_request(frappe.local.form_dict.args) result = frappe.call(method, args) if result: if isinstance(result, dict): return get_response(message="Success", status_code=1, args=result) else: return get_response(message="Success", status_code=1) else: return get_response( message="Error occured, Please contact administrator") except Exception, e: raise e
def clear_rules(): res = response.get_response( 'GET', 'https://api.twitter.com/2/tweets/search/stream/rules') response_json = json.loads(res.text) ids = [] if 'data' in response_json: for rule in response_json['data']: ids.append(rule['id']) response.get_response( 'POST', 'https://api.twitter.com/2/tweets/search/stream/rules', {'delete': { 'ids': ids }})
def logout(args): args = json.loads(args) try: if args.get("user") and args.get("sid"): manage_user() frappe.local.login_manager.logout() frappe.db.commit() print "hello" return get_response( message="Logged Out", status_code=1, ) else: raise Exception("Invalid Input") except frappe.AuthenticationError,e: return get_response(message="Logout unsuccessful")
def calculateWithK(test_set_by_user=[], k=-1, trainingSet=[]): if (k == -1): k = raw_input("Please input K: ") k = int(k) global neighbors, accuracy # data preparation if (test_set_by_user == -1): testSet = get_test_set() else: testSet = test_set_by_user trainingSet = get_training_set() print 'training set --> ' + repr(trainingSet) print 'testing set --> ' + repr(testSet) # predictions predictions = [] for x in range(len(testSet)): neighbors = get_neighbors(trainingSet, testSet[x], k) responses_result = get_response(neighbors) predictions.append(responses_result) print('> predicted = ' + repr(responses_result) + ', actual = ' + repr(testSet[x][-1])) # accuracy: accuracy = get_accuracy(testSet, predictions) print('Accuracy: ' + repr(accuracy) + '%')
def logout(args): args = json.loads(args) try: if args.get("user") and args.get("sid"): manage_user() frappe.local.login_manager.logout() frappe.db.commit() print "hello" return get_response( message="Logged Out", status_code=1, ) else: raise Exception("Invalid Input") except frappe.AuthenticationError, e: return get_response(message="Logout unsuccessful")
def hello(): in_text = request.form["Body"] ph_number = request.form["From"] in_text = in_text.lower() out_text = get_response(in_text) response = twiml.Response() response.message(out_text) return str(response)
def process(): try: queries = get_json_queries() response = get_response(queries) return response except Exception as e: #we can log any exception ex: logger.error('Failed to process : '+ str(e)) print("sorry we are unable to process the request ")
def login(args): args = json.loads(args) try: if args.get("user") and args.get("password"): frappe.clear_cache(user = args["user"]) frappe.local.login_manager.authenticate(args["user"],args["password"]) frappe.local.login_manager.post_login() return get_response( message="Logged In", status_code=1, args={ "sid":frappe.session.sid, "user": args.get("user") } ) else: raise Exception("Invalid Input") except frappe.AuthenticationError,e: # http_status_code = getattr(e, "http_status_code", 500) return get_response(message="Authentication Error, Please check user id and password")
def login(args): args = json.loads(args) try: if args.get("user") and args.get("password"): frappe.clear_cache(user=args["user"]) frappe.local.login_manager.authenticate(args["user"], args["password"]) frappe.local.login_manager.post_login() return get_response(message="Logged In", status_code=1, args={ "sid": frappe.session.sid, "user": args.get("user") }) else: raise Exception("Invalid Input") except frappe.AuthenticationError, e: # http_status_code = getattr(e, "http_status_code", 500) return get_response( message="Authentication Error, Please check user id and password")
def main(): training_set, test_set = data.load_dataset('formatted_file.data') predictions = [] k = 3 for x in range(len(test_set)): neighbors = ns.get_neighbors(training_set, test_set[x], k) result = rs.get_response(neighbors) predictions.append(result[0][0]) print('> predicted = ' + repr(result) + ', actual = ' + repr(test_set[x][-1])) accuracy = acc.accuracy(test_set, predictions) print('Accuracy: ' + repr(accuracy) + '%')
def execute_cmd(cmd): try: manage_user() method = get_attr(cmd) # check if method is whitelisted if frappe.session['user'] == 'Guest' and (method not in frappe.guest_methods): return get_response(message="Not Allowed", args={"http_status_code":403}) elif not method in frappe.whitelisted: return get_response(message="Not Allowed", args={"http_status_code":403}) else: args = get_json_request(frappe.local.form_dict.args) result = frappe.call(method, args) if result: if isinstance(result, dict): return get_response(message="Success", status_code=1, args=result) else: return get_response(message="Success", status_code=1) else: return get_response(message="Error occured, Please contact administrator") except Exception, e: raise e
def generate_recent_tweets_file(cant, search, lang): if cant <= 10: tweets_per_request = 10 next_requests = 1 else: tweets_per_request = 100 next_requests = int(cant / 100) query = { 'max_results': tweets_per_request, 'query': '{} lang:{}'.format(search, lang), } print('Download started') tmpfile = '.' + str(uuid.uuid4()) + '.txt' file = open(tmpfile, 'w') response = get_response( 'GET', 'https://api.twitter.com/2/tweets/search/recent?{}'.format( urllib.parse.urlencode(query))) json_response = json.loads(response.text) file.write('{}\n'.format(json.dumps(json_response['data']))) for i in range(1, next_requests): response = get_response( 'GET', 'https://api.twitter.com/2/tweets/search/recent?{}'.format( urllib.parse.urlencode({ **query, **{ 'next_token': json_response['meta']['next_token'] }, }))) json_response = json.loads(response.text) file.write('{}\n'.format(json.dumps(json_response['data']))) file.close() print('Download done') os.system('hdfs dfs -rm -f recent.txt') os.system('hdfs dfs -copyFromLocal ' + tmpfile + ' recent.txt') os.system('rm -f ' + tmpfile)
def handle(): """ Handler for `/helpdesk` methods ### Examples: `/helpdesk/method/{methodname}` will call a whitelisted method """ try: validate_request() return handler.handle() except Exception, e: import traceback print traceback.format_exc() return get_response(message=str(e))
def handle(): """ Handler for `/helpdesk` methods ### Examples: `/helpdesk/method/{methodname}` will call a whitelisted method """ try: validate_request() return handler.handle() except Exception, e: import traceback print traceback.format_exc() return get_response(0, str(e))
def calculateWithKFofGraph(test_set_by_user=[], trainingSet=[], k = 1): global neighbors, accuracy testSet = test_set_by_user # predictions predictions = [] for x in range(len(testSet)): neighbors = get_neighbors(trainingSet, testSet[x], k) responses_result = get_response(neighbors) predictions.append(responses_result) print('> predicted = ' + repr(responses_result) + ', actual = ' + repr(testSet[x][-1])) # accuracy: accuracy = get_accuracy(testSet, predictions) print('Accuracy: ' + repr(accuracy) + '%') return accuracy
def process_input(): filePath = app.config['UPLOAD_PATH'] + str(request.args.get('id')) timelineJson = get_json_from_path(filePath) os.remove(filePath) # Delete tempFile once processed tObj = timelineObject( timelineJson) # Convert input json into python object placeVisits = tObj.getPlaceVisits() placeVisits = filterPlacesStayedLongerThan(placeVisits, 10 * 60 * 1000) #10 minutes if (request.args.get('uploadOption') == "countyLevel"): countyMatches = get_county_matches(placeVisits) return json.dumps({ "uploadOption": "countyLevel", "placesVisited": placeVisits, "counties": countyMatches }) elif (request.args.get('uploadOption') == "infectedPlaces"): radius = int(request.args.get('radius')) timeSpan = int(request.args.get('time')) matchLocations = getSpatioTemporalMatch(placeVisits, radius, timeSpan) return json.dumps({ "uploadOption": "infectedPlaces", "infectedPlaces": get_response(matchLocations) })
return self.__reponse def get_intents(self) -> json: """ Returns string containing the intent of the message from wit.ai json reponse :param jsonResponse: json file :return: a json which is the intent of the message. """ return self.__intents def get_entities(self) -> json: """ Returns string containing the intent of the message from wit.ai json reponse :param jsonResponse: json file :return: a json which is the entities of the file """ return self.__entities if __name__ == '__main__': import response import json response = witObjects(response.get_response_wit("i want to buy a porsche 911")) print(response.get_intents()) print(response.get_entities()) print(response.get_response()) # print(json.dumps(response, indent=4, sort_keys=True))
while runflag: try: confd, addr = lisfd.accept() except socket.error as e: if e.errno == errno.EINTR: print 'get a except EINTR' else: print 'get a error', e.errno raise continue if runflag == False: break print "connect by ", addr data = confd.recv(1024) if not data: break print "receve >>>>", data, "<<<<<" http_request.request = HttpRequest(data) print http_request.request.method, http_request.request.path, http_request.request.params confd.send(response.get_response()) #confd.send(HttpResponse(httpheader,'index.html')) confd.close() else: print 'runflag#', runflag lisfd.shutdown(socket.SHUT_RD) print 'Done'
def create_rule(search, lang): response.get_response( 'POST', 'https://api.twitter.com/2/tweets/search/stream/rules', {'add': [{ 'value': '{} lang:{}'.format(search, lang) }]})
while runflag: try: confd,addr = lisfd.accept() except socket.error as e: if e.errno == errno.EINTR: print 'get a except EINTR' else: print 'get a error', e.errno raise continue if runflag == False: break; print "connect by ",addr data = confd.recv(1024) if not data: break print "receve >>>>", data, "<<<<<" http_request.request = HttpRequest(data) print http_request.request.method, http_request.request.path, http_request.request.params confd.send(response.get_response()) #confd.send(HttpResponse(httpheader,'index.html')) confd.close() else: print 'runflag#',runflag lisfd.shutdown(socket.SHUT_RD) print 'Done'
from accuracy import get_accuracy from neighbors import get_neighbors # trainingSet = get_training_set() # testSet = get_test_set() # neighbors: from response import get_response trainingSetDemo = [[2, 2, 2, 'a'], [4, 4, 4, 'b']] testSetDemo = [5, 5, 5] k = 1 neighbors = get_neighbors(trainingSetDemo, testSetDemo, k) print neighbors # response: neighborsDemo = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']] response = get_response(neighbors) print(response) # accuracy: testSetAccuracy = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']] predictions = ['a', 'a,', 'a'] accuracy = get_accuracy(testSetAccuracy, predictions) print(accuracy)
def get_response(object): return response.get_response(object)