<commit_before>/*
 * predixy - A high performance and full features proxy for redis.
 * Copyright (C) 2017 Joyield, Inc. <joyield.com@gmail.com>
 * All rights reserved.
 */

#include <string.h>
#include <strings.h>
#include <map>
#include "String.h"
#include "Command.h"
#include "Conf.h"

Command Command::CmdPool[AvailableCommands] = {
    {None,              "",                 0,  MaxArgs,   Read},
    {Ping,              "ping",             1,  2,         Read},
    {PingServ,          "ping",             1,  2,         Inner},
    {Echo,              "echo",             2,  2,         Read},
    {Auth,              "auth",             2,  2,         Read},
    {AuthServ,          "auth",             2,  2,         Inner},
    {Select,            "select",           2,  2,         Read},
    {SelectServ,        "select",           2,  2,         Inner},
    {Quit,              "quit",             1,  MaxArgs,   Read},
    {SentinelSentinels, "sentinel sentinels",3, 3,         Inner},
    {SentinelGetMaster, "sentinel get-m-a..",3, 3,         Inner},
    {SentinelSlaves,    "sentinel slaves",  3,  3,         Inner},
    {Cmd,               "command",          1,  1,         Read},
    {Info,              "info",             1,  4,         Read},
    {Config,            "config",           2,  4,         Admin},
    {Cluster,           "cluster",          2,  2,         Inner},
    {ClusterNodes,      "cluster nodes",    2,  2,         SubCmd|Inner},
    {Asking,            "asking",           1,  1,         Inner},
    {Readonly,          "readonly",         1,  1,         Inner},
    {Watch,             "watch",            2,  MaxArgs,   Write|Private},
    {Unwatch,           "unwatch",          1,  1,         Write},
    {UnwatchServ,       "unwatch",          1,  1,         Inner},
    {Multi,             "multi",            1,  1,         Write|Private|NoKey},
    {Exec,              "exec",             1,  1,         Write|NoKey},
    {Discard,           "discard",          1,  1,         Write|NoKey},
    {DiscardServ,       "discard",          1,  1,         Inner|NoKey},
    {Eval,              "eval",             3,  MaxArgs,   Write|KeyAt3},
    {Evalsha,           "evalsha",          3,  MaxArgs,   Write|KeyAt3},
    {Script,            "script",           2,  MaxArgs,   Write},
    {ScriptLoad,        "script",           3,  3,         Write|SubCmd},
    {Del,               "del",              2,  MaxArgs,   Write|MultiKey},
    {Dump,              "dump",             2,  2,         Read},
    {Exists,            "exists",           2,  MaxArgs,   Read|MultiKey},
    {Expire,            "expire",           3,  3,         Write},
    {Expireat,          "expireat",         3,  3,         Write},
    {Move,              "move",             3,  3,         Write},
    {Persist,           "persist",          2,  2,         Write},
    {Pexpire,           "pexpire",          3,  3,         Write},
    {Pexpireat,         "pexpireat",        3,  3,         Write},
    {Pttl,              "pttl",             2,  2,         Read},
    {Randomkey,         "randomkey",        1,  1,         Read|NoKey},
    {Rename,            "rename",           3,  3,         Write},
    {Renamenx,          "renamenx",         3,  3,         Write},
    {Restore,           "restore",          4,  5,         Write},
    {Sort,              "sort",             2,  MaxArgs,   Write},
    {Touch,             "touch",            2,  MaxArgs,   Write|MultiKey},
    {Ttl,               "ttl",              2,  2,         Read},
    {TypeCmd,           "type",             2,  2,         Read},
    {Unlink,            "unlink",           2,  MaxArgs,   Write|MultiKey},
    {Scan,              "scan",             2,  6,         Read},
    {Append,            "append",           3,  3,         Write},
    {Bitcount,          "bitcount",         2,  4,         Read},
    {Bitfield,          "bitfield",         2,  MaxArgs,   Write},
    {Bitop,             "bitop",            4,  MaxArgs,   Write|KeyAt2},
    {Bitpos,            "bitpos",           3,  5,         Read},
    {Decr,              "decr",             2,  2,         Write},
    {Decrby,            "decrby",           3,  3,         Write},
    {Get,               "get",              2,  2,         Read},
    {Getbit,            "getbit",           3,  3,         Read},
    {Getrange,          "getrange",         4,  4,         Read},
    {Getset,            "getset",           3,  3,         Write},
    {Incr,              "incr",             2,  2,         Write},
    {Incrby,            "incrby",           3,  3,         Write},
    {Incrbyfloat,       "incrbyfloat",      3,  3,         Write},
    {Mget,              "mget",             2,  MaxArgs,   Read|MultiKey},
    {Mset,              "mset",             3,  MaxArgs,   Write|MultiKeyVal},
    {Msetnx,            "msetnx",           3,  MaxArgs,   Write|MultiKeyVal},
    {Psetex,            "psetex",           4,  4,         Write},
    {Set,               "set",              3,  8,         Write},
    {Setbit,            "setbit",           4,  4,         Write},
    {Setex,             "setex",            4,  4,         Write},
    {Setnx,             "setnx",            3,  3,         Write},
    {Setrange,          "setrange",         4,  4,         Write},
    {Strlen,            "strlen",           2,  2,         Read},
    {Hdel,              "hdel",             3,  MaxArgs,   Write},
    {Hexists,           "hexists",          3,  3,         Read},
    {Hget,              "hget",             3,  3,         Read},
    {Hgetall,           "hgetall",          2,  2,         Read},
    {Hincrby,           "hincrby",          4,  4,         Write},
    {Hincrbyfloat,      "hincrbyfloat",     4,  4,         Write},
    {Hkeys,             "hkeys",            2,  2,         Read},
    {Hlen,              "hlen",             2,  2,         Read},
    {Hmget,             "hmget",            3,  MaxArgs,   Read},
    {Hmset,             "hmset",            4,  MaxArgs,   Write},
    {Hscan,             "hscan",            3,  7,         Read},
    {Hset,              "hset",             4,  4,         Write},
    {Hsetnx,            "hsetnx",           4,  4,         Write},
    {Hstrlen,           "hstrlen",          3,  3,         Read},
    {Hvals,             "hvals",            2,  2,         Read},
    {Blpop,             "blpop",            3,  MaxArgs,   Write|Private},
    {Brpop,             "brpop",            3,  MaxArgs,   Write|Private},
    {Brpoplpush,        "brpoplpush",       4,  4,         Write|Private},
    {Lindex,            "lindex",           3,  3,         Read},
    {Linsert,           "linsert",          5,  5,         Write},
    {Llen,              "llen",             2,  2,         Read},
    {Lpop,              "lpop",             2,  2,         Write},
    {Lpush,             "lpush",            3,  MaxArgs,   Write},
    {Lpushx,            "lpushx",           3,  3,         Write},
    {Lrange,            "lrange",           4,  4,         Read},
    {Lrem,              "lrem",             4,  4,         Write},
    {Lset,              "lset",             4,  4,         Write},
    {Ltrim,             "ltrim",            4,  4,         Write},
    {Rpop,              "rpop",             2,  2,         Write},
    {Rpoplpush,         "rpoplpush",        3,  3,         Write},
    {Rpush,             "rpush",            3,  MaxArgs,   Write},
    {Rpushx,            "rpushx",           3,  3,         Write},
    {Sadd,              "sadd",             3,  MaxArgs,   Write},
    {Scard,             "scard",            2,  2,         Read},
    {Sdiff,             "sdiff",            2,  MaxArgs,   Read},
    {Sdiffstore,        "sdiffstore",       3,  MaxArgs,   Write},
    {Sinter,            "sinter",           2,  MaxArgs,   Read},
    {Sinterstore,       "sinterstore",      3,  MaxArgs,   Write},
    {Sismember,         "sismember",        3,  3,         Read},
    {Smembers,          "smembers",         2,  2,         Read},
    {Smove,             "smove",            4,  4,         Write},
    {Spop,              "spop",             2,  3,         Write},
    {Srandmember,       "srandmember",      2,  3,         Read},
    {Srem,              "srem",             3,  MaxArgs,   Write},
    {Sscan,             "sscan",            3,  7,         Read},
    {Sunion,            "sunion",           2,  MaxArgs,   Read},
    {Sunionstore,       "sunionstore",      3,  MaxArgs,   Write},
    {Zadd,              "zadd",             4,  MaxArgs,   Write},
    {Zcard,             "zcard",            2,  2,         Read},
    {Zcount,            "zcount",           4,  4,         Read},
    {Zincrby,           "zincrby",          4,  4,         Write},
    {Zinterstore,       "zinterstore",      4,  MaxArgs,   Write},
    {Zlexcount,         "zlexcount",        4,  4,         Read},
    {Zrange,            "zrange",           4,  5,         Read},
    {Zrangebylex,       "zrangebylex",      4,  7,         Read},
    {Zrangebyscore,     "zrangebyscore",    4,  8,         Read},
    {Zrank,             "zrank",            3,  3,         Read},
    {Zrem,              "zrem",             3,  MaxArgs,   Write},
    {Zremrangebylex,    "zremrangebylex",   4,  4,         Write},
    {Zremrangebyrank,   "zremrangebyrank",  4,  4,         Write},
    {Zremrangebyscore,  "zremrangebyscore", 4,  4,         Write},
    {Zrevrange,         "zrevrange",        4,  5,         Read},
    {Zrevrangebylex,    "zrevrangebylex",   4,  7,         Read},
    {Zrevrangebyscore,  "zrevrangebyscore", 4,  8,         Read},
    {Zrevrank,          "zrevrank",         3,  3,         Read},
    {Zscan,             "zscan",            3,  7,         Read},
    {Zscore,            "zscore",           3,  3,         Read},
    {Zunionstore,       "zunionstore",      4,  MaxArgs,   Write},
    {Pfadd,             "pfadd",            3,  MaxArgs,   Write},
    {Pfcount,           "pfcount",          2,  MaxArgs,   Read},
    {Pfmerge,           "pfmerge",          3,  MaxArgs,   Write},
    {Geoadd,            "geoadd",           5,  MaxArgs,   Write},
    {Geodist,           "geodist",          4,  5,         Read},
    {Geohash,           "geohash",          3,  MaxArgs,   Read},
    {Geopos,            "geopos",           3,  MaxArgs,   Read},
    {Georadius,         "georadius",        6,  16,        Write},
    {Georadiusbymember, "georadiusbymember",5,  15,        Write},
    {Psubscribe,        "psubscribe",       2,  MaxArgs,   Write|SMultiKey|Private},
    {Publish,           "publish",          3,  3,         Write},
    {Pubsub,            "pubsub",           2,  MaxArgs,   Read},
    {Punsubscribe,      "punsubscribe",     1,  MaxArgs,   Write|SMultiKey},
    {Subscribe,         "subscribe",        2,  MaxArgs,   Write|SMultiKey|Private},
    {Unsubscribe,       "unsubscribe",      1,  MaxArgs,   Write|SMultiKey},
    {SubMsg,            "\000SubMsg",       0,  0,         Admin}
};

