random_state.shuffle is throwing exceptions in Python - python

I am trying to call the random_state.shuffle method in Python and keep getting the following error:
random_state.shuffle(class_data)
File "mtrand.pyx", line 4417, in numpy.random.mtrand.RandomState.shuffle
TypeError: len() of unsized object
I have initialized random_state as shown below:
random_state = np.random.RandomState(100)
After that I try to create SFrame:
def build_bitmap_sframe():
bitmaps_list, labels_list = [], []
for category in categories:
class_data = np.load(os.path.join(bitmap_directory, category + ".npy"))
print(class_data)
random_state.shuffle(class_data) # this line error
What am I missing?
Here is the link for docs: https://apple.github.io/turicreate/docs/userguide/drawing_classifier/data-preparation.html

Related

Default function parameter is not initialized in Python 3

The following code
def score_track(details, result_details, top_score=200):
if top_score < 120:
# do smth
return None
works in Python 2 but throws exception in Python 3:
Traceback (most recent call last):
File "function.py", line 280, in <module>
search_result.get('score'))
File "ImportList.py", line 131, in score_track
if top_score < 120:
TypeError: '<' not supported between instances of 'NoneType' and 'int'
If I initialize top_score explicitly it goes fine.
score_track function is called like this:
add_song(details,score_track(details,details))
search_result list is constructed like this:
search_results = []
dlog('search details: '+str(details))
lib_album_match = False
if details['artist'] and details['title'] and search_personal_library:
lib_results = [item for item in library if s_in_s(details['artist'],item.get('artist')) and s_in_s(details['title'],item.get('title'))]
dlog('lib search results: '+str(len(lib_results)))
for result in lib_results:
if s_in_s(result['album'],details['album']):
lib_album_match = True
item = {}
item[u'track'] = result
item[u'score'] = 200
search_results.append(item)
What is wrong? I didn't find any information about different behavior of default parameter values in Python3 vs Python2.

AttributeError: 'Series' object has no attribute 'Id'

I am trying to create a malware classifier and I am experiencing the error
AttributeError: 'Series' object has no attribute 'Id. Not sure of the error.
Traceback (most recent call last):
File"C:/Users/Afiqmatters/PycharmProjects/MajorProject/feature_extraction.py", line 23, in <module>
rids = [mids.loc[i].Id for i in rchoice]
File "C:\Users\Afiqmatters\Miniconda\lib\site-packages\pandas\core\generic.py", line 2744, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'Id'
Here is the codes I have up to the error.
rs = Random()
rs.seed(1)
trainLabels = pd.read_csv('trainLabels.csv')
#print trainLabels
fids = []
opd = pd.DataFrame()
for label in range(1,10):
mids = trainLabels[trainLabels.Class == label]
mids = mids.reset_index(drop=True)
#print mids
rchoice = [rs.randint(0, len(mids) - 1) for i in range(10)]
print len
#print rchoice
rids = [mids.loc[i].Id for i in rchoice]
The error happens at rids = [mids.loc[i].Id for i in rchoice] and I am not sure of the error.
A sample of what is stored in the trainLabels.csv
Id Class
0A32eTdBKayjCWhZqDOQ 2
mids.loc[i] in this context is a "Series" object which is detailed here
This object type does not have an attribute Series.Id, so that's why you're seeing this error.
Did you mean to call the built-in function id( ) on the object?
rids = [id(mids.loc[i]) for i in rchoice]

AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'

