问:
Define a decision variable of M0 in CPLEX
Good day to you.
From a previous model with cplex (MIP 1), I use M0 as a parameter.

```<code>Total_P = 8
M0 = np.array([[0,1,0,1,0,0,0,2]]).reshape(Total_P,1)
</code>```

Then, I tried to develop a different model (MIP 2) with adjusted objectives and constraints from MIP2, however, the M0 now becomes a decision variable and use for several constraints (#constraint 38). So, I created a code as follows:

```<code>Total_P = 8
M0 = np.empty((Total_P,1), dtype = object)
for l in range(0,Total_P):
    M0[l][0]= mdl.integer_var(name='M0'+ str(',') + str(l+1))

for l in range(0,Total_P):
    if M0[l][0] is not None:
        mdl.add_constraint((M0[1][0] + M0[5][0]) == 1)
        mdl.add_constraint((M0[3][0] + M0[6][0]) == 1)
        mdl.add_constraint((M0[0][0] + M0[2][0] + M0[4][0] + M0[7][0]) == 2)
</code>```

After running the cplex with the same parameters input:

The result from MIP 1:  obj_lambda=213

The result from MIP 2: obj_lamba= 205.0 and the M0 is [[0,1,1,0,0,0,1,1]]

The correct result of M0 from the MIP 2 should be [[0,1,0,1,0,0,0,2]] as in the M0 (parameter in MIP 1) and obj_lambda=213.

Here is the full code of MIP 1:

```<code>import cplex
from docplex.mp.model import Model
import numpy as np

mdl = Model(name='Scheduling MIP 1')
inf = cplex.infinity
bigM= 10000

Total_P = 8 # number of places
Total_T = 6 # number of transitions

r1 = 100 #processing time for PM1 (second)
r2 = 200 #processing time for PM2 (second)

v = 3 #robot moving time (second)
w = 5 #loading or unloading time (second)

M0 = np.array([[0,1,1,0,0,0,1,1]]).reshape(Total_P,1)
M0_temp = M0.reshape(1,Total_P)
M0_final = M0_temp.tolist()*Total_T

h = np.array([v+w,w+r1,v+w,w+r2,v+w,0,0,0]).reshape(Total_P,1)

#Parameter
AT =np.array([[1,-1,0,0,0,0],
              [0,1,-1,0,0,0],
              [0,0,1,-1,0,0],
              [0,0,0,1,-1,0],
              [0,0,0,0,1,-1],
              [0,-1,1,0,0,0],
              [0,0,0,-1,1,0],
              [-1,1,-1,1,-1,1]])
AT_temp = AT.transpose()

places = np.array(['p1','p2','p3','p4','p5','p6','p7','p8'])
P_conflict = np.empty((1,Total_P), dtype = object)
P_zero = np.empty((1,Total_P), dtype = object)

#Define the place without conflict place
CP = np.count_nonzero(AT, axis=1, keepdims=True) #calculate the nonzero elements for each row
P_conflict = []
P_zero = []

for a in range(0, len(CP)):
    if CP[a].item(0) > 2:
        P_conflict.append(places[a])
    else:
        P_zero.append(places[a])

print('p_zero', np.shape(P_zero))

obj_lambda = [ ]
obj_lambda = mdl.continuous_var(lb = 0, ub=inf, name='obj_lambda')

x = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='x')).reshape(Total_T,)
ind_x = np.where(AT[0] == 1)

print('ind_x', ind_x)

def get_index_value(input):
  data = []
  for l in range(len(P_zero)):
    ind_x = np.where(AT[l] == input)
    get_value = x[ind_x]
    data.append(get_value)
  return data

x_in = get_index_value(1)
x_out = get_index_value(-1)

#constraint 16
for l in range(0,len(P_zero)): #only for P non conflict
    #if x_in is not None and x_out is not None and obj_lambda is not None:
    mdl.add_constraint(x_out[l][0]-x_in[l][0] >= h[l][0] - M0[l][0]*obj_lambda)

#Decision Var
Z = np.empty((Total_T, Total_T), dtype = object)
for k in range(Total_T):
    for i in range(Total_T):
     Z[k][i] = mdl.binary_var(name='Z' + str(k+1) + str(',') + str(i+1))

storage_ZAT = []
for k in range(Total_T):
    ZAT = np.matmul(Z[k].reshape(1,Total_T),AT_temp)
    storage_ZAT.append(ZAT)    #storage_ZAT = np.append(storage_ZAT, ZAT, axis=0)

ZAT_final = np.asarray(storage_ZAT).reshape(Total_T,Total_P)

M = np.empty((Total_T, Total_P), dtype = object)
for k in range(0,Total_T):
    for l in range (0,Total_P):
        if k == Total_T-1:
            M[Total_T-1][l] = M0_final[0][l]
        else:
            M[k][l] = mdl.continuous_var(name='M' + str(k + 1) + str(',') + str(l + 1))

M_prev = np.empty((Total_T, Total_P), dtype = object)
if M is not None:
    for k in range(0,Total_T):
        for l in range (0,Total_P):
            if k is not 0:
                M_prev[k][l] = M[k-1][l]
            else:
                M_prev[0][l] = M0_final[0][l]

#Constraint 17
for k in range(Total_T):
  for l in range(Total_P):
          mdl.add_constraint(M[k][l] == M_prev[k][l] + ZAT_final[k][l])

#Constraint 18
mdl.add_constraints(mdl.sum(Z[k][i] for k in range(Total_T)) == 1 for i in range(Total_T))

# Constraint 19
mdl.add_constraints(mdl.sum(Z[k][i] for i in range(Total_T)) == 1 for k in range(Total_T))

# # Parameters
VW_temp = [[v + w]]
VW_temp = VW_temp*Total_T
VW = np.array(VW_temp) #eshape(Total_T,)

#Define S
S = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='S')).reshape(Total_T,1)

 #Constraint 20

for k in range(Total_T-1):
    mdl.add_constraint(S[k][0] - S[k+1][0] <= -VW[k][0])

# # Constraint 21
mdl.add_constraint(S[Total_T-1][0] - (S[0][0] + obj_lambda) <=-VW[Total_T-1][0])

x_temp = x.reshape(Total_T,1)
print('x_temp',x_temp)

# Constraint 22
for k in range(Total_T):
    for i in range(Total_T):
         mdl.add_constraint(S[k][0] - x_temp[i][0] <= (1-Z[k][i])*bigM) #why x_temp? because it is the reshape of x

# Constraint 23
for k in range(Total_T):
    for i in range(Total_T):
        mdl.add_constraint(S[k][0] - x_temp[i][0] >= (Z[k][i]-1)*bigM)

mdl.minimize(obj_lambda)
mdl.print_information()
solver = mdl.solve() #(log_output=True)
if solver is not None:
    mdl.print_solution()
    miu = 1 / obj_lambda.solution_value
    print('obj_lamba=', obj_lambda.solution_value)
    print('miu =', miu)
else:
    print("Solver is error")

</code>```

Here is the code of MIP 2:

```<code>import cplex
from docplex.mp.model import Model
import numpy as np

mdl = Model(name='Scheduling MILP 2')
inf = cplex.infinity
bigM= 10000

Total_P = 8 # number of places
Total_T = 6 # number of transitions

r1 = 100 #processing time for PM1 (second)
r2 = 200 #processing time for PM2 (second)

v = 3 #robot moving time (second)
w = 5 #loading or unloading time (second)

h = np.array([v+w,w+r1,v+w,w+r2,v+w,0,0,0]).reshape(Total_P,1)

#Parameter
AT =np.array([[1,-1,0,0,0,0],
              [0,1,-1,0,0,0],
              [0,0,1,-1,0,0],
              [0,0,0,1,-1,0],
              [0,0,0,0,1,-1],
              [0,-1,1,0,0,0],
              [0,0,0,-1,1,0],
              [-1,1,-1,1,-1,1]])
AT_temp = AT.transpose()

places = np.array(['p1','p2','p3','p4','p5','p6','p7','p8'])
P_conflict = np.empty((1,Total_P), dtype = object)
P_zero = np.empty((1,Total_P), dtype = object)

#Define the place without conflict place
CP = np.count_nonzero(AT, axis=1, keepdims=True) #calculate the nonzero elements for each row
P_conflict = []
P_zero = []

for a in range(0, len(CP)):
    if CP[a].item(0) > 2:
        P_conflict.append(places[a])
    else:
        P_zero.append(places[a])

print('p_zero', P_zero)

y = [ ] #miu

y = mdl.continuous_var(lb = 0, ub=inf, name='miu') #error: docplex.mp.utils.DOcplexException: Variable obj_lambda cannot be used as denominator of 1

x = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='x')).reshape(Total_T,)
ind_x = np.where(AT[0] == 1)

def get_index_value(input):
  data = []
  for l in range(len(P_zero)):
    ind_x = np.where(AT[l] == input)
    get_value = x[ind_x]
    data.append(get_value)
  return data

x_in_hat = get_index_value(1)
x_out_hat = get_index_value(-1)

M0 = np.empty((Total_P,1), dtype = object)
for l in range(0,Total_P):
    M0[l][0]= mdl.integer_var(name='M0'+ str(',') + str(l+1))

M0_temp= M0.reshape(1,Total_P)
M0_final = M0_temp.tolist()*Total_T

for k in range(Total_T):
    for l in range(Total_P):
        if M0_final[k][l] is not None:
            mdl.add_constraint((M0_final[0][1] + M0_final[0][5]) == 1)
            mdl.add_constraint((M0_final[0][3] + M0_final[0][6]) == 1)
            mdl.add_constraint((M0_final[0][0] + M0_final[0][2] + M0_final[0][4] + M0_final[0][7]) == 2)

#constraint 30
for l in range(0,len(P_zero)): #only for P non conflict
    mdl.add_constraint(x_out_hat[l][0]-x_in_hat[l][0] >= h[l][0]*y - M0[l][0])

#Decision Var
Z = np.empty((Total_T, Total_T), dtype = object)
for k in range(Total_T):
    for i in range(Total_T):
         # if k == 0 and i == 0:
         #     Z[0][0]=1
         # else:
             Z[k][i] = mdl.binary_var(name='Z' + str(k+1) + str(',') + str(i+1))
#
storage_ZAT = []
for k in range(Total_T):
    ZAT = np.matmul(Z[k].reshape(1,Total_T),AT_temp)
    storage_ZAT.append(ZAT)    #storage_ZAT = np.append(storage_ZAT, ZAT, axis=0)

ZAT_final = np.asarray(storage_ZAT).reshape(Total_T,Total_P)

M = np.empty((Total_T, Total_P), dtype = object)

for k in range(0,Total_T):
    for l in range (0,Total_P):
        if k == Total_T-1:
            M[Total_T-1][l] = M0_final[0][l]
        else:
            M[k][l] = mdl.continuous_var(name='M' + str(k + 1) + str(',') + str(l + 1))

M_prev = np.empty((Total_T, Total_P), dtype = object)
if M is not None:
    for k in range(0,Total_T):
        for l in range (0,Total_P):
            if k is not 0:
                M_prev[k][l] = M[k-1][l]
            else:
                M_prev[0][l] = M0_final[0][l]
#
#Constraint 31
for k in range(Total_T):
  for l in range(Total_P):
        mdl.add_constraint(M[k][l] == M_prev[k][l] + ZAT_final[k][l])
#
#Constraint 32

mdl.add_constraints(mdl.sum(Z[k][i] for k in range(Total_T)) == 1 for i in range(Total_T))

# Constraint 33
mdl.add_constraints(mdl.sum(Z[k][i] for i in range(Total_T)) == 1 for k in range(Total_T))
# #
# # # # Parameters
VW_temp = [[v + w]]
VW_temp = VW_temp*Total_T
VW = np.array(VW_temp) #eshape(Total_T,)
#
S_hat = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='S_hat')).reshape(Total_T,1)

#Constraint 34

for k in range(0,Total_T-1):
    if k < (Total_T-1):
        mdl.add_constraint(S_hat[k][0] - S_hat[k+1][0] <= -VW[k][0]*y)
    if k == (Total_T - 1):
        mdl.add_constraint(S_hat[k][0] - (S_hat[0][0] + 1) <= -VW[Total_T - 1][0] * y)# Constraint 35
#
#
x_temp_hat = x.reshape(Total_T,1)
#
# Constraint 36
for k in range(Total_T):
   for i in range(Total_T):
        mdl.add_constraint((S_hat[k][0] - x_temp_hat[i][0]) <= (1-Z[k][i])*bigM) #why x_temp? because it is the reshape of x

# Constraint 37
for k in range(Total_T):
     for i in range(Total_T):
        mdl.add_constraint((S_hat[k][0] - x_temp_hat[i][0]) >= (Z[k][i]-1)*bigM)

mdl.maximize(y)
mdl.print_information()
solver = mdl.solve()

if solver is not None:
    mdl.print_solution()
    obj_lambda = 1/y.solution_value
    print('miu =', y.solution_value)
    print('obj_lamba=', obj_lambda)
    print('M0 final=', M0_temp)
else:
    print("Solver is error")

</code>```

In this case, could anyone tell me: did I define the M0 as a decision variable and put them into the constraints correctly, please?

Thank you.

Body:
Good day to you.
From a previous model with cplex (MIP 1), I use M0 as a parameter.

Total_P = 8
M0 = np.array([[0,1,0,1,0,0,0,2]]).reshape(Total_P,1)

Then, I tried to develop a different model (MIP 2) with adjusted objectives and constraints from MIP2, however, the M0 now becomes a decision variable and use for several constraints (#constraint 38). So, I created a code as follows:

Total_P = 8
M0 = np.empty((Total_P,1), dtype = object)
for l in range(0,Total_P):
    M0[l][0]= mdl.integer_var(name='M0'+ str(',') + str(l+1))

for l in range(0,Total_P):
    if M0[l][0] is not None:
        mdl.add_constraint((M0[1][0] + M0[5][0]) == 1)
        mdl.add_constraint((M0[3][0] + M0[6][0]) == 1)
        mdl.add_constraint((M0[0][0] + M0[2][0] + M0[4][0] + M0[7][0]) == 2)

After running the cplex with the same parameters input:

The result from MIP 1:  obj_lambda=213

The result from MIP 2: obj_lamba= 205.0 and the M0 is [[0,1,1,0,0,0,1,1]]

The correct result of M0 from the MIP 2 should be [[0,1,0,1,0,0,0,2]] as in the M0 (parameter in MIP 1) and obj_lambda=213.

Here is the full code of MIP 1:

import cplex
from docplex.mp.model import Model
import numpy as np

mdl = Model(name='Scheduling MIP 1')
inf = cplex.infinity
bigM= 10000

Total_P = 8 # number of places
Total_T = 6 # number of transitions

r1 = 100 #processing time for PM1 (second)
r2 = 200 #processing time for PM2 (second)

v = 3 #robot moving time (second)
w = 5 #loading or unloading time (second)

M0 = np.array([[0,1,1,0,0,0,1,1]]).reshape(Total_P,1)
M0_temp = M0.reshape(1,Total_P)
M0_final = M0_temp.tolist()*Total_T

h = np.array([v+w,w+r1,v+w,w+r2,v+w,0,0,0]).reshape(Total_P,1)

#Parameter
AT =np.array([[1,-1,0,0,0,0],
              [0,1,-1,0,0,0],
              [0,0,1,-1,0,0],
              [0,0,0,1,-1,0],
              [0,0,0,0,1,-1],
              [0,-1,1,0,0,0],
              [0,0,0,-1,1,0],
              [-1,1,-1,1,-1,1]])
AT_temp = AT.transpose()

places = np.array(['p1','p2','p3','p4','p5','p6','p7','p8'])
P_conflict = np.empty((1,Total_P), dtype = object)
P_zero = np.empty((1,Total_P), dtype = object)

#Define the place without conflict place
CP = np.count_nonzero(AT, axis=1, keepdims=True) #calculate the nonzero elements for each row
P_conflict = []
P_zero = []

for a in range(0, len(CP)):
    if CP[a].item(0) > 2:
        P_conflict.append(places[a])
    else:
        P_zero.append(places[a])

print('p_zero', np.shape(P_zero))

obj_lambda = [ ]
obj_lambda = mdl.continuous_var(lb = 0, ub=inf, name='obj_lambda')

x = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='x')).reshape(Total_T,)
ind_x = np.where(AT[0] == 1)

