Passing variables in python from radio buttons - scripting

I want to set values depends on the selected radio button and to use that values in other function.
Whatever i try, i always get the same answer
NameError: global name 'tX' is not defined #
import maya.cmds as cmds
from functools import partial
winID='MSDKID'
def init(*args):
print tX
print tY
print tZ
print rX
print rY
print rZ
return
def prozor():
if cmds.window(winID, exists = True):
cmds.deleteUI(winID);
cmds.window()
cmds.columnLayout( adjustableColumn=True, rowSpacing=10 )
cmds.button(label = "Init")
cmds.button(label = "MirrorSDK",command=init)
cmds.setParent( '..' )
cmds.setParent( '..' )
cmds.frameLayout( label='Position' )
cmds.columnLayout()
collection2 = cmds.radioCollection()
RButton0 = cmds.radioButton( label='Behavior' )
RButton1 = cmds.radioButton( label='Orientation' )
cmds.button(l='Apply', command = partial(script,RButton0,RButton1,))
cmds.setParent( '..' )
cmds.setParent( '..' )
print script(RButton0,RButton1)
cmds.showWindow()
def script(RButton0,RButton1,*_cb_val):
X = 0
rb0 = cmds.radioButton(RButton0, q = True, sl = True)
rb1 = cmds.radioButton(RButton1,q = True, sl = True)
if (rb0 == True):
tX = -1
tY = -1
tZ = -1
rX = 1
rY = 1
rZ = 1
if (rb1 == True):
tX = -1
tY = 1
tZ = 1
rX = 1
rY = -1
rZ = -1
return tX,tY,tZ,rX,rY,rZ
prozor()

The variables you are defining in script() are local to that function. The other functions don't see them.
If you need multiple UI elements to share data, you'll probably need to create a class to let them share variables. Some reference here and here

Related

How to propagate `\n` to sympy.latex()

The Goal is to format a polynomial with more than 6 parameters into a plot title.
Here is my polynomial parameter to string expression function, inspired by this answer, followed by sym.latex():
def func(p_list):
str_expr = ""
for i in range(len(p_list)-1,-1,-1):
if (i%2 == 0 and i !=len(p_list)):
str_expr =str_expr + " \n "
if p_list[i]>0:
sign = " +"
else:
sign = ""
if i > 1:
str_expr = str_expr+" + %s*x**%s"%(p_list[i],i)
if i == 1:
str_expr = str_expr+" + %s*x"%(p_list[i])
if i == 0:
str_expr = str_expr+sign+" %s"%(p_list[i])
print("str_expr",str_expr)
return sym.sympify(str_expr)
popt = [-2,1,1] # some toy data
tex = sym.latex(func(popt))
print("tex",tex)
Outputs:
str_expr
+ -1*x**2 + 1*x
-2
tex - x^{2} + x - 2
in str_expr the line breaks from \n are visible, yet in the sympy.latex output the are gone.
How to propagate this linebreak?
Edit: I took # wsdookadr answer and modified it, so that plt.title takes the result of the function as text the argument
def tex_multiline_poly(e, chunk_size=2, separator="\n"):
tex = ""
# split into monomials
print("reversed(e.args)",reversed(e.args))
mono = list(e.args)
print("mono",mono)
mono.reverse()
print("mono",mono)
# we're going split the list of monomials into chunks of chunk_size
# serialize each chunk, and insert separators between the chunks
for i in range(0,len(mono),chunk_size):
chunk = mono[i:i + chunk_size]
print("sum(chunk)",sum(chunk))
print("sym.latex(sum(chunk))",sym.latex(sum(chunk)))
if i == 0:
tex += r'$f(x)= %s$'%(sym.latex(sum(chunk)))+separator
else:
tex += '$%s$'%(sym.latex(sum(chunk))) + separator
return tex
popt = est.params
x = sym.symbols('x')
p = sym.Poly.from_list(reversed(popt),gens=x)
tex = tex_multiline_poly(p.as_expr(),chunk_size=2)
plt.title(text=tex)
In your code, you're inserting a linebreak for every even-power monomial, except for the last one.
if (i%2 == 0 and i !=len(p_list)):
str_expr =str_expr + " \n "
Since you are just building a polynomial from a list of coefficients, your code can be simplified.
Generally what we want is to build/transform/handle things symbolically, and only at the end serialize them and print the result in some specific format
import sympy as sym
x = sym.symbols('x')
def func(p_list):
expr = 0
for i in range(len(p_list)-1,-1,-1):
expr += p_list[i] * (x ** i)
return sym.sympify(expr)
popt = [-2,1,1]
p = func(popt)
p_tex = sym.latex(p)
p_str = str(p)
print("str:", p_str)
print("tex:", p_tex)
Output:
str: x**2 + x - 2
tex: x^{2} + x - 2
We could simplify this even further by using SymPy's built-in functions to build the poly from a list of coefficients:
import sympy as sym
from sympy import symbols
popt = [-2,1,1]
x = symbols('x')
p = sym.Poly.from_list(reversed(popt),gens=x)
p_tex = sym.latex(p.as_expr())
p_str = str(p.as_expr())
print("str:", p_str)
print("tex:", p_tex)
Output:
str: x**2 + x - 2
tex: x^{2} + x - 2
Does the output look like what you would expect?
UPDATE:
After learning more about the use-case, here's a version that inserts separators every N=2 monomials in the latex form of your expression.
import sympy as sym
from sympy import symbols
popt = [-2,1,1]
x = symbols('x')
p = sym.Poly.from_list(reversed(popt),gens=x)
def tex_multiline_poly(e, chunk_size=2, separator="\n"):
tex = ""
# split into monomials
mono = list(reversed(e.args))
# we're going split the list of monomials into chunks of chunk_size
# serialize each chunk, and insert separators between the chunks
for i in range(0,len(mono),chunk_size):
chunk = mono[i:i + chunk_size]
tex += sym.latex(sum(chunk)) + separator
return tex
p_tex = tex_multiline_poly(p.as_expr(),chunk_size=2)
p_str = str(p.as_expr())
print("str:",p_str)
print("tex:",p_tex)
Output:
str: x**2 + x - 2
tex: x^{2} + x
-2
Edit: wrong edit

