I think there is something wrong with my naming convention but I'm not sure how to fix it. it keeps giving me an invalid object even when tried to name it based on the vertex please help.
for i in range(1,100):
print i
def cactus():
#creating base of cactus
cmds.polyCylinder(sc=1,sa=10,sh=10, n= "cactus1_Base["+str(i)+"]")
The error I'm getting is:
# Error: TypeError: file <maya console> line 17: Object cactus1_Base[99].e[140:169] is invalid this is the error im getting and the code is
I dont have maya this week so I cant really check the result of this code
The first piece of codes woulld be for me the best solution but you have also the second one.
Note that in your code, character '[' and ']' are reserved in maya for components : vtx[], e[], f[]...etc
so you cant use them for naming
Secondly when you create your iteration 'i', it is outside your function so there is no real connection between i and your function cactus()
So you have to think on how you want to create cactus. That why I have written those two examples :
the first consider that you are creating cactus elements
the second one is just for creating a bunch of cactus
You could go beyond with kwargs and try to mimic cmds.polyCylinder
Just in case a bit python lessons for maya : https://www.youtube.com/watch?v=PDKxDbt6EGQ&t=4s
def nameChecker(name, start=0, max=100000, stringFormat=True):
if not '{' in name:
stringFormat = False
a = start
while a < max:
if stringFormat:
confName = name.format(a)
else:
confName = name + str(a)
if not cmds.objExists(confName):
return confName
a+=1
def create_cactus(baseName='cactus1_Base_{:03d}'):
name_conform = nameChecker(baseName)
cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name_conform)[0]
return cactus
cactus_output = []
for i in range(1,100):
cactus = create_cactus()
cactus_output.append(cactus)
print(cactus_output )
OR more simple :
def create_cactus(nb_of_cactus=100):
cactus_output = []
for nb in range(nb_of_cactus):
name = "cactus1_Base_{}".format(nb)
cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name)[0]
cactus_output.append(cactus)
return cactus
myCactus= create_cactus(100)
print(myCactus)
or based on selection :
def create_cactusVtx():
mysel = cmds.ls(sl=True, fl=True)
for i in range(len(mysel)):
id = mysel.split('[')[-1][:-1]
name = "cactus1_Base_{}".format(i)
cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name)[0]
Related
I'm trying to use the following script (which is largely based off of this wonderful Colab here: https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold2.ipynb#scrollTo=UGUBLzB3C6WN) to visualize the predicted folding of an amino acid sequence. I'm having trouble configuring the script in a way that will run, and for largely-institutional reasons, I'm not able to freely run-and-debug the script on my data, and can really only use it for the final runs. The error message I'm receiving right now (in reference to the show_pdb() third-to-last line) is:
AttributeError: 'NoneType' object has no attribute 'show'
Can someone help me resolve this issue, and possibly others that aren't yet apparent to me? I've included the hashed-out parts for context, if it's necessary or desired, but the main part I'd like help with is the construction of the show_pdb() function.
import os
import re
import glob
##title Display 3D structure {run: "auto"}
model_num = 1 ##param ["1", "2", "3", "4", "5"] {type:"raw"}
color = "lDDT" ##param ["chain", "lDDT", "rainbow"]
show_sidechains = False ##param {type:"boolean"}
show_mainchains = False ##param {type:"boolean"}
def get_filepaths(root_path: str, file_regex: str):
return glob.glob(os.path.join(root_path, file_regex))
rootdir = '/projects/p31492/long_alphafold/alphafold__long_sequence_file'
regex = '.pdb'
pdb_files = get_filepaths(rootdir, regex)
def show_pdb(model_num=1, show_sidechains=False, show_mainchains=False, color="lDDT"):
for file in pdb_files:
view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js',)
view.addModel(open(file,'r').read(),'pdb')
if color == "lDDT":
view.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':50,'max':90}}})
elif color == "rainbow":
view.setStyle({'cartoon': {'color':'spectrum'}})
elif color == "chain":
for n,chain,color in zip(range(homooligomer),list("ABCDEFGH"),
["lime","cyan","magenta","yellow","salmon","white","blue","orange"]):
view.setStyle({'chain':chain},{'cartoon': {'color':color}})
if show_sidechains:
BB = ['C','O','N']
view.addStyle({'and':[{'resn':["GLY","PRO"],'invert':True},{'atom':BB,'invert':True}]},
{'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
view.addStyle({'and':[{'resn':"GLY"},{'atom':'CA'}]},
{'sphere':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
view.addStyle({'and':[{'resn':"PRO"},{'atom':['C','O'],'invert':True}]},
{'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
if show_mainchains:
BB = ['C','O','N','CA']
view.addStyle({'atom':BB},{'stick':{'colorscheme':f"WhiteCarbon",'radius':0.3}})
view.zoomTo()
return view
show_pdb(model_num,show_sidechains, show_mainchains, color="1DDT").show()
if color == "lDDT": plot_plddt_legend().show()
plot_confidence(model_num).show()
The view object needs to be created before the for loop so that it gets updated every cycle instead of overwriting the previous version.
So the following code
for file in pdb_files:
view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js',)
view.addModel(open(file,'r').read(),'pdb')
...
will look something like below.
view = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')
for file in pdb_files:
view.addModel(open(file,'r').read(),'pdb')
...
And you need to assign a value to the variable homooligomer prior to its use later in the code.
elif color == "chain":
for n,chain,color in zip(range(homooligomer),list("ABCDEFGH"),
["lime","cyan","magenta","yellow","salmon","white","blue","orange"]):
view.setStyle({'chain':chain},{'cartoon': {'color':color}})
i know there are a lot of people asking a similar question and i also understand what the answers are trying to say but no matter what i try,it just doesnt work.
someone help!
here is my code (well a shorter version)
import random
##opening all the files and reading them line by line.
file_1 = open("devices.txt","r")
read_1 = file_1.readlines()
file_2 = open("phones.txt","r")
read_2 = file_2.readlines()
def choose_device():##creating function
device = input(read_1[0]).lower()##asking the user by printing a question from file_1
if device == "phone" or device == "phones" or device == "smartphone" or device == "smartphones" or device == "1":
brand = input(read_2[0])
if brand == "samsung":
version = input(read_2[1])
raw_memory = input(read_2[4])
solution_for_phones()
elif brand == "iphone":
version = input(read_2[2])
raw_memory = input(read_2[4])
solution_for_phones()
elif brand == "sony":
version = input(read_2[3])
raw_memory = input(read_2[4])
solution_for_phones()
else:
print(read_2[5])
do_again()##restart
def solution_for_phones():
datadict = {} ##creating a dictionary
with open('phonesolution.txt') as file: ##opening file
for rec in file: ##looping through every line
rec = rec.split(':') ##delimiter is :
problem = rec[0] ##first values before the delimiter are saved as problems
answer = rec[1] ##second values after the delimiter are saved as answers
problem = problem.split(" ") ##problems is further split by the delimiter "space"
for item in problem: ##every word in the problem section is assigned to an answer
datadict[item] = answer
user_problem = input('What is the problem?: ')##asking the user where the problem is
split_answer = user_problem.split(" ")##splitting the users answer into separate words
for option in datadict.keys():
if option in split_answer:##mathcing the users answer to keywords in the problem
print(datadict[option])
else:
CaseNo = (random.randrange(100000,999999))
print (CaseNo)
ReportFile = open('not_found.txt', 'a')
ReportFile.write ("\n"+"-------------------------------------------")
ReportFile.write ("\n"+"Case No is : "+str(CaseNo))
ReportFile.write ("\n"+"Case No is : "+(device))
ReportFile.close
do_again()
and here is the error message. anybody knows how to fix it?
welcome to our trouble shooting system
what device do you have a problem with? (these are the options:1.smartphones, 2.laptops, 3.game consoles)
smartphones
what brand is your phone? (eg: samsung, iphone)
samsung
what version is your samsung? (eg:J3, S7 edge)
J3
what is the memory size? (eg:8g, 16gb)
8
What is the problem?: vZrfvSZ
109451
Traceback (most recent call last):
File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 156, in <module>
choose_device()##calling the function
File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 110, in choose_device
solution_for_phones()
File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 58, in solution_for_phones
ReportFile.write ("\n"+"Case No is : "+(device))
NameError: name 'device' is not defined
Zwol's comment is the correct answer:
device is a local variable within choose_device. To make it accessible
from inside solution_for_phones you will have to pass it there as an
argument.
Here is how that works in code, since from your last comment it seems like you're still confused.
You define solution_for_phones with def solution_for_phones():. But it needs a value for device to work, since it uses device. So first change your function definition to:
def solution_for_phones(device):
Now solution_for_phones requires a value for device to be passed to it to run.
Next you need to make sure that everytime you call solution_for_phones, you pass a value for device. Everywhere in choose_device() where you have solution_for_phones(), you need to replace that with solution_for_phones(device).
You should also probably google something like "python passing values between functions" and read up some more on this, such as the difference between "positional" vs "keyword" parameters of functions.
This is the error which comes up:
What type of device is it?phone
What make of phone is it? [Iphone, Samsung or other]samsung
Traceback (most recent call last):
File "C:\Users\Chris\Documents\Chris\School\School\computing\task 3 testing.py", line 79, in <module>
if ('4') in model_iphone:
NameError: name 'model_iphone' is not defined
I have no idea how to fix it. It would be helpful if someone could point out some potential problems with my code. I know its not the most efficient code but it would be great to have some help with it thanks.
My code:
apple_question = []
for row in apple_file:
apple_question.append(row)
other = open("task 3 other questions.csv")
other_file = csv.reader(other)
other_question = []
for row in other_file:
other_question.append(row)
pre_questions = open("task 3 pre questions.csv")
pre_questions_file = csv.reader(pre_questions)
pre_questions_question = []
for row in pre_questions_file:
pre_questions_question.append(row)
device_type = input(pre_questions_question[1][0])
device_type.lower()
if ('phone') in device_type:
make = input(pre_questions_question[2][0])
make.lower()
elif ('iphone')in make:
model_iphone = input(samsung_question[1][0])
model_iphone.lower()
elif ('samsung') in make:
model_samsung = input(samsung_question[1][0])
model_samsung.lower()
elif ('other') in make:
make_other = input(other_question[0][0])
make_other.lower()
model_other = input(other_question[1][0])
model_other.lower()
problem_other = input(other_question[2][0])
problem_other.lower
info = print(other_question[3][0])
#other
text_file = open('Otherdevice.txt', 'w' )
text_file.write(make_other)
text_file.write(model_other)
text_file.write(problem_other)
text_file.close()
#apple
if ('4') in model_iphone:
ios = input(apple_question[3][0])
elif ('5') in model_iphone:
ios = input(apple_question[3][0])
elif ('5c') in model_iphone:
ios = input(apple_question[3][0])
if ('7') in ios:
memory = input(apple_question[4][0])
elif ('8') in ios:
memory = input(apple_question[4][0])
elif ('9') in ios:
memory = input(apple_question[4][0])
else:
print("Sorry but you have entered invalid or not surported information please try again")
if ('8gb') in memory:
query = input(apple_question[5][0])
elif ('16gb') in memory:
query = input(apple_question[5][0])
elif ('32gb') in memory:
query = input(apple_question[5][0])
#samsung
if ('s4') in model_samsung:
android = input(samsung_question[2][0])
elif ('s5') in model_samsung:
android = input(samsung_question[2][0])
elif ('s6') in model_samsung:
android = input(samsung_question[2][0])
else:
print("Sorry but you have entered invalid or not surported information please try again")
if ('jellybean') in android:
service_provider = input(samsung_question[3][0])
elif ('lollipop') in android:
service_provider= input(samsung_question[3][0])
elif ('marshmallow') in android:
service_provider = input(samsung_question[3][0])
It's kind of hard to follow what's going on in your code, but from what I can see, it looks like you're never making the variable model_iphone. Instead it seems like, since you're inputting "samsung", the code is making a variable called model_samsung, which does the same thing. Instead of making all these different variables that do the same thing (and only ever initializing one of them), try just making one uniform variable:
#Previous code...
#check for device type
if ('phone') in device_type:
make = input(pre_questions_question[2][0])
make.lower()
#separate if statement block to process the make and model after determining the type
if ('iphone')in make: #I CHANGED THIS LINE AS WELL TO WHAT YOU INTENDED IT TO DO (I think)
model = input(samsung_question[1][0])
model.lower()
elif ('samsung') in make:
model = input(samsung_question[1][0])
model.lower()
elif ('other') in make:
make_other = input(other_question[0][0])
make_other.lower()
model = input(other_question[1][0])
model.lower()
problem_other = input(other_question[2][0])
problem_other.lower
info = print(other_question[3][0])
#other
text_file = open('Otherdevice.txt', 'w' )
text_file.write(make_other)
text_file.write(model)
text_file.write(problem_other)
text_file.close()
#apple
#ask the corresponding questions
if ('4') in model:
ios = input(apple_question[3][0])
#Continue code...
Note how all the inputs to the same question now all channel into the same variable, so that no matter what part of the if block is called, it will always initialize the variable you need, so that you can process later (I used model in the example).
It's also important to note that in an if block, if one part of the if block is used (the first one found when reading down), then all the other elif statements afterwords are ignored as well. If you want two unrelated if statements, you'd create the following code:
if statement1:
#code here
elif statement2:
#code not executed if statement1 is true
if statement3:
#code executed, regardless of whether or not
#either of the above statements are true or not
In this example, statements 1 and 2 are part of one if block, while statement 3 is part of another block. That might help fix some problems in your code as well. Good luck on coding, and keep at it!
I want to append a list of array in dynamodb using python. I am using boto for the same. I am able to append the list in python and saving it in a variable. Now just wanted to append that value in an item (list of array) which is empty right now and don't know how to do it. So it would be great if anyone can help me with that.
result = self.User_Connection.scan(main_user__eq=self.username)
for connection_details in result:
main_user = connection_details['main_user']
connection_list = connection_details['connections']
connection_list.append(frnd_user_id)
I want to add this connection_list.append(frnd_user_id) as an item.
I've tried doing like this:-
if user_connections['connections'] == None:
self.User_Connection.put_item(data={'connections' : set(frnd_user_id)})
else:
self.User_Connection.update_item(Key = {user_connections['id']}, UpdateExpression="SET connections = list_append(connections, :i)",
ExpressionAttributeValues={':i': [frnd_user_id],})
but it is not working. Giving error:-
'Table' has no attribute 'update_item'
I've tried doing like this too:-
result = self.User_Connection.scan(main_user__eq=self.username)
for connection_details in result:
main_user = connection_details['main_user']
main_userid = connection_details['id']
connection_list = connection_details['connections']
print connection_list
if connection_details['connections'] == None:
self.User_Connection.put_item(data={'id' : main_userid,
'main_user':self.username,
'connections[]' : frnd_user_id})
else:
item = self.User_Connection.get_item(id = connection_details['id'])
for i in frnd_user_id:
item[connection_list].append(i)
item.save(overwrite=True)
this is showing error too.
unhashable type: 'list'
I am trying to get maya to check if the listed object is a blendshape node or not.
This is my code:
def bake(self, *args):
self.items["selection"] = cmds.ls(sl = True)
self.items["shapes"] = cmds.listRelatives(self.items["selection"], ad = True)
shapes = ()
for i in self.items["shapes"]:
bs = cmds.listConnections(i, type = "blendShape", exactType = True)
if cmds.objectType(bs, isType = "blendShape"):
print bs
It returns # Error: RuntimeError: file X:/Documents/maya/scripts\jtBakeCharacter.py line 16: No object name specified
Line 16 is: if cmds.objectType(bs, isType = "blendShape"):
Except that I AM specifying an object name, that object name is bs .. I have printed the result of bs and it has many objects listed. Many.
The code is redundant. You don't need most of the lines. The listConnections already ensures that you have only blendshapes. The exact problem is that you are calling something like:
cmds.objectType([])
for some of those extra shapes. And this is illegal. But mostly you code can be encapsulated as follows:
selected = cmds.ls(sl = True, dag=True ,shapes = True)
blends = cmds.listConnections(selected , type = "blendShape", exactType = True)
for item in blends:
print item
But this may not catch your intent perfectly, but shows how may extra steps you take. In reality you don't need the line if cmds.objectType(bs, isType = "blendShape"): for anything
Joojaa's answer is elegant, but you can get it down even shorter by using the default selection behavior:
blendshapes = cmds.ls(cmds.listHistory(pdo=True), type='blendShape') or []
for item in blendshapes:
print item
(In the quest to make it even shorter I'm not checking for the selection, so this one fails if nothing is selected).
PS: if you need to get to the blendshape from one of the upstream shapes, instead of the deformed shape, you can use listHistory (f=True)
You could try this:
from pymel.core import *
for obj in selected():
shapeNode = obj.getChildren()[0]
for output in shapeNode.outputs():
if nodeType(output) == "blendShape":
print obj, "is a blendshape"