print('ind_x', ind_x)

def get_index_value(input):
  data = []
  for l in range(len(P_zero)):
    ind_x = np.where(AT[l] == input)
    get_value = x[ind_x]
    data.append(get_value)
  return data

x_in = get_index_value(1)
x_out = get_index_value(-1)

#constraint 16
for l in range(0,len(P_zero)): #only for P non conflict
    #if x_in is not None and x_out is not None and obj_lambda is not None:
    mdl.add_constraint(x_out[l][0]-x_in[l][0] >= h[l][0] - M0[l][0]*obj_lambda)

#Decision Var
Z = np.empty((Total_T, Total_T), dtype = object)
for k in range(Total_T):
    for i in range(Total_T):
     Z[k][i] = mdl.binary_var(name='Z' + str(k+1) + str(',') + str(i+1))

storage_ZAT = []
for k in range(Total_T):
    ZAT = np.matmul(Z[k].reshape(1,Total_T),AT_temp)
    storage_ZAT.append(ZAT)    #storage_ZAT = np.append(storage_ZAT, ZAT, axis=0)

ZAT_final = np.asarray(storage_ZAT).reshape(Total_T,Total_P)

M = np.empty((Total_T, Total_P), dtype = object)
for k in range(0,Total_T):
    for l in range (0,Total_P):
        if k == Total_T-1:
            M[Total_T-1][l] = M0_final[0][l]
        else:
            M[k][l] = mdl.continuous_var(name='M' + str(k + 1) + str(',') + str(l + 1))

M_prev = np.empty((Total_T, Total_P), dtype = object)
if M is not None:
    for k in range(0,Total_T):
        for l in range (0,Total_P):
            if k is not 0:
                M_prev[k][l] = M[k-1][l]
            else:
                M_prev[0][l] = M0_final[0][l]

#Constraint 17
for k in range(Total_T):
  for l in range(Total_P):
          mdl.add_constraint(M[k][l] == M_prev[k][l] + ZAT_final[k][l])

#Constraint 18
mdl.add_constraints(mdl.sum(Z[k][i] for k in range(Total_T)) == 1 for i in range(Total_T))

# Constraint 19
mdl.add_constraints(mdl.sum(Z[k][i] for i in range(Total_T)) == 1 for k in range(Total_T))

# # Parameters
VW_temp = [[v + w]]
VW_temp = VW_temp*Total_T
VW = np.array(VW_temp) #eshape(Total_T,)

#Define S
S = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='S')).reshape(Total_T,1)

 #Constraint 20

for k in range(Total_T-1):
    mdl.add_constraint(S[k][0] - S[k+1][0] <= -VW[k][0])

# # Constraint 21
mdl.add_constraint(S[Total_T-1][0] - (S[0][0] + obj_lambda) <=-VW[Total_T-1][0])

x_temp = x.reshape(Total_T,1)
print('x_temp',x_temp)

# Constraint 22
for k in range(Total_T):
    for i in range(Total_T):
         mdl.add_constraint(S[k][0] - x_temp[i][0] <= (1-Z[k][i])*bigM) #why x_temp? because it is the reshape of x

# Constraint 23
for k in range(Total_T):
    for i in range(Total_T):
        mdl.add_constraint(S[k][0] - x_temp[i][0] >= (Z[k][i]-1)*bigM)

mdl.minimize(obj_lambda)
mdl.print_information()
solver = mdl.solve() #(log_output=True)
if solver is not None:
    mdl.print_solution()
    miu = 1 / obj_lambda.solution_value
    print('obj_lamba=', obj_lambda.solution_value)
    print('miu =', miu)
else:
    print("Solver is error")

Here is the code of MIP 2:

import cplex
from docplex.mp.model import Model
import numpy as np

mdl = Model(name='Scheduling MILP 2')
inf = cplex.infinity
bigM= 10000

Total_P = 8 # number of places
Total_T = 6 # number of transitions

r1 = 100 #processing time for PM1 (second)
r2 = 200 #processing time for PM2 (second)

v = 3 #robot moving time (second)
w = 5 #loading or unloading time (second)

h = np.array([v+w,w+r1,v+w,w+r2,v+w,0,0,0]).reshape(Total_P,1)

#Parameter
AT =np.array([[1,-1,0,0,0,0],
              [0,1,-1,0,0,0],
              [0,0,1,-1,0,0],
              [0,0,0,1,-1,0],
              [0,0,0,0,1,-1],
              [0,-1,1,0,0,0],
              [0,0,0,-1,1,0],
              [-1,1,-1,1,-1,1]])