int Command::Sentinel = Command::MaxCommands;
Command::CommandMap Command::CmdMap;

void Command::init()
{
    int type = 0;
    for (auto j = 0; j < MaxCommands; j++) {
        const auto& i = CmdPool[j];
        if (i.type != type) {
            Throw(InitFail, "command %s unmatch the index in commands table", i.name);
        }
        ++type;
        if (i.mode & (Command::Inner|Command::SubCmd)) {
            continue;
        }
        CmdMap[i.name] = &i;
    }
}

void Command::addCustomCommand(const CustomCommandConf& ccc) {
    if (Sentinel >= AvailableCommands) {
        Throw(InitFail, "too many custom commands(>%d)", MaxCustomCommands);
    }
    if (nullptr != find(ccc.name)) {
        Throw(InitFail, "custom command %s is duplicated", ccc.name.c_str());
    }
    auto* p = &CmdPool[Sentinel];
    p->name = ccc.name.c_str();
    p->minArgs = ccc.minArgs;
    p->maxArgs = ccc.maxArgs;
    p->mode = ccc.mode;
    p->type = (Command::Type)Sentinel++;
    CmdMap[ccc.name] = p;
}

<commit_msg>Fix HSET to support multiple fields<commit_after>/*
 * predixy - A high performance and full features proxy for redis.
 * Copyright (C) 2017 Joyield, Inc. <joyield.com@gmail.com>
 * All rights reserved.
 */

#include <string.h>
#include <strings.h>
#include <map>
#include "String.h"
#include "Command.h"
#include "Conf.h"

