<commit_before>/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or 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 <alljoyn/BusAttachment.h>
#include <alljoyn/Init.h>
#include <alljoyn/Session.h>
#include <alljoyn/SessionListener.h>

#include <alljoyn/notification/NotificationService.h>
#include <alljoyn/notification/NotificationReceiver.h>
#include <alljoyn/services_common/AsyncTaskQueue.h>

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

#include <libnotify/notify.h>

using namespace ajn;
using namespace ajn::services;

static volatile sig_atomic_t s_interrupt = false;

static void CDECL_CALL SigIntHandler(int sig) {
    QCC_UNUSED(sig);
    s_interrupt = true;
}

BusAttachment* bus = NULL;

class MySessionListener : public SessionListener {
    void SessionLost(SessionId sessionId, SessionLostReason reason) {
        printf("SessionLost sessionId = %u, Reason = %d\n", sessionId, reason);
    }
};

class MyNotificationReceiver : public NotificationReceiver {
    void Receive(Notification const& notification) {
        qcc::String deviceName = qcc::String(notification.getDeviceName());
        qcc::String content = qcc::String(notification.getText()[0].getText());
        printf("%s: %s\n", deviceName.c_str(), content.c_str());

        notify_init("AllJoyn Notification Bridge");
        NotifyNotification* n = notify_notification_new(deviceName.c_str(), content.c_str(), NULL);
        notify_notification_show(n, NULL);
        g_object_unref(G_OBJECT(n));
        notify_uninit();
    }

    void Dismiss(const int32_t msgId, const qcc::String appId) {}
};

int CDECL_CALL main(int argc, char** argv)
{
    QCC_UNUSED(argc);
    QCC_UNUSED(argv);

    if (AllJoynInit() != ER_OK) {
        return 1;
    }
#ifdef ROUTER
    if (AllJoynRouterInit() != ER_OK) {
        AllJoynShutdown();
        return 1;
    }
#endif

    /* Install SIGINT handler so Ctrl + C deallocates memory properly */
    signal(SIGINT, SigIntHandler);

    QStatus status;

    bus = new BusAttachment("AllJoyn Notification Bridge", true);

    status = bus->Start();
    if (ER_OK == status) {
        printf("BusAttachment started.\n");
    } else {
        printf("FAILED to start BusAttachment (%s)\n", QCC_StatusText(status));
        exit(1);
    }

    status = bus->Connect();
    if (ER_OK == status) {
        printf("BusAttachment connect succeeded.\n");
    } else {
        printf("FAILED to connect to router node (%s)\n", QCC_StatusText(status));
        exit(1);
    }

    NotificationService* notificationService = NotificationService::getInstance();
    MyNotificationReceiver* myNotifictionReceiver = new MyNotificationReceiver();
    notificationService->initReceive(bus, myNotifictionReceiver);

    /* Perform the service asynchronously until the user signals for an exit. */
    if (ER_OK == status) {
        while (s_interrupt == false) {
#ifdef _WIN32
            Sleep(100);
#else
            usleep(100 * 1000);
#endif
        }
    }

    delete bus;
#ifdef ROUTER
    AllJoynRouterShutdown();
#endif
    AllJoynShutdown();
    return 0;
}
<commit_msg>Reads URL of icon<commit_after>/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or 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 <alljoyn/BusAttachment.h>
#include <alljoyn/Init.h>
#include <alljoyn/Session.h>
#include <alljoyn/SessionListener.h>

#include <alljoyn/notification/NotificationService.h>
#include <alljoyn/notification/NotificationReceiver.h>
#include <alljoyn/services_common/AsyncTaskQueue.h>

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

#include <libnotify/notify.h>

using namespace ajn;
using namespace ajn::services;

static volatile sig_atomic_t s_interrupt = false;

static void CDECL_CALL SigIntHandler(int sig) {
    QCC_UNUSED(sig);
    s_interrupt = true;
}

BusAttachment* bus = NULL;

class MySessionListener : public SessionListener {
    void SessionLost(SessionId sessionId, SessionLostReason reason) {
        printf("SessionLost sessionId = %u, Reason = %d\n", sessionId, reason);
    }
};

class MyNotificationReceiver : public NotificationReceiver {
    void Receive(Notification const& notification) {
        qcc::String deviceName = qcc::String(notification.getDeviceName());
        qcc::String content = qcc::String(notification.getText()[0].getText());
        qcc::String iconURL = qcc::String(notification.getRichIconUrl());
        size_t index = iconURL.find_last_of("/") + 1;
        qcc::String iconName = iconURL.substr(index);

        printf("%s: %s %s %s\n", deviceName.c_str(), content.c_str(), iconURL.c_str(), iconName.c_str());

        notify_init("AllJoyn Notification Bridge");
        NotifyNotification* n = notify_notification_new(deviceName.c_str(), content.c_str(), NULL);
        notify_notification_show(n, NULL);
        g_object_unref(G_OBJECT(n));
        notify_uninit();
    }

    void Dismiss(const int32_t msgId, const qcc::String appId) {}
};