I am trying to save map and its legends using QGis Map composer. I have already template .
Here is code in python.
layers =iface.legendInterface().layers()
canvas=iface.mapCanvas()
for layer in layers:
# myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
newcomp = iface.createNewComposer()
newcomp.composition().loadFromTemplate(myDocument)
newcomp.composition().refreshItems()
for a in iface.mapCanvas().layers():
iface.legendInterface().setLayerVisible(a, False)
iface.legendInterface().setLayerVisible(layer, True)
newcomp.composition().refreshItems()
map_item = newcomp.composition()
map_item.getComposerItemById('map')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())
newcomp.composition().refreshItems()
legend_item = newcomp.composition().getComposerItemById('legend')
legend_item.updateLegend()
newcomp.composition().refreshItems()
imagePath ='C:/Users/craj/Downloads/'+layer.name()+'.png'
image = newcomp.composition().printPageAsRaster(0)
image.save(imagePath,'png')
An error has occurred while executing Python code:
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'
Traceback (most recent call last):
File "C:/Users/craj/.qgis2/python/plugins\JoinAttribute\Join_Attribute.py", line 436, in run
map_item.setMapCanvas(canvas)
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'
If you look at the docs there is no setMapCanvas on QgsComposition. This method is in several other classes, such as QgsComposerMap. So based on the code calling getComposerItemById() what you likely need is this:
composition = newcomp.composition()
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)

Django create_or_update model attribute command works fine but update fails

I am trying to write a CSV helper that reads the CSV file and updates or creates fields in the model. The create_or_update query is working fine, but it is only creating not updating. On changing the create_or_update to update it throws an error. The code of the CSV helper is :
def insert_books_from_dictionary(data):
category, created = Category.objects.update_or_create(name=data['category'])
sub_category = None
if data['sub_category'].decode('utf-8') != '':
sub_category, created = SubCategory.objects.update_or_create(name=data['sub_category'], category=category)
publisher, created = Publisher.objects.update_or_create(name=data['publishers'])
# convert strings to float
# ToDo : Fix constraints and create a function
# to handle data check and conversion
try:
price = float(data['mrp_price'])
except ValueError:
price = 0.0
pass
try:
pages = float(data['pages'])
except ValueError:
pages = None
pass
isbn_13_str = str(data['isbn_13'])
isbn_10_str = str(data['isbn_10'])
image_url_str = str(data['image_url'])
binding = 1 if data['binding'] == 'Hardboard' else 2
book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
book.publishers.add(publisher)
authors = re.split(",", data['authors'].decode('utf-8'))
for author in authors:
author, created = Author.objects.update_or_create(name=author.strip())
book.authors.add(author)
return dict(book_id=book.id)
It throws the following error:
Traceback (most recent call last):
File "common/util/upload.py", line 18, in <module>
uploadbooks = book_upload(old_file, newfile)
File "common/util/upload.py", line 12, in book_upload
insert_seller_books_from_dictionary(req_data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 132, in insert_seller_books_from_dictionary
book_id = insert_books_from_dictionary(data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 167, in insert_books_from_dictionary
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
TypeError: 'long' object is not iterable
On changing update to create the error is no more. How do i resolve this issue?
in
book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
you are using update, not update_or_create
Book.objects.update updates only and returns the number of rows affected, which is the 'long' object is not iterable python complains about, since it has to assign its elements to the tuple book, created

python: TypeError: 'str' object is not callable

i'm trying to load a binary file with pickle that has a record in a list, like so
import pickle
class player_energy_usage():
def __init__(self):
self.weapons = 25
elf.shields = 25
self.life_support = 25
self.engines = 25
def p_eu_init():
global p_energy
p_energy = []
player_ship_energy = player_energy_usage()
p_energy.append(player_ship_energy)
pickle.dump(p_energy,open('p_energy.dat','wb'))
p_eu_init()
pickle.load('rb'('p_energy.dat'))
print('Weapons are using {0}% of energy'.format(p_energy[0].weapons))
print('Shields are using {0}% of energy'.format(p_energy[0].shields))
print('Life Support is using {0}% of energy'.format(p_energy[0].life_support))
print('Engines is using {0}% of energy'.format(p_energy[0].engines))
However i get a type error,
Traceback (most recent call last):
File "E:/Python texted based game/Tests/file loading test.py", line 18, in <module>
pickle.load('rb'('p_energy.dat'))
TypeError: 'str' object is not callable
thanks for the help.
That is not the correct syntax. It should be instead:
p_energy = pickle.load(open('p_energy.dat', 'rb'))
What you're actually doing is:
'rb'('p_energy.dat') is trying to call the str object 'rb' with an argument of 'p_energy.dat', which is why you get the error 'str' object is not callable.

Categories

Resources