Indentation error in def commonMenu - python-2.7

I'm new to Python but known to MEL.
At the moment I try to create a menu for my specialization project (quick rigging tool).
I'm getting this error every time while I can't find a logical explanation for it.
The error is a unexpected indent, it appears in a def to create a menu.
I really try to get this thing of the ground, thanks in advance :)
The code:
#Python script: Autorig v0.0.1
#Interface
import maya.cmds as cmds
#Create main window
#
class AR_OptionWindow(object):
def __init__(self):
self.window = 'ar_optionsWindow'
self.title = 'Options Window'
self.size = (546, 350)
self.supportsToolAction = False
def commonMenu(self):
self.editMenu = cmds.menu(label = 'Edit')
self.editMenuSave = cmds.menuItem(
label='Save Settings'
)
self.editMenuReset = cmds.menuItem(
label='Reset Settings'
)
self.editMenuDiv = cmds.menuItem(d=True)
self.editMenuRadio = cmds.radioMenuItemCollection()
self.editMenuAction = cmds.menuItem(
label='As Action',
radioButton=True,
enable=self.supportsToolAction
)
self.editMenuTool = cmds.menuItem(
label='As Tool',
radioButton=True,
enable=self.supportsToolAction
)
self.helpMenu = cmds.menuItem(label='Help')
self.helpMenuItem = cmds.menuItem(
label='Help in %s'%self.title
)
def create(self):
if cmds.window(self.window, exists=True):
cmds.deleteUI(self.window, window=True)
self.window = cmds.window(
self.window,
title=self.title,
widthHeight=self.size
)
cmds.showWindow()
I'm getting the following error:
# Error: unexpected indent
# File "<maya console>", line 30
# self.editMenuTool = cmds.menuItem(
# ^
# IndentationError: unexpected indent
#

Your indentation is a mix of tabs and spaces, which can lead to unexpected behavior. This is due to the somewhat arcane rules that determine how tabs are interpreted:
First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
In this image, tabs are arrows and spaces are dots. Your self.editMenuAction = line effectively has 12 spaces of indentation. Your self.editMenuTool = line effectively has 16.
According to PEP 8, you should exclusively use spaces for indentation.

Related

How to add a string to a file with the execution of a regular expression?

import re
import logging
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
f.write(x + '\n')
else:
logging.debug("does not match")
However, nothing is written in the file some.txt
I got a logging file which wrote away 'does not match' with the following changes:
import re
import logging
logging.basicConfig(filename = ( "loggingfile.log"), level = logging.DEBUG, format = '%(message)s')
x = input("enter number of bad car")
if re.match('/^[A-ZА-Я]{1}[0-9]{3}[A-ZА-Я]{2}([0-9]{0,3})?$/', x):
logging.debug("found match" + x)
with open("some.txt" , 'w') as f:
needed = str(x + '\n')
logging.info(needed)
else:
logging.info("does not match")
So, I added:
logging.basicConfig, which set some basic configuration stuff
for your logging file (name, path, format...)
I created needed up front, which has all the needed data in it, and then wrote it away to the logging file using logging.info()
I think that that is all that I changed, hope I helped out!
I got output like this from 'logging.log' with input (the random number) 56184615:
does not match
Your regex cannot match. `/^' means a slash, followed by the start of the string. Try to remove the two slashes in the regex.

Django Python shell indentation error

when i paste the below code in my python shell. I get an Indentation error.
... print "this is an ideal answer for both" File "", line
2
print "this is an ideal answer for both"
^ IndentationError: expected an indented block
def get_match(user_a, user_b):
user_a_answers = UserAnswer.objects.filter(user=user_a)[0]
user_b_answers = UserAnswer.objects.filter(user=user_b)[0]
if user_a_answers.question.id == user_b_answers.question.id:
user_a_answer = user_a_answers.my_answer
user_a_pref = user_a_answers.their_answer
user_b_answer = user_b_answers.my_answer
user_b_pref = user_b_answers.their_answer
if user_a_answer == user_b_pref:
print "%s fits with %s's preference" %(user_a_answers.user.username, user_b_answers.user.username)
if user_a_pref == user_b_answer:
print "%s fits with %s's preference" %(user_a_answers.user.username, user_b_answers.user.username)
if user_a_answer == user_b_pref and user_a_pref == user_b_answer:
print "this is an ideal answer for both"
get_match(mohit, saraswati)
get_match(saraswati, userc)
get_match(mohit, userc)
i get an indentation error , when i run this from the shell , why?`
It is hard to determine your indentation error. Because Python supports one-way indentation. You may be used Tab and spaces at a time. Please check by yourself and use only one at a time. Spaces are recommended.

