<commit_before>/*
 * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <Debugger.h>

#include <DebuggerIO.h>
#include <LocalIO.h>
#include <SerialIO.h>

#include <utilities/StaticString.h>

#include <processor/Processor.h>
#include <machine/Machine.h>

#include <Log.h>
#include <utilities/utility.h>

static size_t newlineCount(const char *pString)
{
  size_t nNewlines = 0;
  while (*pString != '\0')
    if (*pString++ == '\n')
      ++nNewlines;

  return nNewlines;
}

// TODO: We might want a separate parameter for a stacktrace/register dump
void _panic( const char* msg, DebuggerIO* pScreen )
{
  static HugeStaticString panic_output;
  panic_output.clear();

  panic_output.append( "PANIC: " );
  panic_output.append( msg );

  // write the final string to the screen
  pScreen->drawString( panic_output, 0, 0, DebuggerIO::Red, DebuggerIO::Black );

  size_t nLines = newlineCount(panic_output) + 2;

  Log &log = Log::instance();
  Log::SeverityLevel level;
  static NormalStaticString Line;

  size_t iEntry = 0, iUsedEntries = 0;
  if ((pScreen->getHeight() - nLines) < (log.getStaticEntryCount() + log.getDynamicEntryCount()))
    iEntry = log.getStaticEntryCount() + log.getDynamicEntryCount() - (pScreen->getHeight() - nLines) + 1;
  bool bPrintThisLine = false;
  for( ; iEntry < (log.getStaticEntryCount() + log.getDynamicEntryCount()); iEntry++ )
  {
    if( iEntry < log.getStaticEntryCount() )
    {
      const Log::StaticLogEntry &entry = log.getStaticEntry(iEntry);
      level = entry.type;

//      if( level == Log::Fatal || level == Log::Error )
//      {
        Line.clear();
        Line.append("[");
        Line.append(entry.timestamp, 10, 8, '0');
        Line.append("] ");
        Line.append(entry.str);
        Line.append( "\n" );

        bPrintThisLine = true;
//      }
    }
    else
    {
      const Log::DynamicLogEntry &entry = log.getDynamicEntry(iEntry);
      level = entry.type;

//      if( level == Log::Fatal || level == Log::Error )
//      {
        Line.clear();
        Line.append("[");
        Line.append(entry.timestamp, 10, 8, '0');
        Line.append("] ");
        Line.append(entry.str);
        Line.append( "\n" );

        bPrintThisLine = true;
//      }
    }

    // print the line
    if( bPrintThisLine == true )
    {
      ++iUsedEntries;
      pScreen->drawString( Line, nLines + iUsedEntries, 0, DebuggerIO::White, DebuggerIO::Black );
      bPrintThisLine = false;
    }
  }
}

void panic( const char* msg )
{
  /*
   * I/O implementations.
   */
  SerialIO serialIO(Machine::instance().getSerial(0));

  DebuggerIO *pInterfaces[2] = {0};

  int nInterfaces = 0;
  if(Machine::instance().getNumVga()) // Not all machines have "VGA", so handle that
  {
    static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard());
#ifdef DONT_LOG_TO_SERIAL
    pInterfaces[0] = &localIO;
    nInterfaces = 1;
#else
    pInterfaces[0] = &localIO;
    pInterfaces[1] = &serialIO;
    nInterfaces = 2;
#endif
  }
#ifndef DONT_LOG_TO_SERIAL
  else
  {
    pInterfaces[0] = &serialIO;
    nInterfaces = 1;
  }
#endif

  for( int nIFace = 0; nIFace < nInterfaces; nIFace++ )
    _panic( msg, pInterfaces[nIFace] );

  // Halt the processor
  Processor::halt();
}
<commit_msg>Fixed panic to drop out of a graphics mode if one is being used.<commit_after>/*
 * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <Debugger.h>

#include <DebuggerIO.h>
#include <LocalIO.h>
#include <SerialIO.h>

#include <utilities/StaticString.h>

#include <processor/Processor.h>
#include <machine/Machine.h>

#include <Log.h>
#include <utilities/utility.h>

#include <graphics/GraphicsService.h>

static size_t newlineCount(const char *pString)
{
  size_t nNewlines = 0;
  while (*pString != '\0')
    if (*pString++ == '\n')
      ++nNewlines;

  return nNewlines;
}

// TODO: We might want a separate parameter for a stacktrace/register dump
void _panic( const char* msg, DebuggerIO* pScreen )
{
  static HugeStaticString panic_output;
  panic_output.clear();

  panic_output.append( "PANIC: " );
  panic_output.append( msg );

  // write the final string to the screen
  pScreen->drawString( panic_output, 0, 0, DebuggerIO::Red, DebuggerIO::Black );

  size_t nLines = newlineCount(panic_output) + 2;

  Log &log = Log::instance();
  Log::SeverityLevel level;
  static NormalStaticString Line;

  size_t iEntry = 0, iUsedEntries = 0;
  if ((pScreen->getHeight() - nLines) < (log.getStaticEntryCount() + log.getDynamicEntryCount()))
    iEntry = log.getStaticEntryCount() + log.getDynamicEntryCount() - (pScreen->getHeight() - nLines) + 1;
  bool bPrintThisLine = false;
  for( ; iEntry < (log.getStaticEntryCount() + log.getDynamicEntryCount()); iEntry++ )
  {
    if( iEntry < log.getStaticEntryCount() )
    {
      const Log::StaticLogEntry &entry = log.getStaticEntry(iEntry);
      level = entry.type;

//      if( level == Log::Fatal || level == Log::Error )
//      {
        Line.clear();
        Line.append("[");
        Line.append(entry.timestamp, 10, 8, '0');
        Line.append("] ");
        Line.append(entry.str);
        Line.append( "\n" );

        bPrintThisLine = true;
//      }
    }
    else
    {
      const Log::DynamicLogEntry &entry = log.getDynamicEntry(iEntry);
      level = entry.type;

//      if( level == Log::Fatal || level == Log::Error )
//      {
        Line.clear();
        Line.append("[");
        Line.append(entry.timestamp, 10, 8, '0');
        Line.append("] ");
        Line.append(entry.str);
        Line.append( "\n" );

        bPrintThisLine = true;
//      }
    }

    // print the line
    if( bPrintThisLine == true )
    {
      ++iUsedEntries;
      pScreen->drawString( Line, nLines + iUsedEntries, 0, DebuggerIO::White, DebuggerIO::Black );
      bPrintThisLine = false;
    }
  }
}

void panic( const char* msg )
{
  // Drop out of whatever graphics mode we were in
  GraphicsService::GraphicsProvider provider;
  memset(&provider, 0, sizeof(provider));
  provider.bTextModes = true;

  ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics"));
  Service         *pService  = ServiceManager::instance().getService(String("graphics"));
  bool bSuccess = false;
  if(pFeatures->provides(ServiceFeatures::probe))
    if(pService)
      bSuccess = pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&provider), sizeof(provider));

  if(bSuccess && !provider.bTextModes)
    provider.pDisplay->setScreenMode(0);

#ifdef MULTIPROCESSOR
  Machine::instance().stopAllOtherProcessors();
#endif

  /*
   * I/O implementations.
   */
  SerialIO serialIO(Machine::instance().getSerial(0));

  DebuggerIO *pInterfaces[2] = {0};

  int nInterfaces = 0;
  if(Machine::instance().getNumVga()) // Not all machines have "VGA", so handle that
  {
    static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard());
#ifdef DONT_LOG_TO_SERIAL
    pInterfaces[0] = &localIO;
    nInterfaces = 1;
#else
    pInterfaces[0] = &localIO;
    pInterfaces[1] = &serialIO;
    nInterfaces = 2;
#endif
  }
#ifndef DONT_LOG_TO_SERIAL
  else
  {
    pInterfaces[0] = &serialIO;
    nInterfaces = 1;
  }
#endif

  for( int nIFace = 0; nIFace < nInterfaces; nIFace++ )
    _panic( msg, pInterfaces[nIFace] );

  // Halt the processor
  Processor::halt();
}
<|endoftext|>


<commit_before>/*
   Copyright 2011 StormMQ Limited

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#include <TestHarness.h>
#include "Transport/Frame/Frame.h"
#include "Transport/Frame/FrameTestSupport.h"

#include "Codec/Decode/Decode.h"
#include "debug_helper.h"

SUITE(Frame)
{
    TEST_FIXTURE(FrameFixture, multiple_symbol_null)
    {
        test_data::multiple_symbol_null.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_null(type));
    }

    TEST_FIXTURE(FrameFixture, multiple_symbol_one_value)
    {
        test_data::multiple_symbol_one_value.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_symbol(type));
    }

    TEST_FIXTURE(FrameFixture, multiple_symbol_many_values)
    {
        test_data::multiple_symbol_many_values.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_array(type));
        CHECK_EQUAL(3U, type->value.array.count);
        CHECK(amqp_type_is_symbol(type->value.array.elements[0]));
    }

    TEST_FIXTURE(FrameFixture, multiple_symbol_many_values)
    {
        test_data::multiple_symbol_many_values.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_array(type));
        CHECK_EQUAL(3U, type->value.array.count);
        CHECK(amqp_type_is_symbol(type->value.array.elements[0]));
    }
}
<commit_msg>Add test data for multiple symbols.<commit_after>/*
   Copyright 2011 StormMQ Limited

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#include <TestHarness.h>
#include "Transport/Frame/Frame.h"
#include "Transport/Frame/FrameTestSupport.h"

#include "Codec/Decode/Decode.h"
#include "debug_helper.h"

SUITE(Frame)
{
    TEST_FIXTURE(FrameFixture, multiple_symbol_null)
    {
        test_data::multiple_symbol_null.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_null(type));
    }

    TEST_FIXTURE(FrameFixture, multiple_symbol_one_value)
    {
        test_data::multiple_symbol_one_value.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_symbol(type));
    }

    TEST_FIXTURE(FrameFixture, multiple_symbol_many_values)
    {
        test_data::multiple_symbol_many_values.transfer_to(buffer);
        type = amqp_decode(context, buffer);

        CHECK(amqp_type_is_array(type));
        CHECK_EQUAL(3U, type->value.array.count);
        CHECK(amqp_type_is_symbol(type->value.array.elements[0]));
    }

}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2011-2017 Andreas F. Borchert
   All rights reserved.

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
*/