Command Command::CmdPool[AvailableCommands] = {
    {None,              "",                 0,  MaxArgs,   Read},
    {Ping,              "ping",             1,  2,         Read},
    {PingServ,          "ping",             1,  2,         Inner},
    {Echo,              "echo",             2,  2,         Read},
    {Auth,              "auth",             2,  2,         Read},
    {AuthServ,          "auth",             2,  2,         Inner},
    {Select,            "select",           2,  2,         Read},
    {SelectServ,        "select",           2,  2,         Inner},
    {Quit,              "quit",             1,  MaxArgs,   Read},
    {SentinelSentinels, "sentinel sentinels",3, 3,         Inner},
    {SentinelGetMaster, "sentinel get-m-a..",3, 3,         Inner},
    {SentinelSlaves,    "sentinel slaves",  3,  3,         Inner},
    {Cmd,               "command",          1,  1,         Read},
    {Info,              "info",             1,  4,         Read},
    {Config,            "config",           2,  4,         Admin},
    {Cluster,           "cluster",          2,  2,         Inner},
    {ClusterNodes,      "cluster nodes",    2,  2,         SubCmd|Inner},
    {Asking,            "asking",           1,  1,         Inner},
    {Readonly,          "readonly",         1,  1,         Inner},
    {Watch,             "watch",            2,  MaxArgs,   Write|Private},
    {Unwatch,           "unwatch",          1,  1,         Write},
    {UnwatchServ,       "unwatch",          1,  1,         Inner},
    {Multi,             "multi",            1,  1,         Write|Private|NoKey},
    {Exec,              "exec",             1,  1,         Write|NoKey},
    {Discard,           "discard",          1,  1,         Write|NoKey},
    {DiscardServ,       "discard",          1,  1,         Inner|NoKey},
    {Eval,              "eval",             3,  MaxArgs,   Write|KeyAt3},
    {Evalsha,           "evalsha",          3,  MaxArgs,   Write|KeyAt3},
    {Script,            "script",           2,  MaxArgs,   Write},
    {ScriptLoad,        "script",           3,  3,         Write|SubCmd},
    {Del,               "del",              2,  MaxArgs,   Write|MultiKey},
    {Dump,              "dump",             2,  2,         Read},
    {Exists,            "exists",           2,  MaxArgs,   Read|MultiKey},
    {Expire,            "expire",           3,  3,         Write},
    {Expireat,          "expireat",         3,  3,         Write},
    {Move,              "move",             3,  3,         Write},
    {Persist,           "persist",          2,  2,         Write},
    {Pexpire,           "pexpire",          3,  3,         Write},
    {Pexpireat,         "pexpireat",        3,  3,         Write},
    {Pttl,              "pttl",             2,  2,         Read},
    {Randomkey,         "randomkey",        1,  1,         Read|NoKey},
    {Rename,            "rename",           3,  3,         Write},
    {Renamenx,          "renamenx",         3,  3,         Write},
    {Restore,           "restore",          4,  5,         Write},
    {Sort,              "sort",             2,  MaxArgs,   Write},
    {Touch,             "touch",            2,  MaxArgs,   Write|MultiKey},
    {Ttl,               "ttl",              2,  2,         Read},
    {TypeCmd,           "type",             2,  2,         Read},
    {Unlink,            "unlink",           2,  MaxArgs,   Write|MultiKey},
    {Scan,              "scan",             2,  6,         Read},
    {Append,            "append",           3,  3,         Write},
    {Bitcount,          "bitcount",         2,  4,         Read},
    {Bitfield,          "bitfield",         2,  MaxArgs,   Write},
    {Bitop,             "bitop",            4,  MaxArgs,   Write|KeyAt2},
    {Bitpos,            "bitpos",           3,  5,         Read},
    {Decr,              "decr",             2,  2,         Write},
    {Decrby,            "decrby",           3,  3,         Write},
    {Get,               "get",              2,  2,         Read},
    {Getbit,            "getbit",           3,  3,         Read},
    {Getrange,          "getrange",         4,  4,         Read},
    {Getset,            "getset",           3,  3,         Write},
    {Incr,              "incr",             2,  2,         Write},
    {Incrby,            "incrby",           3,  3,         Write},
    {Incrbyfloat,       "incrbyfloat",      3,  3,         Write},
    {Mget,              "mget",             2,  MaxArgs,   Read|MultiKey},
    {Mset,              "mset",             3,  MaxArgs,   Write|MultiKeyVal},
    {Msetnx,            "msetnx",           3,  MaxArgs,   Write|MultiKeyVal},
    {Psetex,            "psetex",           4,  4,         Write},
    {Set,               "set",              3,  8,         Write},
    {Setbit,            "setbit",           4,  4,         Write},
    {Setex,             "setex",            4,  4,         Write},
    {Setnx,             "setnx",            3,  3,         Write},
    {Setrange,          "setrange",         4,  4,         Write},
    {Strlen,            "strlen",           2,  2,         Read},
    {Hdel,              "hdel",             3,  MaxArgs,   Write},
    {Hexists,           "hexists",          3,  3,         Read},
    {Hget,              "hget",             3,  3,         Read},
    {Hgetall,           "hgetall",          2,  2,         Read},
    {Hincrby,           "hincrby",          4,  4,         Write},
    {Hincrbyfloat,      "hincrbyfloat",     4,  4,         Write},
    {Hkeys,             "hkeys",            2,  2,         Read},
    {Hlen,              "hlen",             2,  2,         Read},
    {Hmget,             "hmget",            3,  MaxArgs,   Read},
    {Hmset,             "hmset",            4,  MaxArgs,   Write},
    {Hscan,             "hscan",            3,  7,         Read},
    {Hset,              "hset",             4,  MaxArgs,   Write},
    {Hsetnx,            "hsetnx",           4,  4,         Write},
    {Hstrlen,           "hstrlen",          3,  3,         Read},
    {Hvals,             "hvals",            2,  2,         Read},
    {Blpop,             "blpop",            3,  MaxArgs,   Write|Private},
    {Brpop,             "brpop",            3,  MaxArgs,   Write|Private},
    {Brpoplpush,        "brpoplpush",       4,  4,         Write|Private},
    {Lindex,            "lindex",           3,  3,         Read},
    {Linsert,           "linsert",          5,  5,         Write},
    {Llen,              "llen",             2,  2,         Read},
    {Lpop,              "lpop",             2,  2,         Write},
    {Lpush,             "lpush",            3,  MaxArgs,   Write},
    {Lpushx,            "lpushx",           3,  3,         Write},
    {Lrange,            "lrange",           4,  4,         Read},
    {Lrem,              "lrem",             4,  4,         Write},
    {Lset,              "lset",             4,  4,         Write},
    {Ltrim,             "ltrim",            4,  4,         Write},
    {Rpop,              "rpop",             2,  2,         Write},
    {Rpoplpush,         "rpoplpush",        3,  3,         Write},
    {Rpush,             "rpush",            3,  MaxArgs,   Write},
    {Rpushx,            "rpushx",           3,  3,         Write},
    {Sadd,              "sadd",             3,  MaxArgs,   Write},
    {Scard,             "scard",            2,  2,         Read},
    {Sdiff,             "sdiff",            2,  MaxArgs,   Read},
    {Sdiffstore,        "sdiffstore",       3,  MaxArgs,   Write},
    {Sinter,            "sinter",           2,  MaxArgs,   Read},
    {Sinterstore,       "sinterstore",      3,  MaxArgs,   Write},
    {Sismember,         "sismember",        3,  3,         Read},
    {Smembers,          "smembers",         2,  2,         Read},
    {Smove,             "smove",            4,  4,         Write},
    {Spop,              "spop",             2,  3,         Write},
    {Srandmember,       "srandmember",      2,  3,         Read},
    {Srem,              "srem",             3,  MaxArgs,   Write},
    {Sscan,             "sscan",            3,  7,         Read},
    {Sunion,            "sunion",           2,  MaxArgs,   Read},
    {Sunionstore,       "sunionstore",      3,  MaxArgs,   Write},
    {Zadd,              "zadd",             4,  MaxArgs,   Write},
    {Zcard,             "zcard",            2,  2,         Read},
    {Zcount,            "zcount",           4,  4,         Read},
    {Zincrby,           "zincrby",          4,  4,         Write},
    {Zinterstore,       "zinterstore",      4,  MaxArgs,   Write},
    {Zlexcount,         "zlexcount",        4,  4,         Read},
    {Zrange,            "zrange",           4,  5,         Read},
    {Zrangebylex,       "zrangebylex",      4,  7,         Read},
    {Zrangebyscore,     "zrangebyscore",    4,  8,         Read},
    {Zrank,             "zrank",            3,  3,         Read},
    {Zrem,              "zrem",             3,  MaxArgs,   Write},
    {Zremrangebylex,    "zremrangebylex",   4,  4,         Write},
    {Zremrangebyrank,   "zremrangebyrank",  4,  4,         Write},
    {Zremrangebyscore,  "zremrangebyscore", 4,  4,         Write},
    {Zrevrange,         "zrevrange",        4,  5,         Read},
    {Zrevrangebylex,    "zrevrangebylex",   4,  7,         Read},
    {Zrevrangebyscore,  "zrevrangebyscore", 4,  8,         Read},
    {Zrevrank,          "zrevrank",         3,  3,         Read},
    {Zscan,             "zscan",            3,  7,         Read},
    {Zscore,            "zscore",           3,  3,         Read},
    {Zunionstore,       "zunionstore",      4,  MaxArgs,   Write},
    {Pfadd,             "pfadd",            3,  MaxArgs,   Write},
    {Pfcount,           "pfcount",          2,  MaxArgs,   Read},
    {Pfmerge,           "pfmerge",          3,  MaxArgs,   Write},
    {Geoadd,            "geoadd",           5,  MaxArgs,   Write},
    {Geodist,           "geodist",          4,  5,         Read},
    {Geohash,           "geohash",          3,  MaxArgs,   Read},
    {Geopos,            "geopos",           3,  MaxArgs,   Read},
    {Georadius,         "georadius",        6,  16,        Write},
    {Georadiusbymember, "georadiusbymember",5,  15,        Write},
    {Psubscribe,        "psubscribe",       2,  MaxArgs,   Write|SMultiKey|Private},
    {Publish,           "publish",          3,  3,         Write},
    {Pubsub,            "pubsub",           2,  MaxArgs,   Read},
    {Punsubscribe,      "punsubscribe",     1,  MaxArgs,   Write|SMultiKey},
    {Subscribe,         "subscribe",        2,  MaxArgs,   Write|SMultiKey|Private},
    {Unsubscribe,       "unsubscribe",      1,  MaxArgs,   Write|SMultiKey},
    {SubMsg,            "\000SubMsg",       0,  0,         Admin}
};