PyYAML, safe_dump adding line breaks and indent to the YAML file

I want to receive following YAML file:
---
classes:
- apache
- ntp
apache::first: 1
apache::package_ensure: present
apache::port: 999
apache::second: 2
apache::service_ensure: running
ntp::bla: bla
ntp::package_ensure: present
ntp::servers: '-'
After parsing, I received such output:
---
apache::first: 1
apache::package_ensure: present
apache::port: 999
apache::second: 2
apache::service_ensure: running
classes:
- apache
- ntp
ntp::bla: bla
ntp::package_ensure: present
ntp::servers: '-'
Here, I have found the properties that give possibility to style document. I tried to set line_break and indent, but it does not work.
with open(config['REPOSITORY_PATH'] + '/' + file_name, 'w+') as file:
yaml.safe_dump(data_map, file, indent=10, explicit_start=True, explicit_end=True, default_flow_style=False,
line_break=1)
file.close()
Please, advice me simple approach to style the output.
You cannot do that in PyYAML. The indent option only affects mappings and not sequences. PyYAML also doesn't preserve order of mapping keys on round-tripping.
If you use ruamel.yaml (dislaimer: I am the author of that package), then getting the exact same input as output is easy:
import ruamel.yaml
yaml_str = """\
---
classes:
- apache # keep the indentation
- ntp
apache::first: 1
apache::package_ensure: present
apache::port: 999
apache::second: 2
apache::service_ensure: running
ntp::bla: bla
ntp::package_ensure: present
ntp::servers: '-'
"""
data = ruamel.yaml.round_trip_load(yaml_str)
res = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2,
explicit_start=True)
assert res == yaml_str
please note that it also preserves the comment I added to the first sequence element.
You can build this from "scratch" but adding a newline is not something for which a call exists in ruamel.yaml:
import ruamel.yaml
from ruamel.yaml.tokens import CommentToken
from ruamel.yaml.error import Mark
from ruamel.yaml.comments import CommentedMap, CommentedSeq
data = CommentedMap()
data['classes'] = classes = CommentedSeq()
classes.append('apache')
classes.append('ntp')
data['apache::first'] = 1
data['apache::package_ensure'] = 'present'
data['apache::port'] = 999
data['apache::second'] = 2
data['apache::service_ensure'] = 'running'
data['ntp::bla'] = 'bla'
data['ntp::package_ensure'] = 'present'
data['ntp::servers'] = '-'
m = Mark(None, None, None, 0, None, None)
data['classes'].ca.items[1] = [CommentToken('\n\n', m, None), None, None, None]
# ^ 1 is the last item in the list
data.ca.items['apache::service_ensure'] = [None, None, CommentToken('\n\n', m, None), None]
res = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2,
explicit_start=True)
print(res, end='')
You will have to add the newline as comment (without '#') to the last element before the newline, i.e. the last list element and the apache::service_ensure mapping entry.
Apart from that you should ask yourself if you really want to use PyYAML which only supports (most of) YAML 1.1 from 2005 and not the latest revision YAML 1.2 from 2009.
The wordpress page you linked to doesn't seem very serious (it doesn't even have the package name, PyYAML, correct).

c++ macro for saving enum element names and values to file