int CDECL_CALL main(int argc, char** argv)
{
    QCC_UNUSED(argc);
    QCC_UNUSED(argv);

    if (AllJoynInit() != ER_OK) {
        return 1;
    }
#ifdef ROUTER
    if (AllJoynRouterInit() != ER_OK) {
        AllJoynShutdown();
        return 1;
    }
#endif

    /* Install SIGINT handler so Ctrl + C deallocates memory properly */
    signal(SIGINT, SigIntHandler);

    QStatus status;

    bus = new BusAttachment("AllJoyn Notification Bridge", true);

    status = bus->Start();
    if (ER_OK == status) {
        printf("BusAttachment started.\n");
    } else {
        printf("FAILED to start BusAttachment (%s)\n", QCC_StatusText(status));
        exit(1);
    }

    status = bus->Connect();
    if (ER_OK == status) {
        printf("BusAttachment connect succeeded.\n");
    } else {
        printf("FAILED to connect to router node (%s)\n", QCC_StatusText(status));
        exit(1);
    }

    NotificationService* notificationService = NotificationService::getInstance();
    MyNotificationReceiver* myNotifictionReceiver = new MyNotificationReceiver();
    notificationService->initReceive(bus, myNotifictionReceiver);

    /* Perform the service asynchronously until the user signals for an exit. */
    if (ER_OK == status) {
        while (s_interrupt == false) {
#ifdef _WIN32
            Sleep(100);
#else
            usleep(100 * 1000);
#endif
        }
    }

    delete bus;
#ifdef ROUTER
    AllJoynRouterShutdown();
#endif
    AllJoynShutdown();
    return 0;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
//		E L E N A   P r o j e c t:  ELENA command-Line Compiler
//
//		This file contains the main body of the Linux command-line compiler
//
//                                             (C)2021-2022, by Aleksey Rakov
//---------------------------------------------------------------------------

#include "elena.h"
// --------------------------------------------------------------------------
#include "cliconst.h"
#include "compiling.h"
#include "project.h"
#include "elfimage.h"

#if defined(__x86_64__)

#include "elflinker32.h"
#include "elflinker64.h"
#include "x86compiler.h"
#include "x86_64compiler.h"

#elif defined(__i386__)

#include "elflinker32.h"
#include "x86compiler.h"

#elif defined(__PPC64__)

#include "elfppclinker64.h"
#include "ppc64compiler.h"
#include "elfppcimage.h"

#elif defined(__aarch64__)

#include "elfarmlinker64.h"
#include "arm64compiler.h"
#include "elfarmimage.h"

#endif

#include "constants.h"
#include "messages.h"

#include <stdarg.h>

using namespace elena_lang;

#if defined(__x86_64__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_x86_64;

constexpr int MINIMAL_ARG_LIST            = 2;

constexpr auto DEFAULT_STACKALIGNMENT     = 2;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 16;

typedef ElfAmd64Linker           LinuxLinker;
typedef ElfAmd64ImageFormatter   LinuxImageFormatter;

#elif defined(__i386__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_x86;

constexpr int MINIMAL_ARG_LIST            = 1;

constexpr auto DEFAULT_STACKALIGNMENT     = 1;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 4;

typedef ElfI386Linker            LinuxLinker;
typedef ElfI386ImageFormatter    LinuxImageFormatter;

#elif defined(__PPC64__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_PPC64le;

constexpr int MINIMAL_ARG_LIST            = 2;

constexpr auto DEFAULT_STACKALIGNMENT     = 2;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 16;

typedef ElfPPC64leLinker         LinuxLinker;
typedef ElfPPC64leImageFormatter LinuxImageFormatter;

#elif defined(__aarch64__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_ARM64;

constexpr int MINIMAL_ARG_LIST            = 2;

constexpr auto DEFAULT_STACKALIGNMENT     = 2;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 16;

typedef ElfARM64Linker         LinuxLinker;
typedef ElfARM64ImageFormatter LinuxImageFormatter;

#endif

constexpr int DEFAULT_MGSIZE = 688128;
constexpr int DEFAULT_YGSIZE = 204800;

void print(const char* msg, ...)
{
   va_list argptr;
   va_start(argptr, msg);

   vprintf(msg, argptr);
   va_end(argptr);
   printf("\n");

   fflush(stdout);
}

class Presenter : public PresenterBase
{
public:
   ustr_t getMessage(int code)
   {
      for(size_t i = 0; i < MessageLength; i++) {
         if (Messages[i].value1 == code)
            return Messages[i].value2;
      }

      return errMsgUnrecognizedError;
   }

   static Presenter& getInstance()
   {
      static Presenter instance;

      return instance;
   }

   void print(ustr_t msg, ustr_t arg) override
   {
      ::print(msg.str(), arg.str());
   }
   void print(ustr_t msg, ustr_t arg1, ustr_t arg2) override
   {
      ::print(msg.str(), arg1.str(), arg2.str());
   }
   void print(ustr_t msg, ustr_t arg1, ustr_t arg2, ustr_t arg3) override
   {
      ::print(msg.str(), arg1.str(), arg2.str(), arg3.str());
   }
   void print(ustr_t msg, int arg1, int arg2, int arg3) override
   {
      ::print(msg.str(), arg1, arg2, arg3);
   }
   void printPath(ustr_t msg, path_t arg1, int arg2, int arg3, ustr_t arg4) override
   {
      ::print(msg.str(), arg1.str(), arg2, arg3, arg4.str());
   }
   void print(ustr_t msg, int arg1, int arg2) override
   {
      ::print(msg.str(), arg1, arg2);
   }
   void print(ustr_t msg, int arg1) override
   {
      ::print(wstr.str(), arg1);
   }
   void printPath(ustr_t msg, path_t arg)
   {
      ::print(msg.str(), arg.str());
   }
   void print(ustr_t msg)
   {
      ::print(msg.str());
   }
   void print(ustr_t msg, ustr_t path, int col, int row, ustr_t s) override
   {
      ::print(msg.str(), path.str(), row, col, s.str());
   }

private:
   Presenter() = default;

public:
   Presenter(Presenter const&) = delete;
   void operator=(Presenter const&) = delete;

   ~Presenter() = default;
};

JITCompilerBase* createJITCompiler(LibraryLoaderBase* loader, PlatformType platform)
{
   switch (platform) {
#if defined(__i386__) || defined(__x86_64__)
      case PlatformType::Linux_x86:
         return new X86JITCompiler();
#endif
#if defined(__x86_64__)
      case PlatformType::Linux_x86_64:
         return new X86_64JITCompiler();
#endif
#if defined(__PPC64__)
      case PlatformType::Linux_PPC64le:
         return new PPC64leJITCompiler();
#endif
#if defined(__aarch64__)
      case PlatformType::Linux_ARM64:
         return new ARM64JITCompiler();
#endif
      default:
         return nullptr;
   }
}

int main(int argc, char* argv[])
{
   try
   {
      PathString dataPath(DATA_PATH);

      JITSettings      defaultCoreSettings = { DEFAULT_MGSIZE, DEFAULT_YGSIZE };
      ErrorProcessor   errorProcessor(&Presenter::getInstance());
      Project          project(*dataPath, CURRENT_PLATFORM, &Presenter::getInstance());
      LinuxLinker      linker(&errorProcessor, &LinuxImageFormatter::getInstance(&project));
      CompilingProcess process(dataPath, &Presenter::getInstance(), &errorProcessor,
         VA_ALIGNMENT, defaultCoreSettings, createJITCompiler);

      process.greeting();

      // Initializing...
      PathString configPath(*dataPath, DEFAULT_CONFIG);
      project.loadConfig(*configPath, false/*, true, false*/);

       // Reading command-line arguments...
      if (argc < 2) {
         Presenter::getInstance().print(ELC_HELP_INFO);
         return -3;
      }

      for (int i = 1; i < argc; i++) {
         if (PathUtil::checkExtension(argv[i], "project")) {
            PathString path(argv[i]);

            if (!project.loadProject(*path)) {
               errorProcessor.raisePathError(errProjectAlreadyLoaded, *path);
            }
         }
         else {
            FileNameString fileName(argv[i]);

            project.addSource(*fileName, argv[i]);
         }
      }

      // Building...
      return process.build(project, linker,
         DEFAULT_STACKALIGNMENT,
         DEFAULT_RAW_STACKALIGNMENT,
         MINIMAL_ARG_LIST);
   }
   catch (CLIException e)
   {
      return -2;
   }

}
<commit_msg>fixing code<commit_after>//---------------------------------------------------------------------------
//		E L E N A   P r o j e c t:  ELENA command-Line Compiler
//
//		This file contains the main body of the Linux command-line compiler
//
//                                             (C)2021-2022, by Aleksey Rakov
//---------------------------------------------------------------------------

#include "elena.h"
// --------------------------------------------------------------------------
#include "cliconst.h"
#include "compiling.h"
#include "project.h"
#include "elfimage.h"

#if defined(__x86_64__)

#include "elflinker32.h"
#include "elflinker64.h"
#include "x86compiler.h"
#include "x86_64compiler.h"

#elif defined(__i386__)

#include "elflinker32.h"
#include "x86compiler.h"

#elif defined(__PPC64__)

#include "elfppclinker64.h"
#include "ppc64compiler.h"
#include "elfppcimage.h"

#elif defined(__aarch64__)

#include "elfarmlinker64.h"
#include "arm64compiler.h"
#include "elfarmimage.h"

#endif

#include "constants.h"
#include "messages.h"

#include <stdarg.h>

using namespace elena_lang;

#if defined(__x86_64__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_x86_64;

constexpr int MINIMAL_ARG_LIST            = 2;

constexpr auto DEFAULT_STACKALIGNMENT     = 2;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 16;

typedef ElfAmd64Linker           LinuxLinker;
typedef ElfAmd64ImageFormatter   LinuxImageFormatter;

#elif defined(__i386__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_x86;

constexpr int MINIMAL_ARG_LIST            = 1;

constexpr auto DEFAULT_STACKALIGNMENT     = 1;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 4;

typedef ElfI386Linker            LinuxLinker;
typedef ElfI386ImageFormatter    LinuxImageFormatter;

#elif defined(__PPC64__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_PPC64le;

constexpr int MINIMAL_ARG_LIST            = 2;

constexpr auto DEFAULT_STACKALIGNMENT     = 2;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 16;

typedef ElfPPC64leLinker         LinuxLinker;
typedef ElfPPC64leImageFormatter LinuxImageFormatter;

#elif defined(__aarch64__)

constexpr auto CURRENT_PLATFORM           = PlatformType::Linux_ARM64;

constexpr int MINIMAL_ARG_LIST            = 2;

constexpr auto DEFAULT_STACKALIGNMENT     = 2;
constexpr auto DEFAULT_RAW_STACKALIGNMENT = 16;

typedef ElfARM64Linker         LinuxLinker;
typedef ElfARM64ImageFormatter LinuxImageFormatter;

#endif

constexpr int DEFAULT_MGSIZE = 688128;
constexpr int DEFAULT_YGSIZE = 204800;

void print(const char* msg, ...)
{
   va_list argptr;
   va_start(argptr, msg);

   vprintf(msg, argptr);
   va_end(argptr);
   printf("\n");

   fflush(stdout);
}

class Presenter : public PresenterBase
{
public:
   ustr_t getMessage(int code)
   {
      for(size_t i = 0; i < MessageLength; i++) {
         if (Messages[i].value1 == code)
            return Messages[i].value2;
      }

      return errMsgUnrecognizedError;
   }

   static Presenter& getInstance()
   {
      static Presenter instance;

      return instance;
   }

   void print(ustr_t msg, ustr_t arg) override
   {
      ::print(msg.str(), arg.str());
   }
   void print(ustr_t msg, ustr_t arg1, ustr_t arg2) override
   {
      ::print(msg.str(), arg1.str(), arg2.str());
   }
   void print(ustr_t msg, ustr_t arg1, ustr_t arg2, ustr_t arg3) override
   {
      ::print(msg.str(), arg1.str(), arg2.str(), arg3.str());
   }
   void print(ustr_t msg, int arg1, int arg2, int arg3) override
   {
      ::print(msg.str(), arg1, arg2, arg3);
   }
   void printPath(ustr_t msg, path_t arg1, int arg2, int arg3, ustr_t arg4) override
   {
      ::print(msg.str(), arg1.str(), arg2, arg3, arg4.str());
   }
   void print(ustr_t msg, int arg1, int arg2) override
   {
      ::print(msg.str(), arg1, arg2);
   }
   void print(ustr_t msg, int arg1) override
   {
      ::print(msg.str(), arg1);
   }
   void printPath(ustr_t msg, path_t arg)
   {
      ::print(msg.str(), arg.str());
   }
   void print(ustr_t msg)
   {
      ::print(msg.str());
   }
   void print(ustr_t msg, ustr_t path, int col, int row, ustr_t s) override
   {
      ::print(msg.str(), path.str(), row, col, s.str());
   }

private:
   Presenter() = default;

public:
   Presenter(Presenter const&) = delete;
   void operator=(Presenter const&) = delete;

   ~Presenter() = default;
};

JITCompilerBase* createJITCompiler(LibraryLoaderBase* loader, PlatformType platform)
{
   switch (platform) {
#if defined(__i386__) || defined(__x86_64__)
      case PlatformType::Linux_x86:
         return new X86JITCompiler();
#endif
#if defined(__x86_64__)
      case PlatformType::Linux_x86_64:
         return new X86_64JITCompiler();
#endif
#if defined(__PPC64__)
      case PlatformType::Linux_PPC64le:
         return new PPC64leJITCompiler();
#endif
#if defined(__aarch64__)
      case PlatformType::Linux_ARM64:
         return new ARM64JITCompiler();
#endif
      default:
         return nullptr;
   }
}

int main(int argc, char* argv[])
{
   try
   {
      PathString dataPath(DATA_PATH);

      JITSettings      defaultCoreSettings = { DEFAULT_MGSIZE, DEFAULT_YGSIZE };
      ErrorProcessor   errorProcessor(&Presenter::getInstance());
      Project          project(*dataPath, CURRENT_PLATFORM, &Presenter::getInstance());
      LinuxLinker      linker(&errorProcessor, &LinuxImageFormatter::getInstance(&project));
      CompilingProcess process(dataPath, &Presenter::getInstance(), &errorProcessor,
         VA_ALIGNMENT, defaultCoreSettings, createJITCompiler);

      process.greeting();

      // Initializing...
      PathString configPath(*dataPath, DEFAULT_CONFIG);
      project.loadConfig(*configPath, false/*, true, false*/);

       // Reading command-line arguments...
      if (argc < 2) {
         Presenter::getInstance().print(ELC_HELP_INFO);
         return -3;
      }

      for (int i = 1; i < argc; i++) {
         if (PathUtil::checkExtension(argv[i], "project")) {
            PathString path(argv[i]);

            if (!project.loadProject(*path)) {
               errorProcessor.raisePathError(errProjectAlreadyLoaded, *path);
            }
         }
         else {
            FileNameString fileName(argv[i]);

            project.addSource(*fileName, argv[i]);
         }
      }

      // Building...
      return process.build(project, linker,
         DEFAULT_STACKALIGNMENT,
         DEFAULT_RAW_STACKALIGNMENT,
         MINIMAL_ARG_LIST);
   }
   catch (CLIException e)
   {
      return -2;
   }

}
<|endoftext|>


<commit_before>/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-15 23:25:04
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, M, Q;
int a[50];
int l[50];
int r[50];
bool used[50];

ll solve()
{
  ll ans = 0;
  for (auto i = 0; i < Q; i++)
  {
    int maxi = 0;
    for (auto j = l[i]; j <= r[i]; j++)
    {
      if (!used[j] && a[j] > maxi)
      {
        maxi = a[j];
      }
    }
    // cerr << maxi << " ";
    ans += maxi;
  }
  // cerr << ", ans = " << ans << endl;
  return ans;
}

void solveA()
{
  ll ans = 100000000;
  for (auto i = 0; i < (1 << N); i++)
  {
    int cnt = 0;
    for (auto j = 0; j < N; j++)
    {
      if ((i >> j) & 1)
      {
        cnt++;
      }
    }
    if (cnt == M)
    {
      for (auto j = 0; j < N; j++)
      {
        used[j] = (i >> j) & 1;
      }
      ans = min(ans, solve());
    }
  }
  cout << ans << endl;
}

void solveB()
{
  fill(used, used + N, false);
  for (auto i = 0; i < M; i++)
  {
    used[i] = true;
  }
  cout << solve() << endl;
}

int main()
{
  cin >> N >> M >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  for (auto i = 0; i < Q; i++)
  {
    cin >> l[i] >> r[i];
  }
  if (N <= 15)
  {
    solveA();
  }
  else
  {
    solveB();
  }
}<commit_msg>submit F.cpp to 'F - Lunch Menu' (s8pc-5) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-15 23:25:04
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, M, Q;
int a[50];
int l[50];
int r[50];
bool used[50];

ll solve()
{
  ll ans = 0;
  for (auto i = 0; i < Q; i++)
  {
    int maxi = 0;
    for (auto j = l[i]; j <= r[i]; j++)
    {
      if (!used[j] && a[j] > maxi)
      {
        maxi = a[j];
      }
    }
    // cerr << maxi << " ";
    ans += maxi;
  }
  // cerr << ", ans = " << ans << endl;
  return ans;
}

void solveA()
{
  ll ans = 100000000;
  for (auto i = 0; i < (1 << N); i++)
  {
    int cnt = 0;
    for (auto j = 0; j < N; j++)
    {
      if ((i >> j) & 1)
      {
        cnt++;
      }
    }
    if (cnt == M)
    {
      for (auto j = 0; j < N; j++)
      {
        used[j] = (i >> j) & 1;
      }
      ans = min(ans, solve());
    }
  }
  cout << ans << endl;
}

void solveB()
{
  fill(used, used + N, false);
  for (auto i = 0; i < M; i++)
  {
    used[i] = true;
  }
  cout << solve() << endl;
}

int main()
{
  cin >> N >> M >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  for (auto i = 0; i < Q; i++)
  {
    cin >> l[i] >> r[i];
    l[i]--;
    r[i]--;
  }
  if (N <= 15)
  {
    solveA();
  }
  else
  {
    solveB();
  }
}<|endoftext|>


<commit_before>// Copyright (c) 2015 Kirurobo

#include "MocapPluginPrivatePCH.h"
#include "MocapReceiver.h"

UMocapReceiver::UMocapReceiver( const FObjectInitializer& ObjectInitializer )
	: Super( ObjectInitializer )
{
	Initialize();
}

UMocapReceiver::~UMocapReceiver()
{
}

// Sets default values
void UMocapReceiver::Initialize()
{
	this->IdentityPose = NewObject<UMocapPose>();
}

/*  ポートに接続 */
//
/*  Begin Play イベントで呼ぶこと。 */
bool UMocapReceiver::Connect()
{
	if (m_Socket == NULL) {
		m_Socket = FUdpSocketBuilder(TEXT("Mocap UDP socket"))
			.BoundToPort(this->Port)
			.Build();
	}

	if (m_Socket != NULL) {
		const bool bAutoDeleteSelf = true;
		const bool bAutoDeleteRunnable = true;

		/* 受信されたデータの保存領域 */
		CurrentPose = NewObject<UMocapPose>();

		/*  パケット解釈部 */
		packetReaderMvn = new FPacketReaderMvn();
		//packetReaderKinect = new FPacketReaderKinect();
		packetReaderNeuron = new FPacketReaderNeuron();

		/* UDP受信を開始 */
		m_Receiver = new FUdpSocketReceiver(m_Socket, FTimespan(0, 0, 1), TEXT("Mocap UDP receiver"));
		m_Receiver->OnDataReceived().BindUObject(this, &UMocapReceiver::UdpReceivedCallback);

		return true;
	}
	return false;
}

/*  受信を終了してポートを閉じる */
/* 	End Play イベントで呼ぶこと。 */
void UMocapReceiver::Close()
{
	if (m_Receiver != NULL) {
		m_Receiver->Exit();
		delete m_Receiver;
		m_Receiver = NULL;
	}

	if (m_Socket != NULL) {
		m_Socket->Close();
		delete m_Socket;
		m_Socket = NULL;
	}
	if (packetReaderMvn != NULL) {
		delete (FPacketReaderMvn*)packetReaderMvn;
		packetReaderMvn = NULL;
	}
	if (packetReaderNeuron != NULL) {
		delete (FPacketReaderNeuron*)packetReaderNeuron;
		packetReaderNeuron = NULL;
	}
}

/*  UDPでデータが届いた際のコールバック */
void UMocapReceiver::UdpReceivedCallback(const FArrayReaderPtr& data, const FIPv4Endpoint&)
{
	bool received = false;

	/* モーキャプソフト毎にその形式か調べて受信する */
	if (packetReaderMvn->Read(data, this->CurrentPose)) {
		received = true;
		this->CurrentPose->UserId += this->MvnUserIdOffset;
	} else if (packetReaderNeuron->Read(data, this->CurrentPose)) {
		received = true;
		this->CurrentPose->UserId += this->NeuronUserIdOffset;
	}

	/* 受信できたらユーザーID毎に保存する */
	if (received) {
		int userId = this->CurrentPose->UserId;

		UMocapPose** pPose = this->PoseMap.Find(userId);
		if (pPose == nullptr) {
			/*  初回受信。現在の位置が原点となるようオフセットを設定 */
			//this->CurrentPose->PositionOffset = -this->CurrentPose->OriginalRootPosition;
			UMocapPose* pose = this->CurrentPose->Clone();
			pose->PositionOffset = -pose->OriginalRootPosition;
			if (this->PoseMap.Num() < 1) {
				this->CurrentPose->PositionOffset = pose->PositionOffset;
			}
			this->Poses.Add(pose);				/* GCで削除されるのを防ぐため、こちらにも登録 */
			this->PoseMap.Add(userId, pose);
		}
		else {
			/* 既に受信されたユーザーならば値の複製のみ */
			this->CurrentPose->CopyTo(*pPose);
		}
	}
}

/* 指定されたユーザーIDの姿勢を返す */
UMocapPose* UMocapReceiver::GetMocapPose(const int32 userId)
{
	if (userId < 0) return this->CurrentPose;
	UMocapPose** pPose =  this->PoseMap.Find(userId);
	if (pPose == nullptr) {
		return this->IdentityPose;
	}
	else {
		return *pPose;
	}
}
<commit_msg>ソケットを開けなかった場合でも空姿勢を返すものとした。<commit_after>// Copyright (c) 2015 Kirurobo

#include "MocapPluginPrivatePCH.h"
#include "MocapReceiver.h"

UMocapReceiver::UMocapReceiver( const FObjectInitializer& ObjectInitializer )
	: Super( ObjectInitializer )
{
	Initialize();
}

UMocapReceiver::~UMocapReceiver()
{
}

// Sets default values
void UMocapReceiver::Initialize()
{
	this->IdentityPose = NewObject<UMocapPose>();
}

/*  ポートに接続 */
//
/*  Begin Play イベントで呼ぶこと。 */
bool UMocapReceiver::Connect()
{
	if (m_Socket == NULL) {
		m_Socket = FUdpSocketBuilder(TEXT("Mocap UDP socket"))
			.BoundToPort(this->Port)
			.Build();
	}

	if (m_Socket != NULL) {
		const bool bAutoDeleteSelf = true;
		const bool bAutoDeleteRunnable = true;

		/* 受信されたデータの保存領域 */
		CurrentPose = NewObject<UMocapPose>();

		/*  パケット解釈部 */
		packetReaderMvn = new FPacketReaderMvn();
		//packetReaderKinect = new FPacketReaderKinect();
		packetReaderNeuron = new FPacketReaderNeuron();

		/* UDP受信を開始 */
		m_Receiver = new FUdpSocketReceiver(m_Socket, FTimespan(0, 0, 1), TEXT("Mocap UDP receiver"));
		m_Receiver->OnDataReceived().BindUObject(this, &UMocapReceiver::UdpReceivedCallback);

		return true;
	}
	return false;
}

/*  受信を終了してポートを閉じる */
/* 	End Play イベントで呼ぶこと。 */
void UMocapReceiver::Close()
{
	if (m_Receiver != NULL) {
		m_Receiver->Exit();
		delete m_Receiver;
		m_Receiver = NULL;
	}

	if (m_Socket != NULL) {
		m_Socket->Close();
		delete m_Socket;
		m_Socket = NULL;
	}
	if (packetReaderMvn != NULL) {
		delete (FPacketReaderMvn*)packetReaderMvn;
		packetReaderMvn = NULL;
	}
	if (packetReaderNeuron != NULL) {
		delete (FPacketReaderNeuron*)packetReaderNeuron;
		packetReaderNeuron = NULL;
	}
}

/*  UDPでデータが届いた際のコールバック */
void UMocapReceiver::UdpReceivedCallback(const FArrayReaderPtr& data, const FIPv4Endpoint&)
{
	bool received = false;

	/* モーキャプソフト毎にその形式か調べて受信する */
	if (packetReaderMvn->Read(data, this->CurrentPose)) {
		received = true;
		this->CurrentPose->UserId += this->MvnUserIdOffset;
	} else if (packetReaderNeuron->Read(data, this->CurrentPose)) {
		received = true;
		this->CurrentPose->UserId += this->NeuronUserIdOffset;
	}

	/* 受信できたらユーザーID毎に保存する */
	if (received) {
		int userId = this->CurrentPose->UserId;

		UMocapPose** pPose = this->PoseMap.Find(userId);
		if (pPose == nullptr) {
			/*  初回受信。現在の位置が原点となるようオフセットを設定 */
			//this->CurrentPose->PositionOffset = -this->CurrentPose->OriginalRootPosition;
			UMocapPose* pose = this->CurrentPose->Clone();
			pose->PositionOffset = -pose->OriginalRootPosition;
			if (this->PoseMap.Num() < 1) {
				this->CurrentPose->PositionOffset = pose->PositionOffset;
			}
			this->Poses.Add(pose);				/* GCで削除されるのを防ぐため、こちらにも登録 */
			this->PoseMap.Add(userId, pose);
		}
		else {
			/* 既に受信されたユーザーならば値の複製のみ */
			this->CurrentPose->CopyTo(*pPose);
		}
	}
}

/* 指定されたユーザーIDの姿勢を返す */
UMocapPose* UMocapReceiver::GetMocapPose(const int32 userId)
{
	if (!this->m_Socket) return this->IdentityPose;
	if (userId < 0) return this->CurrentPose;
	UMocapPose** pPose =  this->PoseMap.Find(userId);
	if (pPose == nullptr) {
		return this->IdentityPose;
	}
	else {
		return *pPose;
	}
}
<|endoftext|>


<commit_before>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-3 21:25:19
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef complex<int> P;

int N;
int D[2];
vector<P> ans;
vector<P> F;

void flush()
{
  for (auto p : ans)
  {
    int x = p.real();
    int y = p.imag();
    cout << x << " " << y << endl;
  }
}

void make_forbid(int X)
{
  for (int i = 0; i <= 2 * N; i++)
  {
    int j = round(sqrt(X - i * i));
    if (i * i + j * j == X)
    {
      F.push_back(P(i, j));
      F.push_back(P(-i, j));
      F.push_back(P(i, -j));
      F.push_back(P(-i, -j));
      F.push_back(P(j, i));
      F.push_back(P(j, -i));
      F.push_back(P(-j, i));
      F.push_back(P(-j, -i));
    }
  }
}

bool valid(P p)
{
  int x = p.real();
  int y = p.imag();
  return (0 <= x && x < 2 * N) && (0 <= y && y < 2 * N);
}

bool B[1010][1010];
vector<P> pts;
random_device seed;
mt19937 engine(seed());

int main()
{
  cin >> N >> D[0] >> D[1];
  make_forbid(D[0]);
  make_forbid(D[1]);
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  for (auto i = 0; i < 2 * N; i++)
  {
    for (auto j = 0; j < 2 * N; j++)
    {
      if (B[i][j])
      {
        P p(i, j);
        ans.push_back(p);
        if (ans.size() == N * N)
        {
          flush();
          return 0;
        }
        for (auto q : F)
        {
          P r = p + q;
          if (valid(r))
          {
            B[r.real()][r.imag()] = false;
          }
        }
      }
    }
  }
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  ans.clear();
  pts.clear();
  for (auto k = 0; k < 4 * N; k++)
  {
    for (auto j = 0; j <= k; j++)
    {
      int i = k - j;
      P p(i, j);
      if (valid(p))
      {
        pts.push_back(p);
      }
    }
  }
  for (auto p : pts)
  {
    int i = p.real();
    int j = p.imag();
    if (B[i][j])
    {
      ans.push_back(p);
      if (ans.size() == N * N)
      {
        flush();
        return 0;
      }
      for (auto q : F)
      {
        P r = p + q;
        if (valid(r))
        {
          B[r.real()][r.imag()] = false;
        }
      }
    }
  }
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  ans.clear();
  pts.clear();
  for (auto k = 0; k < 4 * N; k++)
  {
    for (auto j = 0; j <= k; j++)
    {
      int i = k - j;
      P p(i, j);
      if (valid(p))
      {
        pts.push_back(p);
      }
      P q(2 * N - i, j);
      if (valid(q))
      {
        pts.push_back(q);
      }
      P r(i, 2 * N - j);
      if (valid(r))
      {
        pts.push_back(r);
      }
      P s(2 * N - i, 2 * N - j);
      if (valid(s))
      {
        pts.push_back(s);
      }
    }
  }
  for (auto p : pts)
  {
    int i = p.real();
    int j = p.imag();
    if (B[i][j])
    {
      B[i][j] = false;
      ans.push_back(p);
      if (ans.size() == N * N)
      {
        flush();
        return 0;
      }
      for (auto q : F)
      {
        P r = p + q;
        if (valid(r))
        {
          B[r.real()][r.imag()] = false;
        }
      }
    }
  }
  assert(false);
  /*
  while (true)
  {
    fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
    ans.clear();
    pts.clear();
    for (auto i = 0; i < 2 * N; i++)
    {
      for (auto j = 0; j < 2 * N; j++)
      {
        pts.push_back(P(i, j));
      }
    }
    shuffle(pts.begin(), pts.end(), engine);
    for (auto p : pts)
    {
      int i = p.real();
      int j = p.imag();
      if (B[i][j])
      {
        ans.push_back(p);
        if (ans.size() == N * N)
        {
          flush();
          return 0;
        }
        for (auto q : F)
        {
          P r = p + q;
          if (valid(r))
          {
            B[r.real()][r.imag()] = false;
          }
        }
      }
    }
  }
  */
}<commit_msg>submit D.cpp to 'D - Choosing Points' (agc025) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-3 21:25:19
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

typedef complex<int> P;

int N;
int D[2];
vector<P> ans;
vector<P> F;

void flush()
{
  for (auto p : ans)
  {
    int x = p.real();
    int y = p.imag();
    cout << x << " " << y << endl;
  }
}

void make_forbid(int X)
{
  for (int i = 0; i <= 2 * N; i++)
  {
    int j = round(sqrt(X - i * i));
    if (i * i + j * j == X)
    {
      F.push_back(P(i, j));
      F.push_back(P(-i, j));
      F.push_back(P(i, -j));
      F.push_back(P(-i, -j));
      F.push_back(P(j, i));
      F.push_back(P(j, -i));
      F.push_back(P(-j, i));
      F.push_back(P(-j, -i));
    }
  }
}

bool valid(P p)
{
  int x = p.real();
  int y = p.imag();
  return (0 <= x && x < 2 * N) && (0 <= y && y < 2 * N);
}

bool B[1010][1010];
vector<P> pts;
random_device seed;
mt19937 engine(seed());

int main()
{
  cin >> N >> D[0] >> D[1];
  make_forbid(D[0]);
  make_forbid(D[1]);
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  for (auto i = 0; i < 2 * N; i++)
  {
    for (auto j = 0; j < 2 * N; j++)
    {
      if (B[i][j])
      {
        P p(i, j);
        ans.push_back(p);
        if (ans.size() == N * N)
        {
          flush();
          return 0;
        }
        for (auto q : F)
        {
          P r = p + q;
          if (valid(r))
          {
            B[r.real()][r.imag()] = false;
          }
        }
      }
    }
  }
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  ans.clear();
  pts.clear();
  for (auto k = 0; k < 4 * N; k++)
  {
    for (auto j = 0; j <= k; j++)
    {
      int i = k - j;
      P p(i, j);
      if (valid(p))
      {
        pts.push_back(p);
      }
    }
  }
  for (auto p : pts)
  {
    int i = p.real();
    int j = p.imag();
    if (B[i][j])
    {
      ans.push_back(p);
      if (ans.size() == N * N)
      {
        flush();
        return 0;
      }
      for (auto q : F)
      {
        P r = p + q;
        if (valid(r))
        {
          B[r.real()][r.imag()] = false;
        }
      }
    }
  }
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  ans.clear();
  pts.clear();
  for (auto k = 0; k < 4 * N; k++)
  {
    for (auto j = 0; j <= k; j++)
    {
      int i = k - j;
      P p(i, j);
      if (valid(p))
      {
        pts.push_back(p);
      }
      P q(2 * N - i, j);
      if (valid(q))
      {
        pts.push_back(q);
      }
      P r(i, 2 * N - j);
      if (valid(r))
      {
        pts.push_back(r);
      }
      P s(2 * N - i, 2 * N - j);
      if (valid(s))
      {
        pts.push_back(s);
      }
    }
  }
  for (auto p : pts)
  {
    int i = p.real();
    int j = p.imag();
    if (B[i][j])
    {
      B[i][j] = false;
      ans.push_back(p);
      if (ans.size() == N * N)
      {
        flush();
        return 0;
      }
      for (auto q : F)
      {
        P r = p + q;
        if (valid(r))
        {
          B[r.real()][r.imag()] = false;
        }
      }
    }
  }
  fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
  ans.clear();
  pts.clear();
  for (auto k = 0; k < 4 * N; k++)
  {
    for (auto j = 0; j <= k; j++)
    {
      int i = k - j;
      P p(i, j);
      if (valid(p))
      {
        pts.push_back(p);
      }
      P s(2 * N - i, 2 * N - j);
      if (valid(s))
      {
        pts.push_back(s);
      }
    }
  }
  for (auto p : pts)
  {
    int i = p.real();
    int j = p.imag();
    if (B[i][j])
    {
      B[i][j] = false;
      ans.push_back(p);
      if (ans.size() == N * N)
      {
        flush();
        return 0;
      }
      for (auto q : F)
      {
        P r = p + q;
        if (valid(r))
        {
          B[r.real()][r.imag()] = false;
        }
      }
    }
  }
  assert(false);
  /*
  while (true)
  {
    fill(&B[0][0], &B[0][0] + 1010 * 1010, true);
    ans.clear();
    pts.clear();
    for (auto i = 0; i < 2 * N; i++)
    {
      for (auto j = 0; j < 2 * N; j++)
      {
        pts.push_back(P(i, j));
      }
    }
    shuffle(pts.begin(), pts.end(), engine);
    for (auto p : pts)
    {
      int i = p.real();
      int j = p.imag();
      if (B[i][j])
      {
        ans.push_back(p);
        if (ans.size() == N * N)
        {
          flush();
          return 0;
        }
        for (auto q : F)
        {
          P r = p + q;
          if (valid(r))
          {
            B[r.real()][r.imag()] = false;
          }
        }
      }
    }
  }
  */
}<|endoftext|>


<commit_before>//===- GdbIndex.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// File contains classes for implementation of --gdb-index command line option.
//
// If that option is used, linker should emit a .gdb_index section that allows
// debugger to locate and read .dwo files, containing neccessary debug
// information.
// More information about implementation can be found in DWARF specification,
// latest version is available at http://dwarfstd.org.
//
// .gdb_index section format:
//  (Information is based on/taken from
//  https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html (*))
//
// A mapped index consists of several areas, laid out in order:
// 1) The file header.
// 2) "The CU (compilation unit) list. This is a sequence of pairs of 64-bit
//    little-endian values, sorted by the CU offset. The first element in each
//    pair is the offset of a CU in the .debug_info section. The second element
//    in each pair is the length of that CU. References to a CU elsewhere in the
//    map are done using a CU index, which is just the 0-based index into this
//    table. Note that if there are type CUs, then conceptually CUs and type CUs
//    form a single list for the purposes of CU indices."(*)
// 3) The types CU list. Depricated as .debug_types does not appear in the DWARF
//    v5 specification.
// 4) The address area. The address area is a sequence of address
//    entries, where each entrie contains low address, high address and CU
//    index.
// 5) "The symbol table. This is an open-addressed hash table. The size of the
//    hash table is always a power of 2. Each slot in the hash table consists of
//    a pair of offset_type values. The first value is the offset of the
//    symbol's name in the constant pool. The second value is the offset of the
//    CU vector in the constant pool."(*)
// 6) "The constant pool. This is simply a bunch of bytes. It is organized so
//    that alignment is correct: CU vectors are stored first, followed by
//    strings." (*)
//
// For constructing the .gdb_index section following steps should be performed:
// 1) For file header nothing special should be done. It contains the offsets to
//    the areas below.
// 2) Scan the compilation unit headers of the .debug_info sections to build a
//    list of compilation units.
// 3) CU Types are no longer needed as DWARF skeleton type units never made it
//    into the standard. lld does nothing to support parsing of .debug_types
//    and generates empty types CU area in .gdb_index section.
// 4) Address area entries are extracted from DW_TAG_compile_unit DIEs of
//   .debug_info sections.
// 5) For building the symbol table linker extracts the public names from the
//   .debug_gnu_pubnames and .debug_gnu_pubtypes sections. Then it builds the
//   hashtable in according to .gdb_index format specification.
// 6) Constant pool is populated at the same time as symbol table.
//===----------------------------------------------------------------------===//

#include "GdbIndex.h"
#include "Memory.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Object/ELFObjectFile.h"

using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;

std::pair<bool, GdbSymbol *> GdbHashTab::add(uint32_t Hash, size_t Offset) {
  GdbSymbol *&Sym = Map[Offset];
  if (Sym)
    return {false, Sym};
  Sym = make<GdbSymbol>(Hash, Offset);
  return {true, Sym};
}

void GdbHashTab::finalizeContents() {
  Table.resize(std::max<uint64_t>(1024, NextPowerOf2(Map.size() * 4 / 3)));

  for (auto &P : Map) {
    GdbSymbol *Sym = P.second;

    uint32_t I = Sym->NameHash & (Table.size() - 1);
    uint32_t Step = ((Sym->NameHash * 17) & (Table.size() - 1)) | 1;

    for (;;) {
      if (Table[I]) {
        I = (I + Step) & (Table.size() - 1);
        continue;
      }

      Table[I] = Sym;
      break;
    }
  }
}
<commit_msg>Simplify. NFC.<commit_after>//===- GdbIndex.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// File contains classes for implementation of --gdb-index command line option.
//
// If that option is used, linker should emit a .gdb_index section that allows
// debugger to locate and read .dwo files, containing neccessary debug
// information.
// More information about implementation can be found in DWARF specification,
// latest version is available at http://dwarfstd.org.
//
// .gdb_index section format:
//  (Information is based on/taken from
//  https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html (*))
//
// A mapped index consists of several areas, laid out in order:
// 1) The file header.
// 2) "The CU (compilation unit) list. This is a sequence of pairs of 64-bit
//    little-endian values, sorted by the CU offset. The first element in each
//    pair is the offset of a CU in the .debug_info section. The second element
//    in each pair is the length of that CU. References to a CU elsewhere in the
//    map are done using a CU index, which is just the 0-based index into this
//    table. Note that if there are type CUs, then conceptually CUs and type CUs
//    form a single list for the purposes of CU indices."(*)
// 3) The types CU list. Depricated as .debug_types does not appear in the DWARF
//    v5 specification.
// 4) The address area. The address area is a sequence of address
//    entries, where each entrie contains low address, high address and CU
//    index.
// 5) "The symbol table. This is an open-addressed hash table. The size of the
//    hash table is always a power of 2. Each slot in the hash table consists of
//    a pair of offset_type values. The first value is the offset of the
//    symbol's name in the constant pool. The second value is the offset of the
//    CU vector in the constant pool."(*)
// 6) "The constant pool. This is simply a bunch of bytes. It is organized so
//    that alignment is correct: CU vectors are stored first, followed by
//    strings." (*)
//
// For constructing the .gdb_index section following steps should be performed:
// 1) For file header nothing special should be done. It contains the offsets to
//    the areas below.
// 2) Scan the compilation unit headers of the .debug_info sections to build a
//    list of compilation units.
// 3) CU Types are no longer needed as DWARF skeleton type units never made it
//    into the standard. lld does nothing to support parsing of .debug_types
//    and generates empty types CU area in .gdb_index section.
// 4) Address area entries are extracted from DW_TAG_compile_unit DIEs of
//   .debug_info sections.
// 5) For building the symbol table linker extracts the public names from the
//   .debug_gnu_pubnames and .debug_gnu_pubtypes sections. Then it builds the
//   hashtable in according to .gdb_index format specification.
// 6) Constant pool is populated at the same time as symbol table.
//===----------------------------------------------------------------------===//

#include "GdbIndex.h"
#include "Memory.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Object/ELFObjectFile.h"

using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;

std::pair<bool, GdbSymbol *> GdbHashTab::add(uint32_t Hash, size_t Offset) {
  GdbSymbol *&Sym = Map[Offset];
  if (Sym)
    return {false, Sym};
  Sym = make<GdbSymbol>(Hash, Offset);
  return {true, Sym};
}

void GdbHashTab::finalizeContents() {
  uint32_t Size = std::max<uint32_t>(1024, NextPowerOf2(Map.size() * 4 / 3));
  uint32_t Mask = Size - 1;
  Table.resize(Size);

  for (auto &P : Map) {
    GdbSymbol *Sym = P.second;
    uint32_t I = Sym->NameHash & Mask;
    uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;

    while (Table[I])
      I = (I + Step) & Mask;
    Table[I] = Sym;
  }
}
<|endoftext|>


<commit_before>/*
 * Adplug - Replayer for many OPL2/OPL3 audio file formats.
 * Copyright (C) 1999 - 2007 Simon Peter, <dn.tlp@gmx.net>, et al.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * amd.cpp - AMD Loader by Simon Peter <dn.tlp@gmx.net>
 */

#include <string.h>

#include "amd.h"
#include "debug.h"

CPlayer *CamdLoader::factory(Copl *newopl)
{
  return new CamdLoader(newopl);
}

bool CamdLoader::load(const std::string &filename, const CFileProvider &fp)
{
  binistream *f = fp.open(filename); if(!f) return false;
  struct {
    char id[9];
    unsigned char version;
  } header;
  int i, j, k, t, numtrax, maxi = 0;
  unsigned char buf, buf2, buf3;
  const unsigned char convfx[10] = {0,1,2,9,17,11,13,18,3,14};
  const unsigned char convvol[64] = {
    0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 0xa, 0xa, 0xb,
    0xc, 0xc, 0xd, 0xe, 0xe, 0xf, 0x10, 0x10, 0x11, 0x12, 0x13, 0x14, 0x14,
    0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x21,
    0x22, 0x23, 0x25, 0x26, 0x28, 0x29, 0x2b, 0x2d, 0x2e, 0x30, 0x32, 0x35,
    0x37, 0x3a, 0x3c, 0x3f
  };

  // file validation section
  if(fp.filesize(f) < 1072) { fp.close(f); return false; }
  f->seek(1062); f->readString(header.id, 9);
  header.version = f->readInt(1);
  if(strncmp(header.id, "<o\xefQU\xeeRoR", 9) &&
     strncmp(header.id, "MaDoKaN96", 9)) { fp.close(f); return false; }

  // load section
  memset(inst, 0, sizeof(*inst));
  f->seek(0);
  f->readString(songname, sizeof(songname));
  f->readString(author, sizeof(author));
  for(i = 0; i < 26; i++) {
    f->readString(instname[i], 23);
    for(j = 0; j < 11; j++) inst[i].data[j] = f->readInt(1);
  }
  length = f->readInt(1); nop = f->readInt(1) + 1;
  for(i=0;i<128;i++) order[i] = f->readInt(1);
  f->seek(10, binio::Add);
  if(header.version == 0x10) {	// unpacked module
    maxi = nop * 9;
    for(i=0;i<64*9;i++)
      trackord[i/9][i%9] = i+1;
    t = 0;
    while(!f->ateof()) {
      for(j=0;j<64;j++)
	for(i=t;i<t+9;i++) {
	  buf = f->readInt(1);
	  tracks[i][j].param2 = (buf&127) % 10;
	  tracks[i][j].param1 = (buf&127) / 10;
	  buf = f->readInt(1);
	  tracks[i][j].inst = buf >> 4;
	  tracks[i][j].command = buf & 0x0f;
	  buf = f->readInt(1);
	  if(buf >> 4)	// fix bug in AMD save routine
	    tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4);
	  else
	    tracks[i][j].note = 0;
	  tracks[i][j].inst += (buf & 1) << 4;
	}
      t += 9;
    }
  } else {			// packed module
    for(i=0;i<nop;i++)
      for(j=0;j<9;j++)
	trackord[i][j] = f->readInt(2) + 1;
    numtrax = f->readInt(2);
    for(k=0;k<numtrax;k++) {
      i = f->readInt(2);
      if(i > 575) i = 575;	// fix corrupted modules
      maxi = (i + 1 > maxi ? i + 1 : maxi);
      j = 0;
      do {
	buf = f->readInt(1);
	if(buf & 128) {
	  for(t = j; t < j + (buf & 127) && t < 64; t++) {
	    tracks[i][t].command = 0;
	    tracks[i][t].inst = 0;
	    tracks[i][t].note = 0;
	    tracks[i][t].param1 = 0;
	    tracks[i][t].param2 = 0;
	  }
	  j += buf & 127;
	  continue;
	}
	tracks[i][j].param2 = buf % 10;
	tracks[i][j].param1 = buf / 10;
	buf = f->readInt(1);
	tracks[i][j].inst = buf >> 4;
	tracks[i][j].command = buf & 0x0f;
	buf = f->readInt(1);
	if(buf >> 4)	// fix bug in AMD save routine
	  tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4);
	else
	  tracks[i][j].note = 0;
	tracks[i][j].inst += (buf & 1) << 4;
	j++;
      } while(j<64);
    }
  }
  fp.close(f);

  // convert to protracker replay data
  bpm = 50; restartpos = 0; flags = Decimal;
  for(i=0;i<26;i++) {	// convert instruments
    buf = inst[i].data[0];
    buf2 = inst[i].data[1];
    inst[i].data[0] = inst[i].data[10];
    inst[i].data[1] = buf;
    buf = inst[i].data[2];
    inst[i].data[2] = inst[i].data[5];
    buf3 = inst[i].data[3];
    inst[i].data[3] = buf;
    buf = inst[i].data[4];
    inst[i].data[4] = inst[i].data[7];
    inst[i].data[5] = buf3;
    buf3 = inst[i].data[6];
    inst[i].data[6] = inst[i].data[8];
    inst[i].data[7] = buf;
    inst[i].data[8] = inst[i].data[9];
    inst[i].data[9] = buf2;
    inst[i].data[10] = buf3;
    for(j=0;j<23;j++)	// convert names
      if(instname[i][j] == '\xff')
	instname[i][j] = '\x20';
  }
  for(i=0;i<maxi;i++)	// convert patterns
    for(j=0;j<64;j++) {
      tracks[i][j].command = convfx[tracks[i][j].command];
      // extended command
      if(tracks[i][j].command == 14) {
	if(tracks[i][j].param1 == 2) {
	  tracks[i][j].command = 10;
	  tracks[i][j].param1 = tracks[i][j].param2;
	  tracks[i][j].param2 = 0;
	}

	if(tracks[i][j].param1 == 3) {
	  tracks[i][j].command = 10;
	  tracks[i][j].param1 = 0;
	}
      }

      // fix volume
      if(tracks[i][j].command == 17) {
	int vol = tracks[i][j].param1 * 10 + tracks[i][j].param2;

	if (vol > 63) vol = 63;
	else vol = convvol[vol];

	tracks[i][j].param1 = vol / 10;
	tracks[i][j].param2 = vol % 10;
      }
    }

  rewind(0);
  return true;
}