int Command::Sentinel = Command::MaxCommands;
Command::CommandMap Command::CmdMap;

void Command::init()
{
    int type = 0;
    for (auto j = 0; j < MaxCommands; j++) {
        const auto& i = CmdPool[j];
        if (i.type != type) {
            Throw(InitFail, "command %s unmatch the index in commands table", i.name);
        }
        ++type;
        if (i.mode & (Command::Inner|Command::SubCmd)) {
            continue;
        }
        CmdMap[i.name] = &i;
    }
}

void Command::addCustomCommand(const CustomCommandConf& ccc) {
    if (Sentinel >= AvailableCommands) {
        Throw(InitFail, "too many custom commands(>%d)", MaxCustomCommands);
    }
    if (nullptr != find(ccc.name)) {
        Throw(InitFail, "custom command %s is duplicated", ccc.name.c_str());
    }
    auto* p = &CmdPool[Sentinel];
    p->name = ccc.name.c_str();
    p->minArgs = ccc.minArgs;
    p->maxArgs = ccc.maxArgs;
    p->mode = ccc.mode;
    p->type = (Command::Type)Sentinel++;
    CmdMap[ccc.name] = p;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stack>
#include <sys/wait.h>
#include <vector>
#include <stack>
#include <queue>
#include <stdlib.h>

using namespace std;

#include "Rshell.h"
#include "Command.h"

Command::Command()
{

}

Command::Command(stack<char *> s)
{
	//builds the command into a vector<char*>
	while (!s.empty())
	{
		v.push_back(s.top());
		s.pop();
	}
	v.push_back('\0');
}

Command::~Command()
{

}

bool Command::evaluate()
{
	//evaulates the command in vector
	string exit = "exit";
	int status;
	if (!v.empty())
	{
		//if the exit command is called
		if (v.at(0) == exit)
		{
			_exit(1);
		}
	}
	pid_t child_pid = fork();
	//forks the current process to execute additional processes
	if (child_pid < 0)
	{
		cout << "Fork failed in: " << endl << "bool Command::evaluate()" << endl;
	}
	else if (child_pid == 0)
	{
		//executes the given command
		char ** vloc = &v[0];
		if (execvp(v.at(0), vloc) == -1)
		{
			cout << "-rshell: " << v.at(0) << ": command not found" << endl;
			_exit(1);
		}
	}
	else if (child_pid > 0)
	{
		//handles exit status and wait error
		if (waitpid(child_pid, &status, 0) == -1)
		{
			//cout << "wait error" << endl;
		}
		if (WEXITSTATUS(status) != 0)
		{
			return false;
		}
	}
	return true;
}

<commit_msg>perror<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stack>
#include <sys/wait.h>
#include <vector>
#include <stack>
#include <queue>
#include <stdlib.h>

using namespace std;

#include "Rshell.h"
#include "Command.h"

Command::Command()
{

}

Command::Command(stack<char *> s)
{
	//builds the command into a vector<char*>
	while (!s.empty())
	{
		v.push_back(s.top());
		s.pop();
	}
	v.push_back('\0');
}

Command::~Command()
{

}

bool Command::evaluate()
{
	//evaulates the command in vector
	string exit = "exit";
	int status;
	if (!v.empty())
	{
		//if the exit command is called
		if (v.at(0) == exit)
		{
			_exit(1);
		}
	}
	pid_t child_pid = fork();
	//forks the current process to execute additional processes
	if (child_pid < 0)
	{
		perror("fork failure");
	}
	else if (child_pid == 0)
	{
		//executes the given command
		char ** vloc = &v[0];
		if (execvp(v.at(0), vloc) == -1)
		{
			//cout << "-rshell: " << v.at(0) << ": command not found" << endl;
			perror("execvp");
			_exit(1);
		}
	}
	else if (child_pid > 0)
	{
		//handles exit status and wait error
		if (waitpid(child_pid, &status, 0) == -1)
		{
			perror("wait failed");
		}
		if (WEXITSTATUS(status) != 0)
		{
			return false;
		}
	}
	return true;
}

<|endoftext|>


<commit_before>#ifndef COFFEE_MILL_DCD_DATA
#define COFFEE_MILL_DCD_DATA
#include "math/LinearAlgebra.hpp"

namespace coffeemill
{

class DCDData
{
  public:

    using size_type       = std::size_t;
    using index_type      = size_type;
    using time_type       = double;
    using position_type   = ax::Vector3d;
    using snapshot_type   = std::vector<position_type>;
    using trajectory_type = std::vector<snapshot_type>;
    using iterator        = trajectory_type::iterator;
    using const_iterator  = trajectory_type::const_iterator;
    using string_type     = std::string;
    using header_type     = std::vector<string_type>;

  public:

    DCDData(){}
    DCDData(size_type size) : trajectory_(size){}
    ~DCDData() = default;

    size_type  nset() const {return nset_;}
    size_type& nset()       {return nset_;}
    size_type  istart() const {return istart_;}
    size_type& istart()       {return istart_;}
    size_type  nstep_save() const {return nstep_save_;}
    size_type& nstep_save()       {return nstep_save_;}
    size_type  nstep() const {return nstep_;}
    size_type& nstep()       {return nstep_;}
    size_type  nunit() const {return nunit_;}
    size_type& nunit()       {return nunit_;}
    size_type  verCHARMM() const {return verCHARMM_;}
    size_type& verCHARMM()       {return verCHARMM_;}
    size_type  nparticle() const {return nparticle_;}
    size_type& nparticle()       {return nparticle_;}
    time_type  delta_t() const {return delta_t_;}
    time_type& delta_t()       {return delta_t_;}

    const snapshot_type& front() const {return trajectory_.front();}
          snapshot_type& front()       {return trajectory_.front();}
    const snapshot_type& back() const {return trajectory_.back();}
          snapshot_type& back()       {return trajectory_.back();}
    const snapshot_type& operator[](index_type i) const {return trajectory_[i];}
          snapshot_type& operator[](index_type i)       {return trajectory_[i];}
    const snapshot_type& at(index_type i) const {return trajectory_.at(i);}
          snapshot_type& at(index_type i)       {return trajectory_.at(i);}

    const trajectory_type& traj() const {return trajectory_;}
          trajectory_type& traj()       {return trajectory_;}

    bool      empty() const {return trajectory_.empty();}
    size_type size() const {return trajectory_.size();}

    iterator begin() {return trajectory_.begin();}
    iterator end()   {return trajectory_.end();}
    const_iterator cbegin() const {return trajectory_.cbegin();}
    const_iterator cend()   const {return trajectory_.cend();}

    const header_type&     header() const {return header_;}
          header_type&     header()       {return header_;}

  private:

    size_type       nset_;
    size_type       istart_;     // initial value of isteps (nomally zero)
    size_type       nstep_save_; // nstep_save timesteps per one snapshot
    size_type       nstep_;      // total step number of the simulation
    size_type       nunit_;      // total unit number (chains??)
    size_type       verCHARMM_;  // version of CHARMM (usually unused)
    size_type       nparticle_;  // total number of particle
    time_type       delta_t_;
    header_type     header_;
    trajectory_type trajectory_;
};

}

#endif /* COFFEE_MILL_DCD_DATA */
<commit_msg>add header set function to DCDData<commit_after>#ifndef COFFEE_MILL_DCD_DATA
#define COFFEE_MILL_DCD_DATA
#include "math/LinearAlgebra.hpp"

namespace coffeemill
{

class DCDData
{
  public:

    using size_type       = std::size_t;
    using index_type      = size_type;
    using time_type       = double;
    using position_type   = ax::Vector3d;
    using snapshot_type   = std::vector<position_type>;
    using trajectory_type = std::vector<snapshot_type>;
    using iterator        = trajectory_type::iterator;
    using const_iterator  = trajectory_type::const_iterator;
    using string_type     = std::string;
    using header_type     = std::vector<string_type>;

  public:

    DCDData(){}
    DCDData(size_type size) : trajectory_(size){}
    ~DCDData() = default;

    size_type  nset() const {return nset_;}
    size_type& nset()       {return nset_;}
    size_type  istart() const {return istart_;}
    size_type& istart()       {return istart_;}
    size_type  nstep_save() const {return nstep_save_;}
    size_type& nstep_save()       {return nstep_save_;}
    size_type  nstep() const {return nstep_;}
    size_type& nstep()       {return nstep_;}
    size_type  nunit() const {return nunit_;}
    size_type& nunit()       {return nunit_;}
    size_type  verCHARMM() const {return verCHARMM_;}
    size_type& verCHARMM()       {return verCHARMM_;}
    size_type  nparticle() const {return nparticle_;}
    size_type& nparticle()       {return nparticle_;}
    time_type  delta_t() const {return delta_t_;}
    time_type& delta_t()       {return delta_t_;}

    const snapshot_type& front() const {return trajectory_.front();}
          snapshot_type& front()       {return trajectory_.front();}
    const snapshot_type& back() const {return trajectory_.back();}
          snapshot_type& back()       {return trajectory_.back();}
    const snapshot_type& operator[](index_type i) const {return trajectory_[i];}
          snapshot_type& operator[](index_type i)       {return trajectory_[i];}
    const snapshot_type& at(index_type i) const {return trajectory_.at(i);}
          snapshot_type& at(index_type i)       {return trajectory_.at(i);}

    const trajectory_type& traj() const {return trajectory_;}
          trajectory_type& traj()       {return trajectory_;}

    bool      empty() const {return trajectory_.empty();}
    size_type size() const {return trajectory_.size();}

    iterator begin() {return trajectory_.begin();}
    iterator end()   {return trajectory_.end();}
    const_iterator cbegin() const {return trajectory_.cbegin();}
    const_iterator cend()   const {return trajectory_.cend();}

    const header_type&     header() const {return header_;}
          header_type&     header()       {return header_;}

    void push_header(const std::string& message)
    {
        if(message.size() == 80)
            header_.push_back(message);
        else if(message.size() > 80)
            throw std::invalid_argument("too long message");
        else if(message.size() < 80)
            header_.push_back(message + std::string(80 - message.size()), '=');
    }

  private:

    size_type       nset_;
    size_type       istart_;     // initial value of isteps (nomally zero)
    size_type       nstep_save_; // nstep_save timesteps per one snapshot
    size_type       nstep_;      // total step number of the simulation
    size_type       nunit_;      // total unit number (chains??)
    size_type       verCHARMM_;  // version of CHARMM (usually unused)
    size_type       nparticle_;  // total number of particle
    time_type       delta_t_;
    header_type     header_;
    trajectory_type trajectory_;
};

}

#endif /* COFFEE_MILL_DCD_DATA */
<|endoftext|>


<commit_before>/*
 * Copyright 2012-2013 Falltergeist Developers.
 *
 * This file is part of Falltergeist.
 *
 * Falltergeist is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Falltergeist is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Falltergeist.  If not, see <http://www.gnu.org/licenses/>.
 */

// C++ standard includes
#include <algorithm>

// libfalltergeist includes
#include "../src/DatFile.h"
#include "../src/DatFileItem.h"
#include "../src/DatFileEntry.h"
#include "../src/Exception.h"
#include "../src/AafFileType.h"
#include "../src/BioFileType.h"
#include "../src/FonFileType.h"
#include "../src/FrmFileType.h"
#include "../src/GcdFileType.h"
#include "../src/MapFileType.h"
#include "../src/MsgFileType.h"
#include "../src/LstFileType.h"
#include "../src/PalFileType.h"
#include "../src/ProFileType.h"
#include "../src/RixFileType.h"

// Third party includes

namespace libfalltergeist
{

DatFile::DatFile()
{
}

DatFile::DatFile(std::string filename)
{
    setFilename(filename);
    _initialize();
}

DatFile::~DatFile()
{
    delete _items;
    delete _stream;
}

std::string DatFile::filename()
{
    return _filename;
}

DatFile* DatFile::setFilename(std::string filename)
{
    _filename = filename;
    return this;
}

void DatFile::_initialize()
{
    if (_initialized) return;
    _initialized = true;

    _stream = new std::ifstream();
    _stream->open(filename(), std::ios_base::binary);
    if (!_stream->is_open())
    {
        throw Exception("DatFile::_initialize() - can't open stream: " + filename());
    }
}

DatFile* DatFile::setPosition(unsigned int position)
{
    _stream->seekg(position, std::ios::beg);
    return this;
}

unsigned int DatFile::position()
{
    return _stream->tellg();
}

unsigned int DatFile::size(void)
{
    auto oldPosition = _stream->tellg();
    _stream->seekg(0,std::ios::end);
    auto currentPosition = _stream->tellg();
    _stream->seekg(oldPosition, std::ios::beg);
    return currentPosition;
}

DatFile* DatFile::skipBytes(unsigned int numberOfBytes)
{
    setPosition(position() + numberOfBytes);
    return this;
}

DatFile* DatFile::readBytes(char * destination, unsigned int numberOfBytes)
{
    unsigned int position = this->position();
    _stream->readsome(destination, numberOfBytes);
    setPosition(position + numberOfBytes);
    return this;
}

std::vector<DatFileItem *> * DatFile::items()
{
    // if items are not fetched yet
    if (_items == 0)
    {
        unsigned int oldPos = position();
        _items = new std::vector<DatFileItem *>;

        unsigned int datFileSize;
        unsigned int filesTreeSize;
        unsigned int filesTotalNumber;

        // reading data size from dat file
        setPosition(size() - 4);
        *this >> datFileSize;
        if (datFileSize != size())
        {
            throw Exception("DatFile::items() - wrong file size");
        }
        // reading size of files tree
        setPosition(size() - 8);
        *this >> filesTreeSize;

        // reading total number of items in dat file
        setPosition(size() - filesTreeSize - 8);
        *this >> filesTotalNumber;

        //reading files data one by one
        for (unsigned int i = 0; i != filesTotalNumber; ++i)
        {
            DatFileEntry * entry = new DatFileEntry(this);

            *this >> *entry;

            std::string extension = entry->filename().substr(entry->filename().length() - 3, 3);

            DatFileItem * item;
                 if (extension == "aaf") item = new AafFileType(entry);
            else if (extension == "bio") item = new BioFileType(entry);
            else if (extension == "fon") item = new FonFileType(entry);
            else if (extension == "frm") item = new FrmFileType(entry);
            else if (extension == "gcd") item = new GcdFileType(entry);
            else if (extension == "lst") item = new LstFileType(entry);
            else if (extension == "map") item = new MapFileType(entry);
            else if (extension == "msg") item = new MsgFileType(entry);
            else if (extension == "pal") item = new PalFileType(entry);
            else if (extension == "pro") item = new ProFileType(entry);
            else if (extension == "rix") item = new RixFileType(entry);
            else item = new DatFileItem(entry);

            _items->push_back(item);
        }
        setPosition(oldPos);
    }
    return _items;
}

DatFileItem * DatFile::item(const std::string filename)
{
    std::string name(filename);
    // Replace slashes and transform to lower case
    std::replace(name.begin(),name.end(),'\\','/');
    std::transform(name.begin(),name.end(),name.begin(), ::tolower);
    std::vector<DatFileItem *>::iterator it;

    for (it = this->items()->begin(); it != this->items()->end(); ++it)
    {
        //std::cout << (*it)->filename() << std::endl;
        if (name.compare((*it)->filename()) == 0)
        {
            return *it;
        }
    }
    return 0;
}

DatFile& DatFile::operator>>(int &value)
{
    readBytes(reinterpret_cast<char *>(&value), sizeof(value));
    return *this;
}

DatFile& DatFile::operator>>(unsigned int &value)
{
    return *this >> (int&) value;
}

DatFile& DatFile::operator>>(short &value)
{
    readBytes(reinterpret_cast<char *>(&value), sizeof(value));
    return *this;
}

DatFile& DatFile::operator>>(unsigned short &value)
{
    return *this >> (short&) value;
}

DatFile& DatFile::operator>>(char &value)
{
    readBytes(reinterpret_cast<char *>(&value), sizeof(value));
    return *this;
}

DatFile& DatFile::operator>>(unsigned char &value)
{
    return *this >> (char&) value;
}

DatFile& DatFile::operator>>(DatFileEntry& entry)
{
    unsigned int filenameSize;
    unsigned char compressed;
    unsigned int unpackedSize;
    unsigned int packedSize;
    unsigned int dataOffset;

    *this >> filenameSize;

    char * filename = new char[filenameSize + 1]();
    readBytes(filename, filenameSize);
    entry.setFilename(filename);
    delete [] filename;

    *this >> compressed >> unpackedSize >> packedSize >> dataOffset;

    entry.setCompressed((bool) compressed);
    entry.setUnpackedSize(unpackedSize);
    entry.setPackedSize(packedSize);
    entry.setDataOffset(dataOffset);

    return *this;
}

}
<commit_msg>Refactoring<commit_after>/*
 * Copyright 2012-2013 Falltergeist Developers.
 *
 * This file is part of Falltergeist.
 *
 * Falltergeist is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Falltergeist is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Falltergeist.  If not, see <http://www.gnu.org/licenses/>.
 */

// C++ standard includes
#include <algorithm>

// libfalltergeist includes
#include "../src/DatFile.h"
#include "../src/DatFileItem.h"
#include "../src/DatFileEntry.h"
#include "../src/Exception.h"
#include "../src/AafFileType.h"
#include "../src/BioFileType.h"
#include "../src/FonFileType.h"
#include "../src/FrmFileType.h"
#include "../src/GcdFileType.h"
#include "../src/MapFileType.h"
#include "../src/MsgFileType.h"
#include "../src/LstFileType.h"
#include "../src/PalFileType.h"
#include "../src/ProFileType.h"
#include "../src/RixFileType.h"

// Third party includes

namespace libfalltergeist
{

DatFile::DatFile()
{
}

DatFile::DatFile(std::string filename)
{
    setFilename(filename);
    _initialize();
}

DatFile::~DatFile()
{
    delete _items;
    delete _stream;
}

std::string DatFile::filename()
{
    return _filename;
}

DatFile* DatFile::setFilename(std::string filename)
{
    _filename = filename;
    return this;
}

void DatFile::_initialize()
{
    if (_initialized) return;
    _initialized = true;

    _stream = new std::ifstream();
    _stream->open(filename(), std::ios_base::binary);
    if (!_stream->is_open())
    {
        throw Exception("DatFile::_initialize() - can't open stream: " + filename());
    }
}

DatFile* DatFile::setPosition(unsigned int position)
{
    _stream->seekg(position, std::ios::beg);
    return this;
}

unsigned int DatFile::position()
{
    return _stream->tellg();
}

unsigned int DatFile::size(void)
{
    auto oldPosition = _stream->tellg();
    _stream->seekg(0,std::ios::end);
    auto currentPosition = _stream->tellg();
    _stream->seekg(oldPosition, std::ios::beg);
    return currentPosition;
}

DatFile* DatFile::skipBytes(unsigned int numberOfBytes)
{
    setPosition(position() + numberOfBytes);
    return this;
}

DatFile* DatFile::readBytes(char * destination, unsigned int numberOfBytes)
{
    unsigned int position = this->position();
    _stream->readsome(destination, numberOfBytes);
    setPosition(position + numberOfBytes);
    return this;
}

std::vector<DatFileItem *> * DatFile::items()
{
    // if items are not fetched yet
    if (_items == 0)
    {
        unsigned int oldPos = position();
        _items = new std::vector<DatFileItem *>;

        unsigned int datFileSize;
        unsigned int filesTreeSize;
        unsigned int filesTotalNumber;

        // reading data size from dat file
        setPosition(size() - 4);
        *this >> datFileSize;
        if (datFileSize != size())
        {
            throw Exception("DatFile::items() - wrong file size");
        }
        // reading size of files tree
        setPosition(size() - 8);
        *this >> filesTreeSize;

        // reading total number of items in dat file
        setPosition(size() - filesTreeSize - 8);
        *this >> filesTotalNumber;

        //reading files data one by one
        for (unsigned int i = 0; i != filesTotalNumber; ++i)
        {
            DatFileEntry * entry = new DatFileEntry(this);

            *this >> *entry;

            std::string extension = entry->filename().substr(entry->filename().length() - 3, 3);

            DatFileItem * item;
                 if (extension == "aaf") item = new AafFileType(entry);
            else if (extension == "bio") item = new BioFileType(entry);
            else if (extension == "fon") item = new FonFileType(entry);
            else if (extension == "frm") item = new FrmFileType(entry);
            else if (extension == "gcd") item = new GcdFileType(entry);
            else if (extension == "lst") item = new LstFileType(entry);
            else if (extension == "map") item = new MapFileType(entry);
            else if (extension == "msg") item = new MsgFileType(entry);
            else if (extension == "pal") item = new PalFileType(entry);
            else if (extension == "pro") item = new ProFileType(entry);
            else if (extension == "rix") item = new RixFileType(entry);
            else item = new DatFileItem(entry);

            _items->push_back(item);
        }
        setPosition(oldPos);
    }
    return _items;
}

DatFileItem * DatFile::item(const std::string filename)
{
    std::string name(filename);
    // Replace slashes and transform to lower case
    std::replace(name.begin(),name.end(),'\\','/');
    std::transform(name.begin(),name.end(),name.begin(), ::tolower);
    std::vector<DatFileItem *>::iterator it;

    for (it = this->items()->begin(); it != this->items()->end(); ++it)
    {
        //std::cout << (*it)->filename() << std::endl;
        if (name.compare((*it)->filename()) == 0)
        {
            return *it;
        }
    }
    return 0;
}

DatFile& DatFile::operator>>(int &value)
{
    readBytes(reinterpret_cast<char *>(&value), sizeof(value));
    return *this;
}

DatFile& DatFile::operator>>(unsigned int &value)
{
    return *this >> (int&) value;
}

DatFile& DatFile::operator>>(short &value)
{
    readBytes(reinterpret_cast<char *>(&value), sizeof(value));
    return *this;
}

DatFile& DatFile::operator>>(unsigned short &value)
{
    return *this >> (short&) value;
}

DatFile& DatFile::operator>>(char &value)
{
    readBytes(reinterpret_cast<char *>(&value), sizeof(value));
    return *this;
}

DatFile& DatFile::operator>>(unsigned char &value)
{
    return *this >> (char&) value;
}

DatFile& DatFile::operator>>(DatFileEntry& entry)
{
    unsigned int filenameSize;
    unsigned char compressed;
    unsigned int unpackedSize;
    unsigned int packedSize;
    unsigned int dataOffset;

    *this >> filenameSize;

    std::string filename;
    filename.resize(filenameSize);
    readBytes(&filename[0], filenameSize);
    entry.setFilename(filename);

    *this >> compressed >> unpackedSize >> packedSize >> dataOffset;

    entry.setCompressed((bool) compressed);
    entry.setUnpackedSize(unpackedSize);
    entry.setPackedSize(packedSize);
    entry.setDataOffset(dataOffset);

    return *this;
}

}
<|endoftext|>


<commit_before>/*
 * Define.hpp
 *
 *  Created on: Apr 30, 2014
 *      Author: Pimenta
 */

#ifndef DEFINE_HPP_
#define DEFINE_HPP_

// network addresses
#define IP_MAIN                 "224.69.69.69"
#define TCPUDP_MAIN             "6969"
#define TCP_HTTPSERVER          "8080"

// sizes
#define SIZE_MULTICAST_MAXLEN   0x1000
#define SIZE_HTTPSERVER_MAXLEN  0x1000
#define SIZE_FILEBUFFER_MAXLEN  0x4000

// times
#define MS_INITTIMER            3000
#define MS_SLEEP                20
#define MS_DETECTFAILURE        6000
#define MS_SPEAK                1000
#define MS_LOGINSYNC            2000

#endif /* DEFINE_HPP_ */
<commit_msg>CABAMO SAPORRA<commit_after>/*
 * Define.hpp
 *
 *  Created on: Apr 30, 2014
 *      Author: Pimenta
 */

#ifndef DEFINE_HPP_
#define DEFINE_HPP_

// network addresses
#define IP_MAIN                 "224.69.69.69"
#define TCPUDP_MAIN             "6969"
#define TCP_HTTPSERVER          "8080"

// sizes
#define SIZE_MULTICAST_MAXLEN   0x1000
#define SIZE_HTTPSERVER_MAXLEN  0x1000
#define SIZE_FILEBUFFER_MAXLEN  0x4000

// times
#define MS_INITTIMER            3000
#define MS_SLEEP                20
#define MS_DETECTFAILURE        12000
#define MS_SPEAK                1000
#define MS_LOGINSYNC            2000

#endif /* DEFINE_HPP_ */
<|endoftext|>


<commit_before><commit_msg>Unique BSTs for 1...n values<commit_after><|endoftext|>


<commit_before>// DepthOp.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "DepthOp.h"
#include "CNCConfig.h"
#include "ProgramCanvas.h"
#include "Program.h"
#include "interface/PropertyInt.h"
#include "interface/PropertyDouble.h"
#include "interface/PropertyLength.h"
#include "tinyxml/tinyxml.h"
#include "interface/Tool.h"

CDepthOpParams::CDepthOpParams()
{
	m_tool_number = 0;
	m_tool_diameter = 0.0;
	m_clearance_height = 0.0;
	m_start_depth = 0.0;
	m_step_down = 0.0;
	m_final_depth = 0.0;
	m_rapid_down_to_height = 0.0;
	m_horizontal_feed_rate = 0.0;
	m_vertical_feed_rate = 0.0;
	m_spindle_speed = 0.0;
}

void CDepthOpParams::set_initial_values()
{
	CNCConfig config;
	config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1);
	config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0);
	config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0);
	config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0);
	config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0);
	config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0);
	config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0);
	config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0);
	config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0);
	config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000);
}

