I was here for something else but trying to write up my question, I realize there's no way I'm doing this right.
I've been using mirage and irmin for a little while, and as long as all the code stays in the Main module everything is great. But of course, it quickly becomes a ridiculously huge file, and trying to split it in modules drives me mad with types escaping their scopes and whatnot.
Instead of just passing console from start to some other functions, I have to put those other functions in a functor that will take the Mirage_types_lwt.CONSOLE as well as the actual console variable, which means everything ends up being in functors instantiated from start and passed around in an unreadable mess of code.
I'm having problems making a giant ugly module to store and pass all of this easily (to "isolate" the parts that need this mess from regular code), and I can't figure out how to declare something like this :
module type ContextConfig = sig
module Store
val clientctx : Client.ctx
....
end
let mkContextConfig (module Store : Repo) ctx =
(module struct
(module Store : Repo)
let clientctx = ctx
end : ContextConfig)
(Repo being a module I made to wrap around Irmin's functors).
This obviously doesn't work, and I tried so many syntaxes I'm guessing it's just not possible, that means I'm doing something very wrong ?
I'd love advice on the proper way to deal with all of those functors and types in a clean way, how do I pass around things like the console or a conduit without having to functorize and instantiate everything in the Main module just to pass it around after ?
Definitions like that are possible:
module type REPO = sig end
module type CONTEXT_CONFIG = sig
module Store : REPO
val client_ctx : int
end
let mkContextConfig (module Store : REPO) ctx =
(module struct
module Store = Store
let client_ctx = ctx
end : CONTEXT_CONFIG)
(With some uninteresting changes to make the code type check.)
Related
In a scenario that it is nice to not to change the code, but adding tests
the code to be tested thefile.pl
get_name{
return 'sth';
}
test test_thefile.t
use Test::More;
use Test::MockModule;
require thefile.pl
my $module = Test::MockModule->new('thefile.pl')
$module->mock(get_name => sub { return 'othername' });
my $name = get_name();
ok($name eq 'othername');
I got
Invalid package name thefile.pl
Your problem is that you are using the filename as a bare word, so Perl interprets that as a package name. Since . isn't a legal identifier character (a char you can use in a package name), you get that warning.
If you want to use a filename, use a string instead:
require 'file.pl';
Then, in the call to Test::MockModule, it's expecting the name of a package that you defined in file.pl rather than the file name.
I don't know what you are doing, but when I want to replace a subroutine definition, I just override it. This is the core of the idea and there are ways to do it temporarily. The code behind the interfaces such as Test::MockModule and Hook::LexWrap aren't that complicated:
BEGIN {
require 'file.pl';
package Some::Package;
no warnings 'redefine';
*get_name = sub { ... }
}
The glob (*get_name) is a bit tricky, but just about everything else already shows up in your example. I show some of these tricks in Effective Perl Programming. For my work, reducing the module dependency list (especially in tests) is often worth the advanced trick.
I'm trying to write a simple tower defense game in OCaml as a bit of a learning project and I'm having a problem with how I structure my code. I've been trying to avoid using classes/objects to represent my towers and enemies mostly because I haven't learnt how ocaml objects work, but mostly because I seem to have picked up an aversion to using them from my reading about OCaml. Anyway, what I've been trying to do is have a module for each type of tower, which all have the same signature (TOWER), implementing functions that the mainloop uses to update the game. My idea was to use first class modules so I could then have a function like
let create m =
let module M = (val m : TOWER) in
M.create ()
where TOWER is
module type TOWER = sig
type t
...
val create : unit -> t
end
But now I have a problem in that it seems that when you unwrap a first class module you get a brand new module, whereas I assumed you'd get something like an alias for the module, so at compile time I get an error saying there's a problem with the scope of the type constructor for M.t. From this and the tinkering I've tried to do it seems that my original idea of using first class modules to decide which function to use won't work unless I move the type declaration out of TOWER and make it a shared type that all towers use. Is there a way to get the effect I'm looking for or would I have to some other technique?
If you're using a first class module in a function, and there exists a type constructor in a function type, that depends on a type that is defined inside the module, then it means, that the type escape its scope, and you need to put your function into a prenex normal form, by bounding this type to a new type variable. To clarify this here is the example:
let create_tower (module T : TOWER) = T.create ()
This will not compile, since T.t. escapes the scope. Try to write a type for the function create_tower: (module TOWER) -> ?. We don't have a name for the type t, that is in the scope of the TOWER signature. So we need to bring it out, to get the following type:
(module TOWER with type t = 'a) -> 'a
To get this, we use the following syntax:
let create_tower (type t) (module T : TOWER with type t = t) =
T.create ()
Now it works.
And a usual rant about modules. There is no need to use modules or objects here. Just use records to represent your towers and enemies.
If you use a sum type to represent different towers, you don't have to bother with modules or objects.
For example :
type tower =
| SimpleTower
| SuperTower of int
type position = int * int
type pos_tower = position * tower
let string_of_tower = function
| SimpleTower -> "Simple tower"
| SuperTower i -> "Super Tower level " ^ (string_of_int i)
;;
let my_towers = [ ((0,0) , SimpleTower) ; ( (10,0) , SuperTower 5) ] ;;
The properties of such an architecture are dual to the properties of an object oriented architecture (functions are modular here whereas they crosscut in an object architecture).
I am using this module hierarchy :
Node: {udpApp[0]<->udp<->networkLayer->wlan[0]} and wlan[0]: {CNPCBeacon<->mac<->radio}
I have given some initial parameter in the ini file for udpApp as :
**.host*.numUdpApps = 2
**.host*.udpApp[0].typename = "UDPBasicApp"
**.host*.udpApp[0].chooseDestAddrMode = "perBurst"
**.host*.udpApp[0].destAddresses = "gw1"
**.host*.udpApp[0].startTime = 1.32s
**.host*.udpApp[0].stopTime = 1.48s
But at run time I want to change the startTime and stopTime for udpAPP[0] through CNPCBeacon module. Hence I changed CNPCBeacon.cc as:-
cModule* parentmod = getParentModule();
cModule* grantParentmod = parentmod->getParentModule();
cModule* udpmod;
for (cSubModIterator iter(*grantParentmod); !iter.end(); iter++)
{
//EV<<"get the modulde "<< iter()->getFullName()<<endl;
if (strcmp(iter()->getFullName(), "udpApp[0]") == 0)
{
udpmod = iter();
break;
}
}
cPar& startTime = udpmod->par("startTime");
cPar& stopTime = udpmod->par("stopTime");
And I am successfully able to receive the values of startTime and stopTime. However I want to change these value in current module, which is resulting in an error by following code:
udpmod->par("startTime").setDoubleValue(4.2);
Can anybody please suggest me a way to change it at run time.
Declaring your parameter as volatile should solve your problem. But for future reference I'll provide further explanation below
Volatile vs. non-volatile:
Here it depends how you want to use this parameter. Mainly via the .ini file you have two types of parameters: volatile and non-volatile.
volatile parameters are read every time during your run. That woule be helpful if you want this parameter to be generated by a built-in function, for example, uniform(0,10) each time this volatile parameter will get a different value.
On the other hand non-volatile parameters are read just one, as they don't change from run to run.
Using the volatile type parameter does not give you full flexibility, in the sense that your parameter value will always fall with in a range predefined in the .ini
Dynamic Variable (parameter) Reassignment:
Instead what you could do is use a more robust approach, and re-define the variable which stores the value from that module parameter each time you have to do so.
For example in your case you could do the following:
varHoldingStartTime = par("startTime").doubleValue();
varHoldingStartTime = 4.2;
This way the actual value will change internally without reflecting to your run.
Parameter Studies:
Alternatively if you want this change of the parameter to be applied to multiple runs you could use the advanced built-in approach provided by OMNeT++ which allows you to perform Parameter Studies.
I have explained here how Parameter Studies work: https://stackoverflow.com/a/30572095/4786271 and also here how it can be achieved with constraints etc: https://stackoverflow.com/a/29622426/4786271
If none of the approaches suggested by me fit your case, answers to this question altogether might solve your problem: How to change configuration of network during simulation in OMNeT++?
EDIT: extending the answer to roughly explain handleParameterChange()
I have not used handleParameterChange() before as well, but from what can I see this function provides a watchdog functionality to the module which utilizes it.
To activate this functionality first the void handleParameterChange(const char *parameterName); has to be re-defined.
In essence what it seems to do is the following:
Assume we have two modules moduleA and moduleB and moduleB has parameter parB. moduleA changes the parB and when that happens, moduleB reacts to this change based on the behaviour defined in:
moduleB::handleParameterChange(parB);
The behaviour could be re-reading the original value for parB from the .ini etc.
Using a bunch of generated OCaml files for which it would be simpler to define a top module's signature without using a .mli file the same way it is done for nested modules. For example in Mymodule.ml be able to write something like:
module self/this module : sig
... (* contents of the mli file *)
end =
struct
...
end
I couldn't find the syntax to do it though. Is it even possible?
You'd have to do the following. I really don't know why this is "easier", maybe you should give a few more details to point you in the right direction.
module X : sig ... end =
struct
...
end
include X
I would like to write such a conditional fragment in a Go HTML template :
{{if isUserAdmin}}
<a href"/admin/nuke">Go to the big red nuclear button</a>
{{end}}
However, this is not directly possible because the template is not aware of the request that triggered its execution, so it cannot determine if the user is admin or not.
Is there some normal way to achieve this ?
In advance I point out that :
I do not want to use Pipelines for this specific data (see other question about this)
I acknowledge that only the handlers/controllers should deal with logic, and views should only do the rendering. But the condition {{if isUserAdmin}} is not logic itself, it's a necessary construct to leverage a boolean value already calculated by the controller.
The Funcs method can help, but is currently not lean enough for easily defining specific method isUserAdmin()
I would agree with Darshan Computing, I think the proper way of passing information from the request would be in the pipeline. You can have your data being split between the data you want to render and the context, e.g. by having your template data structure embed them both if you want to clearly separate the two:
type TemplateData struct {
*Content
*Context
}
Which gives this for example. You can then reuse some of your context/content information depending on what is shared and what is query specific.
Here is a working solution attempt (link to Playground) using Funcs to overwrite "isAdmin", after template compilation but before each execution (thanks to Valentin CLEMENT in other question).
But it has several flaws :
It is weird to declare a dummy empty "isAdmin" function before template compilation.
(Using Funcs several times is painful because I cannot just overwrite a single method, I have to provide a complete FuncMap with all the functions) edit : in fact previous funcs are not lost, i was wrong about that.
It is inherently not thread-safe and will fail when several goroutines alter and execute the same template
The normal thing to do is to simply pass your template a struct with whatever static data you like. Unless I've misunderstood what you're trying to do, there doesn't seem to be any need for Funcs here. Simplifying your example:
package main
import (
"html/template"
"os"
)
const hometmpl = `
{{if .IsAdmin}}
Go to the big red nuclear button
{{end}}
`
var t = template.Must(template.New("home").Parse(hometmpl))
func isAdmin(token string) bool {
const adminToken = "0xCAFEBABE"
return token == adminToken
}
func main() {
token := "0xCAFEBABE" // Or extracted from the http.Request
t.ExecuteTemplate(os.Stdout, "home", struct{IsAdmin bool}{isAdmin(token)})
}