float CamdLoader::getrefresh()
{
  if(tempo)
    return (float) (tempo);
  else
    return 18.2f;
}
<commit_msg>amd.cpp: Check for valid command before table lookup<commit_after>/*
 * Adplug - Replayer for many OPL2/OPL3 audio file formats.
 * Copyright (C) 1999 - 2007 Simon Peter, <dn.tlp@gmx.net>, et al.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * amd.cpp - AMD Loader by Simon Peter <dn.tlp@gmx.net>
 */

#include <string.h>

#include "amd.h"
#include "debug.h"

CPlayer *CamdLoader::factory(Copl *newopl)
{
  return new CamdLoader(newopl);
}

bool CamdLoader::load(const std::string &filename, const CFileProvider &fp)
{
  binistream *f = fp.open(filename); if(!f) return false;
  struct {
    char id[9];
    unsigned char version;
  } header;
  int i, j, k, t, numtrax, maxi = 0;
  unsigned char buf, buf2, buf3;
  const unsigned char convfx[10] = {0,1,2,9,17,11,13,18,3,14};
  const unsigned char convvol[64] = {
    0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 0xa, 0xa, 0xb,
    0xc, 0xc, 0xd, 0xe, 0xe, 0xf, 0x10, 0x10, 0x11, 0x12, 0x13, 0x14, 0x14,
    0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x21,
    0x22, 0x23, 0x25, 0x26, 0x28, 0x29, 0x2b, 0x2d, 0x2e, 0x30, 0x32, 0x35,
    0x37, 0x3a, 0x3c, 0x3f
  };

  // file validation section
  if(fp.filesize(f) < 1072) { fp.close(f); return false; }
  f->seek(1062); f->readString(header.id, 9);
  header.version = f->readInt(1);
  if(strncmp(header.id, "<o\xefQU\xeeRoR", 9) &&
     strncmp(header.id, "MaDoKaN96", 9)) { fp.close(f); return false; }

  // load section
  memset(inst, 0, sizeof(*inst));
  f->seek(0);
  f->readString(songname, sizeof(songname));
  f->readString(author, sizeof(author));
  for(i = 0; i < 26; i++) {
    f->readString(instname[i], 23);
    for(j = 0; j < 11; j++) inst[i].data[j] = f->readInt(1);
  }
  length = f->readInt(1); nop = f->readInt(1) + 1;
  for(i=0;i<128;i++) order[i] = f->readInt(1);
  f->seek(10, binio::Add);
  if(header.version == 0x10) {	// unpacked module
    maxi = nop * 9;
    for(i=0;i<64*9;i++)
      trackord[i/9][i%9] = i+1;
    t = 0;
    while(!f->ateof()) {
      for(j=0;j<64;j++)
	for(i=t;i<t+9;i++) {
	  buf = f->readInt(1);
	  tracks[i][j].param2 = (buf&127) % 10;
	  tracks[i][j].param1 = (buf&127) / 10;
	  buf = f->readInt(1);
	  tracks[i][j].inst = buf >> 4;
	  tracks[i][j].command = buf & 0x0f;
	  buf = f->readInt(1);
	  if(buf >> 4)	// fix bug in AMD save routine
	    tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4);
	  else
	    tracks[i][j].note = 0;
	  tracks[i][j].inst += (buf & 1) << 4;
	}
      t += 9;
    }
  } else {			// packed module
    for(i=0;i<nop;i++)
      for(j=0;j<9;j++)
	trackord[i][j] = f->readInt(2) + 1;
    numtrax = f->readInt(2);
    for(k=0;k<numtrax;k++) {
      i = f->readInt(2);
      if(i > 575) i = 575;	// fix corrupted modules
      maxi = (i + 1 > maxi ? i + 1 : maxi);
      j = 0;
      do {
	buf = f->readInt(1);
	if(buf & 128) {
	  for(t = j; t < j + (buf & 127) && t < 64; t++) {
	    tracks[i][t].command = 0;
	    tracks[i][t].inst = 0;
	    tracks[i][t].note = 0;
	    tracks[i][t].param1 = 0;
	    tracks[i][t].param2 = 0;
	  }
	  j += buf & 127;
	  continue;
	}
	tracks[i][j].param2 = buf % 10;
	tracks[i][j].param1 = buf / 10;
	buf = f->readInt(1);
	tracks[i][j].inst = buf >> 4;
	tracks[i][j].command = buf & 0x0f;
	buf = f->readInt(1);
	if(buf >> 4)	// fix bug in AMD save routine
	  tracks[i][j].note = ((buf & 14) >> 1) * 12 + (buf >> 4);
	else
	  tracks[i][j].note = 0;
	tracks[i][j].inst += (buf & 1) << 4;
	j++;
      } while(j<64);
    }
  }
  fp.close(f);

  // convert to protracker replay data
  bpm = 50; restartpos = 0; flags = Decimal;
  for(i=0;i<26;i++) {	// convert instruments
    buf = inst[i].data[0];
    buf2 = inst[i].data[1];
    inst[i].data[0] = inst[i].data[10];
    inst[i].data[1] = buf;
    buf = inst[i].data[2];
    inst[i].data[2] = inst[i].data[5];
    buf3 = inst[i].data[3];
    inst[i].data[3] = buf;
    buf = inst[i].data[4];
    inst[i].data[4] = inst[i].data[7];
    inst[i].data[5] = buf3;
    buf3 = inst[i].data[6];
    inst[i].data[6] = inst[i].data[8];
    inst[i].data[7] = buf;
    inst[i].data[8] = inst[i].data[9];
    inst[i].data[9] = buf2;
    inst[i].data[10] = buf3;
    for(j=0;j<23;j++)	// convert names
      if(instname[i][j] == '\xff')
	instname[i][j] = '\x20';
  }
  for(i=0;i<maxi;i++)	// convert patterns
    for(j=0;j<64;j++) {
      if (tracks[i][j].command < 10)
	tracks[i][j].command = convfx[tracks[i][j].command];
      else
	tracks[i][j].command = 0; // ignore invalid commands

      // extended command
      if(tracks[i][j].command == 14) {
	if(tracks[i][j].param1 == 2) {
	  tracks[i][j].command = 10;
	  tracks[i][j].param1 = tracks[i][j].param2;
	  tracks[i][j].param2 = 0;
	}

	if(tracks[i][j].param1 == 3) {
	  tracks[i][j].command = 10;
	  tracks[i][j].param1 = 0;
	}
      }

      // fix volume
      if(tracks[i][j].command == 17) {
	int vol = tracks[i][j].param1 * 10 + tracks[i][j].param2;

	if (vol > 63) vol = 63;
	else vol = convvol[vol];

	tracks[i][j].param1 = vol / 10;
	tracks[i][j].param2 = vol % 10;
      }
    }

  rewind(0);
  return true;
}