void CDepthOpParams::write_values_to_config()
{
	CNCConfig config;
	config.Write(_T("DepthOpToolNumber"), m_tool_number);
	config.Write(_T("DepthOpToolDiameter"), m_tool_diameter);
	config.Write(_T("DepthOpClearanceHeight"), m_clearance_height);
	config.Write(_T("DepthOpStartDepth"), m_start_depth);
	config.Write(_T("DepthOpStepDown"), m_step_down);
	config.Write(_T("DepthOpFinalDepth"), m_final_depth);
	config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height);
	config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate);
	config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate);
	config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed);
}

static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;}
static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;}
static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;}
static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;}
static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;}
static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;}
static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;}
static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;}
static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;}
static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;}

void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list)
{
	list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number));
	list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter));
	list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height));
	list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down));
	list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth));
	list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth));
	list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height));
	list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate));
	list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate));
	list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed));
}

void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem)
{
	TiXmlElement * element = new TiXmlElement( "depthop" );
	pElem->LinkEndChild( element );
	element->SetAttribute("tooln", m_tool_number);
	element->SetDoubleAttribute("toold", m_tool_diameter);
	element->SetDoubleAttribute("clear", m_clearance_height);
	element->SetDoubleAttribute("down", m_step_down);
	element->SetDoubleAttribute("startdepth", m_start_depth);
	element->SetDoubleAttribute("depth", m_final_depth);
	element->SetDoubleAttribute("r", m_rapid_down_to_height);
	element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate);
	element->SetDoubleAttribute("vfeed", m_vertical_feed_rate);
	element->SetDoubleAttribute("spin", m_spindle_speed);
}

