I am trying to implement the Kotlin scope function so assigning the variable like type/queue is clear to me but the flush() and startTimer() are not clear wheather I am using them correctly or not.
#KotlinCleanup("use scope function")
var c = note.cards()[0]
c.type = CARD_TYPE_REV
c.queue = QUEUE_TYPE_REV
c.due = (col.sched.today - 8).toLong()
c.factor = STARTING_FACTOR
c.setReps(3)
c.lapses = 1
c.ivl = 100
c.startTimer()
c.flush()
Is this the correct way to use the scope function on this variable ?
var c = note.cards()[0].apply {
type = CARD_TYPE_REV
queue = QUEUE_TYPE_REV
due = (col.sched.today - 8).toLong()
factor = STARTING_FACTOR
setReps(3)
lapses = 1
ivl = 100
startTimer()
flush()
}
Related
I Have been browsed on the internet to find an explanation for this problem for 3 days, But I didn't get an explanation to solve this problem. Anyways, I can't solve why "gaming.child.p" return 0 instead of 11. I will be very grateful for your explanation.
Here's the code :
local X = {
p = 1,
diffElementPls = "man"
};
local Y = {__index = X};
function interface()
local o = {};
return setmetatable(o, Y);
end
local w = {
something = "u found me",
child = interface()
};
local noob = {__index = w};
function new()
local o = {};
return setmetatable(o, noob);
end
local gaming = new();
local wd = new()
gaming.something = "noob"
gaming.child.p += 10
wd.child.p = 0
print(gaming.something, wd.something, gaming.child.p, wd.child.p) -- print noob u found me 0 0 instead of noob u found me 11 0
gaming.child and wd.child refer to the same table.
hence modifying wd.child.p also changes the value of gaming.child.p as it is the same variable.
Both wd and gaming don't have a field child. Hence when you index it Lua will refer to their metatable w. So in both cases you're actually modifing w.child.p
Is there a way to pass property values to another object with properties of the same name to avoid having "repeated" code?
For example, avoid having where CepReceiptsInfo is different class than value but they share some properties name and type :
val cepReceiptsInfo = CepRecepitsInfo()
cepReceiptsInfo.operationTimestamp = value.operationTimestamp
cepReceiptsInfo.sentDate = value.sentDate
cepReceiptsInfo.sentTime = value.sentTime
cepReceiptsInfo.concept = value.concept
cepReceiptsInfo.referenceNumber = value.referenceNumber
cepReceiptsInfo.amount = value.amount
cepReceiptsInfo.trackingKey = value.trackingKey
cepReceiptsInfo.bankTarget = value.bankTarget
cepReceiptsInfo.bankSource = value.bankSource
cepReceiptsInfo.sourceClienteName = value.sourceClienteName
cepReceiptsInfo.beneficiaryName = value.beneficiaryName
cepReceiptsInfo.accountNumberTarget = value.accountNumberTarget
cepReceiptsInfo.term = value.term
cepReceiptsInfo.authorizationNumber = value.authorizationNumber
cepReceiptsInfo.linkCep = value.linkCep
cepReceiptsInfo.status = value.status
cepReceiptsInfo.bankSourceRefund = value.bankSourceRefund
cepReceiptsInfo.causeRefund = value.causeRefund
cepReceiptsInfo.accountTargetRefund = value.accountTargetRefund
cepReceiptsInfo.currency = value.currency
cepReceiptsInfo.accountNumberSource = value.accountNumberSource
cepReceiptsInfo.accountTypeSource = value.accountTypeSource
cepReceiptsInfo.accountTypeTarget = value.accountTypeTarget
cepReceiptsInfo.indicatorRefund = value.indicatorRefund
cepReceiptsInfo.amountIntRefund = value.amountIntRefund
cepReceiptsInfo.operationRefundTimestamp = value.operationRefundTimestamp
cepReceiptsInfo.dateMovement = value.dateMovement
cepReceiptsInfo.timeMovement = value.timeMovement
cepReceiptsInfo.dateRefund = value.dateRefund
cepReceiptsInfo.timeRefund = value.timeRefund
to something like f.e.:
val cepReceiptsInfo = CepReceintsInfo()
cepReceiptsInfo.assignFrom(value)
both Classes are data classes.
I don't know of a way without reflection.
fun Any.assignFrom(other: Any) {
val thisProperties = this::class.memberProperties
.filterIsInstance<KMutableProperty<*>>()
.map { it.name to it }
.toMap()
for (property in other::class.memberProperties){
thisProperties[property.name]?.setter?.call(this, property.getter.call(other))
}
}
As Tenfour04 says, the language doesn't provide a direct way of doing this, so you're limited to using extra compile-time tools, or Reflection at runtime.
Since this is a fairly common problem, there's a Java library called ModelMapper which does this for you; and as with just about all Java libraries, you can use it in Kotlin too.
(I've used it on occasion. It can avoid lots of boilerplate. Though I didn't find it as refactoring-safe as the front page claims… It also ‘hides’ references to fields in a way that IDEs won't track. So it's not a perfect solution.)
I don't know how make classes in lua so I used code which was recommended on forum.
But always only one object works. First one have coordinates x,y and the other object share his coordinates. Can you explain what I´m doing wrong in this code.
Thank you for your advice.
My code:
require("class")
asteroid = class:new()
function asteroid:init(x,y)
asteroid.b = love.physics.newBody(world, x ,y , "dynamic")
asteroid.s = love.physics.newCircleShape(35)
asteroid.f = love.physics.newFixture(asteroid.b, asteroid.s)
end
function love.load()
world = love.physics.newWorld(0, 50, true)
asteroid1= asteroid:new(100,100)
asteroid2= asteroid:new(700,100)
end
function love.update(dt)
world:update(dt)
end
function love.draw()
love.graphics.circle("line", asteroid1.b:getX(),asteroid1.b:getY(), asteroid1.s:getRadius(), 35)
love.graphics.circle("line", asteroid2.b:getX(),asteroid2.b:getY(), asteroid2.s:getRadius(), 35)
end
Recommended code:
__HAS_SECS_COMPATIBLE_CLASSES__ = true
local class_mt = {}
function class_mt:__index(key)
return self.__baseclass[key]
end
class = setmetatable({ __baseclass = {} }, class_mt)
function class:new(...)
local c = {}
c.__baseclass = self
setmetatable(c, getmetatable(self))
if c.init then
c:init(...)
end
return c
end
Here is a demo code for you
local MyClass = {}
MyClass.__index = MyClass
setmetatable(MyClass, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function MyClass.new(init)
local self = setmetatable({}, MyClass)
self.value = init
return self
end
-- the : syntax here causes a "self" arg to be implicitly added before any other args
function MyClass:set_value(newval)
self.value = newval
end
function MyClass:get_value()
return self.value
end
local instance = MyClass(5)
-- do stuff with instance...
I would suggest you to follow these tutorials
http://lua-users.org/wiki/ObjectOrientationTutorial
http://lua-users.org/wiki/TutorialDirectory
The : syntax causes an implicit self to be available as a local, referring to the object instance. But you are assigning to b at class level. Use self.b = instead of asteroid.b = so that the assignment is specific to the instance.
The data is not inserted successfully.
Output:
dataHolder.variableNames = []
when it should be :
dataHolder.variableNames = [{'area_12345[<>]6789'}, {'apollo123'}, {'guruX'}, {'ok'}];
% USAGE:
elementNames = {'area_12345[<>]6789', 'apollo123', 'guruX', 'ok'};
elementTypes = {'string', 'specialChar', 'int', 'float'};
elementValues = {'charlie', 'vvv', '09', '123.321'};
dataHolder = dynamicVariableNaming;
str = 'test';
result = dataHolder.ensureCellType(str);
for i = 1:3
dataHolder.addVariables(elementNames(i), elementTypes(i), elementValues(i));
end
dataHolder.variableNames
%%% CLASS
classdef dynamicVariableNaming
%HELLO Summary of this class goes here
% -
properties
variableNames = [];
variableValues = [];
variableTypes = [];
end
methods (Access = public) % (Access = private)
function obj = dynamicVariableNaming (variableName, variableValue, variableType)
% class constructor
if(nargin > 0)
obj.variableNames = variableName;
obj.variableValues = variableValue;
obj.variableTypes = variableType;
end
end
% end
%
% methods (Static = true)
function addVariables (obj, variableName, variableValue, variableType)
obj.variableNames = [obj.variableNames ensureCellType(obj, variableName)];
obj.variableValues = [obj.variableValues ensureCellType(obj, variableValue)];
obj.variableTypes = [obj.variableTypes ensureCellType(obj, variableType)];
end
function cellData = ensureCellType(obj, value)
if (~strcmp(class(value), 'cell'))
cellData = {value};
% cell2string(value);
else
cellData = value;
end
end
end
end
You are not returning the changed opbject from the addVariables method as required when you are working with non-handle objects. Remember, matlab is different in comparison with other reference passing-based languages.
To fix it either make your class enherit from the handle class, or return obj from addVariables
Cant say if there are other problems in the code due to its poor formatting and inability to run in matlab (unbalanced ends, missing constructors, etc.)
Given a number of functions test1, test2, ... belonging to a module:
module Checks =
let test1 x = ...
let test2 x = ...
...
how can the (?) operator be used to give access to both the function name and the function itself? The result should look like:
let name, func = Checks?test1
assert(name = "test1")
assert(func(x) = Checks.test1(x)) //whatever x is (test1 is known to be pure)
You cannot use the ? operator to access functions in a module, because the construct Checks?test1 is not syntactically correct (this would be translated to (?) Checks "test" and you cannot use module names as values).
However, it should be possible to do this for members of a type using an instance of the object (e.g. obj?test). Alternatively you could write a "fake" object instance (that knows the name of the module). The implementation of ? would then look for the module and search static members in the module.
The simplest implementation (of the first case) would look like this:
let (?) obj s =
let memb = obj.GetType().GetMethod(s)
// Return name and a function that runs the method
s, (fun args -> memb.Invoke(obj, args))
// Type that contains tests as members
type Check() =
member x.test1 () = 32
// We need to create instance in order to use '?'
let ch = Check()
let s,f = ch?test1
// Function 'f' takes array of objects as an argument and
// returns object, so the call is not as elegant as it could be
let n = ((f [| |]) :?> int)
You could also add some wrapping to make the function 'f' a little bit nicer, but I hope this demonstrates the idea. Unfortunately, this cannot work for modules.
Here's some sample code that shows off some of this. I use D as the 'dynamic' access of the Checks module plus function name.
module Checks =
let test1(x) = printfn "test1 %d" x
let test2(x,y) = printfn "test2 %s %d" x y
type MyDynamic() = class end
let D = new MyDynamic()
let (?) (md:MyDynamic) fname : (string * ('a -> 'r)) =
let a = md.GetType().Assembly
let t = a.GetType("Program+Checks")
let m = t.GetMethod(fname)
let f arg =
let at = arg.GetType()
let fsharpArgs =
if at.IsGenericType && at.GetGenericTypeDefinition().FullName.StartsWith("System.Tuple`") then
Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields(arg)
else
[| box arg |]
unbox(m.Invoke(null, fsharpArgs))
fname, f
let Main() =
let x = 42
let s = "foo"
let name, func = D?test1
assert(name = "test1")
assert(func(x) = Checks.test1(x))
let name, func = D?test2
assert(name = "test2")
assert(func(s,x) = Checks.test2(s,x))
System.Console.ReadKey()
Main()