What am I doing wrong with this Python class? AttributeError: 'NoneType' object has no attribute 'usernames' - class

Hey there I am trying to make my first class my code is as follows:
class Twitt:
def __init__(self):
self.usernames = []
self.names = []
self.tweet = []
self.imageurl = []
def twitter_lookup(self, coordinents, radius):
twitter = Twitter(auth=auth)
coordinents = coordinents + "," + radius
print coordinents
query = twitter.search.tweets(q="", geocode='33.520661,-86.80249,50mi', rpp=10)
print query
for result in query["statuses"]:
self.usernames.append(result["user"]["screen_name"])
self.names.append(result['user']["name"])
self.tweet.append(h.unescape(result["text"]))
self.imageurl.append(result['user']["profile_image_url_https"])
What I am trying to be able to do is then use my class like so:
test = Twitt()
hello = test.twitter_lookup("38.5815720,-121.4944000","1m")
print hello.usernames
This does not work and I keep getting: "AttributeError: 'NoneType' object has no attribute 'usernames'"
Maybe I just misunderstood the tutorial or am trying to use this wrong. Any help would be appreciated thanks.

I see the error is test.twitter_lookup("38.5815720,-121.4944000","1m") return nothing. If you want the usernames, you need to do
test = Twitt()
test.twitter_lookup("38.5815720,-121.4944000","1m")
test.usernames