#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include "parser.hpp"
#include "scanner.hpp"
#include "symtable.hpp"
#include "yytname.hpp"

using namespace CSP;

void usage(const char* cmdname) {
   std::cerr << "Usage: " << cmdname << " [-epv] source.csp" << std::endl;
   exit(1);
}

int main(int argc, char** argv) {
   const char* cmdname = *argv++; --argc;
   if (argc == 0) usage(cmdname);

   // permit verbose process output to be suppressed
   bool opt_a = true;  // print alphabet at the beginning
   bool opt_e = false; // print events if accepted
   bool opt_p = true;  // print current process after each event
   bool opt_v = true;  // print current set of acceptable events
   while (argc > 0 && **argv == '-') {
      for (char* cp = *argv + 1; *cp; ++cp) {
	 switch (*cp) {
	    case 'a':
	       opt_a = false; break;
	    case 'e':
	       opt_e = true; break;
	    case 'p':
	       opt_p = false; break;
	    case 'v':
	       opt_v = false; break;
	    default:
	       usage(cmdname); break;
	 }
      }
      --argc; ++argv;
   }
   if (argc != 1) usage(cmdname);

   const char* fname = *argv++; --argc;
   std::ifstream fin(fname);
   if (!fin) {
      std::cerr << cmdname << ": unable to open " << fname <<
	 " for reading" << std::endl;
      exit(1);
   }
   SymTable symtab;
   std::string filename(fname);
   Scanner scanner(fin, filename, symtab);

   ProcessPtr process;
   parser p(scanner, symtab, process);
   if (p.parse() == 0) {
      if (opt_p) {
	 std::cout << "Tracing: " << process << std::endl;
      }
      if (opt_a) {
	 std::cout << "Alphabet: " << process->get_alphabet() << std::endl;
      }
      if (opt_v) {
	 std::cout << "Acceptable: " << process->acceptable() << std::endl;
      }
      if (!process->accepts_success()) {
	 std::string event;
	 while (std::cin >> event) {
	    if (process->get_alphabet().is_member(event)) {
	       process = process->proceed(event);
	       if (!process) {
		  std::cerr << "cannot accept " << event << std::endl;
		  exit(1);
	       }
	       if (process->accepts_success()) break;
	       if (opt_e) {
		  std::cout << event << std::endl;
	       }
	       if (opt_p) {
		  std::cout << "Process: " << process << std::endl;
	       }
	       if (opt_v) {
		  std::cout << "Acceptable: " << process->acceptable() <<
		     std::endl;
	       }
	    } else {
	       std::cout << "Not in alphabet: " << event << std::endl;
	    }
	 }
      }
      std::cout << "OK" << std::endl;
   }
}
<commit_msg>usage message extended<commit_after>/*
   Copyright (c) 2011-2017 Andreas F. Borchert
   All rights reserved.

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
*/

#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include "parser.hpp"
#include "scanner.hpp"
#include "symtable.hpp"
#include "yytname.hpp"

using namespace CSP;

void usage(const char* cmdname) {
   std::cerr << "Usage: " << cmdname << " [-aepv] source.csp" << std::endl;
   std::cerr << "Options:" << std::endl;
   std::cerr << " -a   do not print the alphabet at the beginning" << std::endl;
   std::cerr << " -e   print events, if accepted" << std::endl;
   std::cerr << " -p   do not print current process after each event" <<
      std::endl;
   std::cerr << " -v   do not print the set of acceptable events" <<
      std::endl;
   exit(1);
}

