Ohm::DataTypes::Type::Hash can't convert normal hash to SerializedHash - ohm

Maybe this question is too naive, but it really confused me. Here is my code, a profession class.
class Profession < OhmModel
include ProfessionMethods
attribute :type, Type::Integer
attribute :level, Type::Integer
attribute :add_point, Type::Hash
attribute :attribute_add_point, Type::Hash
reference :player, Player
def initialize(args = {})
super
if args.blank?
self.type = 1
self.level = 1
end
#add_point = SerializedHash.new
#attribute_add_point = SerializedHash.new
end
# 初始化加点
def init_add_point(hash)
hash.each do |key, value|
#add_point[key] = value
end
update_add_point
end
def update_add_point
self.add_point = #add_point
self.save
init_attribute_add_point
end
def init_attribute_add_point
self.add_point.each do |key, value|
key_new = key.to_s.gsub('_percent', '').to_sym
PROFESSIONS[type][key_new][:attribute].split(',').each do |attr|
#attribute_add_point[attr] = value
end
end
update_attribute_add_point
end
def update_attribute_add_point
self.attribute_add_point = #attribute_add_point
self.save
end
def name
PROFESSIONS[type][:name]
end
def probability
hash = {}
PROFESSIONS[type].keys.each do |key|
case key
when /property_id_\d?_percent/
hash[key] = PROFESSIONS[type][key]
end
end
return hash
end
def base_value
hash = {}
hash[:basic] = PROFESSIONS[type][:basic]
return hash
end
def points_count
5*level
end
def get_add_point
hash ={}
add_point_hash = self.add_point
add_point_hash.keys.each do |key|
key_new = key.to_s.gsub('_percent', '').to_sym
info = "#{PROFESSIONS[type][key_new][:name]}: #{PROFESSIONS[type][key_new][:des]}"
hash[info] = add_point_hash[key]
end
return hash
end
def fresh_add_point
probability_hash = probability
base_value_hash = base_value
points_count_value = points_count
calculate_probability(probability_hash, base_value_hash, points_count_value)
end
def redistribute_add_point
hash = {}
probability_hash = {}
probability.keys.each do |key|
probability_hash[key] = 1.0/probability.count
end
base_value_hash = base_value
points_count_value = points_count
add_point_hash = calculate_probability(probability_hash, base_value_hash, points_count_value)
init_add_point(add_point_hash)
add_point_hash.keys.each do |key|
key_new = key.to_s.gsub('_percent', '').to_sym
info = "#{PROFESSIONS[type][key_new][:name]}: #{PROFESSIONS[type][key_new][:des]}"
hash[info] = add_point_hash[key]
end
return hash
end
protected
def after_create
hash = fresh_add_point
init_add_point(hash)
end
end
It is all right when initializing.
pro = Profession.create
=> #<Profession:0x9504ffc
#_memo={},
#add_point=
{:property_id_1_percent=>104.0,
:property_id_2_percent=>101.0,
:property_id_3_percent=>100.0,
:property_id_4_percent=>100.0,
:property_id_5_percent=>100.0},
#attribute_add_point=
{"crystal_output"=>104.0,
"tritium_output"=>104.0,
"power_consume"=>101.0,
"speed"=>100.0,
"armor"=>100.0,
"hp_damage"=>100.0,
"armor_damage"=>100.0,
"sheild_damage"=>100.0},
#attributes=
{:type=>1,
:level=>1,
:created_at=>1368756861,
:updated_at=>1368756861,
:id=>"34",
:add_point=>
{:property_id_1_percent=>104.0,
:property_id_2_percent=>101.0,
:property_id_3_percent=>100.0,
:property_id_4_percent=>100.0,
:property_id_5_percent=>100.0},
:attribute_add_point=>
{"crystal_output"=>104.0,
"tritium_output"=>104.0,
"power_consume"=>101.0,
"speed"=>100.0,
"armor"=>100.0,
"hp_damage"=>100.0,
"armor_damage"=>100.0,
"sheild_damage"=>100.0}},
#errors={},
#id="34">
When reassign a hash type value to pro.add_point and save the object, Here is the problem.
pro.add_point = {:one => 1, :two => 2}
pro.save
Profession[34]
=> #<Profession:0x9a544bc
#_memo={},
#add_point={},
#attribute_add_point={},
#attributes=
{:created_at=>"1368756861",
:level=>"1",
:attribute_add_point=>
"{\"crystal_output\":104.0,\"tritium_output\":104.0,\"power_consume\":101.0,\"speed\":100.0,\"armor\":100.0,\"hp_damage\":100.0,\"armor_damage\":100.0,\"sheild_damage\":100.0}",
:add_point=>"{:one=>1, :two=>2}",
:updated_at=>"1368757147",
:type=>"1"},
#id="34">
The "add_point" attribute is saved as a normal string, not convert to a JSON style.