AT_temp = AT.transpose()

places = np.array(['p1','p2','p3','p4','p5','p6','p7','p8'])
P_conflict = np.empty((1,Total_P), dtype = object)
P_zero = np.empty((1,Total_P), dtype = object)

#Define the place without conflict place
CP = np.count_nonzero(AT, axis=1, keepdims=True) #calculate the nonzero elements for each row
P_conflict = []
P_zero = []

for a in range(0, len(CP)):
    if CP[a].item(0) > 2:
        P_conflict.append(places[a])
    else:
        P_zero.append(places[a])

print('p_zero', P_zero)

y = [ ] #miu

y = mdl.continuous_var(lb = 0, ub=inf, name='miu') #error: docplex.mp.utils.DOcplexException: Variable obj_lambda cannot be used as denominator of 1

x = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='x')).reshape(Total_T,)
ind_x = np.where(AT[0] == 1)

def get_index_value(input):
  data = []
  for l in range(len(P_zero)):
    ind_x = np.where(AT[l] == input)
    get_value = x[ind_x]
    data.append(get_value)
  return data

x_in_hat = get_index_value(1)
x_out_hat = get_index_value(-1)

M0 = np.empty((Total_P,1), dtype = object)
for l in range(0,Total_P):
    M0[l][0]= mdl.integer_var(name='M0'+ str(',') + str(l+1))

M0_temp= M0.reshape(1,Total_P)
M0_final = M0_temp.tolist()*Total_T

for k in range(Total_T):
    for l in range(Total_P):
        if M0_final[k][l] is not None:
            mdl.add_constraint((M0_final[0][1] + M0_final[0][5]) == 1)
            mdl.add_constraint((M0_final[0][3] + M0_final[0][6]) == 1)
            mdl.add_constraint((M0_final[0][0] + M0_final[0][2] + M0_final[0][4] + M0_final[0][7]) == 2)

#constraint 30
for l in range(0,len(P_zero)): #only for P non conflict
    mdl.add_constraint(x_out_hat[l][0]-x_in_hat[l][0] >= h[l][0]*y - M0[l][0])

#Decision Var
Z = np.empty((Total_T, Total_T), dtype = object)
for k in range(Total_T):
    for i in range(Total_T):
         # if k == 0 and i == 0:
         #     Z[0][0]=1
         # else:
             Z[k][i] = mdl.binary_var(name='Z' + str(k+1) + str(',') + str(i+1))
#
storage_ZAT = []
for k in range(Total_T):
    ZAT = np.matmul(Z[k].reshape(1,Total_T),AT_temp)
    storage_ZAT.append(ZAT)    #storage_ZAT = np.append(storage_ZAT, ZAT, axis=0)

ZAT_final = np.asarray(storage_ZAT).reshape(Total_T,Total_P)

M = np.empty((Total_T, Total_P), dtype = object)

for k in range(0,Total_T):
    for l in range (0,Total_P):
        if k == Total_T-1:
            M[Total_T-1][l] = M0_final[0][l]
        else:
            M[k][l] = mdl.continuous_var(name='M' + str(k + 1) + str(',') + str(l + 1))

M_prev = np.empty((Total_T, Total_P), dtype = object)
if M is not None:
    for k in range(0,Total_T):
        for l in range (0,Total_P):
            if k is not 0:
                M_prev[k][l] = M[k-1][l]
            else:
                M_prev[0][l] = M0_final[0][l]
#
#Constraint 31
for k in range(Total_T):
  for l in range(Total_P):
        mdl.add_constraint(M[k][l] == M_prev[k][l] + ZAT_final[k][l])
#
#Constraint 32

mdl.add_constraints(mdl.sum(Z[k][i] for k in range(Total_T)) == 1 for i in range(Total_T))

# Constraint 33
mdl.add_constraints(mdl.sum(Z[k][i] for i in range(Total_T)) == 1 for k in range(Total_T))
# #
# # # # Parameters
VW_temp = [[v + w]]
VW_temp = VW_temp*Total_T
VW = np.array(VW_temp) #eshape(Total_T,)
#
S_hat = np.array(mdl.continuous_var_list(Total_T, 0, inf, name='S_hat')).reshape(Total_T,1)

#Constraint 34

for k in range(0,Total_T-1):
    if k < (Total_T-1):
        mdl.add_constraint(S_hat[k][0] - S_hat[k+1][0] <= -VW[k][0]*y)
    if k == (Total_T - 1):
        mdl.add_constraint(S_hat[k][0] - (S_hat[0][0] + 1) <= -VW[Total_T - 1][0] * y)# Constraint 35
#
#
x_temp_hat = x.reshape(Total_T,1)
#
# Constraint 36
for k in range(Total_T):
   for i in range(Total_T):
        mdl.add_constraint((S_hat[k][0] - x_temp_hat[i][0]) <= (1-Z[k][i])*bigM) #why x_temp? because it is the reshape of x

# Constraint 37
for k in range(Total_T):
     for i in range(Total_T):
        mdl.add_constraint((S_hat[k][0] - x_temp_hat[i][0]) >= (Z[k][i]-1)*bigM)

mdl.maximize(y)
mdl.print_information()
solver = mdl.solve()

if solver is not None:
    mdl.print_solution()
    obj_lambda = 1/y.solution_value
    print('miu =', y.solution_value)
    print('obj_lamba=', obj_lambda)
    print('M0 final=', M0_temp)
else:
    print("Solver is error")

In this case, could anyone tell me: did I define the M0 as a decision variable and put them into the constraints correctly, please?

Thank you.


来源: stackexchange

问:
Is there a way to have a Google Form response trigger the creation of a new Google Sheet?
I do not have any experience with apps script. Something I am trying to learn currently and this is my first project that I will be working towards.

My company that I work for use a mundane spreadsheet which is used as our purchase document. I have translated it to a Google Sheet that looks like this: https://docs.google.com/spreadsheets/d/1mZlzeu9-9Mb0B1VmlNSJDfCxELqci4KRc_HFbRt3NwM/edit?usp=sharing

Currently, anyone that makes a purchase needs to fill out this spreadsheet and send along a copy of the receipt of the purchase via email to our billing person.

The Google Form I want to create to streamline this will contain basic information like the name of the person filling it out and an email address. I would add some of the items below along with a Google Drive Upload so that the person can upload a picture of the receipt(s).

What I would want to have happen is on a Google Form response, I would like apps script to do the following, in this order:

Create a copy of the spreadsheet linked above and Title it as "[Team Name] [Date] Credit Card Request"

Fill it with the information that is needed:

Date of Transaction

Amount Request

Vendor Name

Program Name (I think this can be done away with because of Team)

Team

When the spreadsheet is filled out, I would like to then email the billing person a completed XLSX copy along with the file attachments that were uploaded for that response.
3a. Sending a copy of the same email to the person filling out the form originally would be a plus.

Because of the format of this spreadsheet, when the team is specified, I am hoping I can have the Apps Script set the value of the corresponding cell for that team (a checkbox) to TRUE.

I may ask for some assistance with this later on, but I am wondering, **is this possible to do? **

My apologies, I do not have any script experience, not sure where to even start.

ContentLicense: CC BY-SA 4.0


问:
ValueError: The truth value of a DataFrame is ambiguous
I am attempting to insert values from a dataframe to a local MySQL databse. I have not been able to get values inserted. I was able to test that the data is coming in expectedly by using "to_csv". I am working with discord.py. The error I get is below.

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

```<code>cnx = mysql.connector.connect(**config)

if message.content.startswith(syntax):
        #log user that runs command.
        print(message.author.id, message.author, message.content)

        if message.author.id != memberID and message.content == syntax + "load":
            msg = await message.channel.send(embed=discord.Embed(title="You are not authorized to use this bot", description='Please contact my dad to add you to ''the whitelisted members list', color=discord.Color.red()))
            await msg.add_reaction("")
            return
        else:
            limit = 1000
            data = pd.DataFrame(columns=['author', 'content', 'reactions', 'edited_dte', 'created_dte', 'server', 'id', 'channel'])
            tableName = 'lnd_messages'

            async for msg in message.channel.history(limit=limit):
                if msg.author != client.user:
                    if not is_command(msg):
                        data = data.append({'author': msg.author,
                                            'content': msg.content,
                                            'reactions': msg.reactions,
                                            'edited_dte': msg.edited_at,
                                            'created_dte': msg.created_at,
                                            'server': msg.guild,
                                            'id':msg.id,
                                            'channel':msg.channel}, ignore_index=True)
                        if len(data) == limit:
                                break
            queryy = "Insert into lnd_messages (author, content, reactions, edited_dte, created_dte, server, id, channel) values (%s, %s, %s,%s, %s, %s, %s, %s)"
            cursor.execute(queryy, data)
            cnx.commit()
            cnx.close()
</code>```

Also if there is a better way to get this data inserted, I am not opposed to changing it. The end goal is to write the data to the database.

Body:
I am attempting to insert values from a dataframe to a local MySQL databse. I have not been able to get values inserted. I was able to test that the data is coming in expectedly by using "to_csv". I am working with discord.py. The error I get is below.

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

cnx = mysql.connector.connect(**config)

if message.content.startswith(syntax):
        #log user that runs command.
        print(message.author.id, message.author, message.content)

        if message.author.id != memberID and message.content == syntax + "load":
            msg = await message.channel.send(embed=discord.Embed(title="You are not authorized to use this bot", description='Please contact my dad to add you to ''the whitelisted members list', color=discord.Color.red()))
            await msg.add_reaction("")
            return
        else:
            limit = 1000
            data = pd.DataFrame(columns=['author', 'content', 'reactions', 'edited_dte', 'created_dte', 'server', 'id', 'channel'])
            tableName = 'lnd_messages'

            async for msg in message.channel.history(limit=limit):
                if msg.author != client.user:
                    if not is_command(msg):
                        data = data.append({'author': msg.author,
                                            'content': msg.content,
                                            'reactions': msg.reactions,
                                            'edited_dte': msg.edited_at,
                                            'created_dte': msg.created_at,
                                            'server': msg.guild,
                                            'id':msg.id,
                                            'channel':msg.channel}, ignore_index=True)
                        if len(data) == limit:
                                break
            queryy = "Insert into lnd_messages (author, content, reactions, edited_dte, created_dte, server, id, channel) values (%s, %s, %s,%s, %s, %s, %s, %s)"
            cursor.execute(queryy, data)
            cnx.commit()
            cnx.close()