int main(int argc, char** argv) {
   const char* cmdname = *argv++; --argc;
   if (argc == 0) usage(cmdname);

   // permit verbose process output to be suppressed
   bool opt_a = true;  // print alphabet at the beginning
   bool opt_e = false; // print events if accepted
   bool opt_p = true;  // print current process after each event
   bool opt_v = true;  // print current set of acceptable events
   while (argc > 0 && **argv == '-') {
      for (char* cp = *argv + 1; *cp; ++cp) {
	 switch (*cp) {
	    case 'a':
	       opt_a = false; break;
	    case 'e':
	       opt_e = true; break;
	    case 'p':
	       opt_p = false; break;
	    case 'v':
	       opt_v = false; break;
	    default:
	       usage(cmdname); break;
	 }
      }
      --argc; ++argv;
   }
   if (argc != 1) usage(cmdname);

   const char* fname = *argv++; --argc;
   std::ifstream fin(fname);
   if (!fin) {
      std::cerr << cmdname << ": unable to open " << fname <<
	 " for reading" << std::endl;
      exit(1);
   }
   SymTable symtab;
   std::string filename(fname);
   Scanner scanner(fin, filename, symtab);

   ProcessPtr process;
   parser p(scanner, symtab, process);
   if (p.parse() == 0) {
      if (opt_p) {
	 std::cout << "Tracing: " << process << std::endl;
      }
      if (opt_a) {
	 std::cout << "Alphabet: " << process->get_alphabet() << std::endl;
      }
      if (opt_v) {
	 std::cout << "Acceptable: " << process->acceptable() << std::endl;
      }
      if (!process->accepts_success()) {
	 std::string event;
	 while (std::cin >> event) {
	    if (process->get_alphabet().is_member(event)) {
	       process = process->proceed(event);
	       if (!process) {
		  std::cerr << "cannot accept " << event << std::endl;
		  exit(1);
	       }
	       if (process->accepts_success()) break;
	       if (opt_e) {
		  std::cout << event << std::endl;
	       }
	       if (opt_p) {
		  std::cout << "Process: " << process << std::endl;
	       }
	       if (opt_v) {
		  std::cout << "Acceptable: " << process->acceptable() <<
		     std::endl;
	       }
	    } else {
	       std::cout << "Not in alphabet: " << event << std::endl;
	    }
	 }
      }
      std::cout << "OK" << std::endl;
   }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "agent_impl.h"
#include "setting_utils.h"

#include <sofa/pbrpc/pbrpc.h>
#include <glog/logging.h>
#include <gflags/gflags.h>

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <algorithm>
#include <vector>

DECLARE_string(agent_port);

static volatile bool s_quit = false;
static void SignalIntHandler(int /*sig*/)
{
    s_quit = true;
}

void SigChldHandler(int /*sig*/)
{
    int status = 0;
    while (true) {
        pid_t pid = ::waitpid(-1, &status, WNOHANG);
        if (pid == -1 || pid == 0) {
            return;
        }
    }
}

int main(int argc, char* argv[])
{
    // set umask
    umask(22);
    google::ParseCommandLineFlags(&argc, &argv, true);
    google::InitGoogleLogging(argv[0]);
    baidu::galaxy::SetupLog("agent");
    baidu::galaxy::AgentImpl* agent = new baidu::galaxy::AgentImpl();
    sofa::pbrpc::RpcServerOptions options;
    sofa::pbrpc::RpcServer rpc_server(options);

    if (!rpc_server.RegisterService(static_cast<baidu::galaxy::proto::Agent*>(agent))) {
        LOG(WARNING) << "failed to register agent service";
        exit(-1);
    }

    std::string endpoint = "0.0.0.0:" + FLAGS_agent_port;
    agent->Setup();

    if (!rpc_server.Start(endpoint)) {
        LOG(WARNING) << "failed to start server on " << endpoint;
        exit(-2);
    }

    signal(SIGINT, SignalIntHandler);
    signal(SIGTERM, SignalIntHandler);
    signal(SIGCHLD, SigChldHandler);
    LOG(INFO) << "agent started.";

    while (!s_quit) {
        sleep(1);
    }

    return 0;
}

<commit_msg>use defaule umask<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "agent_impl.h"
#include "setting_utils.h"

#include <sofa/pbrpc/pbrpc.h>
#include <glog/logging.h>
#include <gflags/gflags.h>

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <algorithm>
#include <vector>

DECLARE_string(agent_port);

static volatile bool s_quit = false;
static void SignalIntHandler(int /*sig*/)
{
    s_quit = true;
}

void SigChldHandler(int /*sig*/)
{
    int status = 0;
    while (true) {
        pid_t pid = ::waitpid(-1, &status, WNOHANG);
        if (pid == -1 || pid == 0) {
            return;
        }
    }
}

int main(int argc, char* argv[])
{
    // set umask
    //umask(22);
    google::ParseCommandLineFlags(&argc, &argv, true);
    google::InitGoogleLogging(argv[0]);
    baidu::galaxy::SetupLog("agent");
    baidu::galaxy::AgentImpl* agent = new baidu::galaxy::AgentImpl();
    sofa::pbrpc::RpcServerOptions options;
    sofa::pbrpc::RpcServer rpc_server(options);

    if (!rpc_server.RegisterService(static_cast<baidu::galaxy::proto::Agent*>(agent))) {
        LOG(WARNING) << "failed to register agent service";
        exit(-1);
    }

    std::string endpoint = "0.0.0.0:" + FLAGS_agent_port;
    agent->Setup();

    if (!rpc_server.Start(endpoint)) {
        LOG(WARNING) << "failed to start server on " << endpoint;
        exit(-2);
    }

    signal(SIGINT, SignalIntHandler);
    signal(SIGTERM, SignalIntHandler);
    signal(SIGCHLD, SigChldHandler);
    LOG(INFO) << "agent started.";

    while (!s_quit) {
        sleep(1);
    }

    return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sys/types.h>
#include <sys/wait.h>

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#include "gflags/gflags.h"
#include "sofa/pbrpc/pbrpc.h"
#include "utils/http_server.h"
#include "agent/agent_impl.h"
#include "utils/build_info.h"
#include "logging.h"

volatile static bool s_is_stop = false;

DECLARE_bool(v);
DECLARE_string(agent_port);
DECLARE_int32(agent_http_port);
DECLARE_string(agent_work_dir);
DECLARE_string(agent_gc_dir);
DECLARE_string(agent_coredump_dir);
DECLARE_string(log_file);
DECLARE_int32(log_size);
DECLARE_int32(log_cnt);

void StopSigHandler(int /*sig*/) {
    s_is_stop = true;
}

void SigChldHandler(int /*sig*/) {
    int status = 0;
    while (true) {
        pid_t pid = ::waitpid(-1, &status, WNOHANG);
        if (pid == -1 || pid == 0) {
            return;
        }
    }
}

int main (int argc, char* argv[]) {

    using baidu::common::Log;
    using baidu::common::FATAL;
    using baidu::common::INFO;
    using baidu::common::WARNING;

    ::google::ParseCommandLineFlags(&argc, &argv, true);
    if (FLAGS_v) {
        fprintf(stdout, "build version : %s\n", baidu::galaxy::GetVersion());
        fprintf(stdout, "build time : %s\n", baidu::galaxy::GetBuildTime());
        return 0;
    }
    if (FLAGS_log_file != "") {
        baidu::common::SetLogFile(FLAGS_log_file.c_str());
        baidu::common::SetLogSize(FLAGS_log_size);
        baidu::common::SetLogCnt(FLAGS_log_cnt);
    }
    sofa::pbrpc::RpcServerOptions options;
    sofa::pbrpc::RpcServer rpc_server(options);

    baidu::galaxy::AgentImpl* agent_service =
                        new baidu::galaxy::AgentImpl();
    if (!agent_service->Init()) {
        LOG(WARNING, "agent service init failed");
        return EXIT_FAILURE;
    }

    if (!rpc_server.RegisterService(agent_service)) {
        LOG(WARNING, "rpc server regist failed");
        return EXIT_FAILURE;
    }
    std::string server_host = std::string("0.0.0.0:")
        + FLAGS_agent_port;

    if (!rpc_server.Start(server_host)) {
        LOG(WARNING, "Rpc Server Start failed");
        return EXIT_FAILURE;
    }
    std::vector<std::pair<std::string, std::string> > router;
    router.push_back(std::make_pair("/gc", FLAGS_agent_gc_dir));
    router.push_back(std::make_pair("/container", FLAGS_agent_work_dir));
    router.push_back(std::make_pair("/coredump", FLAGS_agent_coredump_dir));
    ::baidu::galaxy::HttpFileServer http_server(router, FLAGS_agent_http_port);
    http_server.Start(10);
    LOG(INFO, "start http server on %d", FLAGS_agent_http_port);
    signal(SIGINT, StopSigHandler);
    signal(SIGTERM, StopSigHandler);
    signal(SIGCHLD, SigChldHandler);
    while (!s_is_stop) {
        sleep(5);
    }

    return EXIT_SUCCESS;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<commit_msg>set total log cnt<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sys/types.h>
#include <sys/wait.h>

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#include "gflags/gflags.h"
#include "sofa/pbrpc/pbrpc.h"
#include "utils/http_server.h"
#include "agent/agent_impl.h"
#include "utils/build_info.h"
#include "logging.h"

volatile static bool s_is_stop = false;

DECLARE_bool(v);
DECLARE_string(agent_port);
DECLARE_int32(agent_http_port);
DECLARE_string(agent_work_dir);
DECLARE_string(agent_gc_dir);
DECLARE_string(agent_coredump_dir);
DECLARE_string(log_file);
DECLARE_int32(log_size);
DECLARE_int32(log_cnt);

void StopSigHandler(int /*sig*/) {
    s_is_stop = true;
}

void SigChldHandler(int /*sig*/) {
    int status = 0;
    while (true) {
        pid_t pid = ::waitpid(-1, &status, WNOHANG);
        if (pid == -1 || pid == 0) {
            return;
        }
    }
}

int main (int argc, char* argv[]) {

    using baidu::common::Log;
    using baidu::common::FATAL;
    using baidu::common::INFO;
    using baidu::common::WARNING;

    ::google::ParseCommandLineFlags(&argc, &argv, true);
    if (FLAGS_v) {
        fprintf(stdout, "build version : %s\n", baidu::galaxy::GetVersion());
        fprintf(stdout, "build time : %s\n", baidu::galaxy::GetBuildTime());
        return 0;
    }
    if (FLAGS_log_file != "") {
        baidu::common::SetLogCnt(FLAGS_log_cnt);
        baidu::common::SetLogFile(FLAGS_log_file.c_str());
        baidu::common::SetLogSize(FLAGS_log_size);
    }
    sofa::pbrpc::RpcServerOptions options;
    sofa::pbrpc::RpcServer rpc_server(options);

    baidu::galaxy::AgentImpl* agent_service =
                        new baidu::galaxy::AgentImpl();
    if (!agent_service->Init()) {
        LOG(WARNING, "agent service init failed");
        return EXIT_FAILURE;
    }

    if (!rpc_server.RegisterService(agent_service)) {
        LOG(WARNING, "rpc server regist failed");
        return EXIT_FAILURE;
    }
    std::string server_host = std::string("0.0.0.0:")
        + FLAGS_agent_port;

    if (!rpc_server.Start(server_host)) {
        LOG(WARNING, "Rpc Server Start failed");
        return EXIT_FAILURE;
    }
    std::vector<std::pair<std::string, std::string> > router;
    router.push_back(std::make_pair("/gc", FLAGS_agent_gc_dir));
    router.push_back(std::make_pair("/container", FLAGS_agent_work_dir));
    router.push_back(std::make_pair("/coredump", FLAGS_agent_coredump_dir));
    ::baidu::galaxy::HttpFileServer http_server(router, FLAGS_agent_http_port);
    http_server.Start(10);
    LOG(INFO, "start http server on %d", FLAGS_agent_http_port);
    signal(SIGINT, StopSigHandler);
    signal(SIGTERM, StopSigHandler);
    signal(SIGCHLD, SigChldHandler);
    while (!s_is_stop) {
        sleep(5);
    }

    return EXIT_SUCCESS;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperQtWidgetInputImageListParameter.h"

namespace otb
{
namespace Wrapper
{

QtWidgetInputImageListParameter::QtWidgetInputImageListParameter(InputImageListParameter* param, QtWidgetModel* m)
: QtWidgetParameterBase(m),
  m_InputImageListParam(param)
{
}

QtWidgetInputImageListParameter::~QtWidgetInputImageListParameter()
{
}

void QtWidgetInputImageListParameter::DoUpdateGUI()
{

}

void QtWidgetInputImageListParameter::DoCreateWidget()
{
hg   m_FileSelectionList.clear();
  const unsigned int sp(2);
  const unsigned int buttonSize(30);

  // Global layout
  QHBoxLayout * hLayout = new QHBoxLayout;
  hLayout->setSpacing(sp);
  hLayout->setContentsMargins(sp, sp, sp, sp);

  // Button layout
  QVBoxLayout * buttonLayout = new QVBoxLayout;
  buttonLayout->setSpacing(sp);
  buttonLayout->setContentsMargins(sp, sp, sp, sp);

  QHBoxLayout * addSupLayout = new QHBoxLayout;
  addSupLayout->setSpacing(sp);
  addSupLayout->setContentsMargins(sp, sp, sp, sp);

  QHBoxLayout * upDownLayout = new QHBoxLayout;
  upDownLayout->setSpacing(sp);
  upDownLayout->setContentsMargins(sp, sp, sp, sp);

  // Add file button
  QPushButton * addButton = new QPushButton;
  addButton->setText("+");
  addButton->setFixedWidth(buttonSize);
  addButton->setToolTip("Add a file selector...");
  addButton->setMaximumWidth(addButton->width());
  connect( addButton, SIGNAL(clicked()), this, SLOT(AddFile()) );
  addSupLayout->addWidget(addButton);

  // Supress file button
  QPushButton * supButton = new QPushButton;
  supButton->setText("-");
  supButton->setFixedWidth(buttonSize);
  supButton->setToolTip("Supress the selected file...");
  supButton->setMaximumWidth(supButton->width());
  connect( supButton, SIGNAL(clicked()), this, SLOT(SupressFile()) );
  addSupLayout->addWidget(supButton);
  buttonLayout->addLayout(addSupLayout);

  // Up file edit
  QPushButton * upButton = new QPushButton;
  upButton->setText("Up");
  upButton->setFixedWidth(buttonSize);
  upButton->setToolTip("Up the selected file in the list...");
  upButton->setMaximumWidth(upButton->width());
  connect( upButton, SIGNAL(clicked()), this, SLOT(UpFile()) );
  upDownLayout->addWidget(upButton);

  // Down file edit
  QPushButton * downButton = new QPushButton;
  downButton->setText("Down");
  downButton->setFixedWidth(buttonSize);
  downButton->setToolTip("Down the selected file in the list...");
  downButton->setMaximumWidth(downButton->width());
  connect( downButton, SIGNAL(clicked()), this, SLOT(DownFile()) );
  upDownLayout->addWidget(downButton);
  buttonLayout->addLayout(upDownLayout);

  // Erase file edit
  QPushButton * eraseButton = new QPushButton;
  eraseButton->setText("Erase");
  eraseButton->setFixedWidth(2*buttonSize);
  eraseButton->setToolTip("Erase the selected file of the list...");
  eraseButton->setMaximumWidth(eraseButton->width());
  connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseFile()) );
  buttonLayout->addWidget(eraseButton);

  QVBoxLayout * fileLayout = new QVBoxLayout();
  fileLayout->setSpacing(0);

  QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget(m_InputImageListParam);
  fileSelection->setFixedHeight(40);
  fileLayout->addWidget( fileSelection );
  m_FileSelectionList.push_back(fileSelection);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(fileLayout);
  QScrollArea * scroll = new QScrollArea();
  scroll->setWidget(mainGroup);
  //scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

  hLayout->addWidget(scroll);
  hLayout->addLayout(buttonLayout);

  hLayout->addStretch();

  this->setLayout(hLayout);

  m_FileLayout = fileLayout;
  m_HLayout = hLayout;
  m_Scroll = scroll;

}

void
QtWidgetInputImageListParameter::UpFile()
{
 if(m_FileSelectionList.size() < 2 )
    return;

  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(2);
  m_FileLayout->addStretch();

  // Map link between old and new index in the list
  std::map<unsigned int, unsigned int> idMap;

  // Init map
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    idMap[i] = i;
    }

  // If the first item is checked, uncheck it...
  // It won't be moved
  if( m_FileSelectionList[0]->IsChecked() )
    {
    m_FileSelectionList[0]->SetChecked(false);
    }

  // If other item are checked, up the index
  // Starts at 1 because the first item mustn't move
  for(unsigned int i=1; i<m_FileSelectionList.size(); i++ )
    {
    if( m_FileSelectionList[i]->IsChecked() )
      {
      unsigned int tmp = idMap[i];
      idMap[i] = i-1;
      idMap[idMap[i-1]] = tmp;
      }
    }

  this->UpdateFileList( idMap );

  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::DownFile()
{
  if(m_FileSelectionList.size() < 2 )
    return;

  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(0);
  m_FileLayout->addStretch();

  // Map link between old and new index in the list
  std::map<unsigned int, unsigned int> idMap;

  // Init map
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    idMap[i] = i;
    }

  // If the last item is checked, uncheck it...
  // It won't be moved
  if( m_FileSelectionList[m_FileSelectionList.size()-1]->IsChecked() )
    {
    m_FileSelectionList[m_FileSelectionList.size()-1]->SetChecked(false);
    }

  // If other item are checked, up the index
  // Stops at size-1 because the last item mustn't move
  for(int i=m_FileSelectionList.size()-2; i>=0; i-- )
    {
    if( m_FileSelectionList[i]->IsChecked() )
      {
      unsigned int tmp = idMap[i];
      idMap[i] = i+1;
       idMap[idMap[i+1]] = tmp;
      }
    }

  this->UpdateFileList( idMap );

  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::UpdateFileList( std::map<unsigned int, unsigned int> idMap )
{
  std::vector<QtFileSelectionWidget *> tmpList;
  // Keys become values and inverse
  std::map<unsigned int, unsigned int> idMapBis;
  for(unsigned int i=0; i<idMap.size(); i++ )
    {
    idMapBis[ idMap[i] ] = i;
    }

  // Create the new item list
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    m_FileLayout->addWidget( m_FileSelectionList[ idMapBis[i] ] );
    tmpList.push_back(m_FileSelectionList[ idMapBis[i] ]);
    }

  m_FileSelectionList =  tmpList;
  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
}

void
QtWidgetInputImageListParameter::AddFile()
{
  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(0);
  m_FileLayout->addStretch();
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    m_FileLayout->addWidget( m_FileSelectionList[i] );
    }

  QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();
  fileSelection->setFixedHeight( 30 );
  m_FileLayout->addWidget( fileSelection );
  m_FileSelectionList.push_back(fileSelection);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::SupressFile()
{
  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(0);
  m_FileLayout->addStretch();
  std::vector<QtFileSelectionWidget *> tmpList;
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    if( !m_FileSelectionList[i]->IsChecked() )
      {
      m_FileLayout->addWidget( m_FileSelectionList[i] );
      tmpList.push_back(m_FileSelectionList[i]);
      }
    }

  m_FileSelectionList =  tmpList;

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::EraseFile()
{
  m_FileSelectionList.clear();

  m_FileLayout = new QVBoxLayout();

  QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();
  fileSelection->setFixedHeight( 40 );
  m_FileLayout->addWidget( fileSelection );
  m_FileSelectionList.push_back(fileSelection);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
  this->RecreateImageList();
}

void QtWidgetInputImageListParameter::RecreateImageList()
{
  // save value
  m_InputImageListParam->Clear();
  for(unsigned int j=0; j<m_FileSelectionList.size(); j++ )
    {
    if( m_FileSelectionList[j]->GetFilename() != "" )
      m_InputImageListParam->AddFromFileName(m_FileSelectionList[j]->GetFilename());
    }

  // notify of value change
  QString key( QString::fromStdString(m_InputImageListParam->GetKey()) );
  emit ParameterChanged(key);
}

}
}
<commit_msg>COMP: error in file<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperQtWidgetInputImageListParameter.h"

namespace otb
{
namespace Wrapper
{

QtWidgetInputImageListParameter::QtWidgetInputImageListParameter(InputImageListParameter* param, QtWidgetModel* m)
: QtWidgetParameterBase(m),
  m_InputImageListParam(param)
{
}

QtWidgetInputImageListParameter::~QtWidgetInputImageListParameter()
{
}

void QtWidgetInputImageListParameter::DoUpdateGUI()
{

}

void QtWidgetInputImageListParameter::DoCreateWidget()
{
  m_FileSelectionList.clear();
  const unsigned int sp(2);
  const unsigned int buttonSize(30);

  // Global layout
  QHBoxLayout * hLayout = new QHBoxLayout;
  hLayout->setSpacing(sp);
  hLayout->setContentsMargins(sp, sp, sp, sp);

  // Button layout
  QVBoxLayout * buttonLayout = new QVBoxLayout;
  buttonLayout->setSpacing(sp);
  buttonLayout->setContentsMargins(sp, sp, sp, sp);

  QHBoxLayout * addSupLayout = new QHBoxLayout;
  addSupLayout->setSpacing(sp);
  addSupLayout->setContentsMargins(sp, sp, sp, sp);

  QHBoxLayout * upDownLayout = new QHBoxLayout;
  upDownLayout->setSpacing(sp);
  upDownLayout->setContentsMargins(sp, sp, sp, sp);

  // Add file button
  QPushButton * addButton = new QPushButton;
  addButton->setText("+");
  addButton->setFixedWidth(buttonSize);
  addButton->setToolTip("Add a file selector...");
  addButton->setMaximumWidth(addButton->width());
  connect( addButton, SIGNAL(clicked()), this, SLOT(AddFile()) );
  addSupLayout->addWidget(addButton);

  // Supress file button
  QPushButton * supButton = new QPushButton;
  supButton->setText("-");
  supButton->setFixedWidth(buttonSize);
  supButton->setToolTip("Supress the selected file...");
  supButton->setMaximumWidth(supButton->width());
  connect( supButton, SIGNAL(clicked()), this, SLOT(SupressFile()) );
  addSupLayout->addWidget(supButton);
  buttonLayout->addLayout(addSupLayout);

  // Up file edit
  QPushButton * upButton = new QPushButton;
  upButton->setText("Up");
  upButton->setFixedWidth(buttonSize);
  upButton->setToolTip("Up the selected file in the list...");
  upButton->setMaximumWidth(upButton->width());
  connect( upButton, SIGNAL(clicked()), this, SLOT(UpFile()) );
  upDownLayout->addWidget(upButton);

  // Down file edit
  QPushButton * downButton = new QPushButton;
  downButton->setText("Down");
  downButton->setFixedWidth(buttonSize);
  downButton->setToolTip("Down the selected file in the list...");
  downButton->setMaximumWidth(downButton->width());
  connect( downButton, SIGNAL(clicked()), this, SLOT(DownFile()) );
  upDownLayout->addWidget(downButton);
  buttonLayout->addLayout(upDownLayout);

  // Erase file edit
  QPushButton * eraseButton = new QPushButton;
  eraseButton->setText("Erase");
  eraseButton->setFixedWidth(2*buttonSize);
  eraseButton->setToolTip("Erase the selected file of the list...");
  eraseButton->setMaximumWidth(eraseButton->width());
  connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseFile()) );
  buttonLayout->addWidget(eraseButton);

  QVBoxLayout * fileLayout = new QVBoxLayout();
  fileLayout->setSpacing(0);

  QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget(m_InputImageListParam);
  fileSelection->setFixedHeight(40);
  fileLayout->addWidget( fileSelection );
  m_FileSelectionList.push_back(fileSelection);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(fileLayout);
  QScrollArea * scroll = new QScrollArea();
  scroll->setWidget(mainGroup);
  //scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

  hLayout->addWidget(scroll);
  hLayout->addLayout(buttonLayout);

  hLayout->addStretch();

  this->setLayout(hLayout);

  m_FileLayout = fileLayout;
  m_HLayout = hLayout;
  m_Scroll = scroll;

}

void
QtWidgetInputImageListParameter::UpFile()
{
 if(m_FileSelectionList.size() < 2 )
    return;

  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(2);
  m_FileLayout->addStretch();

  // Map link between old and new index in the list
  std::map<unsigned int, unsigned int> idMap;

  // Init map
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    idMap[i] = i;
    }

  // If the first item is checked, uncheck it...
  // It won't be moved
  if( m_FileSelectionList[0]->IsChecked() )
    {
    m_FileSelectionList[0]->SetChecked(false);
    }

  // If other item are checked, up the index
  // Starts at 1 because the first item mustn't move
  for(unsigned int i=1; i<m_FileSelectionList.size(); i++ )
    {
    if( m_FileSelectionList[i]->IsChecked() )
      {
      unsigned int tmp = idMap[i];
      idMap[i] = i-1;
      idMap[idMap[i-1]] = tmp;
      }
    }

  this->UpdateFileList( idMap );

  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::DownFile()
{
  if(m_FileSelectionList.size() < 2 )
    return;

  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(0);
  m_FileLayout->addStretch();

  // Map link between old and new index in the list
  std::map<unsigned int, unsigned int> idMap;

  // Init map
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    idMap[i] = i;
    }

  // If the last item is checked, uncheck it...
  // It won't be moved
  if( m_FileSelectionList[m_FileSelectionList.size()-1]->IsChecked() )
    {
    m_FileSelectionList[m_FileSelectionList.size()-1]->SetChecked(false);
    }

  // If other item are checked, up the index
  // Stops at size-1 because the last item mustn't move
  for(int i=m_FileSelectionList.size()-2; i>=0; i-- )
    {
    if( m_FileSelectionList[i]->IsChecked() )
      {
      unsigned int tmp = idMap[i];
      idMap[i] = i+1;
       idMap[idMap[i+1]] = tmp;
      }
    }

  this->UpdateFileList( idMap );

  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::UpdateFileList( std::map<unsigned int, unsigned int> idMap )
{
  std::vector<QtFileSelectionWidget *> tmpList;
  // Keys become values and inverse
  std::map<unsigned int, unsigned int> idMapBis;
  for(unsigned int i=0; i<idMap.size(); i++ )
    {
    idMapBis[ idMap[i] ] = i;
    }

  // Create the new item list
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    m_FileLayout->addWidget( m_FileSelectionList[ idMapBis[i] ] );
    tmpList.push_back(m_FileSelectionList[ idMapBis[i] ]);
    }

  m_FileSelectionList =  tmpList;
  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
}