float CamdLoader::getrefresh()
{
  if(tempo)
    return (float) (tempo);
  else
    return 18.2f;
}
<|endoftext|>


<commit_before>#include "PJobRunnerSessionThread.h"
#include "pjobrunnersessionwrapper.h"
#include "PQueueController.h"

PJobRunnerSessionThread::PJobRunnerSessionThread(QHostAddress address, PQueueController* workspace)
    : m_peer(address), m_workspace(workspace)
{
}

void PJobRunnerSessionThread::run(){
    m_session = new PJobRunnerSessionWrapper(m_peer);
    m_session->enqueue();
    m_session->wait_till_its_your_turn();
    Job* job = m_workspace->startNextJobInQueue();
    if(!job) return;
    job->submited();
    PJobFile* pjob_file = m_workspace->getPJobFile();
    if(!pjob_file) return;
    QByteArray* raw = pjob_file->raw_without_results();
    m_session->upload_pjobfile(*raw);
    delete raw;
    foreach(QString parameter, job->parameters().keys()){
        bool ok;
        double d = job->parameters()[parameter].toDouble(&ok);
        if(ok) m_session->set_parameter(parameter, d);
    }
    connect(m_session, SIGNAL(job_std_out(QString)), job, SLOT(err_out(QString)));
    connect(m_session, SIGNAL(job_error_out(QString)), job, SLOT(err_out(QString)));
    if(m_session->run_job()){
        job->started();
        if(!m_session->wait_for_job_finished())
            job->failed();
        else{
            //Job is finished. Get results.
            QByteArray results;
            m_session->download_results(results);
            job->finished();
        }
    }else job->failed();
    disconnect(m_session, SIGNAL(job_std_out(QString)), job, SLOT(err_out(QString)));
    disconnect(m_session, SIGNAL(job_error_out(QString)), job, SLOT(err_out(QString)));
}
<commit_msg>PJobRunnerSessionThread::run() ++<commit_after>#include "PJobRunnerSessionThread.h"
#include "pjobrunnersessionwrapper.h"
#include "PQueueController.h"