void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem)
{
	TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element();
	if(depthop)
	{
		depthop->Attribute("tooln", &m_tool_number);
		depthop->Attribute("toold", &m_tool_diameter);
		depthop->Attribute("clear", &m_clearance_height);
		depthop->Attribute("down", &m_step_down);
		depthop->Attribute("startdepth", &m_start_depth);
		depthop->Attribute("depth", &m_final_depth);
		depthop->Attribute("r", &m_rapid_down_to_height);
		depthop->Attribute("hfeed", &m_horizontal_feed_rate);
		depthop->Attribute("vfeed", &m_vertical_feed_rate);
		depthop->Attribute("spin", &m_spindle_speed);
	}
}

void CDepthOp::WriteBaseXML(TiXmlElement *element)
{
	m_depth_op_params.WriteXMLAttributes(element);
	COp::WriteBaseXML(element);
}

void CDepthOp::ReadBaseXML(TiXmlElement* element)
{
	m_depth_op_params.ReadFromXMLElement(element);
	COp::ReadBaseXML(element);
}

void CDepthOp::GetProperties(std::list<Property *> *list)
{
	m_depth_op_params.GetProperties(this, list);
	COp::GetProperties(list);
}

void CDepthOp::AppendTextToProgram()
{
	COp::AppendTextToProgram();

	theApp.m_program_canvas->AppendText(_T("clearance = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("start_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("step_down = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("final_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_diameter = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("spindle("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("feedrate("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_change("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number);
	theApp.m_program_canvas->AppendText(_T(")\n"));
}

<commit_msg>line 167 should have been vertical feed instead of horizontal<commit_after>// DepthOp.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "DepthOp.h"
#include "CNCConfig.h"
#include "ProgramCanvas.h"
#include "Program.h"
#include "interface/PropertyInt.h"
#include "interface/PropertyDouble.h"
#include "interface/PropertyLength.h"
#include "tinyxml/tinyxml.h"
#include "interface/Tool.h"

CDepthOpParams::CDepthOpParams()
{
	m_tool_number = 0;
	m_tool_diameter = 0.0;
	m_clearance_height = 0.0;
	m_start_depth = 0.0;
	m_step_down = 0.0;
	m_final_depth = 0.0;
	m_rapid_down_to_height = 0.0;
	m_horizontal_feed_rate = 0.0;
	m_vertical_feed_rate = 0.0;
	m_spindle_speed = 0.0;
}

void CDepthOpParams::set_initial_values()
{
	CNCConfig config;
	config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1);
	config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0);
	config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0);
	config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0);
	config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0);
	config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0);
	config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0);
	config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0);
	config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0);
	config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000);
}

