from PIL import Image
import input_class
import input_function
import input_crop_values
import input_translate
class ImageChanger():
def __init__ ():
image_filename = input_class.input_file_name()
self.my_image = Image.open(image_filename)
chosen_Function = input_function.input_vaild_function()
if chosen_Function == "Crop" or chosen_Function == "crop":
crop_values = input_crop_values.input_crop_data()
my_image.crop(crop_values)
elif chosen_Function == "Translate" or chosen_function == "translate":
translate_values = input_translate.input_translate_data()
my_image.crop(translate_values)
else:
print("unexpected error while running code")
def printState():
print( "Your image file name is %s" % self.my_filename );
return (self.my_filename);
def translate(self,x_cord,y_cord):
return (self.my_image.offset(x_cord,y_cord));
def crop(self, box):
return (self.my_image.crop(box))
sorry for odd formatting,
Error:
Traceback (most recent call last):
File "C:\Users\Alexander\Desktop\Final_Udacity_project\dragon_picture_test.py", line 1, in <module>
import picture_changer
File "C:\Users\Alexander\Desktop\Final_Udacity_project\picture_changer.py", line 3, in <module>
import input_function
File "C:\Users\Alexander\Desktop\Final_Udacity_project\input_function.py", line 14
else
^
SyntaxError: invalid syntax
I have some other functions, not listed that use the input command sort of like a user interface, then it returns it to the larger class.
The places that the values are returned and what is return is:
line 8*: image_filename = input_class.input_file_name() # you would give a name of a picture here,
line 10*: chosen_function = input_function.input_vaild_function() # you Would give it either crop or translate can be sentence case or lowercase
line 11*: crop_values = input_crop_values.input_crop_data() # you would give it data in brackets like [1,2,3,4] and it would crop it.
line 15*: translate_values = input_translate.input_translate_data() # you would give it information in ( ), like (1,2,3,4) and it would translate it.
The code is acting really weird with the Boolean and the error message isn't helping me that much.
else, like other statements that come before a block, requires a colon.
else:
Related
I am trying to make the code cleaner and better manageable and i wanted to start with reading a cisco file. However when i try to put it in a function, it is not able to give me the outputs. The same works perfectly out of a function
Working model
parse = CiscoConfParse("C:\\python\\mydata\\TestConfigFile.txt")
TCPSrv = parse.find_objects("service\stcp\sdestination\seq")
UDPSrv = parse.find_objects("service\sudp\sdestination\seq")
ObjectNetwork = parse.find_objects("^object\snetwork\s")
ObjectGroupSrv = parse.find_objects("^object-group\sservice")
ObjectGroupNetwork = parse.find_objects("^object-group\snetwork\s")
This creates a list for all the above like the one below
TCPSrv = [<IOSCfgLine # 83 ' service tcp destination eq https' (parent is # 82)>,<IOSCfgLine # 97 ' service tcp destination eq www '(parent is # 102)>]
But when i put this into a function, it does not work. This is the first time i am trying out to use functions, and I know that i am doing something wrong.
This is my code for Functions
def cisco(filename):
parse = CiscoConfParse(filename)
TCPSrv = parse.find_objects("service\stcp\sdestination\seq")
UDPSrv = parse.find_objects("service\sudp\sdestination\seq")
ObjectNetwork = parse.find_objects("^object\snetwork\s")
ObjectGroupSrv = parse.find_objects("^object-group\sservice")
ObjectGroupNetwork = parse.find_objects("^object-group\snetwork\s")
return TCPSrv, UDPSrv, ObjectNetwork, ObjectGroupSrv, ObjectGroupNetwork
file = C:\\python\\mydata\\TestConfigFile.txt
cisco(file)
This does not give any output.
>>> TCPSrc
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'TCPSrc' is not defined
I have tried putting it like this below also
cisco("C:\\python\\mydata\\TestConfigFile.txt")
Can someone kindly assist what I am doing wrong.
This does not give any output
>>> TCPSrc
Traceback (most recent call last):
File "", line 1, in
NameError: name 'TCPSrc' is not defined
You have not assigned the return values to anything. When you call cisco(), you need to assign the return values to something... please use:
from ciscoconfparse import CiscoConfParse
def cisco(filename):
parse = CiscoConfParse(filename)
TCPSrv = parse.find_objects("service\stcp\sdestination\seq")
UDPSrv = parse.find_objects("service\sudp\sdestination\seq")
ObjectNetwork = parse.find_objects("^object\snetwork\s")
ObjectGroupSrv = parse.find_objects("^object-group\sservice")
ObjectGroupNetwork = parse.find_objects("^object-group\snetwork\s")
return TCPSrv, UDPSrv, ObjectNetwork, ObjectGroupSrv, ObjectGroupNetwork
values = cisco("C:\\python\\mydata\\TestConfigFile.txt")
TCPsrv = values[0]
UDPsrv = values[1]
# ... etc unpack the remaining values as illustrated above
Im brand new to python and coding, im trying to get below working.
this is test code and if I can get this working I should be able to build on it.
Like I said im new to this so sorry if its a silly mistake.
# coding=utf-8
import ops # Import the OPS module.
import sys # Import the sys module.
import re
# Subscription processing function
def ops_condition (o):
enter code herestatus, err_str = o.timer.relative("tag",10)
return status
def ops_execute (o):
handle, err_desp = o.cli.open()
print("OPS opens the process of command:",err_desp)
result, n11, n21 = o.cli.execute(handle,"return")
result, n11, n21 = o.cli.execute(handle,"display interface brief | include Ethernet0/0/1")
match = re.search(r"Ethernet0/0/1\s*(\S+)\s*", result)
if not match:
print("Could not determine the state.")
return 0
physical_state = match[1] # Gets the first group from the match.
print (physical_state)
if physical_state == "down":
print("down")
result = o.cli.close(handle)
else :
print("up")
return 0
Error
<setup>('OPS opens the process of command:', 'success')
Oct 17 2018 11:53:39+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[4]:Script is test.py, current event is tag, instance is 1515334652, exception reason is Trac eback (most recent call last):
File ".lib/frame.py", line 114, in <module>
ret = m.ops_execute(o)
File "flash:$_user/test.py", line 22, in ops_execute
physical_state = match[1] # Gets the first group from the match.
TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
The __getitem__ method for the regex match objects was only added since Python 3.6. If you're using an earlier version, you can use the group method instead.
Change:
physical_state = match[1]
to:
physical_state = match.group(1)
Please refer to the documentation for details.
I am simply trying to receive an input, run it through some if, elif conditions and replace certain text from a bunch of lines :
def task(appdynhost):
if (appdynhost) == "security":
appdynpass = 'xxxxxxxx'
elif (appdynhost) == "security2":
appdynpass = 'yyyyyyyy'
elif (appdynhost) == "security3":
appdynpass = 'zzzzzzzz'
elif (appdynhost) == "security4":
appdynpass = 'wwwwwwww'
replacements = {'<controller_name>':appdynhost,'<controller_password>';appdynpass}
s = r"""
"standardenv::v2_0_0_0_0":
"appgroups::v1_0_0_0_0":
definitions:
jdk: {gid: 5007}
app: {gid: 5008}
"appusers::v1_0_0_0_0":
definitions:
jdk: {group: jdk, uid: 5007}
app: {group: app, uid: 5008}
"jdk::v1_7_45_2_0::standard":
instance_owner: jdk
instance_group: jdk
"app::v1_1_2_1_0::standard":
instance_owner: app
instance_group: app
controller_host: "<controller_name>.saas.com"
account_name: "<controller_name>"
account_password: "<controller_password>" """
line=s.split()
for line in s.splitlines():
for src, target in replacements.iteritems():
line = line.replace(src, target)
lines.append(line)
with open('DC_mcp.yaml', 'w') as outfile:
for line in lines:
outfile.write(line + '\n')
print (line)
I am getting this error :
Traceback (most recent call last):
File "build/bdist.linux-x86_64/egg/bdblib/task_runner.py", line 72, in run_bdblib_task
File "build/bdist.linux-x86_64/egg/bdblib/run.py", line 38, in run
return task_module.task(env, **inputs)
TypeError: task() got multiple values for keyword argument 'appdynhost'
I am getting the input for appdynhost as a raw input. I am not sure whats going wrong.
You definition of "task" function only has one argument which you named "appdynhost".
def task(appdynhost):
...
Your call however has several:
return task_module.task(env, **inputs)
TypeError: task() got multiple values for keyword argument 'appdynhost'
At either the function or the call you'll need to fix the inputs.
First of, i'm sort of new to Python so sorry if this question is obvious. The detect english module appears to be wrong, but it functions perfectly fine when calling it and running it on its own, theres no errors when running it alone and i've rewritten it a couple times to triple check it.
Traceback (most recent call last):
File "H:\Python\Python Cipher Program\transposition hacker.py", line 49, in <module>
main()
File "H:\Python\Python Cipher Program\transposition hacker.py", line 11, in main
hackedMessage = hackTransposition(myMessage)
File "H:\Python\Python Cipher Program\transposition hacker.py", line 34, in hackTransposition
if detectEnglish.isEnglish(decryptedText):
File "H:\Python\Python Cipher Program\detectEnglish.py", line 48, in isEnglish
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
this is the error i am getting when trying to run the Transposition Hacker (copied directly from here
Here is the code for the Detect English Module
# Detect english Module
# to use this code
# import detectEnglish
# detectEnglish.isEnglish(somestring)
# returns true of false
# there must be a dictionary.txt file in the same directory
# all english words
# one per line
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary()
dictionaryFile = open('Dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
lettersOnly.append(symbol)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage=20, letterPercentage=85):
# by default 20% of the words mustr exist in dictionary file
# 85% of charecters in messafe must be spaces or letters
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
numLetters = len(removeNonLetters(message))
messageLettersPercentage = float(numLetters) / len(message) * 100
lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatcht
getEnglishCount looks like it is missing a return statement. If python gets to the end of a function without hitting a return statement it will return None as you're seeing.
try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
# if possibleWords == []: # redundant
# return 0.0
return len(possibleWords)
Edit: #Kevin Yea I think you're right - there was more in that function. Maybe try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0.
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return matches / len(possibleWords)
I'd guess the indentation somehow got changed when you copy and pasted the code, with the return statement nested under the if.
As the other poster has said, you're missing a return for the getEnglishCount method, so it's returning NoneType, meaning that there is no value to be returned.
You can't do math on NoneTypes, so the NoneType*100 fails, which is what the bottom of your error traceback says.
I am using rpy2 to run some R commands. Dont ask why. It's necessary at this moment. So here's a part of the code.
import pandas.rpy.common as com
from rpy2.robjects import r
#Load emotionsCART decision tree. Successful.
r_dataframe = com.convert_to_r_dataframe(data)
print type(r_dataframe)
(<class 'rpy2.robjects.vectors.DataFrame'>)
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
Here what I want to do is pass this r_dataframe into the calculation. I'm using the decision tree that I'd loaded earlier to predict the values. But the last line gives me an error. It says
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 245, in __call__
p = rinterface.parse(string)
ValueError: Error while parsing the string.
Ideas why this is happening?
I think that:
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
SHould be:
r('pred = predict(emotionsCART, newdata = %s)' % (r_dataframe) )
The %(r_dataframe) was associated with the r() part, while it should be associated with the '' (string).
But it is hard to check without a reproducible example.