PJobRunnerSessionThread::PJobRunnerSessionThread(QHostAddress address, PQueueController* workspace)
    : m_peer(address), m_workspace(workspace)
{
}

void PJobRunnerSessionThread::run(){
    m_session = new PJobRunnerSessionWrapper(m_peer);
    m_session->enqueue();
    m_session->wait_till_its_your_turn();
    Job* job = m_workspace->startNextQueuedJob();
    if(!job) return;
    job->submited();
    PJobFile* pjob_file = m_workspace->getPJobFile();
    if(!pjob_file) return;
    QByteArray* raw = pjob_file->raw_without_results();
    m_session->upload_pjobfile(*raw);
    delete raw;
    foreach(QString parameter, job->parameters().keys()){
        bool ok;
        double d = job->parameters()[parameter].toDouble(&ok);
        if(ok) m_session->set_parameter(parameter, d);
    }
    connect(m_session, SIGNAL(job_std_out(QString)), job, SLOT(err_out(QString)));
    connect(m_session, SIGNAL(job_error_out(QString)), job, SLOT(err_out(QString)));
    if(m_session->run_job()){
        job->started();
        if(!m_session->wait_for_job_finished())
            job->failed();
        else{
            //Job is finished. Get results.
            QByteArray results;
            m_session->download_results(results);
            QString run_name = PJobFile::name_of_first_run_in_raw_bytes(results);
            pjob_file->add_raw_files(results);
            job->process_finished_run(run_name);
            job->finished();
        }
    }else job->failed();
    disconnect(m_session, SIGNAL(job_std_out(QString)), job, SLOT(err_out(QString)));
    disconnect(m_session, SIGNAL(job_error_out(QString)), job, SLOT(err_out(QString)));
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <cassert>
#include "amx_utils.h"
#include "function.h"
#include "function_call.h"
#include "function_statistics.h"
#include "profiler.h"

namespace amxprof {

Profiler::Profiler(AMX *amx, DebugInfo *debug_info)
 : amx_(amx),
   debug_info_(debug_info),
   call_graph_enabled_(false)
{
  // The AMX VM normally replaces SYSREQ.C instructions with SYSREQ.D
  // to speed up native calls. We don't want this to happen as then we
  // would be unable to profile native functions.
  amx->sysreq_d = 0;
}

Profiler::~Profiler() {
  for (FunctionSet::const_iterator iterator = functions_.begin();
       iterator != functions_.end(); ++iterator) {
    delete *iterator;
  }
}

int Profiler::DebugHook(AMX_DEBUG debug) {
  Address prev_frame = amx_->stp;

  if (!call_stack_.is_empty()) {
    prev_frame = call_stack_.top()->frame();
  }

  if (amx_->frm < prev_frame) {
    if (call_stack_.top()->frame() != amx_->frm) {
      Address address = GetCalleeAddress(amx_, amx_->frm);
      if (address != 0) {
        Function *fn = stats_.GetFunction(address);
        if (fn == 0) {
          fn = Function::Normal(address, debug_info_);
          functions_.insert(fn);
          stats_.AddFunction(fn);
        }
        BeginFunction(address, amx_->frm);
      }
    }
  } else if (amx_->frm > prev_frame) {
    if (call_stack_.top()->function()->type() == Function::NORMAL) {
      EndFunction();
    }
  }

  if (debug != 0) {
    return debug(amx_);
  }

  return AMX_ERR_NONE;
}

int Profiler::CallbackHook(cell index, cell *result, cell *params, AMX_CALLBACK callback) {
  if (callback == 0) {
    callback = ::amx_Callback;
  }

  if (index >= 0) {
    Address address = GetNativeAddress(amx_, index);
    if (address != 0) {
      Function *fn = stats_.GetFunction(address);
      if (fn == 0) {
        fn = Function::Native(amx_, index);
        functions_.insert(fn);
        stats_.AddFunction(fn);
      }
      BeginFunction(address, amx_->frm);
    }
    int error = callback(amx_, index, result, params);
    if (address != 0) {
      EndFunction(address);
    }
    return error;
  }

  return callback(amx_, index, result, params);
}

int Profiler::ExecHook(cell *retval, int index, AMX_EXEC exec) {
  if (exec == 0) {
    exec = ::amx_Exec;
  }

  if (index >= 0 || index == AMX_EXEC_MAIN) {
    Address address = GetPublicAddress(amx_, index);
    if (address != 0) {
      Function *fn = stats_.GetFunction(address);
      if (fn == 0) {
        fn = Function::Public(amx_, index);
        functions_.insert(fn);
        stats_.AddFunction(fn);
      }
      BeginFunction(address, amx_->stk - 3 * sizeof(cell));
    }
    int error = exec(amx_, retval, index);
    if (address != 0) {
      EndFunction(address);
    }
    return error;
  }

  return exec(amx_, retval, index);
}

void Profiler::BeginFunction(Address address, cell frm) {
  assert(address != 0);
  FunctionStatistics *fn_stats = stats_.GetFunctionStatistis(address);

  assert(fn_stats != 0);
  fn_stats->AdjustNumCalls(1);

  call_stack_.Push(fn_stats->function(), frm);
  if (call_graph_enabled_) {
    call_graph_.AddCallee(fn_stats)->MakeRoot();
  }
}

void Profiler::EndFunction(Address address) {
  assert(!call_stack_.is_empty());
  assert(address == 0 || stats_.GetFunction(address) != 0);

  while (true) {
    FunctionCall fn_call = call_stack_.Pop();

    FunctionStatistics *fn_stats = stats_.GetFunctionStatistis(fn_call.function()->address());
    assert(fn_stats != 0);

    fn_stats->AdjustSelfTime(fn_call.timer()->self_time());
    fn_stats->AdjustTotalTime(fn_call.timer()->total_time());

    Nanoseconds total_time = fn_call.timer()->latest_total_time();
    if (total_time > fn_stats->worst_total_time()) {
      fn_stats->set_worst_total_time(total_time);
    }

    Nanoseconds self_time = fn_call.timer()->latest_self_time();
    if (self_time > fn_stats->worst_self_time()) {
      fn_stats->set_worst_self_time(self_time);
    }

    if (call_graph_enabled_) {
      assert(call_graph_.root() != call_graph_.sentinel());
      call_graph_.set_root(call_graph_.root()->caller());
    }

    if (address == 0 || fn_call.function()->address() == address) {
      break;
    }
  }
}

} // namespace amxprof
<commit_msg>Correct method parameter type (cell -> Address)<commit_after>// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <cassert>
#include "amx_utils.h"
#include "function.h"
#include "function_call.h"
#include "function_statistics.h"
#include "profiler.h"

namespace amxprof {

Profiler::Profiler(AMX *amx, DebugInfo *debug_info)
 : amx_(amx),
   debug_info_(debug_info),
   call_graph_enabled_(false)
{
  // The AMX VM normally replaces SYSREQ.C instructions with SYSREQ.D
  // to speed up native calls. We don't want this to happen as then we
  // would be unable to profile native functions.
  amx->sysreq_d = 0;
}

Profiler::~Profiler() {
  for (FunctionSet::const_iterator iterator = functions_.begin();
       iterator != functions_.end(); ++iterator) {
    delete *iterator;
  }
}

int Profiler::DebugHook(AMX_DEBUG debug) {
  Address prev_frame = amx_->stp;

  if (!call_stack_.is_empty()) {
    prev_frame = call_stack_.top()->frame();
  }

  if (amx_->frm < prev_frame) {
    if (call_stack_.top()->frame() != amx_->frm) {
      Address address = GetCalleeAddress(amx_, amx_->frm);
      if (address != 0) {
        Function *fn = stats_.GetFunction(address);
        if (fn == 0) {
          fn = Function::Normal(address, debug_info_);
          functions_.insert(fn);
          stats_.AddFunction(fn);
        }
        BeginFunction(address, amx_->frm);
      }
    }
  } else if (amx_->frm > prev_frame) {
    if (call_stack_.top()->function()->type() == Function::NORMAL) {
      EndFunction();
    }
  }

  if (debug != 0) {
    return debug(amx_);
  }

  return AMX_ERR_NONE;
}

int Profiler::CallbackHook(cell index, cell *result, cell *params, AMX_CALLBACK callback) {
  if (callback == 0) {
    callback = ::amx_Callback;
  }

  if (index >= 0) {
    Address address = GetNativeAddress(amx_, index);
    if (address != 0) {
      Function *fn = stats_.GetFunction(address);
      if (fn == 0) {
        fn = Function::Native(amx_, index);
        functions_.insert(fn);
        stats_.AddFunction(fn);
      }
      BeginFunction(address, amx_->frm);
    }
    int error = callback(amx_, index, result, params);
    if (address != 0) {
      EndFunction(address);
    }
    return error;
  }

  return callback(amx_, index, result, params);
}

int Profiler::ExecHook(cell *retval, int index, AMX_EXEC exec) {
  if (exec == 0) {
    exec = ::amx_Exec;
  }

  if (index >= 0 || index == AMX_EXEC_MAIN) {
    Address address = GetPublicAddress(amx_, index);
    if (address != 0) {
      Function *fn = stats_.GetFunction(address);
      if (fn == 0) {
        fn = Function::Public(amx_, index);
        functions_.insert(fn);
        stats_.AddFunction(fn);
      }
      BeginFunction(address, amx_->stk - 3 * sizeof(cell));
    }
    int error = exec(amx_, retval, index);
    if (address != 0) {
      EndFunction(address);
    }
    return error;
  }

  return exec(amx_, retval, index);
}

void Profiler::BeginFunction(Address address, Address frm) {
  assert(address != 0);
  FunctionStatistics *fn_stats = stats_.GetFunctionStatistis(address);

  assert(fn_stats != 0);
  fn_stats->AdjustNumCalls(1);

  call_stack_.Push(fn_stats->function(), frm);
  if (call_graph_enabled_) {
    call_graph_.AddCallee(fn_stats)->MakeRoot();
  }
}

void Profiler::EndFunction(Address address) {
  assert(!call_stack_.is_empty());
  assert(address == 0 || stats_.GetFunction(address) != 0);

  while (true) {
    FunctionCall fn_call = call_stack_.Pop();

    FunctionStatistics *fn_stats = stats_.GetFunctionStatistis(fn_call.function()->address());
    assert(fn_stats != 0);

    fn_stats->AdjustSelfTime(fn_call.timer()->self_time());
    fn_stats->AdjustTotalTime(fn_call.timer()->total_time());

    Nanoseconds total_time = fn_call.timer()->latest_total_time();
    if (total_time > fn_stats->worst_total_time()) {
      fn_stats->set_worst_total_time(total_time);
    }

    Nanoseconds self_time = fn_call.timer()->latest_self_time();
    if (self_time > fn_stats->worst_self_time()) {
      fn_stats->set_worst_self_time(self_time);
    }

    if (call_graph_enabled_) {
      assert(call_graph_.root() != call_graph_.sentinel());
      call_graph_.set_root(call_graph_.root()->caller());
    }

    if (address == 0 || fn_call.function()->address() == address) {
      break;
    }
  }
}

} // namespace amxprof
<|endoftext|>


<commit_before>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 12/29/2018, 10:01:22 PM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;

const int MAX_SIZE = 1000010;
const long long MOD = 1000000007;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = (i * fact[i - 1]) % MOD;
    factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
  }
}