Also if there is a better way to get this data inserted, I am not opposed to changing it. The end goal is to write the data to the database.


问:
Flutter - Divider widget changing width based on screen position
I am trying to use the Divider class. It seems that its rendered width is changing based on where it is on the screen even though I have explicitly set the width.

I have the following code (which I've simplified a bit):

```<code>class HistoryListState extends State<HistoryList> {
  // use this function to generate the list of widgets used as a label for each list item
  // each label consists of the workout name, a divider, and the first 3 exercises
  List<Widget> generateLabel(TrackedWorkout workout) {
    List<Widget> widgets = [
      Text(workout.name),

      // DIVIDER IN QUESTION
      const Divider(
        color: Color.fromARGB(255, 0, 0, 0),
        thickness: 1,
      ),
    ];

    for (int i = 0; i < workout.exercises.length; i++) {
      if (i > 2) {
        widgets.add(const Text('...'));
        break;
      }

      widgets.add(Text(workout.exercises[i].name));
    }

    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      child: ListView.builder(
          itemCount: widget.workouts.length,
          itemBuilder: (BuildContext context, int index) {
            return ElevatedButton(
              onPressed: () {},
              child: Column(
                children: generateLabel(widget.workouts[index]),
              ),
            );
          }),
    );
  }
}
</code>```

Video demo

As you can see, initially, each divider has slightly different widths. Then when the list is scrolled, the dividers change widths too.

Body:
I am trying to use the Divider class. It seems that its rendered width is changing based on where it is on the screen even though I have explicitly set the width.

I have the following code (which I've simplified a bit):

class HistoryListState extends State<HistoryList> {
  // use this function to generate the list of widgets used as a label for each list item
  // each label consists of the workout name, a divider, and the first 3 exercises
  List<Widget> generateLabel(TrackedWorkout workout) {
    List<Widget> widgets = [
      Text(workout.name),

      // DIVIDER IN QUESTION
      const Divider(
        color: Color.fromARGB(255, 0, 0, 0),
        thickness: 1,
      ),
    ];

    for (int i = 0; i < workout.exercises.length; i++) {
      if (i > 2) {
        widgets.add(const Text('...'));
        break;
      }

      widgets.add(Text(workout.exercises[i].name));
    }

    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      child: ListView.builder(
          itemCount: widget.workouts.length,
          itemBuilder: (BuildContext context, int index) {
            return ElevatedButton(
              onPressed: () {},
              child: Column(
                children: generateLabel(widget.workouts[index]),
              ),
            );
          }),
    );
  }
}

Video demo

As you can see, initially, each divider has slightly different widths. Then when the list is scrolled, the dividers change widths too.


问:
How to use escape sequences in Xcode?
Here is a program. Its only purpose is to delete the line printed, after some user input.

main.cpp

```<code>#include <iostream>
#define ESC_PREV_LINE "\e[F"
#define ESC_CLEAR_TO_END "\e[K"
int main(){
    int i;
    std::cerr << "Some input to clear: " << std::flush;
    std:: cin >> i;
    std::cerr << ESC_PREV_LINE ESC_CLEAR_TO_END << std::flush;
}
</code>```

Inside Xcode, if the user were to input 2, this is the output:

```<code>Some input to clear: 2
[F[KProgram ended with exit code: 0
</code>```

If compiled in terminal, using: g++ -std=c++20 main.cpp -o test, the output is cleared after user input, right before the program exists, and the shell looks like the program never ran.

How can I include this functionality within Xcode? I am writing a program that requires it, but developing inside Xcode, and it would be highly inconvenient to have to swap to the terminal just to test my program output.

Title: How to use escape sequences in Xcode?

Body:
Here is a program. Its only purpose is to delete the line printed, after some user input.

main.cpp

#include <iostream>
#define ESC_PREV_LINE "\e[F"
#define ESC_CLEAR_TO_END "\e[K"
int main(){
    int i;
    std::cerr << "Some input to clear: " << std::flush;
    std:: cin >> i;
    std::cerr << ESC_PREV_LINE ESC_CLEAR_TO_END << std::flush;
}

Inside Xcode, if the user were to input 2, this is the output:

Some input to clear: 2
[F[KProgram ended with exit code: 0

If compiled in terminal, using: g++ -std=c++20 main.cpp -o test, the output is cleared after user input, right before the program exists, and the shell looks like the program never ran.

How can I include this functionality within Xcode? I am writing a program that requires it, but developing inside Xcode, and it would be highly inconvenient to have to swap to the terminal just to test my program output.


问:
Javac will not run despite Java being installed
While I have some experience in Python and JavaScript, I am new to Java and am trying it out for the first time. To get started, I went to http://www.java.com, downloaded the dmg there, and then used the package it gave me to install Java. After doing so, I received confirmation that Java had been installed successfully and I closed and trashed the dmg and package. Afterwards, I hopped on my terminal (I am using a Mac running on MacOS Monterey) and tried to use javac on a script I wrote. I received the following error message:

```<code>The operation couldn’t be completed. Unable to locate a Java Runtime that supports javac.
Please visit http://www.java.com for information on installing Java.
</code>```

I went online and did some typical troubleshooting searches. First, I found a site suggesting that I create an environment variable $JAVA_HOME and set it equal to $(/usr/libexec/java_home) in .zshenv (yes, I use zsh not bash). I followed this instruction and when I run echo $JAVA_HOME I get /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home. However, running javac still did not work.
Once more, I went online and this time, I found the suggestion of adding javac to $PATH. So I went into .zshenv and added usr/bin/javac to $PATH (the $PATH export line now looks like this: export PATH="/Users/[redacted]/Library/Python/3.8/bin:/usr/bin/javac:$PATH"). This alteration was confirmed when I exited an reentered terminal and ran echo $PATH. However, once again, running javac yielded the same error.
I feel as if I am facing what must be a pretty common and easily fixable issue, but yet, I haven't yet been able to find a solution that works despite perusal of several other StackOverflow posts and tech articles. Still, I know I'm probably missing something simple, and if this is a duplicate of another question, please link that question in a comment, and I'll take this one down.
Thanks!

Body:
While I have some experience in Python and JavaScript, I am new to Java and am trying it out for the first time. To get started, I went to http://www.java.com, downloaded the dmg there, and then used the package it gave me to install Java. After doing so, I received confirmation that Java had been installed successfully and I closed and trashed the dmg and package. Afterwards, I hopped on my terminal (I am using a Mac running on MacOS Monterey) and tried to use javac on a script I wrote. I received the following error message:

The operation couldn’t be completed. Unable to locate a Java Runtime that supports javac.
Please visit http://www.java.com for information on installing Java.

I went online and did some typical troubleshooting searches. First, I found a site suggesting that I create an environment variable $JAVA_HOME and set it equal to $(/usr/libexec/java_home) in .zshenv (yes, I use zsh not bash). I followed this instruction and when I run echo $JAVA_HOME I get /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home. However, running javac still did not work.
Once more, I went online and this time, I found the suggestion of adding javac to $PATH. So I went into .zshenv and added usr/bin/javac to $PATH (the $PATH export line now looks like this: export PATH="/Users/[redacted]/Library/Python/3.8/bin:/usr/bin/javac:$PATH"). This alteration was confirmed when I exited an reentered terminal and ran echo $PATH. However, once again, running javac yielded the same error.
I feel as if I am facing what must be a pretty common and easily fixable issue, but yet, I haven't yet been able to find a solution that works despite perusal of several other StackOverflow posts and tech articles. Still, I know I'm probably missing something simple, and if this is a duplicate of another question, please link that question in a comment, and I'll take this one down.
Thanks!


问:
Non-linear Likelihood Ratio Test in R
Consider following example data:

```<code>x2 <- rnorm(100)
x3 <- rnorm(100)
e <- rnorm(100)
b1 <- 1; b2 <- 2; b3 <- 2;
ys <- b1 + b2*x2 + b3*x3 + e
y <- ys > 0
</code>```

Here, I want to implement the likelihood ratio test for the following non-linear hypothesis:

Null: b2b3=0 vs Alternative: b2b3!=0

How can I implement the non-linear likelihood ratio test in R?

I utilized the fact that the LR test is asymptotically equivalent to the Wald test, so, I ran the Wald test. But, as we know, due to the lack of invariance of the Wald test, I want to implement LR test.

In Google, I found the package {lrtest}, but I think, the package is only applicable to linear hypotheses.

Title: Non-linear Likelihood Ratio Test in R

Body:
Consider following example data:

x2 <- rnorm(100)
x3 <- rnorm(100)
e <- rnorm(100)
b1 <- 1; b2 <- 2; b3 <- 2;
ys <- b1 + b2*x2 + b3*x3 + e
y <- ys > 0

Here, I want to implement the likelihood ratio test for the following non-linear hypothesis:

Null: b2b3=0 vs Alternative: b2b3!=0

How can I implement the non-linear likelihood ratio test in R?

I utilized the fact that the LR test is asymptotically equivalent to the Wald test, so, I ran the Wald test. But, as we know, due to the lack of invariance of the Wald test, I want to implement LR test.

In Google, I found the package {lrtest}, but I think, the package is only applicable to linear hypotheses.


问:
Search PDF In Qt C++ in QPDFView
I want to Search Words in PDF File in my Qt C++ Application. I am using Qt 6.4.1
widget, QPDFView class, and QPdfSearchModel, and I don't know what the syntax is.
As input I am taking in LineEdit Signal from PushButton.

```<code>void MainWindow::SearchString(const QUrl &docLocation)
{
    //*m_document="/home/droid/12.pdf".toLocalFile();
    auto nav = ui->pdfView->pageNavigator();
   //QString res;
  //  res= QString searchString(text);
    //auto navs=ui->pdfView->searchString(text);
//QString find=ui->pdfView->find(text);
//void res;
QString text;

text=ui->lineEdit->text();
QString file=docLocation.toLocalFile();

    QPdfSearchModel *search=new QPdfSearchModel(this);
   search->setDocument(m_document->);//Problem???

</code>```

This is my appLication Widget:

I have used Pdf Search Model but don't know the syntax to use with my application.
Path of my pdf is Stored in const &Qurl docLocation.

Title: Search PDF In Qt C++ in QPDFView

Body:
I want to Search Words in PDF File in my Qt C++ Application. I am using Qt 6.4.1
widget, QPDFView class, and QPdfSearchModel, and I don't know what the syntax is.
As input I am taking in LineEdit Signal from PushButton.

void MainWindow::SearchString(const QUrl &docLocation)
{
    //*m_document="/home/droid/12.pdf".toLocalFile();
    auto nav = ui->pdfView->pageNavigator();
   //QString res;
  //  res= QString searchString(text);
    //auto navs=ui->pdfView->searchString(text);
//QString find=ui->pdfView->find(text);
//void res;
QString text;

text=ui->lineEdit->text();
QString file=docLocation.toLocalFile();

    QPdfSearchModel *search=new QPdfSearchModel(this);
   search->setDocument(m_document->);//Problem???

This is my appLication Widget:

I have used Pdf Search Model but don't know the syntax to use with my application.
Path of my pdf is Stored in const &Qurl docLocation.


问:
Question Answering training with using BERT
I'm developing a project by myself and I need help. I just created a dataset of questions and answers. Like this;

```<code>    Questions                                                    Answer
Where is my laptop?                                 On the work table in the living room.
Where is the bakery?                                The oven is under the counter in the kitchen.
How can ı go to Bedroom from the living room?       After exiting the living room, if we go straight to the left, the first room on our left is the bedroom.
</code>```

In this way, I was able to generate 400 data. I encoded the data but I don't know how to train it. Can you help me to train this? How can I train the data after encoding it? Or do you have any idea about this dataset?

```<code>import re
import pandas as pd
from sentence_transformers import SentenceTransformer
import numpy as np
import torch
import torch.nn as nn

df = pd.read_excel('Book.xlsx')

questions = df['Questions'].tolist()
answers = df['Answer'].tolist()

lowercased_questions = []
lowercased_answers = []

for question in questions:
  lowercased_questions.append(question.lower())

for answer in answers:
  lowercased_answers.append(answer.lower())

cleaned_questions = []
cleaned_answers = []

for lowercased_questions in lowercased_questions:
  cleaned_questions.append(re.sub(r'[^\w\s]', '', lowercased_questions))

for lowercased_answers in lowercased_answers:
  cleaned_answers.append(re.sub(r'[^\w\s]', '', lowercased_answers))

model = SentenceTransformer('bert-base-nli-mean-tokens')

questions_encoded = model.encode(questions)
answers_encoded = model.encode(answers)

questions_tensor = torch.from_numpy(questions_encoded)
answers_tensor = torch.from_numpy(answers_encoded)
</code>```

I tried this way but my accuracy is so low (0.012626262626262626)

I know it is about my data but I want to know if there is any other way.

```<code># Define the model
class DNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, hidden_size)
        self.fc3 = nn.Linear(hidden_size, output_size)
        self.relu = nn.ReLU()
        self.softmax = nn.Softmax(dim=1)  # Add a softmax layer

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        x = self.relu(x)
        x = self.fc3(x)
        x = self.softmax(x)  # Apply the softmax function
        return x

# Initialize the model
input_size = questions_tensor.size(-1)
output_size = answers_tensor.size(-1)
hidden_size = 32
model = DNN(input_size, hidden_size, output_size)

# Define the loss function and the optimizer
loss_fn = torch.nn.CrossEntropyLoss()  # Use the cross-entropy loss functionloss_fn = torch.nn.CrossEntropyLoss()  # Use the cross-entropy loss function
optimizer = torch.optim.Adam(model.parameters())

# Train the model
for epoch in range(500):
    # Forward pass
    logits = model(questions_tensor)
    loss = loss_fn(logits, answers_tensor)

    # Backward pass
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

model = torch.nn.Sequential(
    torch.nn.Linear(questions_tensor.size(-1), answers_tensor.size(-1)),  # change the number of input units to match the number of rows in the questions tensor
    torch.nn.ReLU(),
    torch.nn.Linear(answers_tensor.size(-1), 1)
)

loss_fn = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters())

for epoch in range(500):
    # Forward pass
    logits = model(questions_tensor)
    loss = loss_fn(logits, answers_tensor)

    # Backward pass
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

# Load the SentenceTransformer model
sentence_transformer = SentenceTransformer('bert-base-nli-mean-tokens')

# Encode the input question using the SentenceTransformer model
input_question = "I wanna go bathroom"
input_question_encoded = sentence_transformer.encode([input_question])

# Convert the NumPy array to a PyTorch tensor
input_question_tensor = torch.from_numpy(input_question_encoded)

# Make a prediction using the PyTorch model
prediction = model(input_question_tensor)

# Print the prediction
print(prediction)

# Make a prediction using the PyTorch model
prediction = model(input_question_tensor)

# Get the index of the highest prediction
prediction_index = torch.argmax(prediction).item()

# Get the corresponding answer from the list of answers
prediction_string = answers[prediction_index]

# Print the prediction
print(prediction_string)

# Convert the encoded answers into a tensor
answers_tensor = torch.from_numpy(answers_encoded)

# Initialize a counter for the number of correct predictions
correct_predictions = 0

# Iterate over the list of questions
# Iterate over the list of questions
for question, answer in zip(questions, answers):
    # Encode the question using the SentenceTransformer model
    question_encoded = sentence_transformer.encode([question])

    # Convert the encoded question into a tensor
    question_tensor = torch.from_numpy(question_encoded)

    # Make a prediction using the PyTorch model
    prediction = model(question_tensor)

    # Get the index of the highest prediction
    prediction_index = torch.argmax(prediction).item()

    # Get the corresponding answer from the list of answers
    prediction_string = answers[prediction_index]

    # Check if the prediction is correct
    if prediction_string == answer:
        # Increment the counter for correct predictions
        correct_predictions += 1

# Calculate the accuracy of the model
accuracy = correct_predictions / len(questions)

# Print the accuracy
print(accuracy)
</code>```

Body:
I'm developing a project by myself and I need help. I just created a dataset of questions and answers. Like this;

    Questions                                                    Answer
Where is my laptop?                                 On the work table in the living room.
Where is the bakery?                                The oven is under the counter in the kitchen.
How can ı go to Bedroom from the living room?       After exiting the living room, if we go straight to the left, the first room on our left is the bedroom.

In this way, I was able to generate 400 data. I encoded the data but I don't know how to train it. Can you help me to train this? How can I train the data after encoding it? Or do you have any idea about this dataset?

import re
import pandas as pd
from sentence_transformers import SentenceTransformer
import numpy as np
import torch
import torch.nn as nn

df = pd.read_excel('Book.xlsx')

questions = df['Questions'].tolist()
answers = df['Answer'].tolist()

lowercased_questions = []
lowercased_answers = []

for question in questions:
  lowercased_questions.append(question.lower())

for answer in answers:
  lowercased_answers.append(answer.lower())

cleaned_questions = []
cleaned_answers = []

for lowercased_questions in lowercased_questions:
  cleaned_questions.append(re.sub(r'[^\w\s]', '', lowercased_questions))

for lowercased_answers in lowercased_answers:
  cleaned_answers.append(re.sub(r'[^\w\s]', '', lowercased_answers))

model = SentenceTransformer('bert-base-nli-mean-tokens')

questions_encoded = model.encode(questions)
answers_encoded = model.encode(answers)

questions_tensor = torch.from_numpy(questions_encoded)
answers_tensor = torch.from_numpy(answers_encoded)

I tried this way but my accuracy is so low (0.012626262626262626)

I know it is about my data but I want to know if there is any other way.

# Define the model
class DNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, hidden_size)
        self.fc3 = nn.Linear(hidden_size, output_size)
        self.relu = nn.ReLU()
        self.softmax = nn.Softmax(dim=1)  # Add a softmax layer

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        x = self.relu(x)
        x = self.fc3(x)
        x = self.softmax(x)  # Apply the softmax function
        return x

# Initialize the model
input_size = questions_tensor.size(-1)
output_size = answers_tensor.size(-1)
hidden_size = 32
model = DNN(input_size, hidden_size, output_size)

# Define the loss function and the optimizer
loss_fn = torch.nn.CrossEntropyLoss()  # Use the cross-entropy loss functionloss_fn = torch.nn.CrossEntropyLoss()  # Use the cross-entropy loss function
optimizer = torch.optim.Adam(model.parameters())

# Train the model
for epoch in range(500):
    # Forward pass
    logits = model(questions_tensor)
    loss = loss_fn(logits, answers_tensor)

    # Backward pass
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

model = torch.nn.Sequential(
    torch.nn.Linear(questions_tensor.size(-1), answers_tensor.size(-1)),  # change the number of input units to match the number of rows in the questions tensor
    torch.nn.ReLU(),
    torch.nn.Linear(answers_tensor.size(-1), 1)
)

loss_fn = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters())

for epoch in range(500):
    # Forward pass
    logits = model(questions_tensor)
    loss = loss_fn(logits, answers_tensor)

    # Backward pass
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

# Load the SentenceTransformer model
sentence_transformer = SentenceTransformer('bert-base-nli-mean-tokens')

# Encode the input question using the SentenceTransformer model
input_question = "I wanna go bathroom"
input_question_encoded = sentence_transformer.encode([input_question])

# Convert the NumPy array to a PyTorch tensor
input_question_tensor = torch.from_numpy(input_question_encoded)

# Make a prediction using the PyTorch model
prediction = model(input_question_tensor)

# Print the prediction
print(prediction)

# Make a prediction using the PyTorch model
prediction = model(input_question_tensor)

# Get the index of the highest prediction
prediction_index = torch.argmax(prediction).item()

# Get the corresponding answer from the list of answers
prediction_string = answers[prediction_index]

# Print the prediction
print(prediction_string)

# Convert the encoded answers into a tensor
answers_tensor = torch.from_numpy(answers_encoded)

# Initialize a counter for the number of correct predictions
correct_predictions = 0

# Iterate over the list of questions
# Iterate over the list of questions
for question, answer in zip(questions, answers):
    # Encode the question using the SentenceTransformer model
    question_encoded = sentence_transformer.encode([question])

    # Convert the encoded question into a tensor
    question_tensor = torch.from_numpy(question_encoded)

    # Make a prediction using the PyTorch model
    prediction = model(question_tensor)

    # Get the index of the highest prediction
    prediction_index = torch.argmax(prediction).item()

    # Get the corresponding answer from the list of answers
    prediction_string = answers[prediction_index]

    # Check if the prediction is correct
    if prediction_string == answer:
        # Increment the counter for correct predictions
        correct_predictions += 1

# Calculate the accuracy of the model
accuracy = correct_predictions / len(questions)

# Print the accuracy
print(accuracy)


问:
How can I go back from expo-web-browser by clicking any URL button
I am using the payment merchant where I need to give the return_url which will redirect the user once the transaction is completed, the merchant also gives the payment_url so that the user will be redirected to this URL and once all the steps are completed it will then redirect to return URL.

I want to give the URL which let the user redirect to the app and on the same screen where he left another option could be, we close the browser by clicking the button.

```<code>import * as WebBrowser from 'expo-web-browser';

if (initiatePaymentResponse?.data?.response?.payment_url) {
 const url = initiatePaymentResponse?.data?.response?.payment_url
 WebBrowser.openBrowserAsync(url)
}
</code>```

I am expecting it when the user clicks on the button (as marked) on the browser and then redirects to the back of the application screen.

Body:
I am using the payment merchant where I need to give the return_url which will redirect the user once the transaction is completed, the merchant also gives the payment_url so that the user will be redirected to this URL and once all the steps are completed it will then redirect to return URL.

I want to give the URL which let the user redirect to the app and on the same screen where he left another option could be, we close the browser by clicking the button.

import * as WebBrowser from 'expo-web-browser';

if (initiatePaymentResponse?.data?.response?.payment_url) {
 const url = initiatePaymentResponse?.data?.response?.payment_url
 WebBrowser.openBrowserAsync(url)
}

I am expecting it when the user clicks on the button (as marked) on the browser and then redirects to the back of the application screen.


问:
"Only authorized Google accounts can view this content.". cannot read documentation
Why I cannot see the documentation:
https://developers.google.com/pay/issuers/apis/push-provisioning/android?pli=1

And how to authorized my google account?


问:
Seeding Data from One Table to Another Table
I want to seed data from ProformaInvoice table to BTBPending table. What I did everything is right but in ProformaInvoice table it is being reference with ItemBreakDown& StyleBreakDown tables using foreign key.

The problem is when I send data from obj parameter to BTBPending table I can trigger data which comes from ItemBreakDown & StyleBreakDown.

What I did is shown here - ProformaInvoice controller class, Create method:

```<code>public IActionResult Create(ProformaInvoice obj)
{
        if (ModelState.IsValid)
        {
            _unitOfWork.ProformaInvoice.Add(obj);
            _unitOfWork.Save();

            BTBPending objBTBPendingList = new BTBPending();

            objBTBPendingList.PendingId = obj.PiId;
            objBTBPendingList.SupplierListId = obj.SupplierListId;
            objBTBPendingList.CountryListId = obj.CountryListId;
            objBTBPendingList.ItemListId = obj.ItemBreakDownList;
            objBTBPendingList.PiValue = obj.PiValue;
            objBTBPendingList.PINo = obj.PINo;
            objBTBPendingList.TradeTermListId = obj.TradeTermListId;
            objBTBPendingList.BuyerListId = obj.BuyerListId;
            objBTBPendingList.StyleListId = obj.StyleListId;

            _unitOfWork.BTBPending.Add(objBTBPendingList);
            _unitOfWork.Save();

            return CreatedAtAction("GetDetails", new { id = obj.PiId }, obj);
        }

        _logger.LogError($"Something went wrong in the {nameof(Create)}");
        return StatusCode(500, "Internal Server Error, Please Try Again Later!");
}
</code>```

Problem is here - I can't access ItemListId which is store in the ItemBreakDown table:

```<code>objBTBPendingList.ItemListId = obj.ItemBreakDownList;
</code>```

And on this line also:

```<code>objBTBPendingList.StyleListId = obj.StyleListId
</code>```

ProformaInvoice model class :

```<code>public class ProformaInvoice
{
    [Key]
    public int PiId { get; set; }
    public int? ActualContractId { get; set; }
    //[ForeignKey("ContractListId")]
    public ContractList? ActualContract { get; set; }
    public int? ContractListId { get; set; }
    [ForeignKey("ContractListId")]
    [ValidateNever]
    public ContractList? ContractList { get; set; }
    public int? SupplierListId { get; set; }
    [ForeignKey("SupplierListId")]
    [ValidateNever]
    public SupplierList? SupplierList { get; set; }
    [DisplayName("COUNTRY")]
    public int? CountryListId { get; set; }
    [ForeignKey("CountryListId")]
    [ValidateNever]
    public CountryList? CountryList { get; set; }
    [DisplayName("VALUE")]
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
    public decimal? PiValue { get; set; }
    [DisplayName("P/I No.")]
    public string? PINo { get; set; }
    [DisplayName("BUYER")]
    public int? BuyerListId { get; set; }
    [ForeignKey("BuyerListId")]
    [ValidateNever]
    public BuyerList? BuyerList { get; set; }
    [DisplayName("TRADE TERM")]
    public int? TradeTermListId { get; set; }
    [ForeignKey("TradeTermListId")]
    [ValidateNever]
    public TradeTermList? TradeTermList { get; set; }

    public string? LcNo { get; set; }
    public string? PiStatus { get; set; }

    public virtual List<ItemBreakDown> ItemBreakDownList { get; set; } = new List<ItemBreakDown>();
    public virtual List<StyleBreakDown> StyleBreakDownList { get; set; } = new List<StyleBreakDown>();
}
</code>```

Please help me solve this issue. Thank you.

Body:
I want to seed data from ProformaInvoice table to BTBPending table. What I did everything is right but in ProformaInvoice table it is being reference with ItemBreakDown& StyleBreakDown tables using foreign key.

The problem is when I send data from obj parameter to BTBPending table I can trigger data which comes from ItemBreakDown & StyleBreakDown.

What I did is shown here - ProformaInvoice controller class, Create method:

public IActionResult Create(ProformaInvoice obj)
{
        if (ModelState.IsValid)
        {
            _unitOfWork.ProformaInvoice.Add(obj);
            _unitOfWork.Save();

            BTBPending objBTBPendingList = new BTBPending();

            objBTBPendingList.PendingId = obj.PiId;
            objBTBPendingList.SupplierListId = obj.SupplierListId;
            objBTBPendingList.CountryListId = obj.CountryListId;
            objBTBPendingList.ItemListId = obj.ItemBreakDownList;
            objBTBPendingList.PiValue = obj.PiValue;
            objBTBPendingList.PINo = obj.PINo;
            objBTBPendingList.TradeTermListId = obj.TradeTermListId;
            objBTBPendingList.BuyerListId = obj.BuyerListId;
            objBTBPendingList.StyleListId = obj.StyleListId;

            _unitOfWork.BTBPending.Add(objBTBPendingList);
            _unitOfWork.Save();

            return CreatedAtAction("GetDetails", new { id = obj.PiId }, obj);
        }

        _logger.LogError($"Something went wrong in the {nameof(Create)}");
        return StatusCode(500, "Internal Server Error, Please Try Again Later!");
}

Problem is here - I can't access ItemListId which is store in the ItemBreakDown table:

objBTBPendingList.ItemListId = obj.ItemBreakDownList;

And on this line also:

objBTBPendingList.StyleListId = obj.StyleListId

ProformaInvoice model class :

public class ProformaInvoice
{
    [Key]
    public int PiId { get; set; }
    public int? ActualContractId { get; set; }
    //[ForeignKey("ContractListId")]
    public ContractList? ActualContract { get; set; }
    public int? ContractListId { get; set; }
    [ForeignKey("ContractListId")]
    [ValidateNever]
    public ContractList? ContractList { get; set; }
    public int? SupplierListId { get; set; }
    [ForeignKey("SupplierListId")]
    [ValidateNever]
    public SupplierList? SupplierList { get; set; }
    [DisplayName("COUNTRY")]
    public int? CountryListId { get; set; }
    [ForeignKey("CountryListId")]
    [ValidateNever]
    public CountryList? CountryList { get; set; }
    [DisplayName("VALUE")]
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
    public decimal? PiValue { get; set; }
    [DisplayName("P/I No.")]
    public string? PINo { get; set; }
    [DisplayName("BUYER")]
    public int? BuyerListId { get; set; }
    [ForeignKey("BuyerListId")]
    [ValidateNever]
    public BuyerList? BuyerList { get; set; }
    [DisplayName("TRADE TERM")]
    public int? TradeTermListId { get; set; }
    [ForeignKey("TradeTermListId")]
    [ValidateNever]
    public TradeTermList? TradeTermList { get; set; }

    public string? LcNo { get; set; }
    public string? PiStatus { get; set; }

    public virtual List<ItemBreakDown> ItemBreakDownList { get; set; } = new List<ItemBreakDown>();
    public virtual List


问:
Enabling web in existing Flutter project gets error "Binding has not yet been initialized."
I'm attempting to web-enable a Flutter project that is a couple of years old. I've gone through all of the steps I can find online, but when I attempt to Run Debugging for Chrome I get the error below.

I am aware that the error 'Binding has not yet been initialized' is caused by not calling WidgetsFlutterBinding.ensureInitialized(), however, when I run on Chrome it never gets to my main(), therefore, I never get chance to call ensureInitialized().

What's happening is the debugger launches Chrome and creates a Tab that displays my app name, but my flutter code never gets called.

I would appreciate any help in solving this problem.

```<code>The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.
    at Object.throw_ [as throw] (errors.dart:266:49)
    at binding.dart:284:9
    at BindingBase.checkInstance (binding.dart:365:14)
    at get instance [as instance] (binding.dart:54:54)
    at platform_channel.MethodChannel.new.setMethodCallHandler (platform_channel.dart:519:51)
    at DtmfPlugin.registerWith (dtmf_web.dart:14:12)
    at Object.registerPlugins (web_plugin_registrant.dart:36:14)
    at web_entrypoint.dart:27:24
    at Object._checkAndCall (operations.dart:334:14)
    at Object.dcall (operations.dart:339:39)
    at initialization.dart:73:24
    at Generator.next (<anonymous>)
    at runBody (async_patch.dart:84:54)
    at Object._async [as async] (async_patch.dart:123:5)
    at _engine.AppBootstrap.new.<anonymous> (initialization.dart:71:16)
    at Object._checkAndCall (operations.dart:334:14)
    at Object.callMethod (operations.dart:398:10)
    at Object.dsend (operations.dart:402:5)
    at _engine.AppBootstrap.new.<anonymous> (app_bootstrap.dart:72:22)
    at Generator.next (<anonymous>)
    at runBody (async_patch.dart:84:54)
    at Object._async [as async] (async_patch.dart:123:5)
    at app_bootstrap.dart:70:25
    at Object._checkAndCall (operations.dart:334:14)
    at Object.dcall (operations.dart:339:39)
    at ret (js_patch.dart:413:11)
    at new Promise (<anonymous>)
    at app_bootstrap.dart:68:14
    at Object._checkAndCall (operations.dart:334:14)
    at Object.dcall (operations.dart:339:39)
    at Object.ret [as runApp] (js_patch.dart:413:11)
    at (index):53:26
</code>```

[✓] Flutter (Channel stable, 3.3.10, on macOS 12.5.1 21G83 darwin-x64, locale en-US)
    • Flutter version 3.3.10 on channel stable at /Users/keithblack/GitHub/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (2 weeks ago), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/keithblack/Library/Android/sdk
    • Platform android-33, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F100
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.74.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.56.0

[✓] Connected device (4 available)
    • iPhone 8 (mobile)      • 6F91BC53-6CE3-4AE1-89CF-D076DABD5430 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • iPhone 12 Pro (mobile) • 9CCAD0CA-0B66-42E9-B554-535A45FD5877 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • macOS (desktop)        • macos                                • darwin-x64     • macOS 12.5.1 21G83 darwin-x64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!```
</code>```

Body:
I'm attempting to web-enable a Flutter project that is a couple of years old. I've gone through all of the steps I can find online, but when I attempt to Run Debugging for Chrome I get the error below.

I am aware that the error 'Binding has not yet been initialized' is caused by not calling WidgetsFlutterBinding.ensureInitialized(), however, when I run on Chrome it never gets to my main(), therefore, I never get chance to call ensureInitialized().

What's happening is the debugger launches Chrome and creates a Tab that displays my app name, but my flutter code never gets called.

I would appreciate any help in solving this problem.

The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.
    at Object.throw_ [as throw] (errors.dart:266:49)
    at binding.dart:284:9
    at BindingBase.checkInstance (binding.dart:365:14)
    at get instance [as instance] (binding.dart:54:54)
    at platform_channel.MethodChannel.new.setMethodCallHandler (platform_channel.dart:519:51)
    at DtmfPlugin.registerWith (dtmf_web.dart:14:12)
    at Object.registerPlugins (web_plugin_registrant.dart:36:14)
    at web_entrypoint.dart:27:24
    at Object._checkAndCall (operations.dart:334:14)
    at Object.dcall (operations.dart:339:39)
    at initialization.dart:73:24
    at Generator.next (<anonymous>)
    at runBody (async_patch.dart:84:54)
    at Object._async [as async] (async_patch.dart:123:5)
    at _engine.AppBootstrap.new.<anonymous> (initialization.dart:71:16)
    at Object._checkAndCall (operations.dart:334:14)
    at Object.callMethod (operations.dart:398:10)
    at Object.dsend (operations.dart:402:5)
    at _engine.AppBootstrap.new.<anonymous> (app_bootstrap.dart:72:22)
    at Generator.next (<anonymous>)
    at runBody (async_patch.dart:84:54)
    at Object._async [as async] (async_patch.dart:123:5)
    at app_bootstrap.dart:70:25
    at Object._checkAndCall (operations.dart:334:14)
    at Object.dcall (operations.dart:339:39)
    at ret (js_patch.dart:413:11)
    at new Promise (<anonymous>)
    at app_bootstrap.dart:68:14
    at Object._checkAndCall (operations.dart:334:14)
    at Object.dcall (operations.dart:339:39)
    at Object.ret [as runApp] (js_patch.dart:413:11)
    at (index):53:26

[✓] Flutter (Channel stable, 3.3.10, on macOS 12.5.1 21G83 darwin-x64, locale en-US)
    • Flutter version 3.3.10 on channel stable at /Users/keithblack/GitHub/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (2 weeks ago), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/keithblack/Library/Android/sdk
    • Platform android-33, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F100
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.74.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.56.0

[✓] Connected device (4 available)
    • iPhone 8 (mobile)      • 6F91BC53-6CE3-4AE1-89CF-D076DABD5430 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • iPhone 12 Pro (mobile) • 9CCAD0CA-0B66-42E9-B554-535A45FD5877 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • macOS (desktop)        • macos                                • darwin-x64     • macOS 12.5.1 21G83 darwin-x64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!```


问:
Does vite and rollup apply tree shaking on font icons?
I'm switching from Next.js to Qwik. One problem that I have for this migration, is material icons.

In Next, I could easily use MUI icons.

In Next, I use qwikify$ to use MUI icons, but they cause blanket rendering of components in the production.

I considered using Google Font Icon for this.

I know I can choose each icon and export its SVG. But I wonder if I include the font in my project and use icons there, does Vite and Rollup tree-shake the fonts too?

Because if they don't, then adding a huge font-icon just to use some icons is a very heavy overhead.

And if they do, then adding each icon individually as an SVG means slower development.


问:
Google map multiple vehicle realtime location with laravel
I have a vehicle model that has a one to one relationship with location model. Google Map is being used to display the locations of vehicles, and the locations are updated every 5 seconds.

I tried this script

```<code><script>
        var map;
        var markers = [];
        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: 24.8949, lng: 91.8687},
                zoom: 14
            });
            var i =0;
            function addMarker(lat, lng) {
                var marker = new google.maps.Marker({
                    position: {lat: lat, lng: lng},
                    map: map,
                    icon: {
                        url: "{{ asset('/assets/uploads/default/mapVehicle.png') }}",
                        scaledSize: new google.maps.Size(30, 30),
                    },
                });
                markers.push(marker);
            }
            function getLocations() {
                $.ajax({
                    url: '/api/vehicles/location',
                    type: 'GET',
                    success: function(vehicle) {
                        markers = [];
                        for (var i = 0; i < vehicle.length; i++) {
                            if(vehicle[i].location){
                                var newlat = parseFloat(vehicle[i].location['lat']);
                                var newlong = parseFloat(vehicle[i].location['long']);
                                addMarker(newlat, newlong);
                            }
                        }
                        console.log(markers);
                    }
                });
            }
            setInterval(function() {
                getLocations();
            }, 5000);
        }
    </script>