void
QtWidgetInputImageListParameter::AddFile()
{
  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(0);
  m_FileLayout->addStretch();
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    m_FileLayout->addWidget( m_FileSelectionList[i] );
    }

  QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();
  fileSelection->setFixedHeight( 30 );
  m_FileLayout->addWidget( fileSelection );
  m_FileSelectionList.push_back(fileSelection);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::SupressFile()
{
  m_FileLayout = new QVBoxLayout();
  m_FileLayout->setSpacing(0);
  m_FileLayout->addStretch();
  std::vector<QtFileSelectionWidget *> tmpList;
  for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )
    {
    if( !m_FileSelectionList[i]->IsChecked() )
      {
      m_FileLayout->addWidget( m_FileSelectionList[i] );
      tmpList.push_back(m_FileSelectionList[i]);
      }
    }

  m_FileSelectionList =  tmpList;

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
  this->RecreateImageList();
}

void
QtWidgetInputImageListParameter::EraseFile()
{
  m_FileSelectionList.clear();

  m_FileLayout = new QVBoxLayout();

  QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();
  fileSelection->setFixedHeight( 40 );
  m_FileLayout->addWidget( fileSelection );
  m_FileSelectionList.push_back(fileSelection);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(m_FileLayout);
  m_Scroll->setWidget(mainGroup);

  this->update();
  this->RecreateImageList();
}