Normally I try to avoid the use of macros, so I actually don't know how to use them beyond the very most basic ones, but I'm trying to do some meta-manipulation so I assume macros are needed.
I have an enum listing various log entries and their respective id, e.g.
enum LogID
{
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
...
}
which is used within my program when writing data to the log file. Note that they will not, in general, be in any order.
I do most of my log file post-processing in Matlab so I'd like to write the same variable names and values to a file for Matlab to load in. e.g., a file looking like
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
...
I have no idea how to go about doing this, but it seems like it shouldn't be too complicated. If it helps, I am using c++11.
edit:
For clarification, I'm not looking for the macro itself to write the file. I want a way to store the enum element names and values as strings and ints somehow so I can then use a regular c++ function to write everything to file. I'm thinking the macro might then be used to build up the strings and values into vectors? Does that work? If so, how?
I agree with Adam Burry that a separate script is likely best for this. Not sure which languages you're familiar with, but here's a quick Python script that'll do the job:
#!/usr/bin/python
'''Makes a .m file from an enum in a C++ source file.'''
from __future__ import print_function
import sys
import re
def parse_cmd_line():
'''Gets a filename from the first command line argument.'''
if len(sys.argv) != 2:
sys.stderr.write('Usage: enummaker [cppfilename]\n')
sys.exit(1)
return sys.argv[1]
def make_m_file(cpp_file, m_file):
'''Makes an .m file from enumerations in a .cpp file.'''
in_enum = False
enum_val = 0
lines = cpp_file.readlines()
for line in lines:
if in_enum:
# Currently processing an enumeration
if '}' in line:
# Encountered a closing brace, so stop
# processing and reset value counter
in_enum = False
enum_val = 0
else:
# No closing brace, so process line
if '=' in line:
# If a value is supplied, use it
ev_string = re.match(r'[^=]*=(\d+)', line)
enum_val = int(ev_string.group(1))
# Write output line to file
e_out = re.match(r'[^=\n,]+', line)
m_file.write(e_out.group(0).strip() + '=' +
str(enum_val) + ';\n')
enum_val += 1
else:
# Not currently processing an enum,
# so check for an enum definition
enumstart = re.match(r'enum \w+ {', line)
if enumstart:
in_enum = True
def main():
'''Main function.'''
# Get file names
cpp_name = parse_cmd_line()
m_name = cpp_name.replace('cpp', 'm')
print('Converting ' + cpp_name + ' to ' + m_name + '...')
# Open the files
try:
cpp_file = open(cpp_name, 'r')
except IOError:
print("Couldn't open " + cpp_name + ' for reading.')
sys.exit(1)
try:
m_file = open(m_name, 'w')
except IOError:
print("Couldn't open " + m_name + ' for writing.')
sys.exit(1)
# Translate the cpp file
make_m_file(cpp_file, m_file)
# Finish
print("Done.")
cpp_file.close()
m_file.close()
if __name__ == '__main__':
main()
Running ./enummaker.py testenum.cpp on the following file of that name:
/* Random code here */
enum LogID {
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
LOG_ID_ITEM4
};
/* More random code here */
enum Stuff {
STUFF_ONE,
STUFF_TWO,
STUFF_THREE=99,
STUFF_FOUR,
STUFF_FIVE
};
/* Yet more random code here */
produces a file testenum.m containing the following:
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
LOG_ID_ITEM4=11;
STUFF_ONE=0;
STUFF_TWO=1;
STUFF_THREE=99;
STUFF_FOUR=100;
STUFF_FIVE=101;
This script assumes that the closing brace of an enum block is always on a separate line, that the first identifier is defined on the line following the opening brace, that there are no blank lines between the braces, that enum appears at the start of a line, and that there is no space following the = and the number. Easy enough to modify the script to overcome these limitations. You could have your makefile run this automatically.
Have you considered "going the other way"? It usually makes more sense to maintain your data definitions in a (text) file, then as part of your build process you can generate a C++ header and include it. Python and mako is a good tool for doing this.

Python List NoneType Error

I'm having an issue with an OpenCourseWare project I'm trying to implement. I'm creating a hangman game and everything seems to be okay until I attempt to run the actual function for playing the game.
I'm receiving the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "Game of Hangman/hangman.py", line 118, in play_hangman
print(print_guessed())
File "Game of Hangman/hangman.py", line 92, in print_guessed
if letter in letters_guessed == True:
TypeError: argument of type 'NoneType' is not iterable
I can't seem to understand why the list is evaluating to a NoneType even though it is declared as an empty list. I've used the console to attempt to find the answer and says the type is NoneType. Could someone help me please? I've provided the code as a reference.
# Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = split(line)
print " ", len(wordlist), "words loaded."
print 'Enter play_hangman() to play a game of hangman!'
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = get_word()
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
wordGuessed = False
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
wordGuessed = True
else:
wordGuessed = False
break
return wordGuessed
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
printedWord = []
####### YOUR CODE HERE ######
for letter in secret_word:
if letter in letters_guessed:
printedWord.append(letter)
else:
printedWord.append("-")
return printedWord
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
# Update secret_word. Don't uncomment this line until you get to Step 8.
secret_word = get_word()
####### YOUR CODE HERE ######
while mistakes_made < MAX_GUESSES or word_guessed() == False:
print("WORD:")
userGuess = raw_input("What is your guess?\n").lower()
if userGuess in secret_word:
letters_guessed = letters_guessed.append(userGuess)
else:
letters_guessed = letters_guessed.append(userGuess)
mistakes_made += 1
print(print_guessed())
if word_guessed() == False:
print("Sorry but you've run out of guesses...")
else:
print("You've correctly guessed the secret word!")
print("Secret Word: " + secret_word)
Just as a disclaimer, this isn't an assignment in the sense I'm not enrolled in school. I'm just a guy trying to get back in to programming and found some assignments to play with.
Looks like I've found my answer. The problem appeared to be with the assignment I was doing with the letters_guessed variable.
Instead of doing:
letters_guessed = letters_guessed.append(userGuess)
I should have done:
letters_guessed.append(userGuess)