Why is setting the expiry time ineffective in Redis

Now i use redispipeline to set key to redis ,and set key timeout.After running codes and timeout,and the keys are still in redis?It seemed doesn't work.Is there sth wrong with my code.
X[1] is dict,such as dict["a"]=b dict["c"]=d
redis_pool = redis.ConnectionPool(host = redis_ip, port = redis_port, decode_responses = False)
redis_connection = redis.StrictRedis(connection_pool = redis_pool)
redis_pipeline = redis_connection.pipeline(transaction = False)
sync_count = 0
for x in iterator:
key = suffix + x[0]
#value = str(x['tagid'])+"\t"+x['tag_name']
value = x[1]
redis_pipeline.hmset(key, value)
redis_pipeline.expire(key,60)
sync_count += 1
if (sync_count % 100 == 0):
result = redis_pipeline.execute()
print (result)
time.sleep(0.001)
break
if sync_count == 10000:
break
redis_pipeline.execute()

How to fix "submatrix incorrectly defined" in Scilab?

I am trying to find three parameters (a, b, c) to fit my experimental data using ODE solver and optimization by least squares using Scilab in-built functions.
However, I keep having the message "submatrix incorrectly defined" at line "y_exp(:,1) = [0.135 ..."
When I try another series of data (t, yexp) such as the one used in the original template I get no error messages. The template I use was found here: https://wiki.scilab.org/Non%20linear%20optimization%20for%20parameter%20fitting%20example
function dy = myModel ( t , y , a , b, c )
// The right-hand side of the Ordinary Differential Equation.
dy(1) = -a*y(1) - b*y(1)*y(2)
dy(2) = a*y(1) - b*y(1)*y(2) - c*y(2)
endfunction
function f = myDifferences ( k )
// Returns the difference between the simulated differential
// equation and the experimental data.
global MYDATA
t = MYDATA.t
y_exp = MYDATA.y_exp
a = k(1)
b = k(2)
c = k(3)
y0 = y_exp(1,:)
t0 = 0
y_calc=ode(y0',t0,t,list(myModel,a,b,c))
diffmat = y_calc' - y_exp
// Make a column vector
f = diffmat(:)
MYDATA.funeval = MYDATA.funeval+ 1
endfunction
// Experimental data
t = [0,20,30,45,75,105,135,180,240]';
y_exp(:,1) =
[0.135,0.0924,0.067,0.0527,0.0363,0.02445,0.01668,0.012,0.009]';
y_exp(:,2) =
[0,0.00918,0.0132,0.01835,0.0261,0.03215,0.0366,0.0393,0.0401]';
// Store data for future use
global MYDATA;
MYDATA.t = t;
MYDATA.y_exp = y_exp;
MYDATA.funeval = 0;
function val = L_Squares ( k )
// Computes the sum of squares of the differences.
f = myDifferences ( k )
val = sum(f.^2)
endfunction
// Initial guess
a = 0;
b = 0;
c = 0;
x0 = [a;b;c];
[fopt ,xopt]=leastsq(myDifferences, x0)
Does anyone know how to approach this problem?
Just rewrite lines 28,29 as
y_exp = [0.135,0.0924,0.067,0.0527,0.0363,0.02445,0.01668,0.012,0.009
0,0.00918,0.0132,0.01835,0.0261,0.03215,0.0366,0.0393,0.0401]';
or insert a clear at line 1 (you may have defined y_exp before with a different size).

the object variable in link list reverse codes

Hi this is a link list reverse code. Anyone can help me understand that the differecen between r = Solution().reverseList(n1) and r = Solution().reverseList(ListNode(1)).
I wonder why the output which is [1] and [3,2,1] respectively and what is the purpose of to assign the ListNode object to a variable.
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
#if not head:
# return None
prev = head
curr = prev.next
while curr:
next =curr.next
curr.next = prev
prev = curr
curr = next
head.next = None
return prev
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
def to_list(self):
return[self.val] + self.next.to_list() if self.next else [self.val]
if __name__ == "__main__":
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
r = Solution().reverseList(n1)
print r.to_list()
#assert r.to_list() == [3,2,1]
I understood now.
ListNode(1) has no "next" set, so it will forever return 1 as it's list, whereas n1 starts the same way (as just node of 1), but the "next" attribute is set to node of 2 whose "next" is set to node of 3, so n1 carries all of this information with it, and ListNode(1) does not.
welcome any comments.

Vpython greyscreen crash

I have found many times a solution for my problems from here, but this time I am totally baffled. I don't know what's wrong at my code.
I made a code to create a box with charged particles inside with Vpython. As I launch the program, I get only a grey screen and the program crash. No error message, nothing.
from visual import *
from random import *
def electronizer(num):
list = []
electron_charge = -1.60217662e-19
electron_mass = 9.10938356e-31
for i in range(num):
another_list = []
e = sphere(pos=(random(), random(),random()), radius=2.818e-15,
color=color.cyan)
e.v = vector(random(), random(), random())
another_list.append(e)
another_list.append(e.v)
another_list.append(electron_charge)
another_list.append(electron_mass)
list.append(another_list)
return list
def protonizer(num):
list = []
proton_charge = 1.60217662e-19
proton_mass = 1.6726219e-27
for i in range(num):
another_list = []
p = sphere(pos=(random(), random(),random()), radius=0.8408739e-15, color=color.red)
p.v = vector(random(), random(), random())
another_list.append(p)
another_list.append(p.v)
another_list.append(proton_charge)
another_list.append(proton_mass)
list.append(another_list)
return list
def cross(a, b):
c = vector(a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0])
return c
def positioner(work_list):
k = 8.9875517873681764e3 #Nm2/C2
G = 6.674e-11 # Nm2/kg2
vac_perm = 1.2566370614e-6 # H/m
pi = 3.14159265
dt = 0.1e-3
constant = 1
force = vector(0,0,0)
for i in range(len(work_list)):
for j in range(len(work_list)):
if i != j:
r = work_list[i][0].pos - work_list[j][0].pos
r_mag = mag(r)
r_norm = norm(r)
F = k * ((work_list[i][2] * work_list[j][2]) / (r_mag**2)) * r_norm
force += F
B = constant*(vac_perm / 4*pi) * (cross(work_list[j][2] * work_list[j][1], norm(r)))/r_mag**2
F = cross(work_list[i][2] * work_list[i][1], B)
force += F
F = -(G * work_list[i][3] * work_list[j][3]) / r_mag**2 * r_norm
force += F
acceleration = force / work_list[i][3]
difference_in_velocity = acceleration * dt
work_list[i][1] += difference_in_velocity
difference_in_position = work_list[i][1] * dt
work_list[i][0].pos += difference_in_position
if abs(work_list[i][0].pos[0]) > 2.5e-6:
work_list[i][1][0] = -work_list[i][1][0]
elif abs(work_list[i][0][1]) > 2.5e-6:
work_list[i][1][1] = -work_list[i][1][1]
elif abs(work_list[i][0][2]) > 2.5e-6:
work_list[i][1][2] = -work_list[i][1][2]
return work_list
box = box(pos=(0, 0, 0), length = 5e-6, width = 5e-6, height = 5e-6, opacity = 0.5)
protons_num = raw_input("number of protons: ")
electrons_num = raw_input("number of electrons: ")
list_of_electrons = electronizer(int(electrons_num))
list_of_protons = protonizer(int(protons_num))
work_list = list_of_electrons + list_of_protons
while True:
work_list = positioner(work_list)
You should ask your question on the VPython.org forum where the VPython experts hang out and will be able to answer your question. You should mention which operating system you are using and which version of python you are using. From your code I see that you are using classic VPython. There is a newer version of VPython 7 that just came out but the VPython syntax has changed.