Change maya global preferences via Pymel - python

I'm trying to make a simple button that wiil set global animation preferences in maya.
The script is supposed to change the animation preferences of DEFAULT IN TANGENT , DEFAULT OUT TANGENT and DEFAULT TANGENT WEIGHT.
so far this is what I got:
import pymel.core as pm
def setBlockingPrefs():
pm.keyTangent(edit = True, g = True, itt = 'clamped')
pm.keyTangent(edit = True, g = True, ott = 'step')
pm.keyTangent(edit = True, g = True, weightedTangents = 1)
def setSpliningPrefs():
pm.keyTangent(edit = True, g = True, itt = 'auto')
pm.keyTangent(edit = True, g = True, ott = 'auto')
pm.keyTangent(edit = True, g = True, weightedTangents = 1)
I get no error with this code, but then, i get nothing at all, the preferences are not changed.
What am I missing?
Thank you

Related

"ValueError: `x0` is infeasible." for least_squares.py

I'm trying to use this code in Webots for one of the universal robots. The code works well until I try to the "ikResults" in line 49. The program is trying to use the least_squares.py but I'm getting the error for "'x0' is infeasible". This is the code I'm using:
import sys
import tempfile
try:
import ikpy
from ikpy.chain import Chain
import math
from controller import Supervisor
IKPY_MAX_ITERATIONS = 4
supervisor = Supervisor()
timeStep = int(4 * supervisor.getBasicTimeStep())
filename = None
with tempfile.NamedTemporaryFile(suffix='.urdf', delete=False) as file:
filename = file.name
file.write(supervisor.getUrdf().encode('utf-8'))
armChain = Chain.from_urdf_file(filename, active_links_mask=[False, True, True, True, True,
True, True, False, True, True, True])
motors = []
for link in armChain.links:
if 'joint' in link.name and link.name !="wrist_3_link_gripper_joint":
motor = supervisor.getDevice(link.name)
motor.setVelocity(1.0)
position_sensor = motor.getPositionSensor()
position_sensor.enable(timeStep)
motors.append(motor)
target = supervisor.getFromDef('TARGET')
arm = supervisor.getSelf()
while supervisor.step(timeStep) != -1:
targetPosition = target.getPosition()
armPosition = arm.getPosition()
x = targetPosition[0] - armPosition[0]
y = targetPosition[1] - armPosition[1]
z = targetPosition[2] - armPosition[2]
initial_position = [0] + [m.getPositionSensor().getValue() for m in motors] + [0]
ikResults = armChain.inverse_kinematics([x, y, z], max_iter=IKPY_MAX_ITERATIONS,
initial_position=initial_position)`
I've tried incrementing the iterations, changing the target's position, changing the status for the links in armChain (true or false), but nothing seemed to solve this issue. Reading other similar forums, it seems to do something with the bounds, not sure how to check on this.

Passing defined function in np.where() for conditional output (Pandas, Python, Numpy)

I have the following sample DataFrame:
data = {'ID': ['14','15','16','18','19','20','21'],
'LOB': ["BNK", "BNK", "BNK", "BNK", "XYZ", "XYZ", "XYZ",],
'US_ALL': [False, False, True, True, True, False, True],
'US_50_States': [True, False, True, False, True, False, False],
'Primary': [False, True, True, False, True, False, True],
'Secondary': [True, False, True, False, False, True, True]}
I have the following defined function. My goal is to pass arguments based on the LOB column using conditional results.
def logic_for_bnk():
# Country and State Flag Logic
country_state_flag_conditions = [
(df['US_ALL'] == True) & (df['US_50_States'] == True),
(df['US_ALL'] == False) & (df['US_50_States'] == False),
(df['US_ALL'] == True) & (df['US_50_States'] == False),
(df['US_ALL'] == False) & (df['US_50_States'] == True),
]
country_state_flag_values = [
"""%keep(criteria="country = 'US' and states_50 = 1", desc="Keep only US and in 50 states customers");""",
"",
"""%keep(criteria="country = 'US'",desc="Keep customers in the US");""",
"""%keep(criteria="states_50 = 1", desc="Keep customers in 50 states");"""
]
df['Country_State_Logic'] = np.select(country_state_flag_conditions, country_state_flag_values, None)
# Primary and Secondary Logic
primary_secondary_flag_conditions = [
(df['Primary'] == True) & (df['Secondary'] == True),
(df['Primary'] == False) & (df['Secondary'] == False),
(df['Primary'] == True) & (df['Secondary'] == False),
(df['Primary'] == False) & (df['Secondary'] == True)
]
primary_secondary_flag_values = [
"""%keep(criteria="acct_ownership = '1' or acct_ownership = '2'",desc="Keep primary and secondary ownership");""",
"""%keep(criteria="acct_ownership = '1' or acct_ownership = '2'",desc="Keep primary and secondary ownership");""",
"""%keep(criteria="acct_ownership = '1'",desc="Keep primary ownership");""",
"""%keep(criteria="acct_ownership = '2'",desc="Keep secondary ownership");"""
]
df['Primary_Secondary_Logic'] = np.select(primary_secondary_flag_conditions, primary_secondary_flag_values, None)
# concatenating columns with SAS language output
df['SAS'] = df['Country_State_Logic'].astype(str) + df['Primary_Secondary_Logic'].astype(str)
# replacing all 'None' values with empty string ""
df.fillna("",inplace=True)
Following the function, I have the following which is where I am having issues. I'm trying to pass the logic_for_bnk() function into the following new column using np.where():
df['SAS Program Language'] = np.where((df['LOB'] == "BNK"), logic_for_bnk(),
np.where(df['LOB'] == "XYZ", "Pending XYZ Logic",
0))
I want my output to have 3 columns: ID, LOB, and SAS Program Language so I'm then adding the following drop argument to remove excess columns in the DataFrame:
df.drop(['US_ALL','US_50_States','Primary', 'Secondary','Country_State_Logic','Primary_Secondary_Logic'], axis = 1, inplace = True)
The issue here is that the resulting DataFrame contains 4 columns: ID LOB SAS SAS Program Language.
SAS is coming from the def logic_for_bnk() while SAS Program Language is coming from the new column I'm using along with np.where() arguments.
The SAS Program Language is passing None for BNK=LOB instead of the concatenated df['SAS'] and looks like this:
ID LOB SAS SAS Program Language
0 14 BNK %keep(criteria="states_50 = 1", desc="Keep cus... None
1 15 BNK %keep(criteria="acct_ownership = '1'",desc="Ke... None
2 16 BNK %keep(criteria="country = 'US' and states_50 =... None
3 18 BNK %keep(criteria="country = 'US'",desc="Keep cus... None
4 19 XYZ %keep(criteria="country = 'US' and states_50 =... Pending XYZ Logic
5 20 XYZ %keep(criteria="acct_ownership = '2'",desc="Ke... Pending XYZ Logic
6 21 XYZ %keep(criteria="country = 'US'",desc="Keep cus... Pending XYZ Logic
My goal is for the SAS Program Language column to have the concatenation defined in def logic_for_bnk() where LOB=BNK and have Pending XYZ Logic where LOB=XYZ.
Your function doesn't return anything! Add return df to the last line of your function. Other than that, it seems pd.DataFrame.apply is enough to create your desired output
sas_lang = df.LOB.apply(lambda x: logic_for_bnk() if x == 'BNK' else "Pending XYZ Logic")
sas_lang.name = 'SAS Program Language'
new_df = df.join(sas_lang)
Your desired output:
new_df[['ID', 'LOB', 'SAS Program Language']]

How to make variable local to runtime loop in Python (potentially due to asyncio)

I am currently making a discord bot using discord.py. Anyway, with my code, whenever I have a variable within an async loop, it gets (in my words) applied globally.
How do I make a variable exclusive to one runtime loop?
(observe the image below if you don't understand me, ignore the "Hey {}. You already have a game running", that's expected.)
The top is the pervious set of buttons, but I can interact with the bottom set of buttons by clicking the top set as they both share one list to store data.
Please help...
(Code shown below):
DiscordComponents(client)
compontentColours = [ButtonStyle.grey, ButtonStyle.grey, ButtonStyle.grey, ButtonStyle.grey,
ButtonStyle.grey, ButtonStyle.grey, ButtonStyle.grey, ButtonStyle.grey, ButtonStyle.grey]
matrix = ['', '', '', '', '', '', '', '', '']
disabled = [False, False, False, False,
False, False, False, False, False]
label = [1, 2, 3, 4, 5, 6, 7, 8, 9]
components = returnButton(
compontentColours, l=label, disabled=disabled)
embed = discord.Embed(
title=f"Let's play Tic Tac Toe, {message.author.name}!", color=0x7fffd4)
await message.channel.send(embed=embed)
msgAwaitInfo = await message.channel.send('Select a square', components=components)
# Awaiting keypress
for _ in range(5):
# Awaiting button click
res = await client.wait_for("button_click")
await res.respond(type=6)
# Processing the matrix
matrix[int(res.component.label)-1] = 'O'
disabled[int(res.component.label)-1] = True
compontentColours[int(res.component.label) -
1] = ButtonStyle.blue
# Check if player has won
iW = ifWon(matrix, lastMoveIndex=int(res.component.label)-1)
if not not iW[0]:
embed = discord.Embed(
title='{}'.format('Congratulations! You won, {}'.format(
message.author.name)),
color=0x008000
)
await message.channel.send(embed=embed)
disabled = [True, True, True, True, True, True, True, True, True]
if True: # Updating Matrix
# Creating the matrix labels
label = list(matrix[i] if matrix[i] != '' else str(i+1)
for i in range(0, len(matrix)))
components = returnButton(compontentColours, label, disabled)
await msgAwaitInfo.edit('Game Over.', components=components)
return
# The opponent's move - finding the best move for the bot
if matrix.count('O') == 5:
break
iW =guarranteedWin(matrix, toPlay = 'X')
if iW[0]:
indx = cordsToIndx[iW[1][0][1:3]]
matrix[indx] = 'X'
compontentColours[indx] = ButtonStyle.blue
label[indx] = 'X'
disabled[indx] = True
else:
while True:
rand = randint(0, 8)
if matrix[rand] == '':
matrix[rand] = 'X'
compontentColours[rand] = ButtonStyle.blue
label[rand] = 'X'
disabled[rand] = True
break
else:
continue
iW = ifWon(matrix, lastMoveIndex=rand)
print(iW)
if not not iW[0] and iW[1] == 'X':
embed = discord.Embed(
title='{}'.format('Oh no... you lost, {}'.format(
message.author.name)),
color=0xe32636
)
await message.channel.send(embed=embed)
disabled = [True, True, True, True, True, True, True, True, True]
if True: # Updating Matrix
# Creating the matrix labels
label = list(matrix[i] if matrix[i] != '' else str(i+1)
for i in range(0, len(matrix)))
components = returnButton(compontentColours, label, disabled)
await msgAwaitInfo.edit('Game Over.', components=components)
return
# Creating the matrix labels
label = list(matrix[i] if matrix[i] != '' else str(i+1)
for i in range(0, len(matrix)))
components = returnButton(compontentColours, label, disabled)
await msgAwaitInfo.edit('Select a square', components=components)
Note some functions are just the AI for the tic tac toe
Thank you,
(and sorry for the lengthy code)

How can I create a seamless backdrop with python in Blender?

I want to create a seamless backdrop for my blender project. It's done in a script and I want to add the backdrop to that script.
The problem is that I don't figure how to extrude a plane only in an edge so I can later bevel it and make it seamless. It's really easy to do with the GUI but I don't know how to do it in scripting.
I'm trying a few things, but for now I only have this code (which is obviously unfinished and not very well done):
bpy.ops.mesh.primitive_plane_add(radius=1, view_align=False, enter_editmode=False, location=(0, 0, 0), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))
plane2 = bpy.data.objects['Plane']
dims = plane2.dimensions
plane2.dimensions = 100, 70, 35
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='EDGE')
bpy.context.scene.objects[0].data.edges[0]
me = bpy.context.object.data
"""
# Get a BMesh representation
bm = bmesh.new() # create an empty BMesh
bm.from_mesh(me) # fill it in from a Mesh
# Modify the BMesh, can do anything here...
for e in bm.edges:
e.co.x += 1.0
"""
bpy.context.tool_settings.mesh_select_mode = (False, True, False)
bpy.ops.mesh.extrude_region_move(MESH_OT_extrude_region={"mirror":False}, TRANSFORM_OT_translate={"value":(0, 0, 88.1553), "constraint_axis":(False, False, True), "constraint_orientation":'GLOBAL', "mirror":False, "proportional":'DISABLED', "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False})
bpy.ops.object.editmode_toggle()
I want the backdrop to look like this, in case it helps to understand better the goal:
https://www.youtube.com/watch?v=Ycz1wQY_7KI
As you only need two faces for the backdrop, I would make the mesh from a python list. Then add a bevel modifier to round out the back corner.
import bpy
from bpy_extras.object_utils import object_data_add
from mathutils import Vector
verts = [
Vector(( 50,-35, 0)),
Vector(( 50, 35, 0)),
Vector((-50, 35, 0)),
Vector((-50,-35, 0)),
Vector((-50, 35, 35)),
Vector(( 50, 35, 35)),
]
faces = [[2,3,0,1], [5,4,2,1]]
mesh = bpy.data.meshes.new(name="Backdrop")
mesh.from_pydata(verts, [], faces)
object_data_add(bpy.context, mesh)
backdrop = bpy.context.object
bpy.ops.object.shade_smooth()
bev_mod = backdrop.modifiers.new('bevel', 'BEVEL')
bev_mod.width = 12
bev_mod.segments = 5
mat = bpy.data.materials.new('back_mat')
if bpy.app.version[1] < 80:
mat.diffuse_color = [1,1,1] # white
else:
# 2.80 needs alpha value in colour
mat.diffuse_color = [1,1,1,1]
backdrop.active_material = mat

Hexadecimals to pysical variables in Python

I bought a MCP23017 for my Raspberry Pi to increase the GPIO pins.
With the help of you guys I was able to install and read from the device. That means, I've interfaced with the MCP23017 and set the bus to 0x20 as I have A0-A3 connected to ground. Then, I've set the GPA and GPB with pull-up resistors.
The script looks as follows:
import smbus
import time
mcp = 0x20
address_map = {
0x12: 'GPIOA', 0x13: 'GPIOB',
}
register_map = {value: key for key, value in address_map.iteritems()}
max_len = max(len(key) for key in register_map)
def print_values(bus):
for addr in address_map:
value = bus.read_byte_data(mcp, addr)
print "%-*s: 0x%02X" % (max_len, address_map[addr], value)
bus = smbus.SMBus(1)
bus.write_byte_data(mcp, int(12), 0xFF)
bus.write_byte_data(mcp, int(13), 0xFF)
while True:
print_values(bus)
time.sleep(0.1)
This will print out the GPA or GPB in Hex per bank, like so if nothing is connected:
>>> GPIOA = 0xFF
>>> GPIOB = 0xFF
But if I connect GPB0 to GND for example, it becomes:
>>> GPIOA = 0xFF
>>> GPIOB = 0xFE
So the question is, how can I from this Hex (0000 0000 1111 1110) to assigning a dictionary so that I can tell which pin is which?
You could use bitstruct.
>>> GPIOA = 0xf0
>>> gpa = list(reversed(bitstruct.unpack('b1'*8, chr(GPIOA))))
>>> gpa
[False, False, False, False, True, True, True, True]
>>> gpa[3]
False
>>> gpa[4]
True
>>> GPIOA = 0x18
>>> gpa = list(reversed(bitstruct.unpack('b1'*8, chr(GPIOA))))
>>> gpa[5]
False
>>> gpa[4]
True
>>> gpa
[False, False, False, True, True, False, False, False]
This allows you to access the bits by index. Unfortunately, you have to reverse the resulting tuple for the indexes to be right, but it does work.
There is also a manual way:
>>> gpa = [False]*8
>>> GPIOA = 0xf0
>>> for i in range(8):
... gpa[i] = bool((1 << i) & GPIOA)
...
>>> gpa
[False, False, False, False, True, True, True, True]
With either method, you can get it into a dictionary like this:
>>> names = ['GPIOA0', 'GPIOA1', 'GPIOA2', 'GPIOA3', 'GPIOA4', 'GPIOA5', 'GPIOA6', 'GPIOA7']
>>> gpadict = dict(zip(names, gpa))
>>> gpadict
{'GPIOA4': True, 'GPIOA5': True, 'GPIOA6': True, 'GPIOA7': True, 'GPIOA0': False, 'GPIOA1': False, 'GPIOA2': False, 'GPIOA3': False}

Categories