Your function twitter_lookup is modifying the Twitt object in-place. You didn't make it return any kind of value, so when you call hello = test.twitter_lookup(), there's no return value to assign to hello, and it ends up as None. Try test.usernames instead.
Alternatively, have the twitter_lookup function put its results in some new object (perhaps a dictionary?) and return it. This is probably the more sensible solution.
Also, the function accepts a coordinents (it's 'coordinates') argument, but then throws it away and uses a hard-coded value instead.

Related

QgsField won't accept parameter typeName

I'm trying to create new vector layer with the same fields as contained in original layer.
original_layer_fields_list = original_layer.fields().toList()
new_layer = QgsVectorLayer("Point", "new_layer", "memory")
pr = new_layer.dataProvider()
However, when I try:
for fld in original_layer_fields_list:
type_name = fld.typeName()
pr.addAttributes([QgsField(name = fld.name(), typeName = type_name)])
new_layer.updateFields()
QgsProject.instance().addMapLayer(new_layer)
I get a layer with no fields in attribute table.
If I try something like:
for fld in original_layer_fields_list:
if fld.type() == 2:
pr.addAttributes([QgsField(name = fld.name(), type = QVariant.Int)])
new_layer.updateFields()
QgsProject.instance().addMapLayer(new_layer)
... it works like charm.
Anyway ... I'd rather like the first solution to work in case if one wants to automate the process and not check for every field type and then find an appropriate code. Besides - I really am not able to find any documentation about codes for data types. I managed to find this post https://gis.stackexchange.com/questions/353975/get-only-fields-with-datatype-int-in-pyqgis where in comments Kadir pointed on this sourcecode (https://codebrowser.dev/qt5/qtbase/src/corelib/kernel/qvariant.h.html#QVariant::Type).
I'd really be thankful for any kind of direction.

how to read a multiline element from PySimpleGUI

My program stub looks like this:
import PySimpleGUI as sg
layout = [[sg.Text("Geheime Nachricht eintippen:")],
[sg.Multiline(size=(70,4),key="GEHEIM")],
[sg.Spin([i for i in range(1,26)], initial_value=12, key="SS"), sg.Text("Schlüssel zwischen 1 und 25 wählen")],
[sg.Radio("Codieren:", "RADIO1", key="XX" ,default=True),
sg.Radio("Decodieren:","RADIO1", key="YY")],
[sg.Text("ERGEBNIS:")],
[sg.Multiline(size=(70,4),key="AUSGABE")],
[sg.Button("Weiter"), sg.Button("Ende")]]
window = sg.Window("Geheimcode", layout)
while True: # Ereignisschleife
event, values = window.Read()
geheimertext = values("GEHEIM")
print(values("GEHEIM"))
schluessel = int(values["SS"])
print ("Schlüssel = ", schluessel)
if values["XX"] == True:
codedecode = "C"
print("wir codieren:",codedecode)
else:
codedecode = "D"
print("wir decodieren:",codedecode)
if event is None or event == "Ende":
break
window.Close()
The program-line geheimertext = values("GEHEIM") gives this error:
TypeError: 'dict' object is not callable
I quess that the multiline generates a dictonary in the dictionary values?
so my simple newbie-question is how to read the multiline of a gui made with pysimpleGUI
ok, one possible solution is to iterate over the elements of the multiline:
geheimertext=""
for zeichen in values["GEHEIM"]:
geheimertext = geheimertext +zeichen
print(geheimertext)
Is there a better solution? Please teach a newbie
print(values["GEHEIM"])
values is a dict, and not a callable, so you cannot use () brackets (callables are functions or objects that have a function property). You can access to values through [] brackets. values["GEHEIM"].

pointer to constructor to a class in perl6

I am trying to write some classes with Perl 6 just for testing out Perl 6 classes and methods.
Here is the code:
class human1 {
method fn1() {
print "#from human1.fn1\n";
}
}
class human2 {
method fn1() {
print "#from human2.fn1\n";
}
}
my $a = human1.new();
my $b = human2.new();
$a.fn1();
$b.fn1();
print "now trying more complex stuff\n";
my $hum1_const = &human1.new;
my $hum2_const = &human2.new;
my $c = $hum2_const();
$c.fn1();
Essentially I want to be able to use either the human1 constructor or human2 constructor to be able to build $c object dynamically. But I'm getting the following error:
Error while compiling /usr/bhaskars/code/perl/./a.pl6
Illegally post-declared types:
human1 used at line 23
human2 used at line 24
How do I create $c using the function pointers to choose which constructor I use?
I think this is a case of an LTA error. What I understand you want to achieve, is a lambda that will create a new human1 or human2 object for you. The way you do that is not correct, and the error it causes is confusing.
my $hum1_const = -> { human1.new };
my $hum2_const = -> { human2.new };
would be a correct way of doing this. Although, I would consider this a bit of an obfuscation. Since human1 and human2 are already constants, you can assign them to a variable, and then just call new on that:
my $the_human = $condition ?? human1 !! human2;
my $c = $the_human.new;
$c.fn1;
Does that make sense?
To get a “reference” to .new you have to use the meta object protocol.
Either .^lookup, or .^find_method.
my $hum1-create = human1.^find_method('new');
That is still not quite what you are looking for, as methods require either a class object or an instance, as their first argument.
my $c = $hum1-create( human1 );
So you would probably want to curry the class as the first argument to the method.
my $hum1-create = human1.^find_method('new').assuming(human1);
my $c = $hum1-create();
Note that .assuming in this case basically does the same thing as
-> |capture { human1.^find_method('new').( human1, |capture ) }
So you could just write:
my $hum1-create = -> |capture { human1.new( |capture ) }
Or if you are never going to give it an argument
my $hum1-create = -> { human1.new }
Also you can store it in a & sigiled variable, so you can use it as if it were a normal subroutine.
my &hum1-create = human1.^find_method('new').assuming(human1);
my $c = hum1-create;

cgi.parse_multipart function throws TypeError in Python 3

I'm trying to make an exercise from Udacity's Full Stack Foundations course. I have the do_POST method inside my subclass from BaseHTTPRequestHandler, basically I want to get a post value named message submitted with a multipart form, this is the code for the method:
def do_POST(self):
try:
if self.path.endswith("/Hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ""
output += "<html><body>"
output += "<h2>Ok, how about this?</h2>"
output += "<h1>{}</h1>".format(messagecontent)
output += "<form method='POST' enctype='multipart/form-data' action='/Hello'>"
output += "<h2>What would you like to say?</h2>"
output += "<input name='message' type='text'/><br/><input type='submit' value='Submit'/>"
output += "</form></body></html>"
self.wfile.write(output.encode('utf-8'))
print(output)
return
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info() )
The problem is that the cgi.parse_multipart(self.rfile, pdict) is throwing an exception: TypeError: can't concat bytes to str, the implementation was provided in the videos for the course, but they're using Python 2.7 and I'm using python 3, I've looked for a solution all afternoon but I could not find anything useful, what would be the correct way to read data passed from a multipart form in python 3?
I've came across here to solve the same problem like you have.
I found a silly solution for that.
I just convert 'boundary' item in the dictionary from string to bytes with an encoding option.
ctype, pdict = cgi.parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
In my case, It seems work properly.
To change the tutor's code to work for Python 3 there are three error messages you'll have to combat:
If you get these error messages
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
AttributeError: 'HTTPMessage' object has no attribute 'getheader'
or
boundary = pdict['boundary'].decode('ascii')
AttributeError: 'str' object has no attribute 'decode'
or
headers['Content-Length'] = pdict['CONTENT-LENGTH']
KeyError: 'CONTENT-LENGTH'
when running
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
if c_type == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, p_dict)
message_content = fields.get('message')
this applies to you.
Solution
First of all change the first line to accommodate Python 3:
- c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
+ c_type, p_dict = cgi.parse_header(self.headers.get('Content-Type'))
Secondly, to fix the error of 'str' object not having any attribute 'decode', it's because of the change of strings being turned into unicode strings as of Python 3, instead of being equivalent to byte strings as in Python 3, so add this line just under the above one:
p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
Thirdly, to fix the error of not having 'CONTENT-LENGTH' in pdict just add these lines before the if statement:
content_len = int(self.headers.get('Content-length'))
p_dict['CONTENT-LENGTH'] = content_len
Full solution on my Github:
https://github.com/rSkogeby/web-server
I am doing the same course and was running into the same problem. Instead of getting it to work with cgi I am now using the parse library. This was shown in the same course just a few lessons earlier.
from urllib.parse import parse_qs
length = int(self.headers.get('Content-length', 0))
body = self.rfile.read(length).decode()
params = parse_qs(body)
messagecontent = params["message"][0]
And you have to get rid of the enctype='multipart/form-data' in your form.
In my case I used cgi.FieldStorage to extract file and name instead of cgi.parse_multipart
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print('File', form['file'].file.read())
print('Name', form['name'].value)
Another hack solution is to edit the source of the cgi module.
At the very beginning of the parse_multipart (around the 226th line):
Change the usage of the boundary to str(boundary)
...
boundary = b""
if 'boundary' in pdict:
boundary = pdict['boundary']
if not valid_boundary(boundary):
raise ValueError('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = b"--" + str(boundary)
lastpart = b"--" + str(boundary) + b"--"
...

How to parse json object in UnityScript?

I am following this link http://wiki.unity3d.com/index.php/JSONUtils but not able to parse json object.
What I have tried so far:
function SerializeObject()
{
var object = {"response":[{"id":"100","name":"Guest","score":"14","game":"3,6,9,7,1,8,2,4","date":"2015-02-28 11:22:32"},{"id":"99","name":"Guest","score":"18","game":"7,8,2,5,6,9,4,3","date":"2015-02-28 11:19:35"},{"id":"89","name":"Guest","score":"17","game":"5,7,2,8,6,1,3,9","date":"2015-02-26 16:39:59"},{"id":"96","name":"Guest","score":"18","game":"2,6,1,5,9,7,8,4","date":"2015-02-26 16:34:05"},{"id":"97","name":"Guest","score":"16","game":"1,7,3,4,8,2,6,5","date":"2015-02-26 16:32:30"},{"id":"95","name":"Guest","score":"14","game":"1,3,7,4,6,9,2,8","date":"2015-02-23 19:20:07"},{"id":"90","name":"Guest","score":"16","game":"8,3,9,6,4,5,2,7","date":"2015-02-23 16:48:55"},{"id":"92","name":"Guest","score":"17","game":"5,2,1,9,7,4,3,8","date":"2015-02-23 16:48:28"},{"id":"91","name":"Guest","score":"16","game":"2,1,3,9,6,7,8,4","date":"2015-02-23 16:48:06"},{"id":"94","name":"Guest","score":"14","game":"5,2,8,7,6,1,9,4","date":"2015-02-23 16:47:25"},{"id":"93","name":"Guest","score":"16","game":"8,9,2,7,4,6,3,1","date":"2015-02-23 16:45:44"},{"id":"88","name":"jacky chain","score":"15","game":"1,2,5,4,7,9,3,6","date":"2015-02-23 13:35:20"},{"id":"87","name":"Genie","score":"15","game":"8,9,5,7,1,4,2,3","date":"2015-02-22 16:19:32"},{"id":"86","name":"Genie","score":"15","game":"9,7,3,2,1,5,8,4","date":"2015-02-22 16:16:13"},{"id":"85","name":"Genie","score":"15","game":"7,1,4,6,5,3,9,8","date":"2015-02-22 14:25:39"},{"id":"83","name":"new","score":"18","game":"2,5,4,1,8,9,7,6","date":"2015-02-22 11:11:49"},{"id":"84","name":"Guest","score":"15","game":"9,8,3,5,1,4,2,7","date":"2015-02-22 09:48:28"},{"id":"80","name":"Guest","score":"16","game":"5,4,2,3,1,8,7,6","date":"2015-02-22 08:24:55"},{"id":"82","name":"Guestr","score":"15","game":"8,1,9,5,7,4,6,3","date":"2015-02-21 21:00:37"},{"id":"81","name":"Guest","score":"18","game":"9,4,2,7,6,5,1,8","date":"2015-02-21 20:54:51"},{"id":"79","name":"Guest","score":"15","game":"2,6,9,5,8,3,1,7","date":"2015-02-21 20:37:30"},{"id":"78","name":"Guest","score":"15","game":"3,6,9,7,1,5,4,2","date":"2015-02-21 20:35:27"},{"id":"77","name":"Guest","score":"17","game":"5,3,7,9,8,4,1,6","date":"2015-02-21 16:04:17"},{"id":"64","name":"Guest","score":"17","game":"7,9,8,4,6,1,3,5","date":"2015-02-21 16:03:41"},{"id":"76","name":"new","score":"18","game":"9,3,4,8,6,5,2,1","date":"2015-02-21 15:27:25"}]};
for( var test in object.Keys )
{
Debug.Log( "Object["+test+"] : "+object[test] );
}
}
I see the below line in the Log:
Object[response] : Boo.Lang.Hash[]
Now i want to extract value from this object.
I would appreciate your help on this, thank you.
Your log message is telling you that object["response"] is returning an array of hashes as you would expect from the JSON you parsed. Now you need to iterate over that array which will give you each internal hash object, the first one being:
{"id":"100","name":"Guest","score":"14","game":"3,6,9,7,1,8,2,4","date":"2015-02-28 11:22:32"}