void QtWidgetInputImageListParameter::RecreateImageList()
{
  // save value
  m_InputImageListParam->Clear();
  for(unsigned int j=0; j<m_FileSelectionList.size(); j++ )
    {
    if( m_FileSelectionList[j]->GetFilename() != "" )
      m_InputImageListParam->AddFromFileName(m_FileSelectionList[j]->GetFilename());
    }

  // notify of value change
  QString key( QString::fromStdString(m_InputImageListParam->GetKey()) );
  emit ParameterChanged(key);
}

}
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <string>
#include <assert.h>
#include "phstream.h"
#include <mpi.h>

#ifndef PHSTREAM_TIMERS_ON
#define PHSTREAM_TIMERS_ON 0
#endif

namespace {
  inline double getTime() {
    return MPI_Wtime();
  }
  inline bool isRankZero() {
    int rank = 0;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    return !rank;
  }
  inline void printTime(const char* key, double t) {
    (void) key;
    (void) t;
#if PHSTREAM_TIMERS_ON==1
    if( isRankZero() )
      fprintf(stderr, "%s %f seconds\n", key, t);
#endif
  }
}

extern "C" {
  struct RStream{
    char* restart;
    size_t rSz;
  };
}

extern "C" {
  struct GRStream{
    char *geom, *restart;
    size_t gSz, rSz;
  };
}

RStream* makeRStream() {
  const double t0 = getTime();
  RStream* rs = (RStream*) malloc(sizeof(RStream));
  rs->restart = NULL;
  rs->rSz = 0;
  printTime(__func__, getTime()-t0);
  return rs;
}

