Example #1
0
JSBool
gjs_console_interact(JSContext *context,
                     unsigned   argc,
                     jsval     *vp)
{
    JSObject *object = JS_THIS_OBJECT(context, vp);
    gboolean eof = FALSE;
    jsval result;
    JSString *str;
    GString *buffer = NULL;
    char *temp_buf = NULL;
    int lineno;
    int startline;
    FILE *file = stdin;

    JS_SetErrorReporter(context, gjs_console_error_reporter);

    /* It's an interactive filehandle; drop into read-eval-print loop. */
    lineno = 1;
    do {
        /*
         * Accumulate lines until we get a 'compilable unit' - one that either
         * generates an error (before running out of source) or that compiles
         * cleanly.  This should be whenever we get a complete statement that
         * coincides with the end of a line.
         */
        startline = lineno;
        buffer = g_string_new("");
        do {
            if (!gjs_console_readline(context, &temp_buf, file,
                                      startline == lineno ? "gjs> " : ".... ")) {
                eof = JS_TRUE;
                break;
            }
            g_string_append(buffer, temp_buf);
            g_free(temp_buf);
            lineno++;
        } while (!JS_BufferIsCompilableUnit(context, object, buffer->str, buffer->len));

        JS::CompileOptions options(context);
        options.setUTF8(true)
        .setFileAndLine("typein", startline);
        js::RootedObject rootedObj(context, object);
        JS::Evaluate(context, rootedObj, options, buffer->str, buffer->len,  &result);

        if (JS_GetPendingException(context, &result)) {
            str = JS_ValueToString(context, result);
            JS_ClearPendingException(context);
        } else if (JSVAL_IS_VOID(result)) {
            goto next;
        } else {
            str = JS_ValueToString(context, result);
        }

        if (str) {
            char *display_str;
            display_str = gjs_value_debug_string(context, result);
            if (display_str != NULL) {
                g_fprintf(stdout, "%s\n", display_str);
                g_free(display_str);
            }
        }

next:
        g_string_free(buffer, TRUE);
    } while (!eof);

    g_fprintf(stdout, "\n");

    if (file != stdin)
        fclose(file);

    return JS_TRUE;
}
Example #2
0
int main(int argc, char* argv[]) {
    // build the variable map from our configuration
    po::options_description options("Allowed options");
    options.add_options()
            ("help", "this message")
            ("disable-up", "disable unit propagation")
            ("analyze", po::value<std::string>(), "analyse previously-generated output")
            ("seed", po::value<unsigned int>(), "rng seed")
            ("name", po::value<std::string>(), "job name (used for file naming)");
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(options).run(), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << "Usage: volleyball-mcsat [OPTION]..." << std::endl;
        std::cout << options << std::endl;
        return EXIT_FAILURE;
    }
    if (vm.count("analyze")) {
        return analyzeOutput(vm["analyze"].as<std::string>());
    }

    boost::mt19937 rng;
    if (vm.count("rng")) {
        rng.seed(vm["rng"].as<unsigned int>());
    } else {
        rng.seed((time(NULL) * 32)^getpid());
    }
    // disable debug logging
    FileLog::globalLogLevel() = LOG_ERROR;
    std::string facts("# Video002.mat\n"
            "# BackLeft\n"
            "D-Squat(backleft) @ [1:133]\n"
            "\n"
            "# BackMiddle\n"
            "D-Squat(backmiddle) @ [1:133]\n"
            "D-Squat(backmiddle) @ [156:164]\n"
            "D-Squat(backmiddle) @ [329:352]\n"
            "\n"
            "# BackRight\n"
            "D-Squat(backright) @ [1:31]\n"
            "D-Squat(backright) @ [71:122]\n"
            "D-Squat(backright) @ [303:327]\n"
            "\n"
            "# FrontLeft\n"
            "D-Spike(frontleft) @ [377:393]\n"
            "D-Block(frontleft) @ [214:224]\n"
            "D-Squat(frontleft) @ [1:136]\n"
            "\n"
            "# FrontMiddle\n"
            "D-Spike(frontmiddle) @ [223:238]\n"
            "D-Spike(frontmiddle) @ [409:423]\n"
            "D-Block(frontmiddle) @ [304:319]\n"
            "D-Squat(frontmiddle) @ [23:116]\n"
            "\n"
            "# FrontRight\n"
            "D-Set(frontright) @ [199:209]\n"
            "D-Set(frontright) @ [365:389]\n"
            "D-Squat(frontright) @ [43:117]\n"
            "\n"
            "# RefNet\n"
            "D-Flag(refnet) @ [462:541]\n"
            "\n"
            "# RefBack\n"
            "D-Flag(refback) @ [451:541]\n"
            "\n"
            "# Group\n"
            "D-Huddle() @ [484:541]\n"
            "\n"
            "# Ball\n"
            "D-BallTrajectory() @ [113:153]\n"
            "D-BallTrajectory() @ [159:164]\n"
            "D-BallTrajectory() @ [173:228]\n"
            "D-BallTrajectory() @ [307:312]\n"
            "D-BallTrajectory() @ [322:337]\n"
            "D-BallTrajectory() @ [341:381]\n"
            "D-BallTrajectory() @ [387:392]\n"
            "D-BallTrajectory() @ [421:436]\n"
            "\n"
            "D-BallGoingOut() @ [270:270]\n"
            "D-BallGoingOut() @ [393:393]\n"
            "\n"
            "D-BallGoingin() @ [303:303]\n"
            "D-BallGoingin() @ [412:412]\n"
            "\n"
            "D-BallContact(frontleft) @ [233:233]\n"
            "D-BallContact(frontleft) @ [419:419]\n"
            "\n"
            "D-BallContact(frontright) @ [201:201]\n"
            "D-BallContact(frontright) @ [382:382]\n"
            "\n"
            "D-BallContact(backleft) @ [163:163]\n"
            "D-BallContact(backleft) @ [344:344]\n"
            "\n"
            "D-BallContact(them) @ [108:108]\n"
            "D-BallContact(them) @ [127:127]\n"
            "D-BallContact(them) @ [244:244]\n"
            "D-BallContact(them) @ [260:260]\n"
            "D-BallContact(them) @ [310:310]\n"
            "D-BallContact(them) @ [425:425]\n"
            "D-BallContact(them) @ [441:441]\n"
            "\n"
            );
    std::string formulas("1: [ D-BallContact(backleft) -> BallContact(backleft) ]\n"
            "1: [ D-BallContact(backright) -> BallContact(backright) ]\n"
            "1: [ D-BallContact(backmiddle) -> BallContact(backmiddle) ]\n"
            "1: [ D-BallContact(frontleft) -> BallContact(frontleft) ]\n"
            "1: [ D-BallContact(frontright) -> BallContact(frontright) ]\n"
            "1: [ D-BallContact(frontmiddle) -> BallContact(frontmiddle) ]\n"
            "1: [ BallContact(backleft) -> D-BallContact(backleft) ]\n"
            "1: [ BallContact(backright) -> D-BallContact(backright) ]\n"
            "1: [ BallContact(backmiddle) -> D-BallContact(backmiddle) ]\n"
            "1: [ BallContact(frontleft) -> D-BallContact(frontleft) ]\n"
            "1: [ BallContact(frontright) -> D-BallContact(frontright) ]\n"
            "1: [ BallContact(frontmiddle) -> D-BallContact(frontmiddle) ]\n"
            "1: [ D-Spike(backleft) -> Spike(backleft) ]\n"
            "1: [ D-Spike(backright) -> Spike(backright) ]\n"
            "1: [ D-Spike(backmiddle) -> Spike(backmiddle) ]\n"
            "1: [ D-Spike(frontleft) -> Spike(frontleft) ]\n"
            "1: [ D-Spike(frontright) -> Spike(frontright) ]\n"
            "1: [ D-Spike(frontmiddle) -> Spike(frontmiddle) ]\n"
            "1: [ Spike(backleft) -> D-Spike(backleft) ]\n"
            "1: [ Spike(backright) -> D-Spike(backright) ]\n"
            "1: [ Spike(backmiddle) -> D-Spike(backmiddle) ]\n"
            "1: [ Spike(frontleft) -> D-Spike(frontleft) ]\n"
            "1: [ Spike(frontright) -> D-Spike(frontright) ]\n"
            "1: [ Spike(frontmiddle) -> D-Spike(frontmiddle) ]\n"
            "1: [ D-Set(backleft) -> Set(backleft) ]\n"
            "1: [ D-Set(backright) -> Set(backright) ]\n"
            "1: [ D-Set(backmiddle) -> Set(backmiddle) ]\n"
            "1: [ D-Set(frontleft) -> Set(frontleft) ]\n"
            "1: [ D-Set(frontright) -> Set(frontright) ]\n"
            "1: [ D-Set(frontmiddle) -> Set(frontmiddle) ]\n"
            "1: [ Set(backleft) -> D-Set(backleft) ]\n"
            "1: [ Set(backright) -> D-Set(backright) ]\n"
            "1: [ Set(backmiddle) -> D-Set(backmiddle) ]\n"
            "1: [ Set(frontleft) -> D-Set(frontleft) ]\n"
            "1: [ Set(frontright) -> D-Set(frontright) ]\n"
            "1: [ Set(frontmiddle) -> D-Set(frontmiddle) ]\n"
            "1: [ D-Serve(backleft) -> Serve(backleft) ]\n"
            "1: [ D-Serve(backright) -> Serve(backright) ]\n"
            "1: [ D-Serve(backmiddle) -> Serve(backmiddle) ]\n"
            "1: [ D-Serve(frontleft) -> Serve(frontleft) ]\n"
            "1: [ D-Serve(frontright) -> Serve(frontright) ]\n"
            "1: [ D-Serve(frontmiddle) -> Serve(frontmiddle) ]\n"
            "1: [ Serve(backleft) -> D-Serve(backleft) ]\n"
            "1: [ Serve(backright) -> D-Serve(backright) ]\n"
            "1: [ Serve(backmiddle) -> D-Serve(backmiddle) ]\n"
            "1: [ Serve(frontleft) -> D-Serve(frontleft) ]\n"
            "1: [ Serve(frontright) -> D-Serve(frontright) ]\n"
            "1: [ Serve(frontmiddle) -> D-Serve(frontmiddle) ]\n"
            "1: [ D-Dig(backleft) -> Dig(backleft) ]\n"
            "1: [ D-Dig(backright) -> Dig(backright) ]\n"
            "1: [ D-Dig(backmiddle) -> Dig(backmiddle) ]\n"
            "1: [ D-Dig(frontleft) -> Dig(frontleft) ]\n"
            "1: [ D-Dig(frontright) -> Dig(frontright) ]\n"
            "1: [ D-Dig(frontmiddle) -> Dig(frontmiddle) ]\n"
            "1: [ Dig(backleft) -> D-Dig(backleft) ]\n"
            "1: [ Dig(backright) -> D-Dig(backright) ]\n"
            "1: [ Dig(backmiddle) -> D-Dig(backmiddle) ]\n"
            "1: [ Dig(frontleft) -> D-Dig(frontleft) ]\n"
            "1: [ Dig(frontright) -> D-Dig(frontright) ]\n"
            "1: [ Dig(frontmiddle) -> D-Dig(frontmiddle) ]\n"
            "1: [ D-Block(backleft) -> Block(backleft) ]\n"
            "1: [ D-Block(backright) -> Block(backright) ]\n"
            "1: [ D-Block(backmiddle) -> Block(backmiddle) ]\n"
            "1: [ D-Block(frontleft) -> Block(frontleft) ]\n"
            "1: [ D-Block(frontright) -> Block(frontright) ]\n"
            "1: [ D-Block(frontmiddle) -> Block(frontmiddle) ]\n"
            "1: [ Block(backleft) -> D-Block(backleft) ]\n"
            "1: [ Block(backright) -> D-Block(backright) ]\n"
            "1: [ Block(backmiddle) -> D-Block(backmiddle) ]\n"
            "1: [ Block(frontleft) -> D-Block(frontleft) ]\n"
            "1: [ Block(frontright) -> D-Block(frontright) ]\n"
            "1: [ Block(frontmiddle) -> D-Block(frontmiddle) ]\n"
            "1: [ D-Squat(backleft) -> Squat(backleft) ]\n"
            "1: [ D-Squat(backright) -> Squat(backright) ]\n"
            "1: [ D-Squat(backmiddle) -> Squat(backmiddle) ]\n"
            "1: [ D-Squat(frontleft) -> Squat(frontleft) ]\n"
            "1: [ D-Squat(frontright) -> Squat(frontright) ]\n"
            "1: [ D-Squat(frontmiddle) -> Squat(frontmiddle) ]\n"
            "1: [ Squat(backleft) -> D-Squat(backleft) ]\n"
            "1: [ Squat(backright) -> D-Squat(backright) ]\n"
            "1: [ Squat(backmiddle) -> D-Squat(backmiddle) ]\n"
            "1: [ Squat(frontleft) -> D-Squat(frontleft) ]\n"
            "1: [ Squat(frontright) -> D-Squat(frontright) ]\n"
            "1: [ Squat(frontmiddle) -> D-Squat(frontmiddle) ]\n"
            "1: [ D-Flag(refback) -> Flag(refback) ]\n"
            "1: [ Flag(refback) -> D-Flag(refback) ]\n"
            "1: [ D-Flag(refnet) -> Flag(refnet) ]\n"
            "1: [ Flag(refnet) -> D-Flag(refnet) ]\n"
            "1: [ D-BallContact(them) -> BallContact(them) ]\n"
            "1: [ BallContact(them) -> D-BallContact(them) ]\n"
            "1: [ D-Huddle() -> Huddle() ]\n"
            "1: [ Huddle() -> D-Huddle() ]\n"
            "1: [ D-BallTrajectory() -> BallTrajectory() ]\n"
            "1: [ BallTrajectory() -> D-BallTrajectory() ]\n"
            "1: [ D-BallGoingOut() -> BallGoingOut() ]\n"
            "1: [ BallGoingOut() -> D-BallGoingOut() ]\n"
            "1: [ D-BallGoingIn() -> BallGoingIn() ]\n"
            "1: [ BallGoingIn() -> D-BallGoingIn() ]\n"
            "1: [ D-BallGoingin() -> BallGoingin() ]\n"
            "1: [ BallGoingin() -> D-BallGoingin() ]\n"
            "\n"
            "# a player can have at most one pose at a time\n"
            "10: [ (Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ Block(backleft) ^ !Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ Squat(backleft)) v (!Spike(backleft) ^ !Set(backleft) ^ !Serve(backleft) ^ !Dig(backleft) ^ !Block(backleft) ^ !Squat(backleft)) ]\n"
            "10: [ (Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ Dig(backright) ^ !Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ Block(backright) ^ !Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ Squat(backright)) v (!Spike(backright) ^ !Set(backright) ^ !Serve(backright) ^ !Dig(backright) ^ !Block(backright) ^ !Squat(backright)) ]\n"
            "10: [ (Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ Block(backmiddle) ^ !Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ Squat(backmiddle)) v (!Spike(backmiddle) ^ !Set(backmiddle) ^ !Serve(backmiddle) ^ !Dig(backmiddle) ^ !Block(backmiddle) ^ !Squat(backmiddle)) ]\n"
            "10: [ (Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ Block(frontleft) ^ !Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ Squat(frontleft)) v (!Spike(frontleft) ^ !Set(frontleft) ^ !Serve(frontleft) ^ !Dig(frontleft) ^ !Block(frontleft) ^ !Squat(frontleft)) ]\n"
            "10: [ (Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ Block(frontright) ^ !Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ Squat(frontright)) v (!Spike(frontright) ^ !Set(frontright) ^ !Serve(frontright) ^ !Dig(frontright) ^ !Block(frontright) ^ !Squat(frontright)) ]\n"
            "10: [ (Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ Block(frontmiddle) ^ !Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ Squat(frontmiddle)) v (!Spike(frontmiddle) ^ !Set(frontmiddle) ^ !Serve(frontmiddle) ^ !Dig(frontmiddle) ^ !Block(frontmiddle) ^ !Squat(frontmiddle)) ]\n"
            "\n"
            "# only one player can contact the ball at a time\n"
            "10: [ BallContact(backleft) -> !BallContact(backright) ]\n"
            "10: [ BallContact(backleft) -> !BallContact(backmiddle) ]\n"
            "10: [ BallContact(backleft) -> !BallContact(frontleft) ]\n"
            "10: [ BallContact(backleft) -> !BallContact(frontright) ]\n"
            "10: [ BallContact(backleft) -> !BallContact(frontmiddle) ]\n"
            "10: [ BallContact(backleft) -> !BallContact(them) ]\n"
            "10: [ BallContact(backright) -> !BallContact(backleft) ]\n"
            "10: [ BallContact(backright) -> !BallContact(backmiddle) ]\n"
            "10: [ BallContact(backright) -> !BallContact(frontleft) ]\n"
            "10: [ BallContact(backright) -> !BallContact(frontright) ]\n"
            "10: [ BallContact(backright) -> !BallContact(frontmiddle) ]\n"
            "10: [ BallContact(backright) -> !BallContact(them) ]\n"
            "10: [ BallContact(backmiddle) -> !BallContact(backleft) ]\n"
            "10: [ BallContact(backmiddle) -> !BallContact(backright) ]\n"
            "10: [ BallContact(backmiddle) -> !BallContact(frontleft) ]\n"
            "10: [ BallContact(backmiddle) -> !BallContact(frontright) ]\n"
            "10: [ BallContact(backmiddle) -> !BallContact(frontmiddle) ]\n"
            "10: [ BallContact(backmiddle) -> !BallContact(them) ]\n"
            "10: [ BallContact(frontleft) -> !BallContact(backleft) ]\n"
            "10: [ BallContact(frontleft) -> !BallContact(backright) ]\n"
            "10: [ BallContact(frontleft) -> !BallContact(backmiddle) ]\n"
            "10: [ BallContact(frontleft) -> !BallContact(frontright) ]\n"
            "10: [ BallContact(frontleft) -> !BallContact(frontmiddle) ]\n"
            "10: [ BallContact(frontleft) -> !BallContact(them) ]\n"
            "10: [ BallContact(frontright) -> !BallContact(backleft) ]\n"
            "10: [ BallContact(frontright) -> !BallContact(backright) ]\n"
            "10: [ BallContact(frontright) -> !BallContact(backmiddle) ]\n"
            "10: [ BallContact(frontright) -> !BallContact(frontleft) ]\n"
            "10: [ BallContact(frontright) -> !BallContact(frontmiddle) ]\n"
            "10: [ BallContact(frontright) -> !BallContact(them) ]\n"
            "10: [ BallContact(frontmiddle) -> !BallContact(backleft) ]\n"
            "10: [ BallContact(frontmiddle) -> !BallContact(backright) ]\n"
            "10: [ BallContact(frontmiddle) -> !BallContact(backmiddle) ]\n"
            "10: [ BallContact(frontmiddle) -> !BallContact(frontleft) ]\n"
            "10: [ BallContact(frontmiddle) -> !BallContact(frontright) ]\n"
            "10: [ BallContact(frontmiddle) -> !BallContact(them) ]\n"
            "10: [ BallContact(them) -> !BallContact(backleft) ]\n"
            "10: [ BallContact(them) -> !BallContact(backright) ]\n"
            "10: [ BallContact(them) -> !BallContact(backmiddle) ]\n"
            "10: [ BallContact(them) -> !BallContact(frontleft) ]\n"
            "10: [ BallContact(them) -> !BallContact(frontright) ]\n"
            "10: [ BallContact(them) -> !BallContact(frontmiddle) ]\n"
            "\n"
//            "# if the backleft player served, nobody posed before that action\n"
//            "10: Serve(backleft) -> !(<>{<} [Spike(backleft) v Set(backleft) v Serve(backleft) v Dig(backleft) v Block(backleft) v Squat(backleft)])\n"
//            "10: Serve(backleft) -> !(<>{<} [Spike(backright) v Set(backright) v Serve(backright) v Dig(backright) v Block(backright) v Squat(backright)])\n"
//            "10: Serve(backleft) -> !(<>{<} [Spike(backmiddle) v Set(backmiddle) v Serve(backmiddle) v Dig(backmiddle) v Block(backmiddle) v Squat(backmiddle)])\n"
//            "10: Serve(backleft) -> !(<>{<} [Spike(frontleft) v Set(frontleft) v Serve(frontleft) v Dig(frontleft) v Block(frontleft) v Squat(frontleft)])\n"
//            "10: Serve(backleft) -> !(<>{<} [Spike(frontright) v Set(frontright) v Serve(frontright) v Dig(frontright) v Block(frontright) v Squat(frontright)])\n"
//            "10: Serve(backleft) -> !(<>{<} [Spike(frontmiddle) v Set(frontmiddle) v Serve(frontmiddle) v Dig(frontmiddle) v Block(frontmiddle) v Squat(frontmiddle)])\n"
//            "\n"
//            "# if a huddle occurs, it\'s the final pose\n"
//            "10: Huddle() -> !(<>{>} [Spike(backleft) v Set(backleft) v Serve(backleft) v Dig(backleft) v Block(backleft) v Squat(backleft)])\n"
//            "10: Huddle() -> !(<>{>} [Spike(backright) v Set(backright) v Serve(backright) v Dig(backright) v Block(backright) v Squat(backright)])\n"
//            "10: Huddle() -> !(<>{>} [Spike(backmiddle) v Set(backmiddle) v Serve(backmiddle) v Dig(backmiddle) v Block(backmiddle) v Squat(backmiddle)])\n"
//            "10: Huddle() -> !(<>{>} [Spike(frontleft) v Set(frontleft) v Serve(frontleft) v Dig(frontleft) v Block(frontleft) v Squat(frontleft)])\n"
//            "10: Huddle() -> !(<>{>} [Spike(frontright) v Set(frontright) v Serve(frontright) v Dig(frontright) v Block(frontright) v Squat(frontright)])\n"
//            "10: Huddle() -> !(<>{>} [Spike(frontmiddle) v Set(frontmiddle) v Serve(frontmiddle) v Dig(frontmiddle) v Block(frontmiddle) v Squat(frontmiddle)])\n"
//            "\n"
            "# if a player contacts the ball, they are in some sort of pose\n"
            "10: [ BallContact(backleft) -> Spike(backleft) v Set(backleft) v Serve(backleft) v Dig(backleft) v Block(backleft) v Squat(backleft) ]\n"
            "10: [ BallContact(backright) -> Spike(backright) v Set(backright) v Serve(backright) v Dig(backright) v Block(backright) v Squat(backright) ]\n"
            "10: [ BallContact(backmiddle) -> Spike(backmiddle) v Set(backmiddle) v Serve(backmiddle) v Dig(backmiddle) v Block(backmiddle) v Squat(backmiddle) ]\n"
            "10: [ BallContact(frontleft) -> Spike(frontleft) v Set(frontleft) v Serve(frontleft) v Dig(frontleft) v Block(frontleft) v Squat(frontleft) ]\n"
            "10: [ BallContact(frontright) -> Spike(frontright) v Set(frontright) v Serve(frontright) v Dig(frontright) v Block(frontright) v Squat(frontright) ]\n"
            "10: [ BallContact(frontmiddle) -> Spike(frontmiddle) v Set(frontmiddle) v Serve(frontmiddle) v Dig(frontmiddle) v Block(frontmiddle) v Squat(frontmiddle) ]\n"
            "\n"
//            "# if a player served, nobody on our team will touch the ball before the opponents\n"
//            "10: Serve(backleft) ^{<} BallContact(them) -> (<>{d} BallContact(them)) v (!<>{d} [BallContact(backright) v BallContact(backmiddle) v BallContact(frontleft) v BallContact(frontright) v BallContact(frontmiddle)])\n"
//            "\n"
            "# only the back left player may serve\n"
            "10: [ !Serve(backright) ^ !Serve(backmiddle) ^ !Serve(frontleft) ^ !Serve(frontright) ^ !Serve(frontmiddle) ]\n"
            "\n"
            "# only players in the front row may spike\n"
            "10: [ !Spike(backleft) ^ !Spike(backright) ^ !Spike(backmiddle) ]\n"
            "\n"
            );

    Domain d = loadDomainWithStreams(facts, formulas);

    std::set<unsigned int> timePoints;
    for (Domain::fact_const_iterator it = d.facts_begin(); it != d.facts_end(); it++) {
        SISet set = it->second;
        for (SISet::const_iterator siIt = set.begin(); siIt != set.end(); siIt++) {
            SpanInterval si = *siIt;
            timePoints.insert(si.start().start());
            timePoints.insert(si.start().finish());
            timePoints.insert(si.finish().start());
            timePoints.insert(si.finish().finish());
        }
    }

    std::cout << "found " << timePoints.size() << " timepoints." << std::endl;

    MCSat mcSatSolver(&d);
    mcSatSolver.setBurnInIterations(1);
    mcSatSolver.setNumSamples(1);
    if (vm.count("disable-up")) {
        mcSatSolver.setUseUnitPropagation(false);
    } else {
        mcSatSolver.setUseUnitPropagation(true);
    }
    std::cout << "running mcSatSolver with " << mcSatSolver.burnInIterations() << " burn in iterations and a sample size of " << mcSatSolver.numSamples() << std::endl;
    std::string prefix = (vm.count("name") ? vm["name"].as<std::string>() : "mcsat-volleyball");
    std::cout << "saving random seed..." << std::endl;
    {
        std::string rngFilename = prefix + "-seed.txt.gz";
        io::file_descriptor_sink rngOutFile(rngFilename.c_str(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
        if (!rngOutFile.is_open()){
            std::cerr << "unable to open file " + rngFilename + "for RNG writing." << std::endl;
        } else {
            // gzip it using boost iostreams
            io::filtering_ostream rngOut;
            rngOut.push(io::gzip_compressor());
            rngOut.push(rngOutFile);
            rngOut << rng;
        }
    }
    //std::cout << "rng = " << rng << std::endl;
    std::cout << "starting run..." << std::endl;
    mcSatSolver.setSampleStrategy(new MCSatSampleLiquidlyStrategy());
    std::clock_t start = std::clock();
    mcSatSolver.run(rng);
    std::clock_t end = std::clock();
    std::cout << "ran in " << (end - start)/CLOCKS_PER_SEC << " seconds." << std::endl;
    std::cout << "saving model file..." << std::endl;
    {
        std::string outFilename = prefix + "-model.dat.gz";
        io::file_descriptor_sink outFile(outFilename.c_str(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
        if (!outFile.is_open()) {
            std::cerr << "unable to open file " + outFilename + " for model writing." << std::endl;
        } else {
            io::filtering_ostream dataOut;
            dataOut.push(io::gzip_compressor());
            dataOut.push(outFile);
            boost::archive::text_oarchive tout(dataOut);
            registerAllPELTypes(tout);
            tout << mcSatSolver;
        }
    }
}
Example #3
0
void sdl_osd_interface::init(running_machine &machine)
{
	// call our parent
	osd_common_t::init(machine);

	const char *stemp;

	// determine if we are benchmarking, and adjust options appropriately
	int bench = options().bench();
	std::string error_string;
	if (bench > 0)
	{
		options().set_value(OPTION_THROTTLE, false, OPTION_PRIORITY_MAXIMUM, error_string);
		options().set_value(OSDOPTION_SOUND, "none", OPTION_PRIORITY_MAXIMUM, error_string);
		options().set_value(OSDOPTION_VIDEO, "none", OPTION_PRIORITY_MAXIMUM, error_string);
		options().set_value(OPTION_SECONDS_TO_RUN, bench, OPTION_PRIORITY_MAXIMUM, error_string);
		assert(error_string.c_str()[0] == 0);
	}

	// Some driver options - must be before audio init!
	stemp = options().audio_driver();
	if (stemp != nullptr && strcmp(stemp, OSDOPTVAL_AUTO) != 0)
	{
		osd_printf_verbose("Setting SDL audiodriver '%s' ...\n", stemp);
		osd_setenv(SDLENV_AUDIODRIVER, stemp, 1);
	}

	stemp = options().video_driver();
	if (stemp != nullptr && strcmp(stemp, OSDOPTVAL_AUTO) != 0)
	{
		osd_printf_verbose("Setting SDL videodriver '%s' ...\n", stemp);
		osd_setenv(SDLENV_VIDEODRIVER, stemp, 1);
	}

		stemp = options().render_driver();
		if (stemp != nullptr)
		{
			if (strcmp(stemp, OSDOPTVAL_AUTO) != 0)
			{
				osd_printf_verbose("Setting SDL renderdriver '%s' ...\n", stemp);
				//osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
				SDL_SetHint(SDL_HINT_RENDER_DRIVER, stemp);
			}
			else
			{
#if defined(SDLMAME_WIN32)
				// OpenGL renderer has less issues with mode switching on windows
				osd_printf_verbose("Setting SDL renderdriver '%s' ...\n", "opengl");
				//osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
				SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
#endif
			}
		}

	/* Set the SDL environment variable for drivers wanting to load the
	 * lib at startup.
	 */
#if USE_OPENGL
	/* FIXME: move lib loading code from drawogl.c here */

	stemp = options().gl_lib();
	if (stemp != nullptr && strcmp(stemp, OSDOPTVAL_AUTO) != 0)
	{
		osd_setenv("SDL_VIDEO_GL_DRIVER", stemp, 1);
		osd_printf_verbose("Setting SDL_VIDEO_GL_DRIVER = '%s' ...\n", stemp);
	}
#endif

	/* get number of processors */
	stemp = options().numprocessors();

	osd_num_processors = 0;

	if (strcmp(stemp, "auto") != 0)
	{
		osd_num_processors = atoi(stemp);
		if (osd_num_processors < 1)
		{
			osd_printf_warning("numprocessors < 1 doesn't make much sense. Assuming auto ...\n");
			osd_num_processors = 0;
		}
	}

	/* Initialize SDL */

	if (SDL_InitSubSystem(SDL_INIT_VIDEO)) {
		osd_printf_error("Could not initialize SDL %s\n", SDL_GetError());
		exit(-1);
	}
	osd_sdl_info();

	defines_verbose();

	osd_common_t::init_subsystems();

	if (options().oslog())
		machine.add_logerror_callback(output_oslog);



#ifdef SDLMAME_EMSCRIPTEN
	SDL_EventState(SDL_TEXTINPUT, SDL_FALSE);
#else
	SDL_EventState(SDL_TEXTINPUT, SDL_TRUE);
#endif
}
Example #4
0
int main(int argc, char** argv)
{
  try {
    options(argc, argv);
    
    if (grammar_list) {
      std::cout << grammar_type::lists();
      return 0;
    }
    
    if (int(input_lattice_mode) + input_sentence_mode == 0)
      input_sentence_mode = true;
    if (int(input_lattice_mode) + input_sentence_mode > 1)
      throw std::runtime_error("either lattice or sentence input");
    
    threads = utils::bithack::max(1, threads);

    // read grammars...
    grammar_type grammar(grammar_files.begin(), grammar_files.end());
    if (debug)
      std::cerr << "grammar: " << grammar.size() << std::endl;

    typedef Task task_type;
    typedef std::vector<task_type, std::allocator<task_type> > task_set_type;
    
    task_type::queue_type queue(threads);
    task_set_type tasks(threads, task_type(queue, grammar));
    
    boost::thread_group workers;
    for (int i = 0; i != threads; ++ i)
      workers.add_thread(new boost::thread(boost::ref(tasks[i])));
    
    utils::compress_istream is(input_file, 1024 * 1024);
    
    std::string line;
    while (utils::getline(is, line))
      if (! line.empty())
	queue.push_swap(line);
    
    for (int i = 0; i != threads; ++ i)
      queue.push(std::string());
    
    workers.join_all();

    rule_pair_unique_type rules_unique;
    
    for (int i = 0; i != threads; ++ i) {
      if (rules_unique.empty())
	rules_unique.swap(tasks[i].rules_unique);
      else
	rules_unique.insert(tasks[i].rules_unique.begin(), tasks[i].rules_unique.end());
      
      tasks[i].rules_unique.clear();
    }
    tasks.clear();
    
    typedef std::ostream_iterator<char> oiter_type;

    features_generator<oiter_type>   generate_features;
    attributes_generator<oiter_type> generate_attributes;
    
    if (! output_file.empty()) {
      namespace karma = boost::spirit::karma;
      namespace standard = boost::spirit::standard;
      
      utils::compress_ostream os(output_file, 1024 * 1024);
      
      rule_pair_unique_type::const_iterator iter_end = rules_unique.end();
      for (rule_pair_unique_type::const_iterator iter = rules_unique.begin(); iter != iter_end; ++ iter) {
	karma::generate(oiter_type(os),
			standard::string << " ||| " << -(standard::string % ' ') << " ||| " << -(standard::string % ' '),
			iter->lhs,
			symbol_set_type(iter->source.begin(), iter->source.end()),
			symbol_set_type(iter->target.begin(), iter->target.end()));
	
	if (! iter->features.empty()) {
	  feature_set_type features(iter->features.begin(), iter->features.end());
	  karma::generate(oiter_type(os), generate_features, features);
	}
	
	if (! iter->attributes.empty())
	  karma::generate(oiter_type(os), generate_attributes, iter->attributes);
	os << '\n';
      }
    }
  }
  catch (const std::exception& err) {
    std::cerr << "error: " << err.what() << std::endl;
    return 1;
  }
  return 0;
}
Example #5
0
void windows_osd_interface::extract_video_config()
{
	const char *stemp;

	// global options: extract the data
	video_config.windowed      = options().window();
	video_config.prescale      = options().prescale();
	video_config.filter        = options().filter();
	video_config.keepaspect    = options().keep_aspect();
	video_config.numscreens    = options().numscreens();

	// if we are in debug mode, never go full screen
	if (machine().debug_flags & DEBUG_FLAG_OSD_ENABLED)
		video_config.windowed = TRUE;

	// per-window options: extract the data
	const char *default_resolution = options().resolution();
	get_resolution(default_resolution, options().resolution(0), &windows[0], TRUE);
	get_resolution(default_resolution, options().resolution(1), &windows[1], TRUE);
	get_resolution(default_resolution, options().resolution(2), &windows[2], TRUE);
	get_resolution(default_resolution, options().resolution(3), &windows[3], TRUE);

	// video options: extract the data
	stemp = options().video();
	if (strcmp(stemp, "d3d") == 0)
		video_config.mode = VIDEO_MODE_D3D;
	else if (strcmp(stemp, "d3d9ex") == 0)
		video_config.mode = VIDEO_MODE_D3D9EX;
	else if (strcmp(stemp, "auto") == 0)
		video_config.mode = VIDEO_MODE_D3D;
	else if (strcmp(stemp, "ddraw") == 0)
		video_config.mode = VIDEO_MODE_DDRAW;
	else if (strcmp(stemp, "gdi") == 0)
		video_config.mode = VIDEO_MODE_GDI;
#if defined (USE_BGFX)
	else if (strcmp(stemp, "bgfx") == 0)
		video_config.mode = VIDEO_MODE_BGFX;
#endif
	else if (strcmp(stemp, "none") == 0)
	{
		video_config.mode = VIDEO_MODE_NONE;
		if (options().seconds_to_run() == 0)
			osd_printf_warning("Warning: -video none doesn't make much sense without -seconds_to_run\n");
	}
#if (USE_OPENGL)
	else if (strcmp(stemp, "opengl") == 0)
		video_config.mode = VIDEO_MODE_OPENGL;
#endif
	else
	{
		osd_printf_warning("Invalid video value %s; reverting to gdi\n", stemp);
		video_config.mode = VIDEO_MODE_GDI;
	}
	video_config.waitvsync     = options().wait_vsync();
	video_config.syncrefresh   = machine().options().sync_refresh();
	video_config.triplebuf     = options().triple_buffer();
	video_config.switchres     = options().switch_res();

	// ddraw options: extract the data
	video_config.hwstretch     = options().hwstretch();

	if (video_config.prescale < 1 || video_config.prescale > 3)
	{
		osd_printf_warning("Invalid prescale option, reverting to '1'\n");
		video_config.prescale = 1;
	}
	#if (USE_OPENGL)
		// default to working video please
		video_config.forcepow2texture = options().gl_force_pow2_texture();
		video_config.allowtexturerect = !(options().gl_no_texture_rect());
		video_config.vbo         = options().gl_vbo();
		video_config.pbo         = options().gl_pbo();
		video_config.glsl        = options().gl_glsl();
		if ( video_config.glsl )
		{
			int i;

			video_config.glsl_filter = options().glsl_filter();

			video_config.glsl_shader_mamebm_num=0;

			for(i=0; i<GLSL_SHADER_MAX; i++)
			{
				stemp = options().shader_mame(i);
				if (stemp && strcmp(stemp, OSDOPTVAL_NONE) != 0 && strlen(stemp)>0)
				{
					video_config.glsl_shader_mamebm[i] = (char *) malloc(strlen(stemp)+1);
					strcpy(video_config.glsl_shader_mamebm[i], stemp);
					video_config.glsl_shader_mamebm_num++;
				} else {
					video_config.glsl_shader_mamebm[i] = NULL;
				}
			}

			video_config.glsl_shader_scrn_num=0;

			for(i=0; i<GLSL_SHADER_MAX; i++)
			{
				stemp = options().shader_screen(i);
				if (stemp && strcmp(stemp, OSDOPTVAL_NONE) != 0 && strlen(stemp)>0)
				{
					video_config.glsl_shader_scrn[i] = (char *) malloc(strlen(stemp)+1);
					strcpy(video_config.glsl_shader_scrn[i], stemp);
					video_config.glsl_shader_scrn_num++;
				} else {
					video_config.glsl_shader_scrn[i] = NULL;
				}
			}
		} else {
			int i;
			video_config.glsl_filter = 0;
			video_config.glsl_shader_mamebm_num=0;
			for(i=0; i<GLSL_SHADER_MAX; i++)
			{
				video_config.glsl_shader_mamebm[i] = NULL;
			}
			video_config.glsl_shader_scrn_num=0;
			for(i=0; i<GLSL_SHADER_MAX; i++)
			{
				video_config.glsl_shader_scrn[i] = NULL;
			}
		}

	#endif /* USE_OPENGL */

}
Example #6
0
File: q6.c Project: eokeeffe/C-code
int main()
{
	clear_screen();
	options();
	return 0;
}
Example #7
0
void NRemoteFSBrowser::signal_read_dir ( Common::SignalArgs & args )
{
    SignalOptions options( args );
    QStringList completionList;
    int i;

    std::vector<std::string> dirs;
    std::vector<std::string> files;
    std::vector<std::string> dirDates;
    std::vector<std::string> fileDates;
    std::vector<Uint> fileSizes;

    std::vector<std::string>::const_iterator itDirs;
    std::vector<std::string>::const_iterator itFiles;

    m_currentPath = options.value<std::string>("dirPath").c_str();

    // add an ending '/' if the string does not have any
    if( !m_currentPath.endsWith("/") )
        m_currentPath += "/";

//  if(!m_updatingCompletion)
//    m_editPath->setText(m_currentPath);
//  else
//    m_updatingCompletion = false;

    dirs = options.array<std::string>("dirs");
    files = options.array<std::string>("files");
    dirDates = options.array<std::string>("dirDates");
    fileDates = options.array<std::string>("fileDates");
    fileSizes = options.array<Uint>("fileSizes");

    // notice the view(s) that the model is about to be completely changed
    emit layoutAboutToBeChanged();

    //clear();
    m_completionModel->setStringList( QStringList() );

    // delete old data
    while( !m_data.empty() )
        delete m_data.takeFirst();

    // add the directories
    for( i = 0, itDirs = dirs.begin() ; itDirs != dirs.end() ; ++itDirs, ++i )
    {
        FileInfo * fileInfo = new FileInfo();
        QString name = itDirs->c_str();

        fileInfo->name = name;
        fileInfo->type = DIRECTORY;

        fileInfo->dateModified = dirDates[i].c_str();

        if(!m_currentPath.isEmpty() && name != "..")
            name.prepend(m_currentPath + (m_currentPath.endsWith("/") ? "" : "/"));

        m_data.append(fileInfo);
        completionList << name;
    }

    m_completionModel->setStringList( completionList );

    // add the files
    for( i = 0, itFiles = files.begin() ; itFiles != files.end() ; ++itFiles, ++i )
    {
        FileInfo * fileInfo = new FileInfo();

        fileInfo->name = itFiles->c_str();
        fileInfo->type = FILE;
        fileInfo->dateModified = fileDates[i].c_str();
        fileInfo->fileSize = fileSizes[i];

        m_data.append(fileInfo);
    }

    // notice the view(s) that the model has finished changing
    emit layoutChanged();
    emit currentPathChanged(m_currentPath);
}
Example #8
0
void ComputeArea::config_field()
{
  URI uri = options().option(mesh::Tags::area()).value<URI>();
  m_area = Core::instance().root().access_component(uri)->handle<Field>();
}
int PlastikClient::layoutMetric(LayoutMetric lm, bool respectWindowState, const KCommonDecorationButton *btn) const
{
    bool maximized = maximizeMode()==MaximizeFull && !options()->moveResizeMaximizedWindows();

    switch (lm) {
        case LM_BorderLeft:
        case LM_BorderRight:
        case LM_BorderBottom:
        {
            if (respectWindowState && maximized) {
                return 0;
            } else {
                return Handler()->borderSize();
            }
        }

        case LM_TitleEdgeTop:
        {
            if (respectWindowState && maximized) {
                return 0;
            } else {
                return 4;
            }
        }

        case LM_TitleEdgeBottom:
        {
//             if (respectWindowState && maximized) {
//                 return 1;
//             } else {
                return 2;
//             }
        }

        case LM_TitleEdgeLeft:
        case LM_TitleEdgeRight:
        {
            if (respectWindowState && maximized) {
                return 0;
            } else {
                return 6;
            }
        }

        case LM_TitleBorderLeft:
        case LM_TitleBorderRight:
            return 5;

        case LM_ButtonWidth:
        case LM_ButtonHeight:
            return Handler()->titleHeight()-2*2 ;
        case LM_TitleHeight:
        {
            if (respectWindowState && isToolWindow()) {
                return Handler()->titleHeightTool();
            } else {
                return Handler()->titleHeight();
            }
        }

        case LM_ButtonSpacing:
            return 2;

        case LM_ButtonMarginTop:
            return 2;

        default:
            return KCommonDecoration::layoutMetric(lm, respectWindowState, btn);
    }
}
Example #10
0
int main(int argc, const char** argv)
{
    argv0 = argv[0];


    bool print_stats = false;


    U.start();

    // Set up smsh related error codes
    if (! (w_error_t::insert(
                "ss_m shell",
                smsh_error_list, SSH_MAX_ERROR - SSH_MIN_ERROR - 1))) {
        abort();
    }


    /*
     * The following section of code sets up all the various options
     * for the program.  The following steps are performed:
        - determine the name of the program
        - setup an option group for the program
        - initialize the ssm options
        - scan default option configuration files ($HOME/.shoreconfig .shoreconfig)
        - process any options found on the command line
        - use getopt() to process smsh specific flags on the command line
        - check that all required options are set before initializing sm
     */         

    // set prog_name to the file name of the program
    const char* prog_name = strrchr(argv[0], '/');
    if (prog_name == NULL) {
            prog_name = argv[0];
    } else {
            prog_name += 1; /* skip the '/' */
            if (prog_name[0] == '\0')  {
                    prog_name = argv[0];
            }
    }

    /*
     * Set up and option group (list of options) for use by
     * all layers of the system.  Level "smsh" indicates
     * that the program is a a part to the smsh test suite.
     * Level "server" indicates
     * the type of program (the smsh server program).  The third
     * level is the program name itself.
     */
    option_group_t options(3);
    W_COERCE(options.add_class_level("smsh"));
    W_COERCE(options.add_class_level("server"));
    W_COERCE(options.add_class_level(prog_name));

    /*
     * Set up and smsh option for the name of the tcl library directory
     * and the name of the .smshrc file.
     */
    option_t* smsh_libdir;
    option_t* smsh_smshrc;
    W_COERCE(options.add_option("smsh_libdir", "directory name", NULL,
                "directory for smsh tcl libraries",
                true, option_t::set_value_charstr, smsh_libdir));
    W_COERCE(options.add_option("smsh_smshrc", "rc file name", ".smshrc",
                "full path name of the .smshrc file",
                false, option_t::set_value_charstr, smsh_smshrc));

    // have the sm add its options to the group
    W_COERCE(ss_m::setup_options(&options));


    /*
     * Scan the default configuration files: $HOME/.shoreconfig, .shoreconfig.  Note
     * That OS errors are ignored since it is not an error
     * for this file to not be found.
     */
    rc_t        rc;
    {
    char                opt_file[ss_m::max_devname+1];
    for(int file_num = 0; file_num < 2 && !rc.is_error(); file_num++) {
        // scan default option files
        w_ostrstream        err_stream;
        const char*        config = ".shoreconfig";
        if (file_num == 0) {
            if (!getenv("HOME")) {
                // ignore it ...
                // cerr << "Error: environment variable $HOME is not set" << endl;
                // rc = RC(SSH_FAILURE);
                break;
            }
            if (sizeof(opt_file) <= strlen(getenv("HOME")) + strlen("/") + strlen(config) + 1) {
                cerr << "Error: environment variable $HOME is too long" << endl;
                rc = RC(SSH_FAILURE);
                break;
            }
            strcpy(opt_file, getenv("HOME"));
            strcat(opt_file, "/");
            strcat(opt_file, config);
        } else {
            w_assert3(file_num == 1);
            strcpy(opt_file, "./");
            strcat(opt_file, config);
        }
        {
            option_file_scan_t opt_scan(opt_file, &options);
            rc = opt_scan.scan(true, err_stream);
            err_stream << ends;
            if (rc.is_error()) {
                // ignore OS error messages
                if (rc.err_num() == fcOS) {
                    rc = RCOK;
                } else {
                    // this error message is kind of gross but is
                    // sufficient for now
                    cerr << "Error in reading option file: " << opt_file << endl;
                    //cerr << "\t" << w_error_t::error_string(rc.err_num()) << endl;
                    cerr << "\t" << err_stream.c_str() << endl;
                }
            }
        }
    }
    }

    /* 
     * Assuming there has been no error so far, the command line
     * is processed for any options in the option group "options".
     */
    if (!rc.is_error()) {
        // parse command line
        w_ostrstream        err_stream;
        rc = options.parse_command_line(argv, argc, 2, &err_stream);
        err_stream << ends;
        if (rc.is_error()) {
            cerr << "Error on command line " << endl;
            cerr << "\t" << w_error_t::error_string(rc.err_num()) << endl;
            cerr << "\t" << err_stream.c_str() << endl;
            print_usage(cerr, prog_name, false, options);
        }
    } 

    /* 
     * Assuming there has been no error so far, the command line
     * is processed for any smsh specific flags.
     */
    int option;
    //if (!rc) 
    {  // do even if error so that smsh -h can be recognized
        bool verbose_opt = false; // print verbose option values
        while ((option = getopt(argc, (char * const*) argv, "Cf:hLOsTvV")) != -1) {
            switch (option) {
            case 'T':
                extern bool logtrace;
                logtrace = true;
                break;
            case 'O':
                    // Force use of old sort
                cout << "Force use of old sort implementation." <<endl;
                newsort = false;
                break;

            case 'C':
                // force compression of btrees
                force_compress = true;
                break;

            case 's':
                print_stats = true;
                break;

            case 'f':
                f_arg = optarg;
                break;

            case 'L':
                // use log warning callback
                log_warn_callback = true;
                break;

            case 'h':
                // print a help message describing options and flags
                print_usage(cerr, prog_name, true, options);
                // free rc structure to avoid complaints on exit
                W_IGNORE(rc);
                goto done;
                break;
            case 'v':
                verbose_opt = true;
                break;
            case 'V':
                verbose = true;
                break;
            default:
                cerr << "unknown flag: " << option << endl;
                rc = RC(SSH_COMMAND_LINE);
            }
        }

        if (verbose_opt) {
            options.print_values(false, cerr);
        }
    }

    /*
     * Assuming no error so far, check that all required options
     * in option_group_t options are set.  
     */
    if (!rc.is_error()) {
        // check required options
        w_ostrstream        err_stream;
        rc = options.check_required(&err_stream);
        err_stream << ends;
        if (rc.is_error()) {
            cerr << "These required options are not set:" << endl;
            cerr << err_stream.c_str() << endl;
            print_usage(cerr, prog_name, false, options);
        }
    } 


    /* 
     * If there have been any problems so far, then exit
     */
    if (rc.is_error()) {
        // free the rc error structure to avoid complaints on exit
        W_IGNORE(rc);
        goto errordone;
    }

    /*
     * At this point, all options and flags have been properly
     * set.  What follows is initialization for the rest of
     * the program.  The ssm will be started by a tcl_thread.
     */


    // setup table of sm commands - doesn't involve the Tcl_Interp
    dispatch_init();

    // set up the linked variables
    // either these should be read-only or
    // they need to be made thread-safe.  We can assume for smsh they
    // are for all purposes read-only, since only the mama thread sets
    // them in the scripts.
    linked.sm_page_sz = ss_m::page_sz;
    linked.sm_max_exts = ss_m::max_exts;
    linked.sm_max_vols = ss_m::max_vols;
    linked.sm_max_servers = ss_m::max_servers;
    linked.sm_max_keycomp = ss_m::max_keycomp;
    linked.sm_max_dir_cache = ss_m::max_dir_cache;
    linked.sm_max_rec_len = ss_m::max_rec_len;
    linked.sm_srvid_map_sz = ss_m::srvid_map_sz;
    linked.verbose_flag = verbose?1:0;
    linked.verbose2_flag = verbose2?1:0;
    linked.instrument_flag = instrument?1:0;
    linked.compress_flag = force_compress?1:0;
    linked.log_warn_callback_flag = log_warn_callback?1:0;

    {
        int tty = isatty(0);
        interactive = tty && f_arg;
    }

    // Create the main tcl_thread
    {
        tcl_thread_t* tcl_thread = NULL;
        bool ok = true;

        if(ok) {
            if (f_arg) {
                TCL_AV char* av[2];
                av[0] = TCL_AV1 "source";
                av[1] = f_arg;
                // smsh -f <file>
                tcl_thread = new tcl_thread_t(2, av, 
                                smsh_libdir->value(),
                                smsh_smshrc->value()
                                );
            } else {
                // interactive
                /*
                cerr << __func__ << " " << __LINE__ << " " << __FILE__
                << " INTERACTIVE libdir " << smsh_libdir->value()
                << " msshrc " << smsh_smshrc->value()
                << endl;
                */
                tcl_thread = new tcl_thread_t(0, 0,
                                smsh_libdir->value(),
                                smsh_smshrc->value()
                                );
            }
            assert(tcl_thread);

            W_COERCE( tcl_thread->fork() );
            W_COERCE( tcl_thread->join() );

            delete tcl_thread;
        }
    }


    // Shutdown TCL and have it deallocate resources still held!
    Tcl_Finalize();

    U.stop(1); // 1 iteration

    if(print_stats) 
    {
        cout << "Thread stats" <<endl;
        sthread_t::dump_stats(cout);
        cout << endl;

        cout << "Unix stats for parent:" <<endl;
        cout << U << endl << endl;

    }
    cout << flush;

done:
    clean_up_shell();
    fprintf(stderr, "%d tcl threads ran\n", num_tcl_threads_ttl);
    return 0;

errordone:
    clean_up_shell();
    return 1;
}
Example #11
0
void SAppBase::init()
{
	// setup logging
	dlog.add(new dlogprinterfile(Path::localSettings(Path("log.txt"))));
	derr.add(new dlogprinterfile(Path::localSettings(Path("errors.txt"))));

	loadConfig("options.ini", true);
	m_options = &config("options.ini");

	loadConfig("ui.ini", true);
	m_ui = &config("ui.ini");
	
	loadConfig("materials.ini");
	m_materials = &config("materials.ini");

	std::string uistylesConfigName = m_options->get("UI", "StyleFile", std::string("uistyles.ini"));
	loadConfig(uistylesConfigName);
	m_uiStyles = &config(uistylesConfigName);

	// Heap debugging
	if (hasCmdLineOption("heapdebug"))
	{
#if IS_MSVC
		int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
		tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
		_CrtSetDbgFlag( tmpFlag );
#else
		throw("Heap debugging is only enabled in MSVC builds.");
#endif
	}

	// create log
	dlog << m_appName << " - " << getCPUVendorID() << " " << getCPUTicksPerSecond() / 1000000.0f << " Mhz" << dlog.endl;

	// get default window icon, if available
	// tbd:mingw: fix
	//HICON groupIcon = LoadIcon(GetModuleHandle(0), "APP");

    // Register the window class.
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, StaticMsgProc, 0L, sizeof(LONG), 
                      GetModuleHandle(NULL), /*groupIcon*/0, LoadCursor(0, IDC_ARROW), NULL, NULL,
                      m_appName.c_str(), NULL };
    RegisterClassEx( &wc );

	//FreeResource(groupIcon);

    // Create the application's window.
    m_hWnd = CreateWindow( m_appName.c_str(), m_appName.c_str(), 
                              WS_OVERLAPPEDWINDOW, 0, 0, 640, 480,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );

	if (!m_hWnd)
		throwf("Couldn't create a window.");

	// setup device
	bool windowed = hasCmdLineOption("w");
	Point2i fullscreenSize = options().get("Render", "FullscreenSize", Point2i(1024, 768));
	Point2i windowedSize = options().get("Render", "WindowedSize", Point2i(640, 480));
	D3D().newDevice(
		windowed,
		fullscreenSize.x,
		fullscreenSize.y,
		windowedSize.x,
		windowedSize.y
		);

	createFonts();
		
	// create dialog mgr
	m_pDlgMgrSingleton = new SDialogMgr;

	if (!Input().create(GetModuleHandle(NULL)))
		throwf("Couldn't create input");

	if (!Input().createMouse(m_hWnd))
		throwf("Couldn't create mouse");

	// setup ui
	DialogMgr().create();

	m_textureAnimation = new TextureAnimationManager("animations.ini");
	m_particles = new ParticleFactory("particles.ini", m_textureAnimation->set("particles"));
	m_spriteFX = new SpriteFXFactory("spritefx.ini");

	timer().restart();

	m_updateLoopFreq = options().get("Game", "UpdateLoopFreq", 0.0f);

	// create sound
	std::string soundProvider = options().get("Sound", "Provider", std::string("FMODProvider"));
	dlog << "AppBase: Initialising sound provider '" << soundProvider << "'" << dlog.endl;
	m_sound = (ISoundProvider*)Base::newObject(soundProvider);
	if (!m_sound)
		throwf("Couldn't initialize sound provider '" + soundProvider + "'");

	// music manager
	loadConfig("music.ini");
	loadConfig("musicmanager.ini");

	m_music = new MusicManager;

	// Add sounds path
	filesystem().addFileMethod(new FileMethodDiskRelative(pathResources() + m_options->get("Sound", "SoundsPath", std::string("media\\sounds"))));

	// make main loop update thread
#if USE_FIBERS
	m_mainLoopStep = new ThreadStepper(ThreadStepper::Delegate(this, (ThreadStepper::Delegate::FuncType)&SAppBase::doMainLoopUpdate));
	add(*m_mainLoopStep);
#endif
}
Example #12
0
int 
begin(int argc, char *argv[])
{
        int                   	i, j;
	uint32_t		ph_flags = 0;
        thread_pool_attr_t	tp_attr;
	static void 		*tpp;
        dispatch_t              *dpp;

        dpp = dispatch_create();
        if (dpp == NULL) {
               char * pMsgTxt = "Error: cannot create dispatch interface\n";
               fprintf(stderr, pMsgTxt);
               slogf(_SLOG_SETCODE(_SLOGC_INPUT, 0), _SLOG_ERROR, pMsgTxt);
                return (EXIT_FAILURE);
        }
        devi_set_dispatch_handle(dpp);
        /* set up the module table */
        if (modules != NULL) {

                for (i = 0; i < MODULE_TABLE_SIZE && ModuleTable[i] != NULL; 
		     i++)
                        ;
                /* add extra modules to end of ModuleTable */
                
                for (j = 0; j < (MODULE_TABLE_SIZE - i) && modules[j] != NULL; 
		     j++, i++) 
                        ModuleTable[i] = modules[j];
        }
        
        if(ThreadCtl(_NTO_TCTL_IO, 0) == -1) {
                errno_print("ThreadCtl");
                return (EXIT_FAILURE);
        }
        // Call global callback if it was specified        
        if(commonCallbacks.pre_init && commonCallbacks.pre_init())
		return (EXIT_FAILURE);
        if (options(argc, argv, &ph_flags, &OptFlags) < 0)
		return (EXIT_FAILURE);
        // Call global callback if it was specified        
        if(commonCallbacks.post_init && commonCallbacks.post_init())
		return (EXIT_FAILURE);
        sig_install(signal_table, termination_hndlr);

	if (procmgr_daemon(0, PROCMGR_DAEMON_NODEVNULL | 
			   PROCMGR_DAEMON_NOCLOSE) < 0) {
		errno_print("procmgr_daemon");
		return (EXIT_FAILURE);
	}


        if (!(OptFlags & OPT_NO_PHOTON))  {
                if (start_photon_interface(ph_flags) < 0) {
                        errno_print("unable to start photon interface");
                        return (EXIT_FAILURE);
                }
        }

	memset(&tp_attr, 0, sizeof(tp_attr));
        tp_attr.handle = devi_get_dispatch_handle();
        tp_attr.context_alloc = dispatch_context_alloc;
        tp_attr.block_func = dispatch_block;
        tp_attr.handler_func = dispatch_handler;
        tp_attr.context_free = dispatch_context_free;
    /* We'd rather not to use thread pool for device driver - it could 
       cause desynchronizing and data losing                       */
	tp_attr.lo_water  = 1;   /* min amount threads waiting blocked */
	tp_attr.hi_water  = 1;   /* max amount threads waiting blocked */
	tp_attr.increment = 1;  
	tp_attr.maximum   = 1;    

	tpp = thread_pool_create(&tp_attr, POOL_FLAG_USE_SELF);
	if (tpp == NULL) {
                errno_print("thread_pool_create");
                return (EXIT_FAILURE);
        }

	thread_pool_start(tpp);

        return (EOK);
}
int main(int argc, const char **argv) {

	Options options(argc, argv);
	Timer timer;

	log_setlevel(options.getVerbosity());

	/* Get the number of neutrons, bins and batches */
	int num_neutrons = options.getNumNeutrons();
	int num_bins = options.getNumBins();
	int num_batches = options.getNumBatches();
    int num_threads = options.getNumThreads();
	int num_gen;
	int num_alive;

	log_printf(NORMAL, "Beginning two region problem with %d neutrons, "
			"%d bins, %d batches, %d threads...", num_neutrons, num_bins,
			num_batches, num_threads);

	/* Create a handle for plotting with gnuplot */
	gnuplot_ctrl* handle;


	/* Create a set of plotting flux bins for each batch */
	BatchBinSet* total_flux = new BatchBinSet();
	BatchBinSet* fuel_flux = new BatchBinSet();
	BatchBinSet* moderator_flux = new BatchBinSet();

	total_flux->createBinners(1E-6, 1E7, num_bins, num_batches,
							LOGARITHMIC, FLUX_ENERGY, (char*)"all");
	fuel_flux->createBinners(1E-6, 1E7, num_bins, num_batches,
							LOGARITHMIC, FLUX_ENERGY, (char*)"all");
	moderator_flux->createBinners(1E-6, 1E7, num_bins, num_batches,
							LOGARITHMIC, FLUX_ENERGY, (char*)"all");


	/* Create bins to compute total fission and absorption rates */
	BatchBinSet* tot_fiss_rate = new BatchBinSet();
	BatchBinSet* tot_abs_rate = new BatchBinSet();

	tot_fiss_rate->createBinners(1E-7, 1E7, 1, num_batches, EQUAL,
									FISSION_RATE_ENERGY, (char*)"all");
	tot_abs_rate->createBinners(1E-7, 1E7, 1, num_batches, EQUAL,
									ABSORPTION_RATE_ENERGY, (char*)"all");
	float nu_bar = 2.455;	/* CASMO edit for average # neutrons per fission */

	/* Create bins to compute two group cell-averaged cross-sections */
	BatchBinSet* capture_2G = new BatchBinSet();
	BatchBinSet* absorb_2G = new BatchBinSet();
	BatchBinSet* fission_2G = new BatchBinSet();
	BatchBinSet* elastic_2G = new BatchBinSet();
	BatchBinSet* total_2G = new BatchBinSet();
	BatchBinSet* two_group_flux = new BatchBinSet();

	float two_group_E_ranges[3] = {0.0, 0.625, 1E7};

	capture_2G->createBinners(two_group_E_ranges, 2, num_batches,
							CAPTURE_RATE_ENERGY, (char*)"all");
	absorb_2G->createBinners(two_group_E_ranges, 2, num_batches,
							ABSORPTION_RATE_ENERGY, (char*)"all");
	fission_2G->createBinners(two_group_E_ranges, 2, num_batches,
							FISSION_RATE_ENERGY, (char*)"all");
	elastic_2G->createBinners(two_group_E_ranges, 2, num_batches,
							ELASTIC_RATE_ENERGY, (char*)"all");
	total_2G->createBinners(two_group_E_ranges, 2, num_batches,
							COLLISION_RATE_ENERGY, (char*)"all");
	two_group_flux->createBinners(two_group_E_ranges, 2, num_batches,
									FLUX_ENERGY, (char*)"all");


	/* Create bins to compute two group isotopic cross-sections */
	BatchBinSet* H1_capture_rate_2G = new BatchBinSet();
	BatchBinSet* H1_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* O16_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* ZR90_elastic_rate_2G = new BatchBinSet();

	BatchBinSet* U235_capture_rate_2G = new BatchBinSet();
	BatchBinSet* U235_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* U235_fission_rate_2G = new BatchBinSet();
	BatchBinSet* U238_capture_rate_2G = new BatchBinSet();
	BatchBinSet* U238_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* U238_fission_rate_2G = new BatchBinSet();

	H1_capture_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										CAPTURE_RATE_ENERGY, (char*)"H1");
	H1_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"H1");
	O16_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"O16");
	ZR90_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"ZR90");

	U235_capture_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										CAPTURE_RATE_ENERGY, (char*)"U235");
	U235_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"U235");
	U235_fission_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										FISSION_RATE_ENERGY, (char*)"U235");
	U238_capture_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										CAPTURE_RATE_ENERGY, (char*)"U238");
	U238_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"U238");
	U238_fission_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										FISSION_RATE_ENERGY, (char*)"U238");


	/* Create bins to compute moderator to fuel flux ratios */
	int num_ratios = 13;
	BatchBinSet* fuel_flux_ratio = new BatchBinSet();
	BatchBinSet* moderator_flux_ratio = new BatchBinSet();

	float flux_ratio_E_ranges[14] = {0.0, 0.1, 0.5, 1.0, 6.0, 10.0, 25.0,
									50.0, 100.0, 1000.0, 10000.0, 100000.0,
									500000.0, 10000000.0};

	fuel_flux_ratio->createBinners(flux_ratio_E_ranges, num_ratios,
							num_batches, FLUX_ENERGY, (char*)"all");

	moderator_flux_ratio->createBinners(flux_ratio_E_ranges, num_ratios,
							num_batches, FLUX_ENERGY, (char*)"all");


	/* Create bins to compute the diffusion coefficient for three methods */
	BatchBinSet* coll_rate_2G = new BatchBinSet();
	BatchBinSet* transport_rate_2G = new BatchBinSet();
	BatchBinSet* diffusion_rate_2G = new BatchBinSet();

	coll_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
								COLLISION_RATE_ENERGY, (char*)"all");
	transport_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
								TRANSPORT_RATE_ENERGY, (char*)"all");
	diffusion_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
								DIFFUSION_RATE_ENERGY, (char*)"all");


	/* 2-region pin cell geometric parameters (units in cm) */
	float r_fuel = 0.4096;
	float r_gap = 0.4178;
	float r_cladding = 0.4750;
	float pitch = 1.26;
	float p2 = pitch * pitch;

	/* 2-region homogenized densities (g/cm^3) and enrichment */
	float rho_fuel = 10.2;
	float rho_cladding = 6.549;
	float rho_coolant = 0.9966;
	float enrichment = 0.03035;

	/* Isotope number densities */
	float N_A = 6.023E23;	/* Avogadro's number (at / mol) */
	float N_U238 = rho_fuel*N_A*(1.0 - enrichment) / ((238.0 *
					(1.0 - enrichment)) + (235.0*enrichment) + (16.0*2.0));
	float N_U235 = rho_fuel*N_A*enrichment / ((238.0 *
					(1.0 - enrichment)) + (235.0*enrichment) + (16.0*2.0));
	float N_O16 = rho_fuel*N_A*2.0 / ((238.0 *
					(1.0 - enrichment)) + (235.0*enrichment) + (16.0*2.0));
	float N_ZR90 = rho_cladding*N_A / 90.0;
	float N_H2O = rho_coolant*N_A / 18.0;
	float N_H1 = rho_coolant*N_A*2.0 / 18.0;

	/* 2-region pin cell volumes (cm^3) */
	float v_fuel = M_PI*r_fuel*r_fuel;
	float v_gap = M_PI*(r_gap*r_gap - r_fuel*r_fuel);
	float v_cladding = M_PI*(r_cladding*r_cladding - r_gap*r_gap);
	float v_coolant = p2 - M_PI*r_cladding*r_cladding;
	float v_moderator = v_gap + v_cladding + v_coolant;
	float v_total = v_fuel + v_moderator;

	/* Compute homogenized moderator number densities using volume weighting */
	N_H2O *= (v_coolant / v_moderator);
	N_H1 *= (v_coolant / v_moderator);
	N_ZR90 *= (v_cladding / v_moderator);

	/* Dancoff factor from CASMO-5 */
	float dancoff = 0.277;

	/* Escape cross-section */
	float sigma_e = 1.0 / (2.0*r_fuel);

	/* Carlvik's two-term rational model */
	float A = (1.0 - dancoff) / dancoff;
	float alpha1 = ((5.0*A + 6.0) - sqrt(A*A + 36.0*A + 36.0)) /
														(2.0*(A+1.0));
	float alpha2 = ((5.0*A + 6.0) + sqrt(A*A + 36.0*A + 36.0)) /
														(2.0*(A+1.0));
	float beta = (((4.0*A + 6.0) / (A + 1.0)) - alpha1) / (alpha2 - alpha1);

	/* Print out the geometry parameters */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\t\tGeometry Parameters (cm)");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(NORMAL, "r_fuel = %f", r_fuel);
	log_printf(NORMAL, "r_gap  = %f", r_gap);
	log_printf(NORMAL, "r_cladding = %f", r_cladding);
	log_printf(NORMAL, "pitch = %f", pitch);
	log_printf(NORMAL, "total cell area = %f", p2);
	log_printf(NORMAL, "v_fuel = %f", v_fuel);
	log_printf(NORMAL, "v_gap = %f", v_gap);
	log_printf(NORMAL, "v_cladding = %f", v_cladding);
	log_printf(NORMAL, "v_coolant = %f", v_coolant);
	log_printf(NORMAL, "v_moderator = %f", v_moderator);
	log_printf(NORMAL, "v_total = %f", v_total);
	log_printf(NORMAL, "");

	/* Print to the console the number densities */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\t\tNumber Densities (at/cm^3)");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(NORMAL, "H1:\t%1.5e", N_H1);
	log_printf(NORMAL, "H2O:\t%1.5e", N_H2O);
	log_printf(NORMAL, "ZR90:\t%1.5e", N_ZR90);
	log_printf(NORMAL, "U235:\t%1.5e", N_U235);
	log_printf(NORMAL, "U238:\t%1.5e", N_U238);
	log_printf(NORMAL, "O16:\t%1.5e", N_O16);
	log_printf(NORMAL, "");

	/* Print to the console the collision probability parameters */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\tTwo Region Collision Probability Parameters");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(NORMAL, "dancoff = %f", dancoff);
	log_printf(NORMAL, "sigma_e = %f", sigma_e);
	log_printf(NORMAL, "A = %f", A);
	log_printf(NORMAL, "alpha1 = %f", alpha1);
	log_printf(NORMAL, "alpha2 = %f", alpha2);
	log_printf(NORMAL, "beta = %f", beta);
	log_printf(NORMAL, "");


	/* Create isotopes*/
	char* delim = (char*)"\t";

	Isotope* H1 = new Isotope();
	H1->setA(1);
	H1->setIsotopeType((char*)"H1");
	H1->loadXS((char*)"pendf/h-1_capture.txt", CAPTURE, delim);
	H1->loadXS((char*)"pendf/h-1_elastic.txt", ELASTIC, delim);
	H1->setElasticAngleType(ISOTROPIC_LAB);
	H1->initializeThermalScattering(1E-6, 15, 1000, 15);

	Isotope* O16 = new Isotope();
	O16->setA(16);
	O16->setIsotopeType((char*)"O16");
	O16->loadXS((char*)"pendf/o-16_elastic.txt", ELASTIC, delim);
	O16->setElasticAngleType(ISOTROPIC_LAB);

	Isotope* ZR90 = new Isotope();
	ZR90->setA(90);
	ZR90->setIsotopeType((char*)"ZR90");
	ZR90->loadXS((char*)"pendf/zr-90_elastic.txt", ELASTIC, delim);
	ZR90->setElasticAngleType(ISOTROPIC_LAB);

	Isotope* U235 = new Isotope();
	U235->setA(235);
	U235->setIsotopeType((char*)"U235");
	U235->loadXS((char*)"pendf/u-235_capture.txt", CAPTURE, delim);
	U235->setOneGroupElasticXS(11.4, ISOTROPIC_LAB);
	U235->loadXS((char*)"pendf/u-235_fission.txt", FISSION, delim);

	Isotope* U238 = new Isotope();
	U238->setA(238);
	U238->setIsotopeType((char*)"U238");
	U238->loadXS((char*)"pendf/u-238_capture.txt", CAPTURE, delim);
	U238->setOneGroupElasticXS(11.3, ISOTROPIC_LAB);
	U238->loadXS((char*)"pendf/u-238_fission.txt", FISSION, delim);


	/* Create Materials */
	Material* moderator = new Material[num_threads];
	Material* fuel = new Material[num_threads];


	/* Create Regions for each thread */
	Region1D* pellet = new Region1D[num_threads];
	Region1D* coolant = new Region1D[num_threads];

	/* Create Fissioners for each thread */
	Fissioner* fissioners = new Fissioner[num_threads];

	/* Create Region class objects for each thread */
	for (int i=0; i < num_threads; i++) {

		/* Initialize Materials for each thread with isotope clones */
		moderator[i].setMaterialName((char*)"moderator");
		fuel[i].setMaterialName((char*)"fuel");

		moderator[i].addIsotope(ZR90->clone(), N_ZR90);
		moderator[i].addIsotope(H1->clone(), N_H1);
		moderator[i].addIsotope(O16->clone(), N_H2O);
		moderator[i].rescaleCrossSections(1E-7, 1E7, 50000, LOGARITHMIC);

		fuel[i].addIsotope(U235->clone(), N_U235);
		fuel[i].addIsotope(U238->clone(), N_U238);
		fuel[i].addIsotope(O16->clone(), N_O16);
		fuel[i].rescaleCrossSections(1E-7, 1E7, 50000, LOGARITHMIC);

		/* Set the two region collision probability parameters */
		pellet[i].setRegionName((char*)"pellet");
		pellet[i].setMaterial(&fuel[i]);
		pellet[i].setAsFuel();
		pellet[i].setOtherPinCellRegion(&coolant[i]);
		pellet[i].setVolume(v_fuel);
		pellet[i].setTwoRegionPinCellParams(sigma_e, beta, alpha1, alpha2);

		coolant[i].setRegionName((char*)"coolant");
		coolant[i].setMaterial(&moderator[i]);
		coolant[i].setAsModerator();
		coolant[i].setOtherPinCellRegion(&pellet[i]);
		coolant[i].setVolume(v_moderator);
		coolant[i].setTwoRegionPinCellParams(sigma_e, beta, alpha1, alpha2);

		/* Set the fissioner class for this thread to have 10MeV maximum and
		 * 5000 sample bins */
		fissioners[i].setEMax(10.0);
		fissioners[i].setNumBins(200);
		fissioners[i].buildCDF();
	}


	/* Run the simulation */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\t\tBeginning Simulation...");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");

	timer.start();

	omp_set_num_threads(num_threads);
	#pragma omp parallel shared(total_flux, fuel_flux, moderator_flux,\
							fuel_flux_ratio, moderator_flux_ratio,\
							tot_fiss_rate, tot_abs_rate, U235_capture_rate_2G,\
							U235_elastic_rate_2G, U235_fission_rate_2G,\
							U238_capture_rate_2G, U238_elastic_rate_2G,\
							U238_fission_rate_2G, H1_capture_rate_2G,\
							H1_elastic_rate_2G, O16_elastic_rate_2G,\
							ZR90_elastic_rate_2G, fuel, moderator, \
							pellet, coolant, fissioners)
	{
		/* Loop over batches */
		#pragma omp for private(num_gen, num_alive)
		for (int b=0; b < num_batches; b++) {

			int thread_num = omp_get_thread_num();
			log_printf(NORMAL, "Batch: %d\tThread: %d", b, thread_num);

			/* Set the binns for this batch */
			pellet[thread_num].clearBinners();
			pellet[thread_num].addBinner(total_flux->getBinner(b));
			pellet[thread_num].addBinner(fuel_flux->getBinner(b));
			pellet[thread_num].addBinner(fuel_flux_ratio->getBinner(b));
			pellet[thread_num].addBinner(tot_fiss_rate->getBinner(b));
			pellet[thread_num].addBinner(tot_abs_rate->getBinner(b));
			pellet[thread_num].addBinner(U235_capture_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U235_elastic_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U235_fission_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U238_capture_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U238_elastic_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U238_fission_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(O16_elastic_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(two_group_flux->getBinner(b));
			pellet[thread_num].addBinner(coll_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(transport_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(diffusion_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(capture_2G->getBinner(b));
			pellet[thread_num].addBinner(fission_2G->getBinner(b));
			pellet[thread_num].addBinner(absorb_2G->getBinner(b));
			pellet[thread_num].addBinner(elastic_2G->getBinner(b));
			pellet[thread_num].addBinner(total_2G->getBinner(b));

			coolant[thread_num].clearBinners();
			coolant[thread_num].addBinner(total_flux->getBinner(b));
			coolant[thread_num].addBinner(moderator_flux->getBinner(b));
			coolant[thread_num].addBinner(moderator_flux_ratio->getBinner(b));
			coolant[thread_num].addBinner(tot_fiss_rate->getBinner(b));
			coolant[thread_num].addBinner(tot_abs_rate->getBinner(b));
			coolant[thread_num].addBinner(H1_capture_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(H1_elastic_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(O16_elastic_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(ZR90_elastic_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(two_group_flux->getBinner(b));
			coolant[thread_num].addBinner(coll_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(transport_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(diffusion_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(capture_2G->getBinner(b));
			coolant[thread_num].addBinner(fission_2G->getBinner(b));
			coolant[thread_num].addBinner(absorb_2G->getBinner(b));
			coolant[thread_num].addBinner(elastic_2G->getBinner(b));
			coolant[thread_num].addBinner(total_2G->getBinner(b));

			/* Initialize all neutrons for this batch and add them to slab 1 */
			for (int n=0; n < num_neutrons; n++) {
				neutron* new_neutron = initializeNewNeutron();
				new_neutron->_x = 0.0;
				new_neutron->_mu = (float(rand()) / RAND_MAX) * 2.0 - 1.0;
				new_neutron->_energy = fissioners[thread_num].emitNeutroneV();
				pellet[thread_num].addNeutron(new_neutron);
			}

			/* Loop over all neutrons until they are all dead */
			num_gen = 1;
			num_alive = num_neutrons;

			while (num_alive > 0) {

				log_printf(DEBUG, "batch = %d, thread = %d, gen = %d, "
						"num_alive = %d", b, thread_num, num_gen, num_alive);

				num_gen++;
				num_alive = 0;

				/* Transfer neutrons between regions based on
				 * two region collision probabilities */
				pellet[thread_num].twoRegionNeutronTransferral();
				coolant[thread_num].twoRegionNeutronTransferral();

				/* Update each region's vector of neutrons with those
				 * neutrons which were just transferred */
				pellet[thread_num].initializeTransferredNeutrons();
				coolant[thread_num].initializeTransferredNeutrons();

				/* Move neutrons within each region */
				pellet[thread_num].moveNeutrons();
				coolant[thread_num].moveNeutrons();

				num_alive = pellet[thread_num].getNumNeutrons() +
							coolant[thread_num].getNumNeutrons();
			}
		}
	}

	log_printf(NORMAL, "");

	/* Stop the timer record the timing split for this simulation */
	timer.stop();
	timer.recordSplit("Pset 4 time (sec)");

	/* Compute batch statistics for total flux and flux in fuel, moderator */
	total_flux->computeScaledBatchStatistics(num_neutrons*v_total);
	fuel_flux->computeScaledBatchStatistics(num_neutrons*v_fuel);
	moderator_flux->computeScaledBatchStatistics(num_neutrons*v_moderator);

	/* Compute batch statistics for total fission and absorption rates */
	tot_fiss_rate->computeScaledBatchStatistics(num_neutrons*v_total);
	tot_abs_rate->computeScaledBatchStatistics(num_neutrons*v_total);

	/* Compute batch statistics for cell-averaged macro cross-sections */
	capture_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	fission_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	absorb_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	elastic_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	total_2G->computeScaledBatchStatistics(num_neutrons*v_total);

	/* Compute batch statistics for one group cross-sections */
	H1_capture_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	H1_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	O16_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	ZR90_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U235_capture_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U235_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U235_fission_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U238_capture_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U238_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U238_fission_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	two_group_flux->computeScaledBatchStatistics(num_neutrons*v_total);
	coll_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	transport_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	diffusion_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);

	/* Compute k-infinity */
	float fiss_rate_mu = tot_fiss_rate->getBatchMu()[0];
	float fiss_rate_var = tot_fiss_rate->getBatchVariance()[0];
	float abs_rate_mu = tot_abs_rate->getBatchMu()[0];
	float abs_rate_var = tot_abs_rate->getBatchVariance()[0];

	float k_inf = fiss_rate_mu * nu_bar / abs_rate_mu;

	float k_inf_var = (fiss_rate_mu*fiss_rate_mu)*abs_rate_var +
						(abs_rate_mu*abs_rate_mu)*fiss_rate_var +
									fiss_rate_var*abs_rate_var;

	float k_inf_std_dev = sqrt(k_inf_var);

	/* Compute moderator to fuel flux ratios */
	fuel_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_fuel);
	moderator_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_moderator);
	fuel_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_fuel);
	moderator_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_moderator);

	/* Print to the console the total fission rate */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\tTotal Fission Rate (Batch Statistics)");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(RESULT, "Tot fission rate = %1.8f\t\tVariance = %1.8f",
									tot_fiss_rate->getBatchMu()[0],
									tot_fiss_rate->getBatchVariance()[0]);
	log_printf(RESULT, "Tot absorption rate = %f\t\tVariance = %f",
									tot_abs_rate->getBatchMu()[0],
									tot_abs_rate->getBatchVariance()[0]);
	log_printf(RESULT, "k_inf = %f\t\tvariance = %1.8f \t\t 2 sigma = %1.8f", k_inf,
													k_inf_var, k_inf_std_dev);
	log_printf(RESULT, "");

	/* Print to the console the moderator/fuel flux ratios */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\t\tModerator/Fuel Flux Ratios");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");

	float ratio;
	for (int i=1; i < num_ratios+1; i++) {

		ratio = moderator_flux_ratio->getBatchMu()[i-1] /
						fuel_flux_ratio->getBatchMu()[i-1];

		log_printf(RESULT, "[%2.e eV - %2.e eV]:\t%f",
				flux_ratio_E_ranges[i-1], flux_ratio_E_ranges[i], ratio);
	}

	log_printf(RESULT, "");


	/* Print to the console the cell-averaged fast to thermal flux ratio */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\tCell-Averaged Fast-to-Thermal Flux Ratio");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");
	double* two_group_flux_mu = two_group_flux->getBatchMu();
	double flux1 = two_group_flux_mu[0];
	double flux2 = two_group_flux_mu[1];
	log_printf(RESULT, "Ratio = %f", flux2 / flux1);
	log_printf(RESULT, "");


	/* Print to the console the two group macroscopic cross-sections */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\tTwo Group Macroscopic Cross-Sections (cm^-1)");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");

	float xs1, xs2;

	log_printf(RESULT, "\t\t\t[%1.1f eV - %1.3f eV]\t[%1.3f eV - %1.1e eV]",
						two_group_flux->getBinner(0)->getBinEdges()[0],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[2]);

	/* H1 capture */
	xs1 = H1_capture_rate_2G->getBatchMu()[0] / flux1;
	xs2 = H1_capture_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "H1 Capture: \t\t%f\t\t%f", xs1, xs2);

	/* H1 elastic */
	xs1 = H1_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = H1_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "H1 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* O16 elastic */
	xs1 = O16_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = O16_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "O16 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* ZR90 elastic */
	xs1 = ZR90_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = ZR90_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "ZR90 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* U235 capture */
	xs1 = U235_capture_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U235_capture_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U235 Capture: \t\t%f\t\t%f", xs1, xs2);

	/* U235 elastic */
	xs1 = U235_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U235_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U235 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* U235 fission */
	xs1 = U235_fission_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U235_fission_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U235 Fission: \t\t%f\t\t%f", xs1, xs2);

	/* U238 capture */
	xs1 = U238_capture_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U238_capture_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U238 Capture: \t\t%f\t\t%f", xs1, xs2);

	/* U238 elastic */
	xs1 = U238_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U238_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U238 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* U238 fission */
	xs1 = U238_fission_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U238_fission_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U238 Fission: \t\t%f\t\t%f", xs1, xs2);

	log_printf(RESULT, "");


	/* Print to the console the two group macroscopic cross-sections */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\tTwo Group Cell-Averaged Macroscopic "
			"Cross-Sections (cm^-1)");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");

	log_printf(RESULT, "\t\t\t[%1.1f eV - %1.3f eV]\t[%1.3f eV - %1.1e eV]",
						two_group_flux->getBinner(0)->getBinEdges()[0],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[2]);

	/* Flux */
	log_printf(RESULT, "Flux: \t\t\t%f\t\t%f", flux1, flux2);

	/* Capture */
	xs1 = capture_2G->getBatchMu()[0] / flux1;
	xs2 = capture_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Capture: \t\t\t%f\t\t%f", xs1, xs2);

	/* Fission */
	xs1 = fission_2G->getBatchMu()[0] / flux1;
	xs2 = fission_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Fission: \t\t\t%f\t\t%f", xs1, xs2);

	/* Absorption */
	xs1 = absorb_2G->getBatchMu()[0] / flux1;
	xs2 = absorb_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Absorb: \t\t\t%f\t\t%f", xs1, xs2);

	/* Elastic */
	xs1 = elastic_2G->getBatchMu()[0] / flux1;
	xs2 = elastic_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Elastic: \t\t\t%f\t\t%f", xs1, xs2);

	/* Total */
	xs1 = total_2G->getBatchMu()[0] / flux1;
	xs2 = total_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Total: \t\t\t%f\t\t%f", xs1, xs2);
	log_printf(RESULT, "");


	/* Print to the console the two group macroscopic cross-sections */
	log_printf(RESULT, "*******************************************************"
												"*************************");
	log_printf(RESULT, "\t\t\tTwo Group Diffusion Coefficients");
	log_printf(RESULT, "*******************************************************"
												"*************************");
	log_printf(RESULT, "");
	log_printf(RESULT, "\t\t\t[%1.1f eV - %1.3f eV]\t[%1.3f eV - %1.1e eV]",
						two_group_flux->getBinner(0)->getBinEdges()[0],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[2]);

	float sigma_t1, sigma_t2;
	float sigma_tr1, sigma_tr2;
	float D1, D2;

	sigma_t1 = coll_rate_2G->getBatchMu()[0] / flux1;
	sigma_t2 = coll_rate_2G->getBatchMu()[1] / flux2;
	D1 = 1.0 / (3.0 * sigma_t1);
	D2 = 1.0 / (3.0 * sigma_t2);

	log_printf(RESULT, "1/(3*sigma_t):\t\t%f\t\t%f", D1, D2);

	sigma_tr1 = transport_rate_2G->getBatchMu()[0] / flux1;
	sigma_tr2  = transport_rate_2G->getBatchMu()[1] / flux2;
	D1 = 1.0 / (3.0 * sigma_tr1);
	D2 = 1.0 / (3.0 * sigma_tr2);

	log_printf(RESULT, "1/(3*sigma_tr):\t\t%f\t\t%f", D1, D2);

	D1 = diffusion_rate_2G->getBatchMu()[0] / flux1;
	D2 = diffusion_rate_2G->getBatchMu()[1] / flux2;

	log_printf(RESULT, "Diff coeff:\t\t%f\t\t%f", D1, D2);

	log_printf(RESULT, "");


	/* Plot the total neutron flux */
	handle = gnuplot_init();
	gnuplot_set_xlabel(handle, (char*)"Energy (eV)");
	gnuplot_set_ylabel(handle, (char*)"flux");
	gnuplot_set_xrange(handle, 0.005, 1E7);
	gnuplot_cmd(handle, (char*)"set logscale xy");
	gnuplot_cmd(handle, (char*)"set title \"Normalized Flux\"");
	gnuplot_setstyle(handle, (char*)"lines");
	gnuplot_plot_xy(handle, total_flux->getBinner(0)->getBinCenters(),
			total_flux->getBatchMu(), num_bins, (char*)"Total Flux");
	gnuplot_plot_xy(handle, fuel_flux->getBinner(0)->getBinCenters(),
			fuel_flux->getBatchMu(), num_bins, (char*)"Fuel Flux");
	gnuplot_saveplot(handle, (char*)"flux");
	gnuplot_plot_xy(handle, moderator_flux->getBinner(0)->getBinCenters(),
			moderator_flux->getBatchMu(), num_bins, (char*)"Moderator Flux");
	gnuplot_close(handle);


	/* Free all allocated memory */
	delete [] pellet;
	delete [] coolant;
	delete [] fissioners;

	delete [] moderator;
	delete [] fuel;

	delete total_flux;
	delete fuel_flux;
	delete moderator_flux;
	delete tot_fiss_rate;
	delete tot_abs_rate;
	delete fuel_flux_ratio;
	delete moderator_flux_ratio;
	delete H1_capture_rate_2G;
	delete H1_elastic_rate_2G;
	delete O16_elastic_rate_2G;
	delete U235_capture_rate_2G;
	delete U235_elastic_rate_2G;
	delete U235_fission_rate_2G;
	delete U238_capture_rate_2G;
	delete U238_elastic_rate_2G;
	delete U238_fission_rate_2G;
	delete ZR90_elastic_rate_2G;
	delete two_group_flux;
	delete coll_rate_2G;
	delete transport_rate_2G;
	delete diffusion_rate_2G;

	delete H1;
	delete O16;
	delete ZR90;
	delete U235;
	delete U238;

	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\t\tTiming Results");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	timer.printSplits();
}
Example #14
0
	MySQLService::MySQLService(bool fatal_necessity) : 
	Service(),mysql_lib_handle(nullptr),serviceHandle(nullptr),
	library_init(nullptr),library_end(nullptr),select_db(nullptr),close(nullptr),data_seek(nullptr),my_errno(nullptr),error(nullptr),
	fetch_field_direct(nullptr),
	fetch_lengths(nullptr),fetch_row(nullptr),free_result(nullptr),init(nullptr),insert_id(nullptr),list_fields(nullptr),
	list_tables(nullptr),num_fields(nullptr),num_rows(nullptr),options(nullptr),real_connect(nullptr),real_escape_string(nullptr),
	real_query(nullptr),row_seek(nullptr),row_tell(nullptr),character_set_name(nullptr),set_character_set(nullptr),store_result(nullptr)
	{ 
		if (String::Deflate::available()) {
			string libdir,libname;
			if (!Environment::getbenv("OBYX_LIBMYSQLCRSO",libname)) { 	//legacy method
				if (Environment::getbenv("OBYX_LIBMYSQLDIR",libdir)) {
					if (!libdir.empty() && *libdir.rbegin() != '/') libdir.push_back('/');
				}
				libname = SO(libdir,libmysqlclient_r);
			}
			mysql_lib_handle = dlopen(libname.c_str(),RTLD_LAZY);
			if (mysql_lib_handle != nullptr ) {
				library_init = (int (*)(int, char **,char **)) dlsym(mysql_lib_handle,"mysql_server_init");
				library_end = (void (*)()) dlsym(mysql_lib_handle,"mysql_server_end");
				select_db = (int (*)(MYSQL*, const char*)) dlsym(mysql_lib_handle,"mysql_select_db");
				close = (void (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_close");
				data_seek = (void (*)(MYSQL_RES*,my_ulonglong)) dlsym(mysql_lib_handle,"mysql_data_seek");
				my_errno = (unsigned int (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_errno");
				error = (const char* (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_error");
				fetch_field_direct = (MYSQL_FIELD* (*)(MYSQL_RES*,unsigned int)) dlsym(mysql_lib_handle,"mysql_fetch_field_direct");
				fetch_lengths = (unsigned long* (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_fetch_lengths");
				fetch_row = (MYSQL_ROW (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_fetch_row");
				free_result = (void (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_free_result");
				init = (MYSQL* (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_init");
				insert_id = (my_ulonglong (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_insert_id");
				list_fields = (MYSQL_RES* (*)(MYSQL*, const char*,const char*)) dlsym(mysql_lib_handle,"mysql_list_fields");
				list_tables = (MYSQL_RES* (*)(MYSQL*,const char*)) dlsym(mysql_lib_handle,"mysql_list_tables");
				num_fields = (unsigned int (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_num_fields");
				num_rows = (my_ulonglong (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_num_rows");
				options = (int	(*)(MYSQL *,enum mysql_option,const char*)) dlsym(mysql_lib_handle,"mysql_options");
				real_connect = (MYSQL* (*)(MYSQL*, const char*,const char*,const char*,const char*, unsigned int,const char*, unsigned long)) dlsym(mysql_lib_handle,"mysql_real_connect");
				real_escape_string = (unsigned long (*)(MYSQL*,char*,const char*, unsigned long)) dlsym(mysql_lib_handle,"mysql_real_escape_string");
				real_query = (int (*)(MYSQL*, const char*, unsigned long)) dlsym(mysql_lib_handle,"mysql_real_query");
				row_seek = (MYSQL_ROW_OFFSET (*)(MYSQL_RES*, MYSQL_ROW_OFFSET)) dlsym(mysql_lib_handle,"mysql_row_seek");
				row_tell = (MYSQL_ROW_OFFSET (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_row_tell");
				character_set_name = (const char* (*)(MYSQL *)) dlsym(mysql_lib_handle,"mysql_character_set_name"); 
				set_character_set = (int (*)(MYSQL*, const char*)) dlsym(mysql_lib_handle,"mysql_set_character_set"); 
				store_result = (MYSQL_RES* (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_store_result");
				service=true;
			} else {
				service=false;
				if (fatal_necessity) {
					string msg;	char* err = dlerror(); if ( err != nullptr) msg=err;
					*Logger::log <<  Log::fatal << Log::LI << "MySQLService error:: Failed to load the " << libname << " dynamic library. " << msg << Log::LO << Log::blockend; 
				}
			}
			if (service) {
				serviceHandle = init(nullptr);
				if (serviceHandle == nullptr) {
					service=false;
					if (fatal_necessity) {
						*Logger::log <<  Log::fatal << Log::LI << "MySQLService error:: Failed to initialise a MySQL client service handle." << Log::LO << Log::blockend; 
					}				
					if ( mysql_lib_handle != nullptr ) { 
						if (fatal_necessity) {
							*Logger::log << " mysql_lib_handle was found."; 
						}				
						dlclose(mysql_lib_handle);
						mysql_lib_handle = nullptr;
					} else {
						if (fatal_necessity) {
							*Logger::log << " mysql_lib_handle was NOT found."; 
						}				
					}
					if (fatal_necessity) {
						*Logger::log << Log::LO << Log::blockend; 
					}				
				} else {
					unsigned int c_to_secs = 5;
					unsigned int q_to_secs = 90;
					options(serviceHandle,MYSQL_READ_DEFAULT_GROUP,"cgi_sql_services");
					options(serviceHandle,MYSQL_SET_CHARSET_NAME,"utf8");
					options(serviceHandle,MYSQL_OPT_CONNECT_TIMEOUT,(const char *)&c_to_secs);
					options(serviceHandle,MYSQL_OPT_READ_TIMEOUT,(const char *)&q_to_secs);
					options(serviceHandle,MYSQL_OPT_WRITE_TIMEOUT,(const char *)&q_to_secs);
				}
			}
		} else {
			service=false;
		}
	}
Example #15
0
int
main (int argc, char *argv[])
{
    /* Scan the argument vector and strip off all parameters known to
     * GTK+. */
    Gtk::Main kit(argc, argv);

    /*prepare global MIDI definitions*/
    for ( int i=0; i<c_maxBuses; i++ )
    {
        for ( int j=0; j<16; j++ )
            global_user_midi_bus_definitions[i].instrument[j] = -1;
    }

    for ( int i=0; i<c_max_instruments; i++ )
    {
        for ( int j=0; j<128; j++ )
            global_user_instrument_definitions[i].controllers_active[j] = false;
    }


    /* Init the lash driver (strip lash specific command line
     * arguments and connect to daemon) */
#ifdef LASH_SUPPORT
    lash_driver = new lash(&argc, &argv);
#endif

    /* the main performance object */
    /* lash must be initialized here because mastermidibus uses the global
     * lash_driver variable*/
    perform p;

    /* read user preferences files */
    if ( getenv( HOME ) != NULL )
    {
        Glib::ustring home( getenv( HOME ));
        last_used_dir = home;
        Glib::ustring total_file = home + SLASH + config_filename;
        
        if (Glib::file_test(total_file, Glib::FILE_TEST_EXISTS))
        {
            printf( "Reading [%s]\n", total_file.c_str());

            optionsfile options( total_file );

            if ( !options.parse( &p ) ){
                printf( "Error Reading [%s]\n", total_file.c_str());
            }
        }

        total_file = home + SLASH + user_filename;
        if (Glib::file_test(total_file, Glib::FILE_TEST_EXISTS))
        {
            printf( "Reading [%s]\n", total_file.c_str());

            userfile user( total_file );

            if ( !user.parse( &p ) ){
                printf( "Error Reading [%s]\n", total_file.c_str());
            }
        }

    }
    else
        printf( "Error calling getenv( \"%s\" )\n", HOME );


    /* parse parameters */
    int c;

    while (true) {

        /* getopt_long stores the option index here. */
        int option_index = 0;

        c = getopt_long(argc, argv, "C:hi:jJmM:pPsSU:Vx:", long_options,
                &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch (c){

            case '?':
            case 'h':

                printf( "Usage: seq24 [OPTIONS] [FILENAME]\n\n" );
                printf( "Options:\n" );
                printf( "   -h, --help: show this message\n" );
                printf( "   -v, --version: show program version information\n" );
                printf( "   -m, --manual_alsa_ports: seq24 won't attach alsa ports\n" );
                printf( "   -s, --showmidi: dumps incoming midi events to screen\n" );
                printf( "   -p, --priority: runs higher priority with FIFO scheduler (must be root)\n" );
                printf( "   -P, --pass_sysex: passes any incoming sysex messages to all outputs \n" );
                printf( "   -i, --ignore <number>: ignore ALSA device\n" );
                printf( "   -k, --show_keys: prints pressed key value\n" );
                printf( "   -x, --interaction_method <number>: see .seq24rc for methods to use\n" );
                printf( "   -j, --jack_transport: seq24 will sync to jack transport\n" );
                printf( "   -J, --jack_master: seq24 will try to be jack master\n" );
                printf( "   -C, --jack_master_cond: jack master will fail if there is already a master\n" );
                printf( "   -M, --jack_start_mode <mode>: when seq24 is synced to jack, the following play\n" );
                printf( "                          modes are available (0 = live mode)\n");
                printf( "                                              (1 = song mode) (default)\n" );
                printf( "   -S, --stats: show statistics\n" );
                printf( "   -U, --jack_session_uuid <uuid>: set uuid for jack session\n" );
                printf( "\n\n\n" );

                return EXIT_SUCCESS;
                break;

            case 'S':
                global_stats = true;
                break;

            case 's':
                global_showmidi = true;
                break;

            case 'p':
                global_priority = true;
                break;

            case 'P':
                global_pass_sysex = true;
                break;

            case 'k':
                global_print_keys = true;
                break;

            case 'j':
                global_with_jack_transport = true;
                break;

            case 'J':
                global_with_jack_master = true;
                break;

            case 'C':
                global_with_jack_master_cond = true;
                break;

            case 'M':
                if (atoi( optarg ) > 0) {
                    global_jack_start_mode = true;
                }
                else {
                    global_jack_start_mode = false;
                }
                break;

            case 'm':
                global_manual_alsa_ports = true;
                break;

            case 'i':
                /* ignore alsa device */
                global_device_ignore = true;
                global_device_ignore_num = atoi( optarg );
                break;

            case 'V':
                printf("%s", versiontext);
                return EXIT_SUCCESS;
                break;

            case 'U':
                global_jack_session_uuid = Glib::ustring(optarg);
                break;

            case 'x':
                global_interactionmethod = (interaction_method_e)atoi(optarg);
                break;

            default:
                break;
        }

    } /* end while */


    p.init();
    p.launch_input_thread();
    p.launch_output_thread();
    p.init_jack();


    p_font_renderer = new font();

    mainwnd seq24_window( &p );
    if (optind < argc)
    {
        if (Glib::file_test(argv[optind], Glib::FILE_TEST_EXISTS))
            seq24_window.open_file(argv[optind]);
        else
            printf("File not found: %s\n", argv[optind]);
    }

    /* connect to lash daemon and poll events*/
#ifdef LASH_SUPPORT
    lash_driver->start(&p);
#endif
    kit.run(seq24_window);

    p.deinit_jack();

    if ( getenv( HOME ) != NULL )
    {
        string home( getenv( HOME ));
        Glib::ustring total_file = home + SLASH + config_filename;
        printf( "Writing [%s]\n", total_file.c_str());

        optionsfile options( total_file );

        if (!options.write( &p))
            printf( "Error writing [%s]\n", total_file.c_str());
    }
    else
    {
        printf( "Error calling getenv( \"%s\" )\n", HOME );
    }

#ifdef LASH_SUPPORT
    delete lash_driver;
#endif

    return EXIT_SUCCESS;
}
Example #16
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av );
        if( options.exists( "--help" ) || options.exists( "-h" ) ) { usage(); }

        bool local = options.exists( "--local" );
        char delimiter = options.value( "--delimiter,-d", ',' );

        boost::optional< comma::csv::format > format;
        if( options.exists( "--binary,-b" ))
        {
            format = comma::csv::format( options.value< std::string >( "--binary,-b" ));
        }
        bool binary = options.exists( "--binary,-b,--size" );
        std::size_t size = options.value( "--size", 0 );
        if( binary && size == 0 ) { size = format->size(); }

        #ifdef WIN32
        if( binary )
        {
            _setmode( _fileno( stdin ), _O_BINARY );
            _setmode( _fileno( stdout ), _O_BINARY );
        }
        #endif

        comma::signal_flag is_shutdown;
        if( binary )
        {
            boost::array< char, 65536 > buf;
            char* begin = &buf[0];
            const char* end = begin + ( buf.size() / size ) * size;
            char* cur = begin;
            unsigned int offset = 0;
            while( !is_shutdown && std::cin.good() && !std::cin.eof() )
            {
                if( offset >= size )
                {
                    boost::posix_time::ptime now = local ? boost::posix_time::microsec_clock::local_time() : boost::posix_time::microsec_clock::universal_time();
                    static const unsigned int time_size = comma::csv::format::traits< boost::posix_time::ptime, comma::csv::format::time >::size;
                    static char timestamp[ time_size ];
                    comma::csv::format::traits< boost::posix_time::ptime, comma::csv::format::time >::to_bin( now, timestamp );
                    for( ; offset >= size; cur += size, offset -= size )
                    {
                        std::cout.write( ( char* )( &timestamp ), time_size );
                        std::cout.write( cur, size );
                    }
                    std::cout.flush();
                    if( cur == end ) { cur = begin; }
                }
                int r = ::read( 0, cur + offset, end - cur - offset );
                if( r <= 0 ) { break; }
                offset += r;
            }            
        }
        else
        {
            while( !is_shutdown && std::cin.good() && !std::cin.eof() )
            {
                std::string line;
                std::getline( std::cin, line );
                if( line.empty() ) { continue; }
                boost::posix_time::ptime now = local ? boost::posix_time::microsec_clock::local_time() : boost::posix_time::microsec_clock::universal_time();
                std::cout << boost::posix_time::to_iso_string( now ) << delimiter << line << std::endl;
            }
        }
        if( is_shutdown ) { std::cerr << "csv-time-stamp: interrupted by signal" << std::endl; }
        return 0;
    }
    catch( std::exception& ex ) { std::cerr << "csv-time-stamp: " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << "csv-time-stamp: unknown exception" << std::endl; }
    usage();
}
Example #17
0
int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
				   LPSTR lpCmdLine, int nCmdShow)
{
	HWND hwnd;
	char buf[2048];
	int tmp;
	HANDLE lib;
	void pascal (*regxx)(HANDLE);
	void pascal (*regxy)(HANDLE);
	HANDLE mutex;

        /* create_pnglib();
	exit(1); */

	parse_cmd(lpCmdLine);

	mutex=CreateMutex(NULL,0,"MOAB");
	if (mutex==NULL || GetLastError()==ERROR_ALREADY_EXISTS && strcmp(host_addr,"192.168.42.1")) {
		MessageBox(0,"Another instance of "MNAME" is already running.","Error",MB_OK|MB_ICONSTOP);
		return 0;
	}

	lib=LoadLibrary("CTL3D32.DLL");
	if (lib) {
		regxx=(void pascal *)GetProcAddress(lib,"Ctl3dRegister");
		if (regxx) regxx(GetCurrentProcess());
		ctl3don=(void pascal *)GetProcAddress(lib,"Ctl3dSubclassDlg");
		regxy=(void pascal *)GetProcAddress(lib,"Ctl3dUnregister");
	} else {
		regxy=NULL;
		ctl3don=NULL;
	}

	dlg_col=GetSysColor(COLOR_BTNFACE);
	dlg_back=CreateSolidBrush(dlg_col);
	dlg_fcol=GetSysColor(COLOR_WINDOWTEXT);

	hwnd=InitWindow(hInstance,nCmdShow);

	load_options();
	init_engine();
	options();
	if (quit) exit(0);

	init_sound(hwnd);

	if ((tmp=dd_init(hwnd,MODEX,MODEY))!=0) {

		sprintf(buf,"|DDERROR=%d",-tmp);
		say(buf);
		Sleep(1000);

		sprintf(buf,
				"DirectX init failed with code %d.\n"
				"DDError=%s\n"
				"Client Version %d.%02d.%02d\n"
				"MAXX=%d, MAXY=%d\n"
				"R=%04X, G=%04X, B=%04X\n"
				"RGBM=%d\n"
				"MAXCACHE=%d\n",
				-tmp,DDERR,VERSION>>16,(VERSION>>8)&255,VERSION&255,MAXX,MAXY,RED,GREEN,BLUE,RGBM,MAXCACHE);
		MessageBox(hwnd,buf,"DirectX init failed.",MB_ICONSTOP|MB_OK);
		exit(1);
	}
Example #18
0
 Option get_option() const
 {
   option_set options(get_options());
   return options.get_option<Option>();
 }
Example #19
0
int main( int ac, char* av[] ) {

  try {

    std::cout << "FE analysis of Ducati steel trellis frame using FELyX\n";
   
    // PROGRAM OPTIONS
    // ---------------
    // Declare a group of options that will be allowed only on command line
    po::options_description generic( "Generic options" );
    unsigned noise;
    generic.add_options()
    ( "version,v", "Print version string" )
    ( "help,h", "Produce help message" )
    ( "noise,n", po::value<unsigned>( &noise ) ->default_value( 2 ), "Verbosity level (0-2)" )
    ;

    // Declare groups of options that will be allowed both on command line and in config file
    po::options_description solution( "Solution strategies" );
    std::string bwalgo, solver;
    solution.add_options()
#ifdef HAVE_PARDISO
    ( "bwalgo", po::value<std::string>( &bwalgo ) ->default_value( "mmd" ),
      "Bandwidth algorithm (mmd, sloan, reverse_sloan, cuthill_mckee, reverse_cuthill_mckee)" )
    ( "solver", po::value<std::string>( &solver ) ->default_value( "pardiso" ), "Solver (pardiso, skyline)" )
#else
    ( "bwalgo", po::value<std::string>( &bwalgo ) ->default_value( "sloan" ),
      "Bandwidth algorithm (sloan, reverse_sloan, cuthill_mckee, reverse_cuthill_mckee)" )
    ( "solver", po::value<std::string>( &solver ) ->default_value( "skyline" ), "Solver (pardiso, skyline)" )
#endif
    ;

    // Files to manage
    po::options_description files( "Files" );
    files.add_options()
    ( "model-path", po::value<std::string>() ->default_value( "DucatiFrameFEModel.ansys" ),
      "Finite Element model to be used" )
    ( "res-path", po::value<std::string>() ->default_value( "DucatiFrame.objectives" ),
      "Path to result file where objective values are stored" )
    ( "param-format", po::value<std::string>() ->default_value( "DoubleList" ),
      "Format of param file to read" )
    ( "param-path", po::value<std::string>() ->default_value( "DoubleList.params" ),
      "Path to parameter file")
    ;

    // Put the different option containers together
    po::options_description options( "\nFELyX usage: program [options] model_path \nAllowed options" );
    options.add( generic ).add( solution ).add( files );

    // Store options in variables_map
    po::variables_map vm;
    store( po::parse_command_line( ac, av, options ), vm );
    notify( vm );

    // Define reactions for the different options
    if ( vm.count( "help" ) ) {
      std::cout << options << "\n";
      return 0;
    }

    if ( vm.count( "version" ) ) {
      std::cout << "\nFELyX " << VERSION << " - The Finite Element LibrarY eXperiment \n\n";
      return 0;
    }

    fs::path ModelPath( vm[ "model-path" ].as<std::string>(), fs::native );
    fs::path ResPath  ( vm[ "res-path"   ].as<std::string>(), fs::native );
    std::string ParamFormat = vm[ "param-format"   ].as<std::string>();
    fs::path ParamPath( vm[ "param-path"   ].as<std::string>(), fs::native );

    
    // RUN FEA ANALYSIS
    //StructObject FEM(ModelPath.leaf(), fs::complete(ModelPath).branch_path().native_file_string(),noise );

    DucFelyxObject FEM( noise, 15, ModelPath );
   
    FEM.NodesReordering( bwalgo );

    FEM.updateTubeProperties(ParamPath,ParamFormat);
    
    // Save new model, if needed
    // FEM.SaveAnsysModel();
    
    FEM.ApplyTorsionLoadcase();

    if ( solver == "skyline" )
      FEM.DirectSolver();
    else if ( solver == "pardiso" )
      FEM.SparseSolver();
    else
      std::cerr << "WARNING: No valid solver type specified, evaluating nothing!\n ";

    double Stiffness= FEM.EvalTorsionStiffness();

    FEM.ApplyBrakingLoadcase();

    if ( solver == "skyline" )
      FEM.DirectSolver();
    else if ( solver == "pardiso" )
      FEM.SparseSolver();
    else
      std::cerr << "WARNING: No valid solver type specified, evaluating nothing!\n ";

    double MaxStress= FEM.EvalMaxStress( 1, 2 ) ;

    double Mass= FEM.EvalMass(1,2);
    
    exportObjectives( ResPath, Mass, Stiffness, MaxStress);
     
  }

  // Catch exceptions
  catch ( std::exception & e ) {
    cerr << e.what() << endl;
    return 1;
  }

  std::cout << "FELyX analysis done\n";

  return 0;
}
Example #20
0
void CEigenLSS::solve()
{
#ifdef CF3_HAVE_TRILINOS
  Timer timer;
  const Uint nb_rows = size();
  cf3_assert(nb_rows == m_system_matrix.outerSize());

  Epetra_SerialComm comm;
  Epetra_Map map(nb_rows, 0, comm);

  Epetra_Vector ep_rhs(View, map, m_rhs.data());
  Epetra_Vector ep_sol(View, map, m_solution.data());

  // Count non-zeros
  std::vector<int> nnz(nb_rows, 0);
  for(int row=0; row < nb_rows; ++row)
  {
    for(MatrixT::InnerIterator it(m_system_matrix, row); it; ++it)
    {
      ++nnz[row];
    }
    cf3_assert(nnz[row]);
  }

  Epetra_CrsMatrix ep_A(Copy, map, &nnz[0]);
  time_matrix_construction = timer.elapsed(); timer.restart();

  // Fill the matrix
  for(int row=0; row < nb_rows; ++row)
  {
    std::vector<int> indices; indices.reserve(nnz[row]);
    std::vector<Real> values; values.reserve(nnz[row]);
    for(MatrixT::InnerIterator it(m_system_matrix, row); it; ++it)
    {
      indices.push_back(it.col());
      values.push_back(it.value());
    }
    ep_A.InsertGlobalValues(row, nnz[row], &values[0], &indices[0]);
  }

  ep_A.FillComplete();

  time_matrix_fill = timer.elapsed(); timer.restart();

///////////////////////////////////////////////////////////////////////////////////////////////
//BEGIN////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

  Teuchos::RCP<Epetra_CrsMatrix> epetra_A=Teuchos::rcpFromRef(ep_A);
  Teuchos::RCP<Epetra_Vector>    epetra_x=Teuchos::rcpFromRef(ep_sol);
  Teuchos::RCP<Epetra_Vector>    epetra_b=Teuchos::rcpFromRef(ep_rhs);

  const URI config_uri = options().option("config_file").value<URI>();
  const std::string config_path = config_uri.path();

  Stratimikos::DefaultLinearSolverBuilder linearSolverBuilder(config_path); // the most important in general setup

  Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); // TODO: decouple from fancyostream to ostream or to C stdout when possible
  typedef Teuchos::ParameterList::PrintOptions PLPrintOptions;
  Teuchos::CommandLineProcessor  clp(false); // false: don't throw exceptions

  Teuchos::RCP<const Thyra::LinearOpBase<double> > A = Thyra::epetraLinearOp( epetra_A );
  Teuchos::RCP<Thyra::VectorBase<double> >         x = Thyra::create_Vector( epetra_x, A->domain() );
  Teuchos::RCP<const Thyra::VectorBase<double> >   b = Thyra::create_Vector( epetra_b, A->range() );

  // r = b - A*x, initial L2 norm
  double nrm_r=0.;
  Real systemResidual=-1.;
  {
    Epetra_Vector epetra_r(*epetra_b);
    Epetra_Vector epetra_A_x(epetra_A->OperatorRangeMap());
    epetra_A->Apply(*epetra_x,epetra_A_x);
    epetra_r.Update(-1.0,epetra_A_x,1.0);
    epetra_r.Norm2(&nrm_r);
  }

  // Reading in the solver parameters from the parameters file and/or from
  // the command line.  This was setup by the command-line options
  // set by the setupCLP(...) function above.
  linearSolverBuilder.readParameters(0); // out.get() if want confirmation about the xml file within trilinos
  Teuchos::RCP<Thyra::LinearOpWithSolveFactoryBase<double> > lowsFactory = linearSolverBuilder.createLinearSolveStrategy(""); // create linear solver strategy
  lowsFactory->setVerbLevel(Teuchos::VERB_NONE); // set verbosity

//  // print back default and current settings
//  if (opts->trilinos.dumpDefault!=0) {
//    fflush(stdout); cout << flush;
//    _MMESSAGE_(0,1,"Dumping Trilinos/Stratimikos solver defaults to files: 'trilinos_default.txt' and 'trilinos_default.xml'...\n");
//    fflush(stdout); cout << flush;
//    std::ofstream ofs("./trilinos_default.txt");
//    linearSolverBuilder.getValidParameters()->print(ofs,PLPrintOptions().indent(2).showTypes(true).showDoc(true)); // the last true-false is the deciding about whether printing documentation to option or not
//    ofs.flush();ofs.close();
//    ofs.open("./trilinos_default.xml");
//    Teuchos::writeParameterListToXmlOStream(*linearSolverBuilder.getValidParameters(),ofs);
//    ofs.flush();ofs.close();
//  }
//  if (opts->trilinos.dumpCurrXML!=0) {
//    fflush(stdout); cout << flush;
//    _MMESSAGE_(0,1,"Dumping Trilinos/Stratimikos current settings to file: 'trilinos_current.xml'...\n");
//    fflush(stdout); cout << flush;
//    linearSolverBuilder.writeParamsFile(*lowsFactory,"./trilinos_current.xml");
//  }

  time_solver_setup = timer.elapsed(); timer.restart();

  // solve the matrix
  Teuchos::RCP<Thyra::LinearOpWithSolveBase<double> > lows = Thyra::linearOpWithSolve(*lowsFactory, A); // create solver
  lows->solve(Thyra::NOTRANS, *b, x.ptr()); // solve

  time_solve = timer.elapsed(); timer.restart();

  // r = b - A*x, final L2 norm
  {
    Epetra_Vector epetra_r(*epetra_b);
    Epetra_Vector epetra_A_x(epetra_A->OperatorRangeMap());
    epetra_A->Apply(*epetra_x,epetra_A_x);
    epetra_r.Update(-1.0,epetra_A_x,1.0);
    systemResidual=1./nrm_r;
    nrm_r=0.;
    epetra_r.Norm2(&nrm_r);
    systemResidual*=nrm_r;
  }

  time_residual = timer.elapsed();

///////////////////////////////////////////////////////////////////////////////////////////////
//END//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

#else // no trilinos

#ifdef CF3_HAVE_SUPERLU
  Eigen::SparseMatrix<Real> A(m_system_matrix);
  Eigen::SparseLU<Eigen::SparseMatrix<Real>,Eigen::SuperLU> lu_of_A(A);
  if(!lu_of_A.solve(rhs(), &m_solution))
    throw common::FailedToConverge(FromHere(), "Solution failed.");
#else // no trilinos and no superlu
  RealMatrix A(m_system_matrix);
  Eigen::FullPivLU<RealMatrix> lu_of_A(A);
  m_solution = lu_of_A.solve(m_rhs);
#endif // end ifdef superlu

#endif // end ifdef trilinos

}
Example #21
0
 PSUADEDaceAlgorithmOptions PSUADEDaceAlgorithm_Impl::psuadedaceAlgorithmOptions() const {
   return options().cast<PSUADEDaceAlgorithmOptions>();
 }
Example #22
0
/*
 - main - do the simple case, hand off to regress() for regression
 */
int
main(int argc, char *argv[])

{
	regex_t re;
#	define	NS	10
	regmatch_t subs[NS];
	char erbuf[100];
	int err;
	size_t len;
	int c;
	int errflg = 0;
	register int i;
	extern int optind;
	extern char *optarg;

	progname = argv[0];

	while ((c = getopt(argc, argv, "c:e:S:E:x")) != -1)
		switch (c) {
		case 'c':	/* compile options */
			copts = options('c', optarg);
			break;
		case 'e':	/* execute options */
			eopts = options('e', optarg);
			break;
		case 'S':	/* start offset */
			startoff = (regoff_t)atoi(optarg);
			break;
		case 'E':	/* end offset */
			endoff = (regoff_t)atoi(optarg);
			break;
		case 'x':	/* Debugging. */
			debug++;
			break;
		case '?':
		default:
			errflg++;
			break;
		}
	if (errflg) {
		fprintf(stderr, "usage: %s ", progname);
		fprintf(stderr, "[-c copt][-C][-d] [re]\n");
		exit(2);
	}

	if (optind >= argc) {
		regress(stdin);
		exit(status);
	}

	err = regcomp(&re, argv[optind++], copts);
	if (err) {
		len = regerror(err, &re, erbuf, sizeof(erbuf));
		fprintf(stderr, "error %s, %zu/%zu `%s'\n",
			eprint(err), len, sizeof(erbuf), erbuf);
		exit(status);
	}
	regprint(&re, stdout);	

	if (optind >= argc) {
		regfree(&re);
		exit(status);
	}

	if (eopts&REG_STARTEND) {
		subs[0].rm_so = startoff;
		subs[0].rm_eo = strlen(argv[optind]) - endoff;
	}
	err = regexec(&re, argv[optind], (size_t)NS, subs, eopts);
	if (err) {
		len = regerror(err, &re, erbuf, sizeof(erbuf));
		fprintf(stderr, "error %s, %zu/%zu `%s'\n",
			eprint(err), len, sizeof(erbuf), erbuf);
		exit(status);
	}
	if (!(copts&REG_NOSUB)) {
		len = (size_t)(subs[0].rm_eo - subs[0].rm_so);
		if (subs[0].rm_so != -1) {
			if (len != 0)
				printf("match `%.*s'\n", (int)len,
					argv[optind] + subs[0].rm_so);
			else
				printf("match `'@%.1s\n",
					argv[optind] + subs[0].rm_so);
		}
		for (i = 1; i < NS; i++)
			if (subs[i].rm_so != -1)
				printf("(%d) `%.*s'\n", i,
					(int)(subs[i].rm_eo - subs[i].rm_so),
					argv[optind] + subs[i].rm_so);
	}
	exit(status);
}
Example #23
0
int
main(int argc, char *argv[])
{
	const char *tmpdir;
	size_t tdlen;

	(void) setlocale(LC_ALL, "");
	listf = stderr;
	/*
	 * Keep a reference to cwd, so we can always come back home.
	 */
	cwdfd = open(".", O_RDONLY);
	if (cwdfd < 0) {
		syswarn(0, errno, "Can't open current working directory.");
		return(exit_val);
	}

	/*
	 * Where should we put temporary files?
	 */
	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
		tmpdir = _PATH_TMP;
	tdlen = strlen(tmpdir);
	while(tdlen > 0 && tmpdir[tdlen - 1] == '/')
		tdlen--;
	tempfile = malloc(tdlen + 1 + sizeof(_TFILE_BASE));
	if (tempfile == NULL) {
		paxwarn(1, "Cannot allocate memory for temp file name.");
		return(exit_val);
	}
	if (tdlen)
		memcpy(tempfile, tmpdir, tdlen);
	tempbase = tempfile + tdlen;
	*tempbase++ = '/';

	/*
	 * parse options, determine operational mode, general init
	 */
	options(argc, argv);
	if ((gen_init() < 0) || (tty_init() < 0))
		return(exit_val);

	/*
	 * select a primary operation mode
	 */
	switch(act) {
	case EXTRACT:
		extract();
		break;
	case ARCHIVE:
		archive();
		break;
	case APPND:
		if (gzip_program != NULL)
			err(1, "can not gzip while appending");
		append();
		break;
	case COPY:
		copy();
		break;
	default:
	case LIST:
		list();
		break;
	}
	return(exit_val);
}
Example #24
0
int main(int argc, char **argv) {

  // Parameters
  po::variables_map vm = get_parameters(argc,argv);
  // vector for options values
  std::vector<str> opt;

  // Read PDB
  IMP_NEW(IMP::Model, smodel, ());
  IMP::Pointer<atom::ATOMPDBSelector> ssel= new atom::ATOMPDBSelector();
  // Read only first model
  if(digest_parameter("i",vm,opt) == false) {
      std::cout << "Input file not found or missing parameter." << std::endl;
      exit(0);
  }
  atom::Hierarchy smh = atom::read_pdb(opt[0],smodel,ssel,true);
  IMP::ParticlesTemp sps = core::get_leaves(smh);
//  atom::add_radii(smh);
  double resolution = vm["res"].as<double>();
  IMP_NEW(em2d::SpiderImageReaderWriter,  srw, ());
  IMP_NEW(em::MRCReaderWriter,  mrw, ());


  // Generate a map
  if(digest_parameter("map",vm,opt)) {
    if( check_parameters(vm,"apix") == false) {
      std::cerr << "The requested --map option is missing "
                   "additional parameters"  << std::endl;
      std::exit(0);
    }
    double apix= vm["apix"].as<double>();
    str fn_map= vm["map"].as<str>();
    std::cout << "Generating map ... " << fn_map << std::endl;
    em::SampledDensityMap *map= new em::SampledDensityMap(sps,resolution,apix);
    em::write_map(map,fn_map.c_str(),mrw);
  }

  // Project IMAGES
  if( vm.count("proj_img")) {
    if(check_parameters(vm,"np,apix,size_i,proj_dist,proj_params") == false) {
      std::cerr << "--proj is missing additional parameters." << std::endl;
      std::exit(0);
    }
    // Parameters
    unsigned int np=vm["np"].as<unsigned int>();
    double apix       = vm["apix"].as<double>();
    digest_parameter("size_i",vm,opt);
    unsigned int cols = std::atoi(opt[0].c_str());
    unsigned int rows =std::atoi(opt[1].c_str());
    digest_parameter("proj_dist",vm,opt);
    em2d::RegistrationResults registration_values=
                            get_registration_values(opt,np);
    em2d::ProjectingOptions options( apix, resolution);
    em2d::Images projections = em2d::get_projections(sps,
                                                     registration_values,
                                                     rows,
                                                     cols,
                                                     options);
    // Normalize and add noise if requested
    np = registration_values.size(); // for the case when the values are read
    if(vm.count("SNR")) {
      double SNR = vm["SNR"].as<double>();
      for (unsigned int i=0;i<np;++i) {
        em2d::do_normalize(projections[i]);
        // Noise added of mean = 0  and stddev = stddev_signal / sqrt(SNR)
        // As the image is normalized, stddev_signal is 1.0
        em2d::add_noise(
                  projections[i]->get_data(),0.0,1./sqrt(SNR), "gaussian");
      }
    }
    // Save projections and projection parameters
    IMP::Strings proj_names;
    if(digest_parameter("proj_names",vm,opt)) {
      proj_names = em2d::read_selection_file(opt[0]);
    } else {
      proj_names = em2d::create_filenames(np,"proj","spi");
    }
    for (unsigned int i=0;i<np;++i) {
      projections[i]->write(proj_names[i],srw);
    }
    if(digest_parameter("proj_params",vm,opt)) {
      em2d::write_registration_results(opt[0],registration_values);
    }
  }

  // Project PDBs
  if(vm.count("proj_pdb")) {
    IMP::String param_error = "More parameters are required with --proj_pdb\n";
    IMP_USAGE_CHECK(check_parameters(vm,"np,proj_dist"),param_error);
    // Parameters
    unsigned int np=vm["np"].as<unsigned int>();
    digest_parameter("proj_dist",vm,opt);
    em2d::RegistrationResults registration_values=
                      get_registration_values(opt,np);
    np = registration_values.size(); // for the case when the values are read
    // Get coordinates
    unsigned int n_atoms=sps.size();
    alg::Vector3Ds pdb_atoms(n_atoms);
    for (unsigned i=0;i<n_atoms;++i ) {
      core::XYZ xyz(sps[i]);
      pdb_atoms[i] = xyz.get_coordinates();
    }
    alg::Vector3D centroid = alg::get_centroid(pdb_atoms);
    // Project
    IMP::Strings proj_names;
    if(vm.count("proj_names")) {
      proj_names=em2d::read_selection_file(vm["proj_names"].as<IMP::String>());
    } else {
      proj_names = em2d::create_filenames(np,"proj","pdb");
    }
    for(unsigned int i=0;i<np;++i) {
      // To project vectors here, the shift is understood a as translation
      alg::Vector3D translation = registration_values[i].get_shift_3d();
      alg::Rotation3D R = registration_values[i].get_rotation();
      alg::Vector2Ds projected_points=
                em2d::do_project_vectors(pdb_atoms,R,translation,centroid);
      // Save projection
      em2d::write_vectors_as_pdb(projected_points,proj_names[i]);
    }
    // Save projection parameters
    if(digest_parameter("proj_params",vm,opt)) {
      em2d::write_registration_results(opt[0],registration_values);
    }
  }
}
Example #25
0
File: ui.cpp Project: JUX84/3tXc4
void ui ( void ) { // main menu

	uint8_t selected ( 1 );
	uint8_t defaultHeight ( 5 );
	uint8_t defaultWidth ( 5 );
	uint8_t defaultAlignWinSize ( 5 );
	uint8_t defaultAlignWinTotal ( 1 );
	uint8_t defaultAI_prof ( 3 );
	int32_t Key;
	uint8_t row , col;

	while ( true ) {

		clear ();

		getmaxyx ( stdscr , row , col );

		if ( selected < 1 )
			selected = 1;

		if ( selected > 3 )
			selected = 3;

		attron ( A_BOLD );

		mvprintw ( row / 4 , ( col - STR_TITLE_GAME.length () + 1 ) / 2 , STR_TITLE_GAME.c_str () );

		mvprintw ( ( row / 2 ) + ( ( selected - 1 ) * 2 ) , 5 * col / 20 , STR_ARROW_RIGHT.c_str () );
		mvprintw ( ( row / 2 ) + ( ( selected - 1 ) * 2 ) , 15 * col / 20 , STR_ARROW_LEFT.c_str () );

		mvprintw ( 2 , 2 , STR_HELP.c_str () );

		attroff ( A_BOLD );

		mvprintw ( row / 2 , ( col - STR_PLAY.length () + 1 ) / 2 , STR_PLAY.c_str () );
		mvprintw ( ( row / 2 ) + 2 , ( col - STR_OPTIONS.length () + 1 ) / 2 , STR_OPTIONS.c_str () );
		mvprintw ( ( row / 2 ) + 4 , ( col - STR_EXIT.length () + 1 ) / 2 , STR_EXIT.c_str () );

		refresh();

		Key = getch ();

		if ( Key == KEY_DOWN )
			selected += 1;

		if ( Key == KEY_UP )
			selected -= 1;

		if ( Key == ENTER ) {

			if ( selected == 1 ) {

				play_menu ( defaultHeight , defaultWidth , defaultAlignWinSize , defaultAlignWinTotal , defaultAI_prof );
			}

			if ( selected == 2 )
				options ( defaultHeight , defaultWidth , defaultAlignWinSize , defaultAlignWinTotal , defaultAI_prof );

			if ( selected == 3 ) {
				if ( warnExit () ) {
					endwin ();
					return;
				}
			}
		}

		if ( Key == KEY_P ) {

			play_menu ( defaultHeight , defaultWidth , defaultAlignWinSize , defaultAlignWinTotal , defaultAI_prof );
		}

		if ( Key == KEY_O )
			options ( defaultHeight , defaultWidth , defaultAlignWinSize , defaultAlignWinTotal , defaultAI_prof );

		if ( Key == ESC || Key == KEY_E ) {
			if ( warnExit () ) {
				endwin ();
				return;
			}
		}

		if ( Key == KEY_F ( 5 ) )
			ui_help ();
	}
}
Example #26
0
void KDecoration::maximize(Qt::MouseButtons button)
{
    performWindowOperation(options()->operationMaxButtonClick(button));
}
Example #27
0
void WebView::unsupportedContent(QNetworkReply* pReply)
{
   bool closeAfterDownload = false;
   if (this->page()->history()->count() == 0)
   {
      /* This is for the case where a new browser window was launched just
         to show a PDF or save a file. Otherwise we would have an empty
         browser window with no history hanging around. */
      window()->hide();
      closeAfterDownload = true;
   }

   DownloadHelper* pDownloadHelper = NULL;

   QString contentType =
         pReply->header(QNetworkRequest::ContentTypeHeader).toString();
   if (contentType.contains(QRegExp(QString::fromAscii("^\\s*application/pdf($|;)"),
                                    Qt::CaseInsensitive)))
   {
      core::FilePath dir(options().scratchTempDir());

      QTemporaryFile pdfFile(QString::fromUtf8(
            dir.childPath("rstudio-XXXXXX.pdf").absolutePath().c_str()));
      pdfFile.setAutoRemove(false);
      pdfFile.open();
      pdfFile.close();

      if (pReply->isFinished())
      {
         DownloadHelper::handleDownload(pReply, pdfFile.fileName());
         openFile(pdfFile.fileName());
      }
      else
      {
         // DownloadHelper frees itself when downloading is done
         pDownloadHelper = new DownloadHelper(pReply, pdfFile.fileName());
         connect(pDownloadHelper, SIGNAL(downloadFinished(QString)),
                 this, SLOT(openFile(QString)));
      }
   }
   else
   {
      QString fileName = promptForFilename(pReply->request(), pReply);
      if (fileName.isEmpty())
      {
         pReply->abort();
         if (closeAfterDownload)
            window()->close();
      }
      else
      {
         // DownloadHelper frees itself when downloading is done
         pDownloadHelper = new DownloadHelper(pReply, fileName);
      }
   }

   if (closeAfterDownload && pDownloadHelper)
   {
      connect(pDownloadHelper, SIGNAL(downloadFinished(QString)),
              window(), SLOT(close()));
   }
}
Example #28
0
// Come here from button clicks, or commands
void TranscriptionToolBar::PlayAtSpeed(bool looped, bool cutPreview)
{
   // Can't do anything without an active project
   AudacityProject * p = GetActiveProject();
   if (!p) {
      return;
   }

   // Fixed speed play is the old method, that uses a time track.
   // VariSpeed play reuses Scrubbing.
   bool bFixedSpeedPlay = !gPrefs->ReadBool(wxT("/AudioIO/VariSpeedPlay"), true);
   // Scrubbing doesn't support note tracks, but the fixed-speed method using time tracks does.
   TrackListIterator iter(p->GetTracks());
   for (Track *t = iter.First(); t; t = iter.Next()) {
      if (t->GetKind() == Track::Note) {
         bFixedSpeedPlay = true;
         break;
      }
   }
   // Scrubbing only supports straight through play.
   // So if looped or cutPreview, we have to fall back to fixed speed.
   bFixedSpeedPlay = bFixedSpeedPlay || looped || cutPreview;
   if (bFixedSpeedPlay)
   {
      // Create a TimeTrack if we haven't done so already
      if (!mTimeTrack) {
         mTimeTrack = p->GetTrackFactory()->NewTimeTrack();
         if (!mTimeTrack) {
            return;
         }
      }
      // Set the speed range
      //mTimeTrack->SetRangeUpper((double)mPlaySpeed / 100.0);
      //mTimeTrack->SetRangeLower((double)mPlaySpeed / 100.0);
      mTimeTrack->GetEnvelope()->Flatten((double)mPlaySpeed / 100.0);
   }

   // Pop up the button
   SetButton(false, mButtons[TTB_PlaySpeed]);

   // If IO is busy, abort immediately
   if (gAudioIO->IsBusy()) {
      p->GetControlToolBar()->StopPlaying();
   }

   // Get the current play region
   double playRegionStart, playRegionEnd;
   p->GetPlayRegion(&playRegionStart, &playRegionEnd);

   // Start playing
   if (playRegionStart < 0)
      return;
   if (bFixedSpeedPlay)
   {
      AudioIOStartStreamOptions options(p->GetDefaultPlayOptions());
      options.playLooped = looped;
      // No need to set cutPreview options.
      // Due to a rather hacky approach, the appearance is used
      // to signal use of cutpreview to code below.
      options.timeTrack = mTimeTrack.get();
      ControlToolBar::PlayAppearance appearance =
         cutPreview ? ControlToolBar::PlayAppearance::CutPreview
         : looped ? ControlToolBar::PlayAppearance::Looped
         : ControlToolBar::PlayAppearance::Straight;
      p->GetControlToolBar()->PlayPlayRegion
         (SelectedRegion(playRegionStart, playRegionEnd),
            options,
            PlayMode::normalPlay,
            appearance);
   }
   else
   {
      Scrubber &Scrubber = p->GetScrubber();
      Scrubber.StartSpeedPlay(GetPlaySpeed(), playRegionStart, playRegionEnd);
   }
}
Example #29
0
	int main(int argc, char** argv)
	{
		boost::program_options::options_description options("Usage");
		options.add_options()
			("gridGraph", boost::program_options::value<int>(), "(int) The dimension of the square grid graph to use.")
			("graphFile", boost::program_options::value<std::string>(), "(string) The path to a graphml file. ")
			("completeGraph", boost::program_options::value<int>(), "(int) The number of vertices of the complete graph to use. ")
			("opProbability", boost::program_options::value<std::string>(), "(float) The probability that an edge is operational")
			("seed", boost::program_options::value<int>(), "(int) The random seed used to generate the random graphs")
			("pointSize", boost::program_options::value<float>(), "(float) The size of graph vertices. Defaults to 0.1")
			("interestVertices", boost::program_options::value<std::vector<int> >()->multitoken(), "(int) The vertices of interest, that should be connected. ")
			("help", "Display this message");

#if defined(_WIN32) && defined(_MSC_VER)
		redirectConsoleOutput();
#endif
		boost::program_options::variables_map variableMap;
		try
		{
			boost::program_options::store(boost::program_options::parse_command_line(argc, argv, options), variableMap);
		}
		catch(boost::program_options::error& ee)
		{
			std::cerr << "Error parsing command line arguments: " << ee.what() << std::endl << std::endl;
			std::cerr << options << std::endl;
			std::cerr << "Only one of gridGraph, graphFile and completeGraph can be specified" << std::endl;
			return -1;
		}
		if(variableMap.count("help") > 0)
		{
			std::cout << options << std::endl;
			std::cout << "Only one of gridGraph, graphFile and completeGraph can be specified" << std::endl;
			return 0;
		}

		boost::mt19937 randomSource;
		readSeed(variableMap, randomSource);

		mpfr_class probability;
		if(!readProbabilityString(variableMap, probability))
		{
			std::cout << "Please enter a single value for input `opProbability'" << std::endl;
			return 0;
		}

		Context context = Context::emptyContext();
		if(!readContext(variableMap, context, probability))
		{
			return 0;
		}
#if defined(_WIN32)
		registerQTPluginDir();
#endif
		
		float pointSize = 0.1f;
		if(variableMap.count("pointSize") >= 1)
		{
			pointSize = variableMap["pointSize"].as<float>();
		}
		
		QApplication app(argc, argv);
		observationVisualiser viewer(context, randomSource, pointSize);
		viewer.show();
		app.exec();
		return 0;
	}
Example #30
0
int 
main(int c, char *v[], char *e[])
{
	register int	rflag = ttyflg;
	int		rsflag = 1;	/* local restricted flag */
	register unsigned char *flagc = flagadr;
	struct namnod	*n;

	init_sigval();
	mypid = getpid();
	mypgid = getpgid(mypid);
	mysid = getsid(mypid);

	/*
	 * initialize storage allocation
	 */

	if (stakbot == 0) {
	addblok((unsigned)0);
	}

	/*
	 * If the first character of the last path element of v[0] is "-"
	 * (ex. -sh, or /bin/-sh), this is a login shell
	 */
	if (*simple(v[0]) == '-') {
		signal(SIGXCPU, SIG_DFL);
		signal(SIGXFSZ, SIG_DFL);

		/*
		 * As the previous comment states, this is a login shell.
		 * Therefore, we set the login_shell flag to explicitly
		 * indicate this condition.
		 */
		login_shell = TRUE;
	}

	stdsigs();

	/*
	 * set names from userenv
	 */

	setup_env();

	/*
	 * Do locale processing.
	 */
	setlocale(LC_CTYPE, "");

	/*
	 * 'rsflag' is zero if SHELL variable is
	 *  set in environment and
	 *  the simple file part of the value.
	 *  is rsh
	 */
	if (n = findnam("SHELL"))
	{
		if (eq("rsh", simple(n->namval)))
			rsflag = 0;
	}

	/*
	 * a shell is also restricted if the simple name of argv(0) is
	 * rsh or -rsh in its simple name
	 */

#ifndef RES

	if (c > 0 && (eq("rsh", simple(*v)) || eq("-rsh", simple(*v))))
		rflag = 0;

#endif

	if (eq("jsh", simple(*v)) || eq("-jsh", simple(*v)))
		flags |= monitorflg;

	hcreate();
	set_dotpath();


	/*
	 * look for options
	 * dolc is $#
	 */
	dolc = options(c, (unsigned char **)v);

	if (dolc < 2)
	{
		flags |= stdflg;
		{

			while (*flagc)
				flagc++;
			*flagc++ = STDFLG;
			*flagc = 0;
		}
	}
	if ((flags & stdflg) == 0)
		dolc--;

	if ((flags & privflg) == 0) {
		register uid_t euid;
		register gid_t egid;
		register uid_t ruid;
		register gid_t rgid;

		/*
		 * Determine all of the user's id #'s for this process and
		 * then decide if this shell is being entered as a result
		 * of a fork/exec.
		 * If the effective uid/gid do NOT match and the euid/egid
		 * is < 100 and the egid is NOT 1, reset the uid and gid to
		 * the user originally calling this process.
		 */
		euid = geteuid();
		ruid = getuid();
		egid = getegid();
		rgid = getgid();
		if ((euid != ruid) && (euid < 100))
			setuid(ruid);   /* reset the uid to the orig user */
		if ((egid != rgid) && ((egid < 100) && (egid != 1)))
			setgid(rgid);   /* reset the gid to the orig user */
	}

	dolv = (unsigned char **)v + c - dolc;
	dolc--;

	/*
	 * return here for shell file execution
	 * but not for parenthesis subshells
	 */
	if (setjmp(subshell)) {
		freejobs();
		flags |= subsh;
	}

	/*
	 * number of positional parameters
	 */
	replace(&cmdadr, dolv[0]);	/* cmdadr is $0 */

	/*
	 * set pidname '$$'
	 */
	assnum(&pidadr, (long)mypid);

	/*
	 * set up temp file names
	 */
	settmp();

	/*
	 * default internal field separators
	 * Do not allow importing of IFS from parent shell.
	 * setup_env() may have set anything from parent shell to IFS.
	 * Always set the default ifs to IFS.
	 */
	assign(&ifsnod, sptbnl);

	dfault(&timeoutnod, "0");
	timeoutnod.namflg |= N_RDONLY;

	dfault(&mchknod, MAILCHECK);
	mailchk = stoi(mchknod.namval);

	/* initialize OPTIND for getopt */

	n = lookup("OPTIND");
	assign(n, "1");
	/*
	 * make sure that option parsing starts
	 * at first character
	 */
	getopt_sp = 1;

	/* initialize multibyte information */
	setwidth();

	if ((beenhere++) == FALSE)	/* ? profile */
	{
		if ((login_shell == TRUE) && (flags & privflg) == 0) {

			/* system profile */

#ifndef RES

			if ((input = pathopen(nullstr, sysprofile)) >= 0)
				exfile(rflag);		/* file exists */

#endif
			/* user profile */

			if ((input = pathopen(homenod.namval, profile)) >= 0)
			{
				exfile(rflag);
				flags &= ~ttyflg;
			}
		}
		if (rsflag == 0 || rflag == 0) {
			if ((flags & rshflg) == 0) {
				while (*flagc)
					flagc++;
				*flagc++ = 'r';
				*flagc = '\0';
			}
			flags |= rshflg;
		}

		/*
		 * open input file if specified
		 */
		if (comdiv)
		{
			estabf(comdiv);
			input = -1;
		}
		else
		{
			if (flags & stdflg) {
				input = 0;
			} else {
			/*
			 * If the command file specified by 'cmdadr'
			 * doesn't exist, chkopen() will fail calling
			 * exitsh(). If this is a login shell and
			 * the $HOME/.profile file does not exist, the
			 * above statement "flags &= ~ttyflg" does not
			 * get executed and this makes exitsh() call
			 * longjmp() instead of exiting. longjmp() will
			 * return to the location specified by the last
			 * active jmpbuffer, which is the one set up in
			 * the function exfile() called after the system
			 * profile file is executed (see lines above).
			 * This would cause an infinite loop, because
			 * chkopen() will continue to fail and exitsh()
			 * to call longjmp(). To make exitsh() exit instead
			 * of calling longjmp(), we then set the flag forcexit
			 * at this stage.
			 */

				flags |= forcexit;
				input = chkopen(cmdadr, 0);
				flags &= ~forcexit;
			}

#ifdef ACCT
			if (input != 0)
				preacct(cmdadr);
#endif
			comdiv--;
		}
	}
#ifdef pdp11
	else
		*execargs = (char *)dolv;	/* for `ps' cmd */
#endif


	exfile(0);
	done(0);
	/*NOTREACHED*/
	return 0;
}