long long C(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
  }
  return 0;
}

long long power(long long x, long long n)
{
  if (n == 0)
  {
    return 1;
  }
  else if (n % 2 == 1)
  {
    return (x * power(x, n - 1)) % MOD;
  }
  else
  {
    long long half = power(x, n / 2);
    return (half * half) % MOD;
  }
}

long long gcd(long long x, long long y)
{
  return y ? gcd(y, x % y) : x;
}

ll N;
ll Q;
int A[3010];
int X[3010];
int Y[3010];
map<int, int> M;
int S[3010];
ll T[3010][3010];
ll t_half[3010];

void flush()
{
  ll ans = 0;
  for (auto i = 0; i < N; i++)
  {
    for (auto j = i + 1; j < N; j++)
    {
      ans += ((j - i) * T[i][j]) % MOD;
      ans %= MOD;
    }
  }
  cout << ans << endl;
}

int main()
{
  init();
  cin >> N >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
  }
  for (auto i = 0; i < Q; i++)
  {
    cin >> X[i] >> Y[i];
    X[i]--;
    Y[i]--;
  }
  for (auto i = 0; i < N; i++)
  {
    S[i] = A[i];
  }
  sort(S, S + N);
  for (auto i = 0; i < N; i++)
  {
    M[S[i]] = i;
  }
  for (auto i = 0; i < N; i++)
  {
    A[i] = M[A[i]];
    cerr << "A[" << i << "] = " << A[i] << endl;
  }
  fill(&T[0][0], &T[0][0] + 3010 * 3010, 0);
  ll initial = power(2, Q);
  for (auto i = 0; i < N; i++)
  {
    T[i][A[i]] = initial;
  }
  ll two_inv = inv[2];
  for (auto i = 0; i < Q; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      t_half[j] = T[X[i]][j] * two_inv + T[Y[i]][j] * two_inv;
      t_half[j] %= MOD;
      T[X[i]][j] = t_half[j];
      T[Y[i]][j] = t_half[j];
    }
  }
  flush();
}<commit_msg>tried D.cpp to 'D'<commit_after>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 12/29/2018, 10:01:22 PM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;