#ifdef __APPLE__
FILE* openRStreamRead(RStream* rs) {
  return NULL;
}
#else
FILE* openRStreamRead(RStream* rs) {
  const double t0 = getTime();
  FILE* f = fmemopen(rs->restart, rs->rSz, "r");
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

#ifdef __APPLE__
FILE* openRStreamWrite(RStream* rs) {
  return NULL;
}
#else
FILE* openRStreamWrite(RStream* rs) {
  const double t0 = getTime();
  FILE* f = open_memstream(&(rs->restart), &(rs->rSz));
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

void clearRStream(RStream* rs) {
  const double t0 = getTime();
  if(rs->restart) {
    free(rs->restart);
    rs->restart = NULL;
    rs->rSz = 0;
  }
  printTime(__func__, getTime()-t0);
}

void destroyRStream(RStream* rs) {
  const double t0 = getTime();
  clearRStream(rs);
  free(rs);
  printTime(__func__, getTime()-t0);
}

void attachRStream(GRStream* grs, RStream* rs) {
  const double t0 = getTime();
  rs->restart = grs->restart;
  rs->rSz = grs->rSz;
  grs->restart = NULL;
  grs->rSz = 0;
  printTime(__func__, getTime()-t0);
}

GRStream* makeGRStream() {
  const double t0 = getTime();
  GRStream* grs = (GRStream*) malloc(sizeof(GRStream));
  grs->geom = NULL;
  grs->gSz = 0;
  grs->restart = NULL;
  grs->rSz = 0;
  printTime(__func__, getTime()-t0);
  return grs;
}

void whichStream(const char* name, bool& isR, bool& isG) {
  const double t0 = getTime();
  std::string fname(name);
  std::string restartStr("restart");
  std::string geombcStr("geombc");
  isR = (fname.find(restartStr) != std::string::npos);
  isG = (fname.find(geombcStr)  != std::string::npos);
  assert(isR != isG);
  printTime(__func__, getTime()-t0);
}

void writeUnknown(const char* fname) {
  fprintf(stderr,
      "ERROR %s type of stream %s is unknown... exiting\n",
      __func__, fname);
}

#ifdef __APPLE__
FILE* openGRStreamRead(GRStream* grs, const char* named) {
  return NULL;
}
#else
FILE* openGRStreamRead(GRStream* grs, const char* named) {
  const double t0 = getTime();
  bool isR, isG;
  whichStream(named, isR, isG);
  FILE* f = NULL;
  if( isR && !isG )
    f = fmemopen(grs->restart, grs->rSz, "r");
  else if( isG && !isR )
    f = fmemopen(grs->geom, grs->gSz, "r");
  else {
    writeUnknown(named);
    exit(1);
  }
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

#ifdef __APPLE__
FILE* openGRStreamWrite(GRStream* grs, const char* named) {
  return NULL;
}
#else
FILE* openGRStreamWrite(GRStream* grs, const char* named) {
  const double t0 = getTime();
  bool isR, isG;
  whichStream(named, isR, isG);
  FILE* f = NULL;
  if( isR && !isG )
    f = open_memstream(&(grs->restart), &(grs->rSz));
  else if( isG && !isR )
    f = open_memstream(&(grs->geom), &(grs->gSz));
  else {
    writeUnknown(named);
    exit(1);
  }
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

void clearGRStream(GRStream* grs) {
  const double t0 = getTime();
  if(grs->geom) {
    free(grs->geom);
    grs->geom = NULL;
    grs->gSz = 0;
  }
  if(grs->restart) {
    free(grs->restart);
    grs->restart = NULL;
    grs->rSz = 0;
  }
  printTime(__func__, getTime()-t0);
}

void destroyGRStream(GRStream* grs) {
  const double t0 = getTime();
  clearGRStream(grs);
  free(grs);
  printTime(__func__, getTime()-t0);
}

<commit_msg>phstream : silence unused variable errors<commit_after>#include <stdlib.h>
#include <string>
#include <assert.h>
#include "phstream.h"
#include <mpi.h>

#ifndef PHSTREAM_TIMERS_ON
#define PHSTREAM_TIMERS_ON 0
#endif

namespace {
  inline double getTime() {
    return MPI_Wtime();
  }
#if PHSTREAM_TIMERS_ON==1
  inline bool isRankZero() {
    int rank = 0;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    return !rank;
  }
#endif
  inline void printTime(const char* key, double t) {
    (void) key;
    (void) t;
#if PHSTREAM_TIMERS_ON==1
    if( isRankZero() )
      fprintf(stderr, "%s %f seconds\n", key, t);
#endif
  }
}

extern "C" {
  struct RStream{
    char* restart;
    size_t rSz;
  };
}

extern "C" {
  struct GRStream{
    char *geom, *restart;
    size_t gSz, rSz;
  };
}

RStream* makeRStream() {
  const double t0 = getTime();
  RStream* rs = (RStream*) malloc(sizeof(RStream));
  rs->restart = NULL;
  rs->rSz = 0;
  printTime(__func__, getTime()-t0);
  return rs;
}

#ifdef __APPLE__
FILE* openRStreamRead(RStream*) {
  return NULL;
}
#else
FILE* openRStreamRead(RStream* rs) {
  const double t0 = getTime();
  FILE* f = fmemopen(rs->restart, rs->rSz, "r");
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

#ifdef __APPLE__
FILE* openRStreamWrite(RStream*) {
  return NULL;
}
#else
FILE* openRStreamWrite(RStream* rs) {
  const double t0 = getTime();
  FILE* f = open_memstream(&(rs->restart), &(rs->rSz));
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

void clearRStream(RStream* rs) {
  const double t0 = getTime();
  if(rs->restart) {
    free(rs->restart);
    rs->restart = NULL;
    rs->rSz = 0;
  }
  printTime(__func__, getTime()-t0);
}

void destroyRStream(RStream* rs) {
  const double t0 = getTime();
  clearRStream(rs);
  free(rs);
  printTime(__func__, getTime()-t0);
}

void attachRStream(GRStream* grs, RStream* rs) {
  const double t0 = getTime();
  rs->restart = grs->restart;
  rs->rSz = grs->rSz;
  grs->restart = NULL;
  grs->rSz = 0;
  printTime(__func__, getTime()-t0);
}

GRStream* makeGRStream() {
  const double t0 = getTime();
  GRStream* grs = (GRStream*) malloc(sizeof(GRStream));
  grs->geom = NULL;
  grs->gSz = 0;
  grs->restart = NULL;
  grs->rSz = 0;
  printTime(__func__, getTime()-t0);
  return grs;
}

void whichStream(const char* name, bool& isR, bool& isG) {
  const double t0 = getTime();
  std::string fname(name);
  std::string restartStr("restart");
  std::string geombcStr("geombc");
  isR = (fname.find(restartStr) != std::string::npos);
  isG = (fname.find(geombcStr)  != std::string::npos);
  assert(isR != isG);
  printTime(__func__, getTime()-t0);
}

void writeUnknown(const char* fname) {
  fprintf(stderr,
      "ERROR %s type of stream %s is unknown... exiting\n",
      __func__, fname);
}

#ifdef __APPLE__
FILE* openGRStreamRead(GRStream*, const char*) {
  return NULL;
}
#else
FILE* openGRStreamRead(GRStream* grs, const char* named) {
  const double t0 = getTime();
  bool isR, isG;
  whichStream(named, isR, isG);
  FILE* f = NULL;
  if( isR && !isG )
    f = fmemopen(grs->restart, grs->rSz, "r");
  else if( isG && !isR )
    f = fmemopen(grs->geom, grs->gSz, "r");
  else {
    writeUnknown(named);
    exit(1);
  }
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

#ifdef __APPLE__
FILE* openGRStreamWrite(GRStream*, const char*) {
  return NULL;
}
#else
FILE* openGRStreamWrite(GRStream* grs, const char* named) {
  const double t0 = getTime();
  bool isR, isG;
  whichStream(named, isR, isG);
  FILE* f = NULL;
  if( isR && !isG )
    f = open_memstream(&(grs->restart), &(grs->rSz));
  else if( isG && !isR )
    f = open_memstream(&(grs->geom), &(grs->gSz));
  else {
    writeUnknown(named);
    exit(1);
  }
  printTime(__func__, getTime()-t0);
  return f;
}
#endif

void clearGRStream(GRStream* grs) {
  const double t0 = getTime();
  if(grs->geom) {
    free(grs->geom);
    grs->geom = NULL;
    grs->gSz = 0;
  }
  if(grs->restart) {
    free(grs->restart);
    grs->restart = NULL;
    grs->rSz = 0;
  }
  printTime(__func__, getTime()-t0);
}

void destroyGRStream(GRStream* grs) {
  const double t0 = getTime();
  clearGRStream(grs);
  free(grs);
  printTime(__func__, getTime()-t0);
}

<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2015 VMware, Inc.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 **************************************************************************/

#include "guids.hpp"

#include "gtest/gtest.h"

#define GUID_ENTRY(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8,name) \
    TEST(guids, name_##name) { \
        static const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; \
        EXPECT_STREQ(#name, getGuidName(name)); \
    }

#include "guids_entries.h"

TEST(guids, name_generic) {
    static const GUID dummy = {0x01234567,0x89AB,0xCDEF,{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF}};
    EXPECT_STREQ("uuid(01234567-89ab-cdef-0123-456789abcdef)",
                 getGuidName(dummy));
}

int
main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>guids: Single test for all known GUIDs.<commit_after>/**************************************************************************
 *
 * Copyright 2015 VMware, Inc.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 **************************************************************************/

#include "guids.hpp"

#include "gtest/gtest.h"

TEST(guids, name_known)
{

#   define GUID_ENTRY(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8,name) \
        static const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; \
        EXPECT_STREQ(#name, getGuidName(name));

#   include "guids_entries.h"

}

TEST(guids, name_unknown)
{
    static const GUID dummy = {0x01234567,0x89AB,0xCDEF,{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF}};
    EXPECT_STREQ("uuid(01234567-89ab-cdef-0123-456789abcdef)",
                 getGuidName(dummy));
}

int
main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#include <stdexcept>

#include "neuron.hpp"
#include "network.hpp"

int glob_argc;
char **glob_argv;

void parse_iterable(std::vector<double> &arr, PyObject *iter)
{
    while (true) {
        PyObject *next = PyIter_Next(iter);
        if (!next) {
            // nothing left in the iterator
            break;
        }

        if (!PyFloat_Check(next)) {
            throw std::invalid_argument("One of the arguments contains an illegal value (other than float)");
        }

        double val = PyFloat_AsDouble(next);
        arr.push_back(val);
    }
}

typedef struct {
    PyObject_HEAD
    Network * ptrObj;
} PyNetwork;

typedef struct {
    PyObject_HEAD
    Neuron * ptrObj;
} PyNeuron;

static int PyNetwork_init(PyNetwork *self, PyObject *args, PyObject *kwargs)
{
    int size;
    int input_dim = 0;
    int output_dim = 0;
    double connectivity = 0.01;
    int precision = 2;
    int randomly_fire = false;
    int dynamic_output = false;
    int visualization = false;
    double decay_factor =  1.0;

    static char *kwlist[] = {"size", "input_dim", "output_dim", "connectivity", "precision", "randomly_fire", "dynamic_output", "visualization", "decay_factor", NULL};

    if (! PyArg_ParseTupleAndKeywords(args, kwargs, "i|iidipppd", kwlist, &size, &input_dim, &output_dim, &connectivity, &precision, &randomly_fire, &dynamic_output, &visualization, &decay_factor))
        return -1;

    self->ptrObj = new Network(size, input_dim, output_dim, connectivity, precision, randomly_fire, dynamic_output, visualization, decay_factor);

    return 0;
}

static int PyNeuron_init(PyNeuron *self, PyObject *args)
{
    PyNetwork * network;

    if (! PyArg_ParseTuple(args, "O", &network))
        return -1;

    self->ptrObj = new Neuron(*network->ptrObj);

    return 0;
}

static void PyNetwork_dealloc(PyNetwork * self)
{
    delete self->ptrObj;
    Py_TYPE(self)->tp_free(self);
}

static void PyNeuron_dealloc(PyNeuron * self)
{
    delete self->ptrObj;
    Py_TYPE(self)->tp_free(self);
}

static PyObject * PyNetwork_load(PyNetwork* self, PyObject* args, PyObject *kwargs)
{
    std::vector<double> input_arr;
    std::vector<double> output_arr;
    PyObject *input_obj;
    PyObject *output_obj = Py_None;

    static char *kwlist[] = {"input_obj", "output_obj", NULL};

    if (! PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &input_obj, &output_obj))
        throw std::invalid_argument("Wrong type of argument");

    PyObject *input_iter = PyObject_GetIter(input_obj);
    if (!input_iter) {
        throw std::invalid_argument("Input argument is not iterable");
    }
    parse_iterable(input_arr, input_iter);

    if (output_obj != Py_None) {
        PyObject *output_iter = PyObject_GetIter(output_obj);
        if (!output_iter) {
            throw std::invalid_argument("Output argument is not iterable");
        }
        parse_iterable(output_arr, output_iter);
    }

    (self->ptrObj)->load(input_arr, output_arr);

    return Py_BuildValue("");
}

static PyObject * PyNetwork_freeze(PyNetwork* self)
{
    (self->ptrObj)->freeze();

    return Py_BuildValue("");
}

static PyObject * PyNetwork_get_precision(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->precision);
}

static PyObject * PyNetwork_get_connectivity(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->connectivity);
}

static PyObject * PyNetwork_get_connectivity_sqrt(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->connectivity_sqrt);
}

static PyObject * PyNetwork_get_input_dim(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->input_dim);
}

static PyObject * PyNetwork_get_output_dim(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->output_dim);
}

static PyObject * PyNetwork_get_randomly_fire(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->randomly_fire);
}

static PyObject * PyNetwork_get_motor_randomly_fire_rate(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->motor_randomly_fire_rate);
}

static PyObject * PyNetwork_get_dynamic_output(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->dynamic_output);
}