</code>```

This code worked perfectly. However, it adds new markers to the map rather than removing the old ones when the location changes in the database and an ajax request retrieves the updated location. Additionally, I want an infowindow to open and display different info for each marker when I click on the marker. Can anyone help me with that?

Body:
I have a vehicle model that has a one to one relationship with location model. Google Map is being used to display the locations of vehicles, and the locations are updated every 5 seconds.

I tried this script

This code worked perfectly. However, it adds new markers to the map rather than removing the old ones when the location changes in the database and an ajax request retrieves the updated location. Additionally, I want an infowindow to open and display different info for each marker when I click on the marker. Can anyone help me with that?


问:
How to send data from main page to api [next.js]
Let's say I have a next.js project set up like this:

```<code>—pages
  home.js
    —api
      user.js
</code>```

And in home.js I have data from getServerSideProps(req) that I need to send to the api. Currently, I just have something like this in home.js

export default function Home(props) {

  (async function() {
      try {
      //I get the "Only absolute URL's are supported" error if I only provide `api/user`
      await fetch('https://example.com/api/user', {
        method: 'POST',
        body: JSON.stringify({
          username: props.user.username,
          image: props.user.image
        }),
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.log(error);
    }
  })();

  //...
```

However, I don't feel like this is the best way to do this, as the data often comes back as null and sometimes stalls API requests. What is the ideal way of doing this and sending data from pages/home.js to my api, pages/api/user.js?