Related

how to solve vector-based variable/constraints in python pyomo

enter image description here
I am solving this problem, i write code. but getting error at last line ' results'
please anyone know how to deal vector based dynamic optimization please let me know.
model = ConcreteModel()
model.num_itter = Param(initialize = 0)
global p_
p_ = model.num_itter
# print(value(p_))
torq = np.zeros((14,6))
# global p_
def M_func(model,i):
return np.array(Mqn( *value(model.q[i]) ))
def sai_func(model, i):
return np.array(sain( *value(model.q[i]) ))
def sai_func_T(model, i):
return np.array(sain( *value(model.q[i]) )).T
def c_func(model, i):
return np.array(cqn(*np.append(value(model.q[0]),value(model.u[0])) ))
def dsai_dt_func(model, i):
return np.array(saidn(*np.append(value(model.q[0]),value(model.u[0])) ))
def first_eq(model,i):
return value(model.M[i])#value(model.q[i])-\
value(model.sai[i]).T#value(model.lm[i])+\
torq#value(model.tu[i])
def second_eq(model,i):
return value(model.sai[i])#value(model.a[i])
def third_eq(model,i):
return (-value(model.dsai_dt[i])#value(model.u[i])).reshape(10,1)
def solu_f(model,i):
global p_
s_ = solu10[int(p_/2),:]
# time.sleep(2)
p_= p_+1
print('p',p_)
return s_
def init_q(model,i):
return solu10[i,:]
def init_u(model,i):
return np.zeros((14,))
def init_tu(model,i):
return np.zeros((6,))
def init_lm(model,i):
return np.zeros((10,))
def init_a(model,i):
return np.zeros((14,))
# Define the time horizon
t0 =0 ;tf =40
model.t = ContinuousSet(bounds=(t0,tf))
# measurements = {_: solu10[_,:] for _ in range(len(solu10))}
# Define the state variables, control inputs, and other variables
model.time_points = Set(initialize=range(200))
model.q = Var(model.t,initialize=init_q)
model.u = Var(model.t,initialize=init_u)
model.a = Var(model.t,initialize=init_a)
model.tu =Var(model.t,initialize=init_tu)
model.lm = Var(model.t,initialize=init_lm)
model.dqdt = DerivativeVar(model.q,wrt=model.t)
model.dudt = DerivativeVar(model.u,wrt=model.t)
# Define the parameters
model.M = Param(model.t,mutable=True, initialize=M_func,within=Any)
model.sai = Param(model.t,mutable=True, initialize=sai_func,within=Any)
model.c = Param(model.t,mutable=True, initialize=c_func,within=Any)
model.dsai_dt = Param(model.t,mutable=True, initialize=dsai_dt_func,within=Any)
model.first_meq = Param(model.t,mutable =True, initialize = first_eq,within = Any)
model.solu = Param(model.t,mutable = True,initialize = solu_f, within =Any)
model.second_meq = Param(model.t,mutable =True, initialize = second_eq,within = Any)
model.third_meq = Param(model.t,mutable =True, initialize = third_eq,within = Any)
# print(value(p_))
# Define the Constraint equations
def dyn_eq_1(model,i):
return model.first_meq[i]==-model.c[i]
def dyn_eq_2(model,i):
return model.second_meq[i]==model.third_meq[i]
def vel_constraint(model,i):
return model.dqdt[i]==model.u[i]
def acc_constraint(model,i):
return model.dudt[i]==model.a[i]
def path_constraint(model, i):
return model.q[i] == model.solu[i]
model.dyn_eq_1s= Constraint(model.t, rule=dyn_eq_1)
model.dyn_eq_2s= Constraint(model.t, rule=dyn_eq_2)
model.vel_constraints = Constraint(model.t, rule= vel_constraint)
model.acc_constraints = Constraint(model.t, rule= acc_constraint)
model.path_constraints = Constraint(model.t, rule=path_constraint)
# Define the bounds
u_lb = -np.array([2,2,0.5,0.34,float('inf'),float('inf'),0.20,28,float('inf'),float('inf'),0.20,28,0.25,0.25])
u_ub = [2,2,0.5,0.34,None,None,0.20,28,None,None,0.20,28,0.25,0.25]
a_lb = -np.array([1.5,1.5,0.2,0.10,float('inf'),float('inf'),0.10,5,float('inf'),float('inf'),0.10,5,0.10,0.10])
a_ub = [1.5,1.5,0.2,0.10,None,None,0.10,5,None,None,0.10,5,0.10,0.10]
tu_lb = -np.array([4,0.5,4,0.5,4,4])
tu_ub = [4,4,4,4,4,4]
model.u.setlb(u_lb)
model.u.setub(u_ub)
model.a.setlb(a_lb)
model.a.setub(a_ub)
model.tu.setlb(tu_lb)
model.tu.setub(tu_ub)
def u_nes_fn(model,i):
u_nes = np.array([])
for _ in [6,7,10,11,12,13]:
u_nes = np.append(u_nes,value(model.u[i])[_])
return u_nes.astype('float64')
model.u_nes = Param(model.t,initialize= u_nes_fn,within = Any)
# Define the objective function
def tu_u_(model,i):
return np.linalg.norm(value( model.u_nes[i]*model.tu[i]*model.u_nes[i]*model.tu[i]))
model.tu_u = Integral(model.t,wrt=model.t,rule = tu_u_)
def objfun(model):
return model.tu_u
model.obj = Objective(rule = objfun)
# Define the solver and solve the problem
solver = SolverFactory('ipopt')
results = solver.solve(model)
ValueError Traceback (most recent call last)
c:\Users\pyomo_opti.ipynb Cell 16 in <cell line: 11>()
9 # Define the solver and solve the problem
10 solver = SolverFactory('ipopt')
---> 11 results = solver.solve(model)
File c:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\pyomo\opt\base\solvers.py:570, in OptSolver.solve(self, *args, **kwds)
565 try:
566
...
File pyomo\repn\plugins\ampl\ampl_.pyx:410, in pyomo.repn.plugins.ampl.ampl_.ProblemWriter_nl.call()
File pyomo\repn\plugins\ampl\ampl_.pyx:1072, in pyomo.repn.plugins.ampl.ampl_.ProblemWriter_nl._print_model_NL()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How to use this rewritten QLabel class in pyqt5?

I rewritten the OLabel class naming roiLabel(), and I want to get the ROI in a frame to tracking object.
class roiLabel(QLabel): # use roiLabel class to draw ROI
def __init__(self):
super().__init__()
self.open_keyboard_flag = False
self.open_mouse_flag = False
self.draw_roi_flag = False
self.select_roi_flag = False
self.clear_flag = False
self.x0 = 0
self.y0 = 0
self.x1 = 0
self.y1 = 0
self.rect = QRect()
self.label_show = None
# when clicking mouse, record the top left corner position.
def mousePressEvent(self, event: QMouseEvent):
if event.buttons() == Qt.LeftButton:
if self.open_mouse_flag is True:
self.select_roi_flag = True
self.x0 = event.x()
self.y0 = event.y()
# release the mouse
def mouseReleaseEvent(self, event):
self.select_roi_flag = False
And I instantiate this class to the self.show_windows = roiLabel().
I have the question that how to call the function mousePressEvent():
def mousePressEvent(self, event: QMouseEvent):
if event.buttons() == Qt.LeftButton:
if self.open_mouse_flag is True:
self.select_roi_flag = True
self.x0 = event.x()
self.y0 = event.y()
what should I fill this in (?):
self.show_windows = roiLabel()
self.show_windows.mousePressEvent(?)
I have no idea how to fill using self and event: QMouseEvent two arguments....
Thanks in advance!

How to extract entity from Microsoft LUIS using python?

Following the example code in this link, I can extract the intent using "intent_result.intent_id", but how can I extract the entity/entities of the utterance?
'''
import azure.cognitiveservices.speech as speechsdk
print("Say something...")
intent_config = speechsdk.SpeechConfig(subscription="YourLanguageUnderstandingSubscriptionKey", region="YourLanguageUnderstandingServiceRegion")
intent_recognizer = speechsdk.intent.IntentRecognizer(speech_config=intent_config)
model = speechsdk.intent.LanguageUnderstandingModel(app_id="YourLanguageUnderstandingAppId")
intents = [
(model, "HomeAutomation.TurnOn"),
(model, "HomeAutomation.TurnOff")
]
intent_recognizer.add_intents(intents)
start_continuous_recognition() instead.
intent_result = intent_recognizer.recognize_once()
if intent_result.reason == speechsdk.ResultReason.RecognizedIntent:
print("Recognized: \"{}\" with intent id `{}`".format(intent_result.text, intent_result.intent_id))
elif intent_result.reason == speechsdk.ResultReason.RecognizedSpeech:
print("Recognized: {}".format(intent_result.text))
elif intent_result.reason == speechsdk.ResultReason.NoMatch:
print("No speech could be recognized: {}".format(intent_result.no_match_details))
elif intent_result.reason == speechsdk.ResultReason.Canceled:
print("Intent recognition canceled: {}".format(intent_result.cancellation_details.reason))
if intent_result.cancellation_details.reason == speechsdk.CancellationReason.Error:
print("Error details: {}".format(intent_result.cancellation_details.error_details))
# </IntentRecognitionOnceWithMic>
'''
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.language.luis.runtime.models import EntityModel
from collections import OrderedDict
from typing import Union
class LuisPredictionClass():
def __init__(self, endpoint, appIdLUIS, predictionResourcePrimaryKey):
self.endpoint = endpoint
self.appIdLUIS = appIdLUIS
self.predictionResourcePrimaryKey = predictionResourcePrimaryKey
self.client = LUISRuntimeClient(self.endpoint, CognitiveServicesCredentials(self.predictionResourcePrimaryKey))
def find_LUIS_result(self,Text):
luis_result = self.client.prediction.resolve(self.appIdLUIS,Text)
return luis_result
def extract_entity_value(self,entity: EntityModel) -> object:
if (entity.additional_properties is None or "resolution" not in entity.additional_properties ):
return entity.entity
resolution = entity.additional_properties["resolution"]
if entity.type.startswith("builtin.datetime."):
return resolution
if entity.type.startswith("builtin.datetimeV2."):
if not resolution["values"]:
return resolution
resolution_values = resolution["values"]
val_type = resolution["values"][0]["type"]
timexes = [val["timex"] for val in resolution_values]
distinct_timexes = list(OrderedDict.fromkeys(timexes))
return {"type": val_type, "timex": distinct_timexes}
if entity.type in {"builtin.number", "builtin.ordinal"}:
return self.number(resolution["value"])
if entity.type == "builtin.percentage":
svalue = str(resolution["value"])
if svalue.endswith("%"):
svalue = svalue[:-1]
return self.number(svalue)
if entity.type in {
"builtin.age",
"builtin.dimension",
"builtin.currency",
"builtin.temperature",
}:
units = resolution["unit"]
val = self.number(resolution["value"])
obj = {}
if val is not None:
obj["number"] = val
obj["units"] = units
return obj
value = resolution.get("value")
return value if value is not None else resolution.get("values")
def extract_normalized_entity_name(self,entity: EntityModel) -> str:
# Type::Role -> Role
type = entity.type.split(":")[-1]
if type.startswith("builtin.datetimeV2."):
type = "datetime"
if type.startswith("builtin.currency"):
type = "money"
if type.startswith("builtin."):
type = type[8:]
role = (
entity.additional_properties["role"]
if entity.additional_properties is not None
and "role" in entity.additional_properties
else ""
)
if role and not role.isspace():
type = role
return type.replace(".", "_").replace(" ", "_")
Now you can run it as:
LuisPrediction = LuisPredictionClass("<<endpoint>>", "<<appIdLUIS>>", "<<predictionResourcePrimaryKey>>")
luis_result = LuisPrediction.find_LUIS_result("<<YOUR STRING HERE>>")
if len(luis_result.entities) > 0:
for i in luis_result.entities:
print(LuisPrediction.extract_normalized_entity_name(i),' : ',LuisPrediction.extract_entity_value(i))

Custom Validation in Model with Parameter from controller

i have this chunk of codes in my controller
def create
number = params[:number]
#color = Colors.new(params[:colors])
#color.save
end
and i have this validation in model color.rb
validate :should_be_primary
def should_be_primary
#validations here
end
I just want the validation should only run when my params[:number] == 1
Note: params[:number] is only a parameter and not a table field.
anyone please help me.
def create
number = params[:number]
params[:colors][:param_number] = number
#color = Colors.new(params[:colors])
#color.save
end
validate :should_be_primary
def param_number=(number)
#number = number
end
def should_be_primary
if #number
#blah blah
end
end
Try this on your model.rb
validate :should_be_pimary if self.number == 1
def should_be_primary
#validations here
end

How do I fix error message. "Remember that ordinal parameters are 1-based!"

given the code snippet (please do not ask why I construct it this way...)
...some more Logic...
def blaParam = ['checkinable':checkinable]
def blaQuery = " AND c.product = :checkinable"
...some more Logic...
and
def paramBox = [] + blaParam
def queryBox = "" + blaQuery
def c = Bla.executeQuery("FROM Bla b WHERE 1 = 1 "+queryBox+" ", paramBox, [max:params.max])
I end up with a message
errors.GrailsExceptionResolver Remember that ordinal parameters are 1-based!
How do I prevent this?
Merging the two last parameter maps worked for me:
Bla.executeQuery("FROM Bla b WHERE 1 = 1 "+queryBox+" ", paramBox + [max:params.max])
if I change
def paramBox = [] + blaParam
to
def paramBox = [:] + blaParam
it is working