static PyObject * PyNetwork_get_decay_factor(PyNetwork *self, void *closure)
{
    return Py_BuildValue("d", self->ptrObj->decay_factor);
}

static PyObject * PyNetwork_get_initiated_neurons(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->initiated_neurons);
}

static PyObject * PyNetwork_get_freezer(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->freezer);
}

static PyObject * PyNetwork_get_thread_kill_signal(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->thread_kill_signal);
}

static PyObject * PyNetwork_get_wave_counter(PyNetwork *self, void *closure)
{
    return Py_BuildValue("l", self->ptrObj->wave_counter);
}

static PyObject * PyNetwork_get_fire_counter(PyNetwork *self, void *closure)
{
    return Py_BuildValue("l", self->ptrObj->fire_counter);
}

static PyObject * PyNetwork_get_output(PyNetwork *self, void *closure)
{
    std::vector<double> output;

    output = (self->ptrObj)->get_output();

    PyObject *PList = PyList_New(0);
    std::vector<int>::const_iterator it;

    for (const auto& i: output)
        PyList_Append(PList, Py_BuildValue("d", i));

    return PList;
}

static PyObject * PyNetwork_get_neurons(PyNetwork *self, void *closure)
{
    std::vector<Neuron*> neurons = (self->ptrObj)->neurons;

    PyObject *PList = PyList_New(0);
    std::vector<int>::const_iterator it;

    for (const auto& i: neurons)
        PyList_Append(PList, Py_BuildValue("O", i));

    return PList;
}

static PyMethodDef PyNetwork_methods[] = {
    {"load", (PyCFunction)PyNetwork_load, METH_VARARGS | METH_KEYWORDS, "Load input and output into the neural network" },
    {"freeze", (PyCFunction)PyNetwork_freeze, METH_NOARGS, "Freeze the neural network" },
    {NULL}  /* Sentinel */
};

static PyMethodDef PyNeuron_methods[] = {
    {NULL}  /* Sentinel */
};

static PyMemberDef PyNetwork_members[] = {
    {NULL}  /* Sentinel */
};

static PyMemberDef PyNeuron_members[] = {
    {NULL}  /* Sentinel */
};

static PyGetSetDef PyNetwork_getseters[] = {
    {"precision", (getter)PyNetwork_get_precision, NULL, "Precision of the network", NULL},
    {"connectivity", (getter)PyNetwork_get_connectivity, NULL, "Connectivity of the network", NULL},
    {"connectivity_sqrt", (getter)PyNetwork_get_connectivity_sqrt, NULL, "Square root of the connectivity of the network", NULL},
    {"input_dim", (getter)PyNetwork_get_input_dim, NULL, "Input dimension of the network", NULL},
    {"output_dim", (getter)PyNetwork_get_output_dim, NULL, "Output dimension of the network", NULL},
    {"randomly_fire", (getter)PyNetwork_get_randomly_fire, NULL, "Is randomly fire enabled for the network?", NULL},
    {"motor_randomly_fire_rate", (getter)PyNetwork_get_motor_randomly_fire_rate, NULL, "Motor neurons' randomly fire rate", NULL},
    {"dynamic_output", (getter)PyNetwork_get_dynamic_output, NULL, "Is dynamic output enabled for the network?", NULL},
    {"decay_factor", (getter)PyNetwork_get_decay_factor, NULL, "Decay factor of the network", NULL},
    {"initiated_neurons", (getter)PyNetwork_get_initiated_neurons, NULL, "Initiated neuron count of the network", NULL},
    {"freezer", (getter)PyNetwork_get_freezer, NULL, "Is freezing enabled for the network?", NULL},
    {"thread_kill_signal", (getter)PyNetwork_get_thread_kill_signal, NULL, "Are threads signalled for kill?", NULL},
    {"wave_counter", (getter)PyNetwork_get_wave_counter, NULL, "Holds the integer value of how many waves executed throughout the network", NULL},
    {"fire_counter", (getter)PyNetwork_get_fire_counter, NULL, "Holds the integer value of how many neurons fired during the training", NULL},
    {"output", (getter)PyNetwork_get_output, NULL, "Shows the output of the neural network", NULL},
    {"neurons", (getter)PyNetwork_get_neurons, NULL, "Holds the neurons in the neural network", NULL},
    {NULL}  /* Sentinel */
};

static PyTypeObject PyNetworkType = { PyVarObject_HEAD_INIT(NULL, 0)
    "plexus.Network"   /* tp_name */
};

static PyTypeObject PyNeuronType = { PyVarObject_HEAD_INIT(NULL, 0)
    "plexus.Neuron"   /* tp_name */
};

static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "cplexus",          /* name of module */
    "",                 /* module documentation, may be NULL */
    -1,                 /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
    NULL, NULL, NULL, NULL, NULL
};

PyMODINIT_FUNC PyInit_cplexus(void)
// create the module
{
    PyObject* m;

    PyNetworkType.tp_new = PyType_GenericNew;
    PyNetworkType.tp_basicsize=sizeof(PyNetwork);
    PyNetworkType.tp_dealloc=(destructor) PyNetwork_dealloc;
    PyNetworkType.tp_flags=Py_TPFLAGS_DEFAULT;
    PyNetworkType.tp_doc="Network objects";
    PyNetworkType.tp_methods=PyNetwork_methods;
    PyNetworkType.tp_members=PyNetwork_members;
    PyNetworkType.tp_getset=PyNetwork_getseters;
    PyNetworkType.tp_init=(initproc)PyNetwork_init;

    PyNeuronType.tp_new = PyType_GenericNew;
    PyNeuronType.tp_basicsize=sizeof(PyNeuron);
    PyNeuronType.tp_dealloc=(destructor) PyNeuron_dealloc;
    PyNeuronType.tp_flags=Py_TPFLAGS_DEFAULT;
    PyNeuronType.tp_doc="Neuron objects";
    PyNeuronType.tp_methods=PyNeuron_methods;
    PyNeuronType.tp_members=PyNeuron_members;
    PyNeuronType.tp_init=(initproc)PyNeuron_init;

    if (PyType_Ready(&PyNetworkType) < 0)
        return NULL;

    if (PyType_Ready(&PyNeuronType) < 0)
        return NULL;

    m = PyModule_Create(&moduledef);
    if (m == NULL)
        return NULL;

    Py_INCREF(&PyNetworkType);
    Py_INCREF(&PyNeuronType);
    PyModule_AddObject(m, "Network", (PyObject *)&PyNetworkType); // Add Network object to the module
    PyModule_AddObject(m, "Neuron", (PyObject *)&PyNeuronType); // Add Neuron object to the module
    return m;
}

void initcplexus(void)
{
    PyInit_cplexus();
}

int main(int argc, char *argv[])
{
    glob_argc = argc;
    glob_argv = argv;

    wchar_t *program = Py_DecodeLocale(argv[0], NULL);

    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(program);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Add a static module */
    initcplexus();
}
<commit_msg>Append PyNeuron instead of Neuron to PyList in PyNetwork_get_neurons() function<commit_after>#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#include <stdexcept>

#include "neuron.hpp"
#include "network.hpp"

int glob_argc;
char **glob_argv;

void parse_iterable(std::vector<double> &arr, PyObject *iter)
{
    while (true) {
        PyObject *next = PyIter_Next(iter);
        if (!next) {
            // nothing left in the iterator
            break;
        }

        if (!PyFloat_Check(next)) {
            throw std::invalid_argument("One of the arguments contains an illegal value (other than float)");
        }

        double val = PyFloat_AsDouble(next);
        arr.push_back(val);
    }
}

typedef struct {
    PyObject_HEAD
    Network * ptrObj;
} PyNetwork;

typedef struct {
    PyObject_HEAD
    Neuron * ptrObj;
} PyNeuron;

static int PyNetwork_init(PyNetwork *self, PyObject *args, PyObject *kwargs)
{
    int size;
    int input_dim = 0;
    int output_dim = 0;
    double connectivity = 0.01;
    int precision = 2;
    int randomly_fire = false;
    int dynamic_output = false;
    int visualization = false;
    double decay_factor =  1.0;

    static char *kwlist[] = {"size", "input_dim", "output_dim", "connectivity", "precision", "randomly_fire", "dynamic_output", "visualization", "decay_factor", NULL};

    if (! PyArg_ParseTupleAndKeywords(args, kwargs, "i|iidipppd", kwlist, &size, &input_dim, &output_dim, &connectivity, &precision, &randomly_fire, &dynamic_output, &visualization, &decay_factor))
        return -1;

    self->ptrObj = new Network(size, input_dim, output_dim, connectivity, precision, randomly_fire, dynamic_output, visualization, decay_factor);

    return 0;
}