void CDepthOpParams::write_values_to_config()
{
	CNCConfig config;
	config.Write(_T("DepthOpToolNumber"), m_tool_number);
	config.Write(_T("DepthOpToolDiameter"), m_tool_diameter);
	config.Write(_T("DepthOpClearanceHeight"), m_clearance_height);
	config.Write(_T("DepthOpStartDepth"), m_start_depth);
	config.Write(_T("DepthOpStepDown"), m_step_down);
	config.Write(_T("DepthOpFinalDepth"), m_final_depth);
	config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height);
	config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate);
	config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate);
	config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed);
}

static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;}
static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;}
static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;}
static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;}
static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;}
static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;}
static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;}
static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;}
static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;}
static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;}

void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list)
{
	list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number));
	list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter));
	list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height));
	list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down));
	list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth));
	list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth));
	list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height));
	list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate));
	list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate));
	list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed));
}

void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem)
{
	TiXmlElement * element = new TiXmlElement( "depthop" );
	pElem->LinkEndChild( element );
	element->SetAttribute("tooln", m_tool_number);
	element->SetDoubleAttribute("toold", m_tool_diameter);
	element->SetDoubleAttribute("clear", m_clearance_height);
	element->SetDoubleAttribute("down", m_step_down);
	element->SetDoubleAttribute("startdepth", m_start_depth);
	element->SetDoubleAttribute("depth", m_final_depth);
	element->SetDoubleAttribute("r", m_rapid_down_to_height);
	element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate);
	element->SetDoubleAttribute("vfeed", m_vertical_feed_rate);
	element->SetDoubleAttribute("spin", m_spindle_speed);
}