const int MAX_SIZE = 1000010;
const long long MOD = 1000000007;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = (i * fact[i - 1]) % MOD;
    factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
  }
}

long long C(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
  }
  return 0;
}

long long power(long long x, long long n)
{
  if (n == 0)
  {
    return 1;
  }
  else if (n % 2 == 1)
  {
    return (x * power(x, n - 1)) % MOD;
  }
  else
  {
    long long half = power(x, n / 2);
    return (half * half) % MOD;
  }
}

long long gcd(long long x, long long y)
{
  return y ? gcd(y, x % y) : x;
}

ll N;
ll Q;
int A[3010];
int X[3010];
int Y[3010];
map<int, int> M;
set<int> S;
ll T[3010][3010];
ll t_half[3010];

void flush()
{
  ll ans = 0;
  for (auto i = 0; i < N; i++)
  {
    for (auto j = i + 1; j < N; j++)
    {
      ans += ((j - i) * T[i][j]) % MOD;
      ans %= MOD;
    }
  }
  cout << ans << endl;
}

int main()
{
  init();
  cin >> N >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
  }
  for (auto i = 0; i < Q; i++)
  {
    cin >> X[i] >> Y[i];
    X[i]--;
    Y[i]--;
  }
  for (auto i = 0; i < N; i++)
  {
    S.insert(A[i]);
  }
  int cnt = 0;
  for (auto it = S.begin(); it != S.end(); it++)
  {
    M[*it] = cnt++;
  }
  for (auto i = 0; i < N; i++)
  {
    A[i] = M[A[i]];
    cerr << "A[" << i << "] = " << A[i] << endl;
  }
  fill(&T[0][0], &T[0][0] + 3010 * 3010, 0);
  ll initial = power(2, Q);
  for (auto i = 0; i < N; i++)
  {
    T[i][A[i]] = initial;
  }
  ll two_inv = inv[2];
  for (auto i = 0; i < Q; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      t_half[j] = T[X[i]][j] * two_inv + T[Y[i]][j] * two_inv;
      t_half[j] %= MOD;
      T[X[i]][j] = t_half[j];
      T[Y[i]][j] = t_half[j];
    }
  }
  flush();
}<|endoftext|>