Python evernote api Error - python

Trying to build app that connects with Evernote API, in Python/Django. For the below code i get the following error message: " 'Store' object has no attribute 'NoteFilter' " from http://dev.evernote.com/documentation/reference/NoteStore.html#Svc_NoteStore One can see, that NoteFilter is attribute of NoteStore.
def list(request):
nbname="mihkel's notebook"
client = EvernoteClient(token=token, sandbox=False)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks()
for nb in notebooks:
if nbname == nb.name:
nb = nb
filter = note_store.NoteFilter()
filter.notebookGuid = nb.guid
notelist = note_store.findNotes(token,filter,0,10)
break
return render_to_response('list.html', {'nb': nb, 'notelist':notelist})

Solution:
from evernote.edam.notestore import NoteStore
....
....
def list.. :
...
Filter = NoteStore.NoteFilter()

notestore/ttypes.py has the definition for NoteFilter
Some of the examples in the API code import like this
import evernote.edam.notestore.NoteStore as NoteStore
import evernote.edam.type.ttypes as Types
Not sure if this would be an acceptable way to correct, but I added this:
import evernote.edam.notestore.ttypes as NoteStoreTypes
and created my filter like this:
filter = NoteStoreTypes.NoteFilter()

Related

Internal server error while trying to build an api using a function that takes *args as parameters, in Flask

I have a function which returns me a vector.
def class_vector(*categories):
all_categories = categories
model = Word2Vec.load(r"C:\Users\vector.model")
my_dict = dict({})
for idx, key in enumerate(model.wv.vocab):
my_dict[key] = model.wv[key]
categories_vectors = dict({})
for i in all_categories:
if i.lower() in my_dict.keys():
categories_vectors[i] = my_dict[i]
average_vector = np.mean(list(categories_vectors.values()), axis =0)
average_vector = average_vector.reshape(1, -1)
return average_vector
Now I call this function:
vector_generator_object = class_vector("apple", "banana")
This works perfectly and returns me a vector for the fruits. The above function is in a .py file called vectors_list.py
Now I want to build an api that takes the fruit names as input from a user and use the class_vector function to return the computed vectors.
Api code:
from flask import Flask, request
from vector_list import class_vector
app = Flask(__name__)
#app.route('/')
def status():
fruits = request.args.getlist("param")
str_fruits = ",".join(fruits)
returned_vec = class_vector(*str_fruits )
return returned_vec
Now I do flask run from cmd & curl "http://localhost:5000?param=apple&param=banana". This returns me 500 Internal Server Error. Any idea how to fix this
Your flask code looks fine. I think the issue is with your class_vector. It will be helpful if you can add the traceback for the same.

Can I get the failed test case names using robot.api?

I am trying to get the failed test case names from a output.xml using robot api in python, I am able to get the count for failed/passed tests using the below code but could not find any methods to get test case names.
Thanks in advance.
from robot.api import ExecutionResult
result = ExecutionResult('output.xml')
result.configure(stat_config={'suite_stat_level': 2,
'tag_stat_combine': 'tagANDanother'})
stats = result.statistics
print stats.total.critical.failed
print stats.total.critical.passed
print stats.tags.combined[0].total
Probably you need ResultVisitor. Something like that should help:
from robot.api import ExecutionResult, ResultVisitor
class Visitor(ResultVisitor):
def __init__(self):
self.failed = []
def end_test(self, test):
if test.status == "FAIL":
self.failed.append(test)
visitor = Visitor()
result = ExecutionResult('output.xml')
result.visit(visitor)
print(visitor.failed)
Documentation could be found at https://robot-framework.readthedocs.io/en/v3.1.2/autodoc/robot.result.html#module-robot.result.visitor

Error while creating person group person in microsoft cognitive face API