void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem)
{
	TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element();
	if(depthop)
	{
		depthop->Attribute("tooln", &m_tool_number);
		depthop->Attribute("toold", &m_tool_diameter);
		depthop->Attribute("clear", &m_clearance_height);
		depthop->Attribute("down", &m_step_down);
		depthop->Attribute("startdepth", &m_start_depth);
		depthop->Attribute("depth", &m_final_depth);
		depthop->Attribute("r", &m_rapid_down_to_height);
		depthop->Attribute("hfeed", &m_horizontal_feed_rate);
		depthop->Attribute("vfeed", &m_vertical_feed_rate);
		depthop->Attribute("spin", &m_spindle_speed);
	}
}

void CDepthOp::WriteBaseXML(TiXmlElement *element)
{
	m_depth_op_params.WriteXMLAttributes(element);
	COp::WriteBaseXML(element);
}

void CDepthOp::ReadBaseXML(TiXmlElement* element)
{
	m_depth_op_params.ReadFromXMLElement(element);
	COp::ReadBaseXML(element);
}

void CDepthOp::GetProperties(std::list<Property *> *list)
{
	m_depth_op_params.GetProperties(this, list);
	COp::GetProperties(list);
}

void CDepthOp::AppendTextToProgram()
{
	COp::AppendTextToProgram();

	theApp.m_program_canvas->AppendText(_T("clearance = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("start_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("step_down = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("final_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_diameter = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("spindle("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("feedrate("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_vertical_feed_rate);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_change("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number);
	theApp.m_program_canvas->AppendText(_T(")\n"));
}

<|endoftext|>


<commit_before>#include <memory.h>
#include <memory>

#include "cuda/cudaTextureResource.h"

#include "cuda/cudadefs.h"
#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"

namespace idaten
{
    void CudaLeyered2DTexture::init(
        std::vector<const aten::vec4*>& p,
        uint32_t width,
        uint32_t height)
    {
        int layerNum = static_cast<int>(p.size());
        int imgSize = width * height;

        auto totalSize = imgSize * layerNum;
        std::vector<aten::vec4> hostMem(totalSize);

        for (int n = 0; n < layerNum; n++) {
            for (int i = 0; i < imgSize; i++) {
                hostMem[n * imgSize + i] = p[n][i];
            }
        }

        auto bytes = imgSize * layerNum * sizeof(float4);

        // allocate device memory for result.
        float4* deviceMem = nullptr;
        checkCudaErrors(cudaMalloc((void **)&deviceMem, bytes));

        // allocate array and copy image data.
        cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float4>();

        checkCudaErrors(
            cudaMalloc3DArray(
                &m_array,
                &channelDesc,
                make_cudaExtent(width, height, layerNum),
                cudaArrayLayered));

        cudaMemcpy3DParms memcpyParams = { 0 };
        memcpyParams.srcPos = make_cudaPos(0, 0, 0);
        memcpyParams.dstPos = make_cudaPos(0, 0, 0);
        memcpyParams.srcPtr = make_cudaPitchedPtr(&hostMem[0], width * sizeof(float4), width, height);
        memcpyParams.dstArray = m_array;
        memcpyParams.extent = make_cudaExtent(width, height, layerNum);
        memcpyParams.kind = cudaMemcpyHostToDevice;
        checkCudaErrors(cudaMemcpy3DAsync(&memcpyParams));

        m_width = width;
        m_height = height;
        m_layerNum = layerNum;

        memset(&m_resDesc, 0, sizeof(m_resDesc));
        m_resDesc.resType = cudaResourceTypeArray;
        m_resDesc.res.array.array = m_array;
    }

    cudaTextureObject_t CudaLeyered2DTexture::bind()
    {
        if (m_tex == 0) {
            // Make texture description:
            cudaTextureDesc tex_desc = {};
            tex_desc.readMode = cudaReadModeElementType;
            tex_desc.filterMode = cudaFilterModePoint;
            tex_desc.addressMode[0] = cudaAddressModeWrap;
            tex_desc.addressMode[1] = cudaAddressModeWrap;
            tex_desc.normalizedCoords = true;

            checkCudaErrors(cudaCreateTextureObject(&m_tex, &m_resDesc, &tex_desc, nullptr));
        }

        return m_tex;
    }
}<commit_msg>Add a comment<commit_after>#include <memory.h>
#include <memory>

#include "cuda/cudaTextureResource.h"

#include "cuda/cudadefs.h"
#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"

namespace idaten
{
    void CudaLeyered2DTexture::init(
        std::vector<const aten::vec4*>& p,
        uint32_t width,
        uint32_t height)
    {
        int layerNum = static_cast<int>(p.size());
        int imgSize = width * height;

        auto totalSize = imgSize * layerNum;
        std::vector<aten::vec4> hostMem(totalSize);

        // Copy to 1D array memory.
        for (int n = 0; n < layerNum; n++) {
            for (int i = 0; i < imgSize; i++) {
                hostMem[n * imgSize + i] = p[n][i];
            }
        }

        auto bytes = imgSize * layerNum * sizeof(float4);

        // allocate device memory for result.
        float4* deviceMem = nullptr;
        checkCudaErrors(cudaMalloc((void **)&deviceMem, bytes));

        // allocate array and copy image data.
        cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float4>();

        checkCudaErrors(
            cudaMalloc3DArray(
                &m_array,
                &channelDesc,
                make_cudaExtent(width, height, layerNum),
                cudaArrayLayered));

        cudaMemcpy3DParms memcpyParams = { 0 };
        memcpyParams.srcPos = make_cudaPos(0, 0, 0);
        memcpyParams.dstPos = make_cudaPos(0, 0, 0);
        memcpyParams.srcPtr = make_cudaPitchedPtr(&hostMem[0], width * sizeof(float4), width, height);
        memcpyParams.dstArray = m_array;
        memcpyParams.extent = make_cudaExtent(width, height, layerNum);
        memcpyParams.kind = cudaMemcpyHostToDevice;
        checkCudaErrors(cudaMemcpy3DAsync(&memcpyParams));

        m_width = width;
        m_height = height;
        m_layerNum = layerNum;

        memset(&m_resDesc, 0, sizeof(m_resDesc));
        m_resDesc.resType = cudaResourceTypeArray;
        m_resDesc.res.array.array = m_array;
    }

    cudaTextureObject_t CudaLeyered2DTexture::bind()
    {
        if (m_tex == 0) {
            // Make texture description:
            cudaTextureDesc tex_desc = {};
            tex_desc.readMode = cudaReadModeElementType;
            tex_desc.filterMode = cudaFilterModePoint;
            tex_desc.addressMode[0] = cudaAddressModeWrap;
            tex_desc.addressMode[1] = cudaAddressModeWrap;
            tex_desc.normalizedCoords = true;

            checkCudaErrors(cudaCreateTextureObject(&m_tex, &m_resDesc, &tex_desc, nullptr));
        }

        return m_tex;
    }
}<|endoftext|>