static int PyNeuron_init(PyNeuron *self, PyObject *args)
{
    PyNetwork * network;

    if (! PyArg_ParseTuple(args, "O", &network))
        return -1;

    self->ptrObj = new Neuron(*network->ptrObj);

    return 0;
}

static void PyNetwork_dealloc(PyNetwork * self)
{
    delete self->ptrObj;
    Py_TYPE(self)->tp_free(self);
}

static void PyNeuron_dealloc(PyNeuron * self)
{
    delete self->ptrObj;
    Py_TYPE(self)->tp_free(self);
}

static PyObject * PyNetwork_load(PyNetwork* self, PyObject* args, PyObject *kwargs)
{
    std::vector<double> input_arr;
    std::vector<double> output_arr;
    PyObject *input_obj;
    PyObject *output_obj = Py_None;

    static char *kwlist[] = {"input_obj", "output_obj", NULL};

    if (! PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &input_obj, &output_obj))
        throw std::invalid_argument("Wrong type of argument");

    PyObject *input_iter = PyObject_GetIter(input_obj);
    if (!input_iter) {
        throw std::invalid_argument("Input argument is not iterable");
    }
    parse_iterable(input_arr, input_iter);

    if (output_obj != Py_None) {
        PyObject *output_iter = PyObject_GetIter(output_obj);
        if (!output_iter) {
            throw std::invalid_argument("Output argument is not iterable");
        }
        parse_iterable(output_arr, output_iter);
    }

    (self->ptrObj)->load(input_arr, output_arr);

    return Py_BuildValue("");
}

static PyObject * PyNetwork_freeze(PyNetwork* self)
{
    (self->ptrObj)->freeze();

    return Py_BuildValue("");
}

static PyObject * PyNetwork_get_precision(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->precision);
}

static PyObject * PyNetwork_get_connectivity(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->connectivity);
}

static PyObject * PyNetwork_get_connectivity_sqrt(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->connectivity_sqrt);
}

static PyObject * PyNetwork_get_input_dim(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->input_dim);
}

static PyObject * PyNetwork_get_output_dim(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->output_dim);
}

static PyObject * PyNetwork_get_randomly_fire(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->randomly_fire);
}

static PyObject * PyNetwork_get_motor_randomly_fire_rate(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->motor_randomly_fire_rate);
}

static PyObject * PyNetwork_get_dynamic_output(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->dynamic_output);
}

static PyObject * PyNetwork_get_decay_factor(PyNetwork *self, void *closure)
{
    return Py_BuildValue("d", self->ptrObj->decay_factor);
}

static PyObject * PyNetwork_get_initiated_neurons(PyNetwork *self, void *closure)
{
    return Py_BuildValue("i", self->ptrObj->initiated_neurons);
}

static PyObject * PyNetwork_get_freezer(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->freezer);
}

static PyObject * PyNetwork_get_thread_kill_signal(PyNetwork *self, void *closure)
{
    return Py_BuildValue("b", self->ptrObj->thread_kill_signal);
}

static PyObject * PyNetwork_get_wave_counter(PyNetwork *self, void *closure)
{
    return Py_BuildValue("l", self->ptrObj->wave_counter);
}

static PyObject * PyNetwork_get_fire_counter(PyNetwork *self, void *closure)
{
    return Py_BuildValue("l", self->ptrObj->fire_counter);
}

static PyObject * PyNetwork_get_output(PyNetwork *self, void *closure)
{
    std::vector<double> output;

    output = (self->ptrObj)->get_output();

    PyObject *PList = PyList_New(0);
    std::vector<int>::const_iterator it;

    for (const auto& i: output)
        PyList_Append(PList, Py_BuildValue("d", i));

    return PList;
}

static PyObject * PyNetwork_get_neurons(PyNetwork *self, void *closure)
{
    std::vector<Neuron*> neurons = (self->ptrObj)->neurons;

    PyObject *PList = PyList_New(0);
    std::vector<int>::const_iterator it;

    for (const auto& i: neurons) {
        PyNeuron * neuron = new PyNeuron;
        neuron->ptrObj = i;
        PyList_Append(PList, Py_BuildValue("O", neuron));
    }
    return PList;
}

static PyMethodDef PyNetwork_methods[] = {
    {"load", (PyCFunction)PyNetwork_load, METH_VARARGS | METH_KEYWORDS, "Load input and output into the neural network" },
    {"freeze", (PyCFunction)PyNetwork_freeze, METH_NOARGS, "Freeze the neural network" },
    {NULL}  /* Sentinel */
};

static PyMethodDef PyNeuron_methods[] = {
    {NULL}  /* Sentinel */
};

static PyMemberDef PyNetwork_members[] = {
    {NULL}  /* Sentinel */
};

static PyMemberDef PyNeuron_members[] = {
    {NULL}  /* Sentinel */
};

static PyGetSetDef PyNetwork_getseters[] = {
    {"precision", (getter)PyNetwork_get_precision, NULL, "Precision of the network", NULL},
    {"connectivity", (getter)PyNetwork_get_connectivity, NULL, "Connectivity of the network", NULL},
    {"connectivity_sqrt", (getter)PyNetwork_get_connectivity_sqrt, NULL, "Square root of the connectivity of the network", NULL},
    {"input_dim", (getter)PyNetwork_get_input_dim, NULL, "Input dimension of the network", NULL},
    {"output_dim", (getter)PyNetwork_get_output_dim, NULL, "Output dimension of the network", NULL},
    {"randomly_fire", (getter)PyNetwork_get_randomly_fire, NULL, "Is randomly fire enabled for the network?", NULL},
    {"motor_randomly_fire_rate", (getter)PyNetwork_get_motor_randomly_fire_rate, NULL, "Motor neurons' randomly fire rate", NULL},
    {"dynamic_output", (getter)PyNetwork_get_dynamic_output, NULL, "Is dynamic output enabled for the network?", NULL},
    {"decay_factor", (getter)PyNetwork_get_decay_factor, NULL, "Decay factor of the network", NULL},
    {"initiated_neurons", (getter)PyNetwork_get_initiated_neurons, NULL, "Initiated neuron count of the network", NULL},
    {"freezer", (getter)PyNetwork_get_freezer, NULL, "Is freezing enabled for the network?", NULL},
    {"thread_kill_signal", (getter)PyNetwork_get_thread_kill_signal, NULL, "Are threads signalled for kill?", NULL},
    {"wave_counter", (getter)PyNetwork_get_wave_counter, NULL, "Holds the integer value of how many waves executed throughout the network", NULL},
    {"fire_counter", (getter)PyNetwork_get_fire_counter, NULL, "Holds the integer value of how many neurons fired during the training", NULL},
    {"output", (getter)PyNetwork_get_output, NULL, "Shows the output of the neural network", NULL},
    {"neurons", (getter)PyNetwork_get_neurons, NULL, "Holds the neurons in the neural network", NULL},
    {NULL}  /* Sentinel */
};

static PyTypeObject PyNetworkType = { PyVarObject_HEAD_INIT(NULL, 0)
    "plexus.Network"   /* tp_name */
};

static PyTypeObject PyNeuronType = { PyVarObject_HEAD_INIT(NULL, 0)
    "plexus.Neuron"   /* tp_name */
};

static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "cplexus",          /* name of module */
    "",                 /* module documentation, may be NULL */
    -1,                 /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
    NULL, NULL, NULL, NULL, NULL
};

PyMODINIT_FUNC PyInit_cplexus(void)
// create the module
{
    PyObject* m;

    PyNetworkType.tp_new = PyType_GenericNew;
    PyNetworkType.tp_basicsize=sizeof(PyNetwork);
    PyNetworkType.tp_dealloc=(destructor) PyNetwork_dealloc;
    PyNetworkType.tp_flags=Py_TPFLAGS_DEFAULT;
    PyNetworkType.tp_doc="Network objects";
    PyNetworkType.tp_methods=PyNetwork_methods;
    PyNetworkType.tp_members=PyNetwork_members;
    PyNetworkType.tp_getset=PyNetwork_getseters;
    PyNetworkType.tp_init=(initproc)PyNetwork_init;

    PyNeuronType.tp_new = PyType_GenericNew;
    PyNeuronType.tp_basicsize=sizeof(PyNeuron);
    PyNeuronType.tp_dealloc=(destructor) PyNeuron_dealloc;
    PyNeuronType.tp_flags=Py_TPFLAGS_DEFAULT;
    PyNeuronType.tp_doc="Neuron objects";
    PyNeuronType.tp_methods=PyNeuron_methods;
    PyNeuronType.tp_members=PyNeuron_members;
    PyNeuronType.tp_init=(initproc)PyNeuron_init;

    if (PyType_Ready(&PyNetworkType) < 0)
        return NULL;

    if (PyType_Ready(&PyNeuronType) < 0)
        return NULL;

    m = PyModule_Create(&moduledef);
    if (m == NULL)
        return NULL;

    Py_INCREF(&PyNetworkType);
    Py_INCREF(&PyNeuronType);
    PyModule_AddObject(m, "Network", (PyObject *)&PyNetworkType); // Add Network object to the module
    PyModule_AddObject(m, "Neuron", (PyObject *)&PyNeuronType); // Add Neuron object to the module
    return m;
}

void initcplexus(void)
{
    PyInit_cplexus();
}

int main(int argc, char *argv[])
{
    glob_argc = argc;
    glob_argv = argv;

    wchar_t *program = Py_DecodeLocale(argv[0], NULL);

    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(program);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Add a static module */
    initcplexus();
}
<|endoftext|>