I have a code which uses older API. I don't know new API. Those who know help me with modifying the code.
import cognitive_face as CF
from global_variables import personGroupId
import sqlite3
Key = '###################'
CF.Key.set(Key)
BASE_URL = 'https://region.api.cognitive.microsoft.com/face/v1.0/'
CF.BaseUrl.set(BASE_URL)
if len(sys.argv) is not 1:
res = CF.person.create(personGroupId, str(sys.argv[1])) #error line
print(res)
extractId = str(sys.argv[1])[-2:]
connect = sqlite3.connect("studentdb")
cmd = "SELECT * FROM Students WHERE id = " + extractId
cursor = connect.execute(cmd)
isRecordExist = 0
for row in cursor:
isRecordExist = 1
if isRecordExist == 1:
connect.execute("UPDATE Students SET personID = ? WHERE ID = ?",(res['personId'], extractId))
connect.commit()
connect.close()
As you mentioned you are using older API. You are expected to use the new API. Refer this (official documentation) for installing the package and further reference.
PACKAGE:
pip install --upgrade azure-cognitiveservices-vision-face
Import the following libraries (excluding other basic libraries)
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, SnapshotObjectType, OperationStatusType
The updated API command is as follows:
res = face_client.person_group_person.create(person_group_id, str(sys.argv[1]))
In addition to what Soorya answered above, For those who want the sample code reference, you can see the latest API sample code from here
def build_person_group(client, person_group_id, pgp_name):
print('Create and build a person group...')
# Create empty Person Group. Person Group ID must be lower case, alphanumeric, and/or with '-', '_'.
print('Person group ID:', person_group_id)
client.person_group.create(person_group_id = person_group_id, name=person_group_id)

Get Intent Value in RASA Core/NLU

Greeting
I am working on RASA chatbot. I am handling Custom actions for a particular intent using below code. In the custom action I want to get current intent value. SO i dont know that line of code which can give me value of current intent
#this file will be used to all custom actions
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import requests
import json
from zeep import Client
from random import randint
from rasa_core.actions.action import Action
from rasa_core.events import SlotSet
class ActionWeather(Action):
RANDOMIZE = False
#staticmethod
def required_fields():
return [
EntityFormField("period", "period"),
EntityFormField("product", "product")
]
def name(self):
return 'action_weather'
def run(self,dispatcher, tracker, domain):
#Get Slot values
loc = tracker.get_slot('period')
pro = tracker.get_slot('product')
custname= tracker.get_slot('custName')
#Here I want to get Intent Values as well same like slot value in above code
# So what is code for getting intent value
#make json
data = {}
data['period'] = loc
data['product'] = pro
json_data = json.dumps(data)
jsonobj= json.loads(json_data)
#code for SOAP
client = Client('my webservice URL/testsoap?wsdl')
result = client.service.getData(json_data)
print('**********************')
print(result)
print('#######################')
jsonobj= json.loads(result)
#print(response.content)
#json_response = response.json()
#print (json_response)
result1=jsonobj[0]['result']
#result1=randint(1, 100)
#result='X'
response = """sale is {} """.format(result1)
dispatcher.utter_message(response)
#return [SlotSet('location',loc)]
return []
I want to get current and last value of intent in RASA Core in same way as we can get slots value product = tracker.get_slot('product') in python custom action code. Please help.
This works for me:
def run(self,dispatcher, tracker, domain):
intent = tracker.latest_message['intent'].get('name')
rasa-core 0.11.12
rasa-core-sdk 0.11.5
rasa-nlu 0.13.7
intent = json.dumps(tracker.latest_message.intent)
print(intent)
#particular intent name
print(json.loads(intent)['intent']['name'])
outcome
(u'{"confidence": 0.9092543377510975, "name": "greet"}')
or try this
intent = json.dumps(tracker.latest_message.__dict__)
You can use something like below,
currentIntent = tracker.latest_message.intent["name"]

How to solve "TypeError: expected string or buffer" when importing json data via api?

I'm trying to import JSON data via an API, and use the imported data to construct a DataFrame.
import json
import pandas as pd
import numpy as np
import requests
api_username = 'acb'
api_password = 'efg'
germany_name = 'Germany'
germany_api_url = "https://api.country_data.com/stats/?country=" + germany_name + "&year=2014"
germany_api_resp = requests.get(germany_api_url,auth=(api_username,api_password))
germany_data_json = json.loads(germany_api_resp)
germany_frame = pd.DataFrame(germany_data_json['data']).set_index('tag')
print(germany_frame) shows me the desired DataFrame.
I want to repeat the process for many countries, not just 'Germany', so I created a country object like this:
class Country(object):
def __init__(self,name):
self.name = name
self.api_url = "https://api.country_data.com/stats/?country=" + name + "&year=2014"
self.api_resp = requests.get(self.api_url,auth=(api_username,api_password))
self.data_json = json.loads(self.api_resp)
self.frame = pd.DataFrame(self.data_json['data']).set_index('tag')
When I create my first object, like this:
Germany = Country('Germany')
I get an Error message:
TypeError: expected string or buffer
Can someone help me with this issue?
I don't which version of Python you're using, and which version of requests but I recommend to you to update everything. Here is a error I found :
self.data_json = json.loads(self.api_resp)
You try to load in a json-way a Response from requests, so change it to :
self.data_json = self.api_resp.json()
I replaced your api url to another because yours is wrong and it works for me.
See ya !

Categories