Body:
Let's say I have a next.js project set up like this:

—pages
  home.js
    —api
      user.js

And in home.js I have data from getServerSideProps(req) that I need to send to the api. Currently, I just have something like this in home.js

export default function Home(props) {

  (async function() {
      try {
      //I get the "Only absolute URL's are supported" error if I only provide `api/user`
      await fetch('https://example.com/api/user', {
        method: 'POST',
        body: JSON.stringify({
          username: props.user.username,
          image: props.user.image
        }),
        headers: {
          "Content-Type": "application/json"
        }
      });
    } catch (error) {
      console.log(error);
    }
  })();

  //...

However, I don't feel like this is the best way to do this, as the data often comes back as null and sometimes stalls API requests. What is the ideal way of doing this and sending data from pages/home.js to my api, pages/api/user.js?


问:
Why is the JS-length-function not working on this array?
I want to iteratate through my result array. But even when I am pushing only numbers to the array the length function is not working on this. In the webbrowser I clearly see that the array is created. But when I want to use the lengh-function it only shows 0.

let array = [];

fetch('./api/getFromDatabase', {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
  }).then(response => response.json())
  .then(data => {
    data.forEach(tocken => {
      array.push(3);
    })
  })
  .catch(err => alert(err))

console.log(array);
console.log(array.length); //not working

let array1 = [3, 4, 2];
console.log(array1);
console.log(array1.length); //working
```


问:
Raphael RPG/Sidescroller Game movement
From what I understand, when I want to move an object, on the screen, I can use the .animate function to move it to where I want, e.g.

```<code>R = Raphael( ... );
c = R.circle( ... );
c.animate( ... );
</code>```

would move the circle as specified in my arguments to c.animate( .. ).

However, if I want to translate almost all of my objects, (think, Pokemon on Gameboy or classic Mario platformer, where when the player moves, the player sprite actually stays put, and the rest of the world moves instead), how would it be done? Is the only way to do this by moving every object or by calling .clear() and drawing everything from scratch? There has to be a better way right?

ContentLicense: CC BY-SA 3.0

Title: Raphael RPG/Sidescroller Game movement

Body:
From what I understand, when I want to move an object, on the screen, I can use the .animate function to move it to where I want, e.g.

R = Raphael( ... );
c = R.circle( ... );
c.animate( ... );

would move the circle as specified in my arguments to c.animate( .. ).

However, if I want to translate almost all of my objects, (think, Pokemon on Gameboy or classic Mario platformer, where when the player moves, the player sprite actually stays put, and the rest of the world moves instead), how would it be done? Is the only way to do this by moving every object or by calling .clear() and drawing everything from scratch? There has to be a better way right?


问:
Why SpringBootTest Vm Options Not Working?
It seems there are many similar questions. But my problem is not solved, so I ask.

I am using SpringBoot and Intellij combination.

And the VM Option called "-Djasypt.encryptor.password" is set in Intellij.

This recognizes the option and operates without any problems in the SpringBoot environment.

That is, no problems so far.

However, it is not recognized at all in the @SpringBootTest environment for testing.

Of course, I entered it separately in Test VmOption.

I added the same Vm Option to ProjectNameApplicationTests, which is automatically generated in Run/Debug Configurations, but my tests do not work because the above password is not in the settings.

That is, the Vm Option is being ignored.

In a normal project environment there is no problem. But only in test environment why Vm Option doesn't recognize it?

[Error]

```<code>Reason: java.lang.IllegalArgumentException: Could not resolve placeholder 'jasypt.encryptor.password' in value
</code>```

Body:
It seems there are many similar questions. But my problem is not solved, so I ask.

I am using SpringBoot and Intellij combination.

And the VM Option called "-Djasypt.encryptor.password" is set in Intellij.

This recognizes the option and operates without any problems in the SpringBoot environment.

That is, no problems so far.

However, it is not recognized at all in the @SpringBootTest environment for testing.

Of course, I entered it separately in Test VmOption.

I added the same Vm Option to ProjectNameApplicationTests, which is automatically generated in Run/Debug Configurations, but my tests do not work because the above password is not in the settings.

That is, the Vm Option is being ignored.

In a normal project environment there is no problem. But only in test environment why Vm Option doesn't recognize it?

[Error]

Reason: java.lang.IllegalArgumentException: Could not resolve placeholder 'jasypt.encryptor.password' in value


问:
Child to Parent values update in flutter using global Custom App Bar
How to update cart or wishlist count child to parent whenever navigating one page to another page i am using the global app bar for two screens whenever second screen update anything it's not effecting the first screen.

Custom APP BAR

```<code>class VLAppBar extends StatelessWidget  implements PreferredSizeWidget {

   User? user;
  VLAppBar({this.user});

  @override
  Widget build(BuildContext context) {

    final cwp = Provider.of<CartWishListProvider>(context);

    final deviceWidth = MediaQuery.of(context).size.width;
    return AppBar(
      elevation: 0.0,
      backgroundColor: Colors.white,
      leading:  type =="home"?null:IconButton(onPressed: ()async{

        Navigator.pop(context);

      }, icon: Icon(Icons.arrow_back_ios)),
      title: Center(
        child: Padding(
          padding: const EdgeInsets.only(left: 20),
          child: RichText(
            text: TextSpan(
              text: type =="home"?"$APP_NAME":"${comicBook.courseName} Details",
              style: type =="home"?title_text_style4.copyWith(
                  color: Colors.amber, fontSize: deviceWidth > 320?deviceWidth > 375 ? 25:23:21):title_text_style,
            ),

            //textAlign: TextAlign.right,
          ),
        ),
      ),

      actions: <Widget>[
        Text("${context.read<CartWishListProvider>().getWishlistCount}"),
      ],

    );
  }

  @override
  // TODO: implement preferredSize
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

</code>```

First Screen

Intial time it's coming exact count

Whenever user this screen to new screen navigating that time same app bar using

Whenever back to same screen from new screen the updation values are not coming
Second screen

Intial time it's coming exact count

Add or remove operation are working fine

In this screen to old screen old values only it's showing please provide the solution for this scenario, Thanks for advance.

Body:
How to update cart or wishlist count child to parent whenever navigating one page to another page i am using the global app bar for two screens whenever second screen update anything it's not effecting the first screen.

Custom APP BAR

class VLAppBar extends StatelessWidget  implements PreferredSizeWidget {

   User? user;
  VLAppBar({this.user});

  @override
  Widget build(BuildContext context) {

    final cwp = Provider.of<CartWishListProvider>(context);

    final deviceWidth = MediaQuery.of(context).size.width;
    return AppBar(
      elevation: 0.0,
      backgroundColor: Colors.white,
      leading:  type =="home"?null:IconButton(onPressed: ()async{

        Navigator.pop(context);

      }, icon: Icon(Icons.arrow_back_ios)),
      title: Center(
        child: Padding(
          padding: const EdgeInsets.only(left: 20),
          child: RichText(
            text: TextSpan(
              text: type =="home"?"$APP_NAME":"${comicBook.courseName} Details",
              style: type =="home"?title_text_style4.copyWith(
                  color: Colors.amber, fontSize: deviceWidth > 320?deviceWidth > 375 ? 25:23:21):title_text_style,
            ),

            //textAlign: TextAlign.right,
          ),
        ),
      ),

      actions: <Widget>[
        Text("${context.read<CartWishListProvider>().getWishlistCount}"),
      ],

    );
  }

  @override
  // TODO: implement preferredSize
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

First Screen

Intial time it's coming exact count

Whenever user this screen to new screen navigating that time same app bar using

Whenever back to same screen from new screen the updation values are not coming
Second screen

Intial time it's coming exact count

Add or remove operation are working fine

In this screen to old screen old values only it's showing please provide the solution for this scenario, Thanks for advance.


问:
Implementing R function inside Qt creator
I have this function to connect R with MYSQL and return the connection as global variable to be used in other functions later on. The parameters should be taken from the user. I would like to call this function from Qt creator using RInside and Rcpp libraries.

```<code>connection <- function(username,passwords,databaseName){
 #' create connection with selected database
ConnectedDb <- DBI::dbConnect(RMariaDB::MariaDB(), user=username,
                              password=passwords, dbname=databaseName,
                              host='localhost')
  con <<- ConnectedDb
     #' assign the connection as global variable
  assign("con", ConnectedDb, envir = .GlobalEnv)
  #' return the connection
return(con)}
</code>```

I added RInside and Rcpp to my Qt project and applied the project suggested in https://github.com/eddelbuettel/rinside/tree/master/inst/examples/qt . The project worked fine.

I appreciate any suggestions.

UPDATE: I understand that I need to put the function inside  R.parseEvalQ and then call it using R.parseEval. A summary of what I did:

```<code>    #include <R.h>
    #include <RInside.h>
    #include <Rcpp.h>
    #include <mysql.h>
    #include <driver.h>
    int main(int argc, const char * argv[]) {
    RInside R(argc, argv);
    string username,passwords,databaseName;
    R["username"] = "root";
    R["passwords"] = "pass";
    R["databaseName"] = "Test";

    // define R function in C++ environment
    R.parseEvalQ("connection <- function(username,
     passwords,databaseName){ConnectedDb <<-
 DBI::dbConnect(RMariaDB::MariaDB(),user=username,password=passwords,
     dbname=databaseName,host='localhost'); con <<- ConnectedDb;
     assign('con', ConnectedDb, envir = .GlobalEnv); con}");
     // call R function in C++ environment
     R.parseEval("connection(username,passwords,databaseName)");
     return 0;
}
</code>```

Now I would like to test the function (if it work probably or not). I need to assign variable equal to R.parseEval to print it out. I added the following code:

```<code>sql::Connection *con;
con = R.parseEval("connection(username,passwords,databaseName)");
</code>```

It gave the following error:

```<code>Cannot initialize a member subobject of type 'sql::Connection *' with an lvalue of type 'SEXP' (aka 'SEXPREC *')
</code>```

When I use Rcpp::List as follow:

```<code> Rcpp::List c;
 c = R.parseEval("connection(username,passwords,databaseName)");
</code>```

I got the following error:

```<code>/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/Rcpp/internal/wrap.h:503:18 No viable conversion from 'const RInside::Proxy' to 'SEXP' (aka 'SEXPREC *')
</code>```

Which object in Rcpp or c++ will be equal to returned connection ? because I tried so many types and nothing worked. For now I do not guarantee that the connection is established !

Body:
I have this function to connect R with MYSQL and return the connection as global variable to be used in other functions later on. The parameters should be taken from the user. I would like to call this function from Qt creator using RInside and Rcpp libraries.

connection <- function(username,passwords,databaseName){
 #' create connection with selected database
ConnectedDb <- DBI::dbConnect(RMariaDB::MariaDB(), user=username,
                              password=passwords, dbname=databaseName,
                              host='localhost')
  con <<- ConnectedDb
     #' assign the connection as global variable
  assign("con", ConnectedDb, envir = .GlobalEnv)
  #' return the connection
return(con)}

I added RInside and Rcpp to my Qt project and applied the project suggested in https://github.com/eddelbuettel/rinside/tree/master/inst/examples/qt . The project worked fine.

I appreciate any suggestions.

UPDATE: I understand that I need to put the function inside  R.parseEvalQ and then call it using R.parseEval. A summary of what I did:

    #include <R.h>
    #include <RInside.h>
    #include <Rcpp.h>
    #include <mysql.h>
    #include <driver.h>
    int main(int argc, const char * argv[]) {
    RInside R(argc, argv);
    string username,passwords,databaseName;
    R["username"] = "root";
    R["passwords"] = "pass";
    R["databaseName"] = "Test";

    // define R function in C++ environment
    R.parseEvalQ("connection <- function(username,
     passwords,databaseName){ConnectedDb <<-
 DBI::dbConnect(RMariaDB::MariaDB(),user=username,password=passwords,
     dbname=databaseName,host='localhost'); con <<- ConnectedDb;
     assign('con', ConnectedDb, envir = .GlobalEnv); con}");
     // call R function in C++ environment
     R.parseEval("connection(username,passwords,databaseName)");
     return 0;
}

Now I would like to test the function (if it work probably or not). I need to assign variable equal to R.parseEval to print it out. I added the following code:

sql::Connection *con;
con = R.parseEval("connection(username,passwords,databaseName)");

It gave the following error:

Cannot initialize a member subobject of type 'sql::Connection *' with an lvalue of type 'SEXP' (aka 'SEXPREC *')

When I use Rcpp::List as follow:

 Rcpp::List c;
 c = R.parseEval("connection(username,passwords,databaseName)");

I got the following error:

/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/Rcpp/internal/wrap.h:503:18 No viable conversion from 'const RInside::Proxy' to 'SEXP' (aka 'SEXPREC *')

Which object in Rcpp or c++ will be equal to returned connection ? because I tried so many types and nothing worked. For now I do not guarantee that the connection is established !


问:
Can I send data over radio signals from Android device
I have a question regarding the radio signals, is it possible to send data over a particular frequency band from android ? Without using any external module or Arduino/raspberry pi.
For example sending the data over 60MHz frequency, from android and receiving the data on another android phone on same frequency band.

I am expecting a good solution to this.