<commit_before>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */
#include <vr_defs.h>
#include <cmn/agent_cmn.h>
#include <oper/interface_common.h>
#include <oper/vn.h>

#include <pkt/pkt_init.h>
#include <pkt/flow_table.h>
#include <services/icmp_error_proto.h>
#include <services/icmp_error_handler.h>

IcmpErrorHandler::IcmpErrorHandler(Agent *agent, IcmpErrorProto *proto,
                                   boost::shared_ptr<PktInfo> info,
                                   boost::asio::io_service *io) :
    ProtoHandler(agent, info, *io), proto_(proto) {
}

IcmpErrorHandler::~IcmpErrorHandler() {
}

bool IcmpErrorHandler::ValidatePacket() {
    if (pkt_info_->len < (IPC_HDR_LEN + sizeof(ethhdr) + sizeof(iphdr)))
        return false;
    return true;
}

bool IcmpErrorHandler::Run() {
    if (ValidatePacket() == false) {
        proto_->increment_drops();
        return true;
    }

    VmInterface *vm_itf = dynamic_cast<VmInterface *>
        (agent()->interface_table()->FindInterface(GetInterfaceIndex()));
    if (vm_itf == NULL || vm_itf->ipv4_forwarding() == false || vm_itf->vn() == NULL) {
        proto_->increment_interface_errors();
        return true;
    }

    return SendIcmpError(vm_itf);
}

// Generate ICMP error
bool IcmpErrorHandler::SendIcmpError(VmInterface *intf) {
    char data[ICMP_PAYLOAD_LEN];
    uint16_t data_len = ntohs(pkt_info_->ip->tot_len);
    if (data_len > ICMP_PAYLOAD_LEN)
        data_len = ICMP_PAYLOAD_LEN;
    memcpy(data, pkt_info_->ip, data_len);

    FlowKey key;
    if (proto_->FlowIndexToKey(pkt_info_->agent_hdr.flow_index, &key)
        == false) {
        proto_->increment_invalid_flow_index();
        return true;
    }

    // Get IPAM to find default gateway
    const VnIpam *ipam = intf->vn()->GetIpam(Ip4Address(key.src.ipv4));
    if (ipam == NULL) {
        proto_->increment_interface_errors();
        return true;
    }

    // Retain the agent-header before ethernet header
    uint16_t len = (char *)pkt_info_->eth - (char *)pkt_info_->pkt;
    uint16_t buf_len = pkt_info_->max_pkt_len;

    // Form ICMP Packet with following
    // EthHdr - IP Header - ICMP Header - User IP Packet(max 128 bytes)
    char *ptr = (char *)pkt_info_->pkt;
    len += EthHdr(ptr + len, buf_len - len,
                  agent()->vhost_interface()->mac().ether_addr_octet,
                  pkt_info_->eth->h_source, IP_PROTOCOL, intf->vlan_id());

    uint16_t ip_len = sizeof(iphdr) + sizeof(icmphdr) + data_len;
    len += IpHdr(ptr + len, buf_len - len, ip_len, ipam->default_gw.to_ulong(),
            htonl(key.src.ipv4), IPPROTO_ICMP);

    char *icmp = ptr + len;
    len += IcmpHdr(ptr + len, buf_len - len, ICMP_DEST_UNREACH,
                   ICMP_FRAG_NEEDED, 0, pkt_info_->agent_hdr.mtu);

    // Its possible that user payload has gone thru NAT processing already.
    // Restore the original fields from flow_key
    iphdr *ip = (iphdr *)data;
    uint16_t ip_hlen = ip->ihl * 4;

    ip->saddr = htonl(key.src.ipv4);
    ip->daddr = htonl(key.dst.ipv4);
    ip->check = Csum((uint16_t *)data, ip_hlen, 0);
    if (ip->protocol == IPPROTO_UDP) {
        udphdr *udp = (udphdr *)(data + ip_hlen);
        udp->source = ntohs(key.src_port);
        udp->dest = ntohs(key.dst_port);
    } else if (ip->protocol == IPPROTO_TCP) {
        tcphdr *tcp = (tcphdr *)(data + ip_hlen);
        tcp->source = ntohs(key.src_port);
        tcp->dest = ntohs(key.dst_port);
    }
    memcpy(ptr + len, data, data_len);
    len += data_len;
    IcmpChecksum(icmp, sizeof(icmphdr) + data_len);

    Send(len, GetInterfaceIndex(), pkt_info_->vrf, AGENT_CMD_SWITCH,
         PktHandler::ICMP);
    return true;
}
<commit_msg>send icmp error when DF is set for broadcast address Change-Id: I1f940028caa9b642f74fbbbc6be6f7810a8ec157 (cherry picked from commit fa0730c371d542e3f0a80c8d984cb0c6aa6d60ce)<commit_after>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */
#include <vr_defs.h>
#include <cmn/agent_cmn.h>
#include <oper/interface_common.h>
#include <oper/vn.h>

#include <pkt/pkt_init.h>
#include <pkt/flow_table.h>
#include <services/icmp_error_proto.h>
#include <services/icmp_error_handler.h>

IcmpErrorHandler::IcmpErrorHandler(Agent *agent, IcmpErrorProto *proto,
                                   boost::shared_ptr<PktInfo> info,
                                   boost::asio::io_service *io) :
    ProtoHandler(agent, info, *io), proto_(proto) {
}

IcmpErrorHandler::~IcmpErrorHandler() {
}

bool IcmpErrorHandler::ValidatePacket() {
    if (pkt_info_->len < (IPC_HDR_LEN + sizeof(ethhdr) + sizeof(iphdr)))
        return false;
    return true;
}

bool IcmpErrorHandler::Run() {
    if (ValidatePacket() == false) {
        proto_->increment_drops();
        return true;
    }

    VmInterface *vm_itf = dynamic_cast<VmInterface *>
        (agent()->interface_table()->FindInterface(GetInterfaceIndex()));
    if (vm_itf == NULL || vm_itf->ipv4_forwarding() == false || vm_itf->vn() == NULL) {
        proto_->increment_interface_errors();
        return true;
    }

    return SendIcmpError(vm_itf);
}

// Generate ICMP error
bool IcmpErrorHandler::SendIcmpError(VmInterface *intf) {
    char data[ICMP_PAYLOAD_LEN];
    uint16_t data_len = ntohs(pkt_info_->ip->tot_len);
    if (data_len > ICMP_PAYLOAD_LEN)
        data_len = ICMP_PAYLOAD_LEN;
    memcpy(data, pkt_info_->ip, data_len);

    uint32_t src_ip = 0;
    FlowKey key;
    if (pkt_info_->agent_hdr.flow_index == (uint32_t)-1) {
        // flow index is -1 for 255.255.255.255
        if (pkt_info_->ip_daddr != 0xFFFFFFFF) {
            proto_->increment_invalid_flow_index();
            return true;
        }
        src_ip = pkt_info_->ip_saddr;
    } else {
        if (proto_->FlowIndexToKey(pkt_info_->agent_hdr.flow_index, &key)
            == false) {
            proto_->increment_invalid_flow_index();
            return true;
        }
        src_ip = key.src.ipv4;
    }

    // Get IPAM to find default gateway
    const VnIpam *ipam = intf->vn()->GetIpam(Ip4Address(src_ip));
    if (ipam == NULL) {
        proto_->increment_interface_errors();
        return true;
    }

    // Retain the agent-header before ethernet header
    uint16_t len = (char *)pkt_info_->eth - (char *)pkt_info_->pkt;
    uint16_t buf_len = pkt_info_->max_pkt_len;

    // Form ICMP Packet with following
    // EthHdr - IP Header - ICMP Header - User IP Packet(max 128 bytes)
    char *ptr = (char *)pkt_info_->pkt;
    len += EthHdr(ptr + len, buf_len - len,
                  agent()->vhost_interface()->mac().ether_addr_octet,
                  pkt_info_->eth->h_source, IP_PROTOCOL, intf->vlan_id());

    uint16_t ip_len = sizeof(iphdr) + sizeof(icmphdr) + data_len;
    len += IpHdr(ptr + len, buf_len - len, ip_len, ipam->default_gw.to_ulong(),
            htonl(src_ip), IPPROTO_ICMP);

    char *icmp = ptr + len;
    len += IcmpHdr(ptr + len, buf_len - len, ICMP_DEST_UNREACH,
                   ICMP_FRAG_NEEDED, 0, pkt_info_->agent_hdr.mtu);

    if (pkt_info_->agent_hdr.flow_index != (uint32_t)-1) {
        // Its possible that user payload has gone thru NAT processing already.
        // Restore the original fields from flow_key
        iphdr *ip = (iphdr *)data;
        uint16_t ip_hlen = ip->ihl * 4;

        ip->saddr = htonl(key.src.ipv4);
        ip->daddr = htonl(key.dst.ipv4);
        ip->check = Csum((uint16_t *)data, ip_hlen, 0);
        if (ip->protocol == IPPROTO_UDP) {
            udphdr *udp = (udphdr *)(data + ip_hlen);
            udp->source = ntohs(key.src_port);
            udp->dest = ntohs(key.dst_port);
        } else if (ip->protocol == IPPROTO_TCP) {
            tcphdr *tcp = (tcphdr *)(data + ip_hlen);
            tcp->source = ntohs(key.src_port);
            tcp->dest = ntohs(key.dst_port);
        }
    }
    memcpy(ptr + len, data, data_len);
    len += data_len;
    IcmpChecksum(icmp, sizeof(icmphdr) + data_len);

    Send(len, GetInterfaceIndex(), pkt_info_->vrf, AGENT_CMD_SWITCH,
         PktHandler::ICMP);
    return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"

class GetPosTextPathGM : public skiagm::GM {
public:
    GetPosTextPathGM() {}

protected:
    SkString onShortName() {
        return SkString("getpostextpath");
    }

    SkISize onISize() { return skiagm::make_isize(480, 780); }

    virtual void onDraw(SkCanvas* canvas) {
        const char* text = "Hamburgefons";
        size_t len = strlen(text);

        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setTextSize(SkIntToScalar(48));

        SkAutoTArray<SkPoint>  pos(len);
        SkAutoTArray<SkScalar> widths(len);
        paint.getTextWidths(text, len, &widths[0]);

        SkRandom rand;
        SkScalar x = SkIntToScalar(20);
        SkScalar y = SkIntToScalar(100);
        for (size_t i = 0; i < len; ++i) {
            pos[i].set(x, y + rand.nextSScalar1() * 24);
            x += widths[i];
        }

        canvas->drawPosText(text, len, &pos[0], paint);

        SkPath path;
        paint.setColor(SK_ColorRED);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.getPosTextPath(text, len, &pos[0], &path);
        canvas->drawPath(path, paint);
    }
};

//////////////////////////////////////////////////////////////////////////////

static skiagm::GM* F(void*) { return new GetPosTextPathGM; }

static skiagm::GMRegistry gR(F);

<commit_msg>#include "SkTemplates.h"<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
#include "SkTemplates.h"

class GetPosTextPathGM : public skiagm::GM {
public:
    GetPosTextPathGM() {}

protected:
    SkString onShortName() {
        return SkString("getpostextpath");
    }

    SkISize onISize() { return skiagm::make_isize(480, 780); }

    virtual void onDraw(SkCanvas* canvas) {
        const char* text = "Hamburgefons";
        size_t len = strlen(text);

        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setTextSize(SkIntToScalar(48));

        SkAutoTArray<SkPoint>  pos(len);
        SkAutoTArray<SkScalar> widths(len);
        paint.getTextWidths(text, len, &widths[0]);

        SkRandom rand;
        SkScalar x = SkIntToScalar(20);
        SkScalar y = SkIntToScalar(100);
        for (size_t i = 0; i < len; ++i) {
            pos[i].set(x, y + rand.nextSScalar1() * 24);
            x += widths[i];
        }

        canvas->drawPosText(text, len, &pos[0], paint);

        SkPath path;
        paint.setColor(SK_ColorRED);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.getPosTextPath(text, len, &pos[0], &path);
        canvas->drawPath(path, paint);
    }
};

//////////////////////////////////////////////////////////////////////////////

static skiagm::GM* F(void*) { return new GetPosTextPathGM; }

static skiagm::GMRegistry gR(F);

<|endoftext|>


<commit_before>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

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;
int x[100010];
int y[100010];
vector<int> V[100010];
int parent[100010];

void make_parent(int v, int p) {
  parent[v] = p;
  for (auto x : V[v]) {
    if (x != p) {
      make_parent(x, v);
    }
  }
}

int grundy(int v) {
  int s = V[v].size();
  if (v == 0) ++s;
  int ans;
  if (s == 1) {
    ans = 0;
  } else if (s == 2) {
    for (auto x : V[v]) {
      if (x != parent[v]) {
        ans = grundy(x) + 1;
      }
    }
  } else {
    ans = 0;
    for (auto x : V[v]) {
      if (x != parent[v]) {
        ans ^= grundy(x);
      }
    }
  }
  // cerr << "grundy(" << v << ") = " << ans << endl;
  return ans;
}

int main () {
  cin >> N;
  for (auto i = 0; i < N-1; ++i) {
    cin >> x[i] >> y[i];
    x[i]--;
    y[i]--;
    V[x[i]].push_back(y[i]);
    V[y[i]].push_back(x[i]);
  }
  make_parent(0, -1);
  if (grundy(0) == 0) {
    cout << "Bob" << endl;
  } else {
    cout << "Alice" << endl;
  }
}
<commit_msg>submit D.cpp to 'D - Game on Tree' (agc017) [C++14 (GCC 5.4.1)]<commit_after>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

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;
int x[100010];
int y[100010];
vector<int> V[100010];
int parent[100010];

void make_parent(int v, int p) {
  parent[v] = p;
  for (auto x : V[v]) {
    if (x != p) {
      make_parent(x, v);
    }
  }
}

int grundy(int v) {
  int s = V[v].size();
  if (v == 0) ++s;
  int ans;
  if (s == 1) {
    ans = 0;
  } else if (s == 2) {
    for (auto x : V[v]) {
      if (x != parent[v]) {
        ans = grundy(x) + 1;
      }
    }
  } else {
    ans = 0;
    for (auto x : V[v]) {
      if (x != parent[v]) {
        ans ^= grundy(x);
      }
    }
  }
  cerr << "grundy(" << v << ") = " << ans << endl;
  return ans;
}

int main () {
  cin >> N;
  for (auto i = 0; i < N-1; ++i) {
    cin >> x[i] >> y[i];
    x[i]--;
    y[i]--;
    V[x[i]].push_back(y[i]);
    V[y[i]].push_back(x[i]);
  }
  make_parent(0, -1);
  if (grundy(0) == 0) {
    cout << "Bob" << endl;
  } else {
    cout << "Alice" << endl;
  }
}
<|endoftext|>


<commit_before>
// This file is part of lipstick, a QML desktop library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation
// and appearing in the file LICENSE.LGPL included in the packaging
// of this file.
//
// This code 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.
//
// Copyright (c) 2011, Robin Burchell
// Copyright (c) 2012, Timur Kristóf <venemo@fedoraproject.org>
// Copyright (c) 2010, Nokia Corporation and/or its subsidiary(-ies) <directui@nokia.com>

#include <QApplication>
#include <QPainter>
#include <QTimer>
#include <QX11Info>

#include "switcherpixmapitem.h"
#include "xtools/homewindowmonitor.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xdamage.h>

// Define this if you'd like to see debug messages from the switcher
#ifdef DEBUG_SWITCHER
#define SWITCHER_DEBUG qDebug
#else
#define SWITCHER_DEBUG if (false) qDebug
#endif

#ifdef Q_WS_X11
unsigned char xErrorCode = Success;

static int handleXError(Display *, XErrorEvent *event)
{
    xErrorCode = event->error_code;

    return 0;
}
#endif

struct SwitcherPixmapItem::Private
{
    Private()
        : xWindowPixmapIsValid(false)
        , xWindowPixmap(0)
        , xWindowPixmapDamage(0)
        , windowId(0)
    {}

    bool xWindowPixmapIsValid;
    Pixmap xWindowPixmap;
    Damage xWindowPixmapDamage;
    QPixmap qWindowPixmap;
    WId windowId;
};

SwitcherPixmapItem::SwitcherPixmapItem(QDeclarativeItem *parent)
    : QDeclarativeItem(parent)
    , d(new Private)
{
    setFlag(QGraphicsItem::ItemHasNoContents, false);
    connect(qApp, SIGNAL(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &)), this, SLOT(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &)));
    connect(HomeWindowMonitor::instance(), SIGNAL(isHomeWindowOnTopChanged()), this, SLOT(toggleDamage()));
}

SwitcherPixmapItem::~SwitcherPixmapItem()
{
    destroyDamage();
    if (d->xWindowPixmap)
        XFreePixmap(QX11Info::display(), d->xWindowPixmap);
    delete d;
}

void SwitcherPixmapItem::toggleDamage()
{
    if (HomeWindowMonitor::instance()->isHomeWindowOnTop()) {
        SWITCHER_DEBUG() << Q_FUNC_INFO << "Creating damage for " << d->windowId;
        createDamage();
        update();
    } else {
        SWITCHER_DEBUG() << Q_FUNC_INFO << "Destroying damage for " << d->windowId;
        destroyDamage();
    }
}

void SwitcherPixmapItem::damageEvent(Qt::HANDLE &damage, short &x, short &y, unsigned short &width, unsigned short &height)
{
    Q_UNUSED(x);
    Q_UNUSED(y);
    Q_UNUSED(width);
    Q_UNUSED(height);
#ifdef Q_WS_X11
    if (d->xWindowPixmapDamage == damage) {
        XDamageSubtract(QX11Info::display(), d->xWindowPixmapDamage, None, None);
        update();
    }
#else
    Q_UNUSED(damage);
#endif
}

void SwitcherPixmapItem::destroyDamage()
{
    if (d->xWindowPixmapDamage != 0) {
        XDamageDestroy(QX11Info::display(), d->xWindowPixmapDamage);
        d->xWindowPixmapDamage = 0;
    }
}

void SwitcherPixmapItem::createDamage()
{
    // TODO: check on display status, don't create damage if off
    if (d->windowId == 0)
        return;

    // Register the pixmap for XDamage events
    d->xWindowPixmapDamage = XDamageCreate(QX11Info::display(), d->windowId, XDamageReportNonEmpty);
}

void SwitcherPixmapItem::updateXWindowPixmap()
{
#ifdef Q_WS_X11
    SWITCHER_DEBUG() << Q_FUNC_INFO << "Resetting X pixmap for " << d->windowId;

    // It is possible that the window is not redirected so check for errors.
    // XSync() needs to be called so that previous errors go to the original
    // handler.
    XSync(QX11Info::display(), FALSE);
    XErrorHandler errh = XSetErrorHandler(handleXError);
    xErrorCode = Success;

    // Get the pixmap ID of the X window
    Pixmap newWindowPixmap = XCompositeNameWindowPixmap(QX11Info::display(), d->windowId);

    // XCompositeNameWindowPixmap doesn't wait for the server to reply, we'll
    // need to do it ourselves to catch the possible BadMatch
    XSync(QX11Info::display(), FALSE);

    d->xWindowPixmapIsValid = xErrorCode == Success;
    if (d->xWindowPixmapIsValid) {
        // Unregister the old pixmap from XDamage events
        destroyDamage();

        if (d->xWindowPixmap != 0) {
            // Dereference the old pixmap ID
            XFreePixmap(QX11Info::display(), d->xWindowPixmap);
        }

        d->xWindowPixmap = newWindowPixmap;

        // Register the pixmap for XDamage events
        if (HomeWindowMonitor::instance()->isHomeWindowOnTop())
            createDamage();

        d->qWindowPixmap = QPixmap::fromX11Pixmap(d->xWindowPixmap, QPixmap::ExplicitlyShared);
    } else {
        // If a BadMatch error occurred the window wasn't redirected yet; deference the invalid pixmap
        if (newWindowPixmap != 0) {
            XFreePixmap(QX11Info::display(), newWindowPixmap);
        }
    }

    // Reset the error handler
    XSetErrorHandler(errh);
#else
#error "not implemented"
#endif
}

void SwitcherPixmapItem::setWindowId(int window)
{
    d->windowId = window;
    d->xWindowPixmapIsValid = false;

    // TODO: should we XFreePixmap here?

    update();
}

int SwitcherPixmapItem::windowId() const
{
    return d->windowId;
}

void SwitcherPixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                               QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    if (!d->xWindowPixmapIsValid) {
        updateXWindowPixmap();
    }

    QT_TRY {
        painter->drawPixmap(QRect(0, 0, width(), height()), d->qWindowPixmap);
    } QT_CATCH (std::bad_alloc e) {
        // XGetImage failed, the window has been already unmapped
    }
}

bool SwitcherPixmapItem::handleXEvent(const XEvent &event)
{
    WId windowId;

    if (event.type == VisibilityNotify) {
        if (event.xvisibility.state != VisibilityFullyObscured ||
            event.xvisibility.send_event != True) {
            SWITCHER_DEBUG() << Q_FUNC_INFO << "Ignoring VisibilityNotify that isn't a send_event VisibilityFullyObscured for " << event.xvisibility.window;
            return false;
        }

        windowId = event.xvisibility.window;
        SWITCHER_DEBUG() << Q_FUNC_INFO << "Got obscured for " << windowId << "; want " << d->windowId;
    } else if (event.type == ConfigureNotify) {
        windowId = event.xconfigure.window;
        SWITCHER_DEBUG() << Q_FUNC_INFO << "ConfigureNotify for " << windowId << "; want " << d->windowId;
    } else {
        return false;
    }

    if (windowId != d->windowId)
        return false;

    SWITCHER_DEBUG() << Q_FUNC_INFO << "Invalidated, resetting pixmap for " << d->windowId;
    d->xWindowPixmapIsValid = false;
    update();
    return true;
}

<commit_msg>optionally smooth scale window pixmaps, if smooth property is set.<commit_after>
// This file is part of lipstick, a QML desktop library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation
// and appearing in the file LICENSE.LGPL included in the packaging
// of this file.
//
// This code 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.
//
// Copyright (c) 2011, Robin Burchell
// Copyright (c) 2012, Timur Kristóf <venemo@fedoraproject.org>
// Copyright (c) 2010, Nokia Corporation and/or its subsidiary(-ies) <directui@nokia.com>

#include <QApplication>
#include <QPainter>
#include <QTimer>
#include <QX11Info>

#include "switcherpixmapitem.h"
#include "xtools/homewindowmonitor.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xdamage.h>

// Define this if you'd like to see debug messages from the switcher
#ifdef DEBUG_SWITCHER
#define SWITCHER_DEBUG qDebug
#else
#define SWITCHER_DEBUG if (false) qDebug
#endif

#ifdef Q_WS_X11
unsigned char xErrorCode = Success;

static int handleXError(Display *, XErrorEvent *event)
{
    xErrorCode = event->error_code;

    return 0;
}
#endif

struct SwitcherPixmapItem::Private
{
    Private()
        : xWindowPixmapIsValid(false)
        , xWindowPixmap(0)
        , xWindowPixmapDamage(0)
        , windowId(0)
    {}

    bool xWindowPixmapIsValid;
    Pixmap xWindowPixmap;
    Damage xWindowPixmapDamage;
    QPixmap qWindowPixmap;
    WId windowId;
};

SwitcherPixmapItem::SwitcherPixmapItem(QDeclarativeItem *parent)
    : QDeclarativeItem(parent)
    , d(new Private)
{
    setFlag(QGraphicsItem::ItemHasNoContents, false);
    connect(qApp, SIGNAL(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &)), this, SLOT(damageEvent(Qt::HANDLE &, short &, short &, unsigned short &, unsigned short &)));
    connect(HomeWindowMonitor::instance(), SIGNAL(isHomeWindowOnTopChanged()), this, SLOT(toggleDamage()));
}

SwitcherPixmapItem::~SwitcherPixmapItem()
{
    destroyDamage();
    if (d->xWindowPixmap)
        XFreePixmap(QX11Info::display(), d->xWindowPixmap);
    delete d;
}

void SwitcherPixmapItem::toggleDamage()
{
    if (HomeWindowMonitor::instance()->isHomeWindowOnTop()) {
        SWITCHER_DEBUG() << Q_FUNC_INFO << "Creating damage for " << d->windowId;
        createDamage();
        update();
    } else {
        SWITCHER_DEBUG() << Q_FUNC_INFO << "Destroying damage for " << d->windowId;
        destroyDamage();
    }
}

void SwitcherPixmapItem::damageEvent(Qt::HANDLE &damage, short &x, short &y, unsigned short &width, unsigned short &height)
{
    Q_UNUSED(x);
    Q_UNUSED(y);
    Q_UNUSED(width);
    Q_UNUSED(height);
#ifdef Q_WS_X11
    if (d->xWindowPixmapDamage == damage) {
        XDamageSubtract(QX11Info::display(), d->xWindowPixmapDamage, None, None);
        update();
    }
#else
    Q_UNUSED(damage);
#endif
}

void SwitcherPixmapItem::destroyDamage()
{
    if (d->xWindowPixmapDamage != 0) {
        XDamageDestroy(QX11Info::display(), d->xWindowPixmapDamage);
        d->xWindowPixmapDamage = 0;
    }
}

void SwitcherPixmapItem::createDamage()
{
    // TODO: check on display status, don't create damage if off
    if (d->windowId == 0)
        return;

    // Register the pixmap for XDamage events
    d->xWindowPixmapDamage = XDamageCreate(QX11Info::display(), d->windowId, XDamageReportNonEmpty);
}

void SwitcherPixmapItem::updateXWindowPixmap()
{
#ifdef Q_WS_X11
    SWITCHER_DEBUG() << Q_FUNC_INFO << "Resetting X pixmap for " << d->windowId;

    // It is possible that the window is not redirected so check for errors.
    // XSync() needs to be called so that previous errors go to the original
    // handler.
    XSync(QX11Info::display(), FALSE);
    XErrorHandler errh = XSetErrorHandler(handleXError);
    xErrorCode = Success;

    // Get the pixmap ID of the X window
    Pixmap newWindowPixmap = XCompositeNameWindowPixmap(QX11Info::display(), d->windowId);

    // XCompositeNameWindowPixmap doesn't wait for the server to reply, we'll
    // need to do it ourselves to catch the possible BadMatch
    XSync(QX11Info::display(), FALSE);

    d->xWindowPixmapIsValid = xErrorCode == Success;
    if (d->xWindowPixmapIsValid) {
        // Unregister the old pixmap from XDamage events
        destroyDamage();

        if (d->xWindowPixmap != 0) {
            // Dereference the old pixmap ID
            XFreePixmap(QX11Info::display(), d->xWindowPixmap);
        }

        d->xWindowPixmap = newWindowPixmap;

        // Register the pixmap for XDamage events
        if (HomeWindowMonitor::instance()->isHomeWindowOnTop())
            createDamage();

        d->qWindowPixmap = QPixmap::fromX11Pixmap(d->xWindowPixmap, QPixmap::ExplicitlyShared);
    } else {
        // If a BadMatch error occurred the window wasn't redirected yet; deference the invalid pixmap
        if (newWindowPixmap != 0) {
            XFreePixmap(QX11Info::display(), newWindowPixmap);
        }
    }

    // Reset the error handler
    XSetErrorHandler(errh);
#else
#error "not implemented"
#endif
}

void SwitcherPixmapItem::setWindowId(int window)
{
    d->windowId = window;
    d->xWindowPixmapIsValid = false;

    // TODO: should we XFreePixmap here?

    update();
}

int SwitcherPixmapItem::windowId() const
{
    return d->windowId;
}

void SwitcherPixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                               QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    if (!d->xWindowPixmapIsValid) {
        updateXWindowPixmap();
    }

    QPainter::RenderHints oldHints = painter->renderHints();
    if (smooth())
        painter->setRenderHint(QPainter::SmoothPixmapTransform);

    QT_TRY {
        painter->drawPixmap(QRect(0, 0, width(), height()), d->qWindowPixmap);
    } QT_CATCH (std::bad_alloc e) {
        // XGetImage failed, the window has been already unmapped
    }

    if (smooth())
        painter->setRenderHints(oldHints);
}

bool SwitcherPixmapItem::handleXEvent(const XEvent &event)
{
    WId windowId;

    if (event.type == VisibilityNotify) {
        if (event.xvisibility.state != VisibilityFullyObscured ||
            event.xvisibility.send_event != True) {
            SWITCHER_DEBUG() << Q_FUNC_INFO << "Ignoring VisibilityNotify that isn't a send_event VisibilityFullyObscured for " << event.xvisibility.window;
            return false;
        }

        windowId = event.xvisibility.window;
        SWITCHER_DEBUG() << Q_FUNC_INFO << "Got obscured for " << windowId << "; want " << d->windowId;
    } else if (event.type == ConfigureNotify) {
        windowId = event.xconfigure.window;
        SWITCHER_DEBUG() << Q_FUNC_INFO << "ConfigureNotify for " << windowId << "; want " << d->windowId;
    } else {
        return false;
    }

    if (windowId != d->windowId)
        return false;

    SWITCHER_DEBUG() << Q_FUNC_INFO << "Invalidated, resetting pixmap for " << d->windowId;
    d->xWindowPixmapIsValid = false;
    update();
    return true;
}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_ORDERED_LOGISTIC_LPMF_HPP
#define STAN_MATH_PRIM_PROB_ORDERED_LOGISTIC_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/fun/log1p_exp.hpp>
#include <stan/math/prim/fun/log_inv_logit_diff.hpp>
#include <stan/math/prim/fun/is_integer.hpp>
#include <vector>

namespace stan {
namespace math {

/** \ingroup multivar_dists
 * Returns the (natural) log probability of the specified array
 * of integers given the vector of continuous locations and
 * specified cutpoints in an ordered logistic model.
 *
 *
Typically the continous location
 * will be the dot product of a vector of regression coefficients
 * and a vector of predictors for the outcome
 *
  \f[
    \frac{\partial }{\partial \lambda} =
    \begin{cases}\\
    -\mathrm{logit}^{-1}(\lambda - c_1) & \mbox{if } k = 1,\\
    -(((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) +
    ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)))
    & \mathrm{if } 1 < k < K, \mathrm{and}\\
    \mathrm{logit}^{-1}(c_{K-2}-\lambda) & \mathrm{if } k = K.
    \end{cases}
  \f]

  \f[
    \frac{\partial }{\partial \lambda} =
    \begin{cases}
    -\mathrm{logit}^{-1}(\lambda - c_1) & \text{if } k = 1,\\
    -(((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) +
    ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)))
    & \text{if } 1 < k < K, \text{ and}\\
    \mathrm{logit}^{-1}(c_{K-2}-\lambda) & \text{if } k = K.
    \end{cases}
  \f]
 *
 * @tparam propto True if calculating up to a proportion.
 * @tparam T_y Y variable type (integer or array of integers).
 * @tparam T_loc Location type.
 * @tparam T_cut Cut-point type.
 * @param y Array of integers
 * @param lambda Vector of continuous location variables.
 * @param c Positive increasing vector of cutpoints.
 * @return Log probability of outcome given location and
 * cutpoints.
 * @throw std::domain_error If the outcome is not between 1 and
 * the number of cutpoints plus 2; if the cutpoint vector is
 * empty; if the cutpoint vector contains a non-positive,
 * non-finite value; or if the cutpoint vector is not sorted in
 * ascending order.
 * @throw std::invalid_argument If y and lambda are different
 * lengths.
 */
template <bool propto, typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_logistic_lpmf(const T_y& y,
                                                  const T_loc& lambda,
                                                  const T_cut& c) {
  static const char* function = "ordered_logistic";

  using T_partials_return = partials_return_t<T_loc, T_cut>;
  using T_partials_vec = typename Eigen::Matrix<T_partials_return, -1, 1>;

  scalar_seq_view<T_loc> lam_vec(lambda);
  scalar_seq_view<T_y> y_vec(y);
  vector_seq_view<T_cut> c_vec(c);

  int K = c_vec[0].size() + 1;
  int N = size(lambda);
  int C_l = size_mvt(c);

  check_consistent_sizes(function, "Integers", y, "Locations", lambda);
  if (C_l > 1) {
    check_size_match(function, "Length of location variables ", N,
                     "Number of cutpoint vectors ", C_l);
  }

  int size_c_old = c_vec[0].size();
  for (int i = 1; i < C_l; i++) {
    int size_c_new = c_vec[i].size();

    check_size_match(function, "Size of one of the vectors of cutpoints ",
                     size_c_new, "Size of another vector of the cutpoints ",
                     size_c_old);
  }

  for (int n = 0; n < N; n++) {
    check_bounded(function, "Random variable", y_vec[n], 1, K);
    check_finite(function, "Location parameter", lam_vec[n]);
  }

  for (int i = 0; i < C_l; i++) {
    check_ordered(function, "Cut-points", c_vec[i]);
    check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0);
    check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1));
    check_finite(function, "First cut-point", c_vec[i](0));
  }

  operands_and_partials<T_loc, T_cut> ops_partials(lambda, c);

  T_partials_return logp(0.0);
  T_partials_vec c_dbl = value_of(c_vec[0]).template cast<T_partials_return>();

  for (int n = 0; n < N; ++n) {
    if (C_l > 1) {
      c_dbl = value_of(c_vec[n]).template cast<T_partials_return>();
    }
    T_partials_return lam_dbl = value_of(lam_vec[n]);

    if (y_vec[n] == 1) {
      logp -= log1p_exp(lam_dbl - c_dbl[0]);
      T_partials_return d = inv_logit(lam_dbl - c_dbl[0]);

      if (!is_constant_all<T_loc>::value) {
        ops_partials.edge1_.partials_[n] -= d;
      }

      if (!is_constant_all<T_cut>::value) {
        ops_partials.edge2_.partials_vec_[n](0) += d;
      }

    } else if (y_vec[n] == K) {
      logp -= log1p_exp(c_dbl[K - 2] - lam_dbl);
      T_partials_return d = inv_logit(c_dbl[K - 2] - lam_dbl);

      if (!is_constant_all<T_loc>::value) {
        ops_partials.edge1_.partials_[n] = d;
      }

      if (!is_constant_all<T_cut>::value) {
        ops_partials.edge2_.partials_vec_[n](K - 2) -= d;
      }

    } else {
      T_partials_return d1
          = inv(1 - exp(c_dbl[y_vec[n] - 1] - c_dbl[y_vec[n] - 2]))
            - inv_logit(c_dbl[y_vec[n] - 2] - lam_dbl);
      T_partials_return d2
          = inv(1 - exp(c_dbl[y_vec[n] - 2] - c_dbl[y_vec[n] - 1]))
            - inv_logit(c_dbl[y_vec[n] - 1] - lam_dbl);
      logp += log_inv_logit_diff(lam_dbl - c_dbl[y_vec[n] - 2],
                                 lam_dbl - c_dbl[y_vec[n] - 1]);

      if (!is_constant_all<T_loc>::value) {
        ops_partials.edge1_.partials_[n] -= d1 + d2;
      }

      if (!is_constant_all<T_cut>::value) {
        ops_partials.edge2_.partials_vec_[n](y_vec[n] - 2) += d1;
        ops_partials.edge2_.partials_vec_[n](y_vec[n] - 1) += d2;
      }
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_logistic_lpmf(const T_y& y,
                                                  const T_loc& lambda,
                                                  const T_cut& c) {
  return ordered_logistic_lpmf<false>(y, lambda, c);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Lift two more.<commit_after>#ifndef STAN_MATH_PRIM_PROB_ORDERED_LOGISTIC_LPMF_HPP
#define STAN_MATH_PRIM_PROB_ORDERED_LOGISTIC_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/fun/log1p_exp.hpp>
#include <stan/math/prim/fun/log_inv_logit_diff.hpp>
#include <stan/math/prim/fun/is_integer.hpp>
#include <vector>

namespace stan {
namespace math {

/** \ingroup multivar_dists
 * Returns the (natural) log probability of the specified array
 * of integers given the vector of continuous locations and
 * specified cutpoints in an ordered logistic model.
 *
 *
Typically the continous location
 * will be the dot product of a vector of regression coefficients
 * and a vector of predictors for the outcome
 *
  \f[
    \frac{\partial }{\partial \lambda} =
    \begin{cases}\\
    -\mathrm{logit}^{-1}(\lambda - c_1) & \mbox{if } k = 1,\\
    -(((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) +
    ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)))
    & \mathrm{if } 1 < k < K, \mathrm{and}\\
    \mathrm{logit}^{-1}(c_{K-2}-\lambda) & \mathrm{if } k = K.
    \end{cases}
  \f]

  \f[
    \frac{\partial }{\partial \lambda} =
    \begin{cases}
    -\mathrm{logit}^{-1}(\lambda - c_1) & \text{if } k = 1,\\
    -(((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) +
    ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)))
    & \text{if } 1 < k < K, \text{ and}\\
    \mathrm{logit}^{-1}(c_{K-2}-\lambda) & \text{if } k = K.
    \end{cases}
  \f]
 *
 * @tparam propto True if calculating up to a proportion.
 * @tparam T_y Y variable type (integer or array of integers).
 * @tparam T_loc Location type.
 * @tparam T_cut Cut-point type.
 * @param y Array of integers
 * @param lambda Vector of continuous location variables.
 * @param c Positive increasing vector of cutpoints.
 * @return Log probability of outcome given location and
 * cutpoints.
 * @throw std::domain_error If the outcome is not between 1 and
 * the number of cutpoints plus 2; if the cutpoint vector is
 * empty; if the cutpoint vector contains a non-positive,
 * non-finite value; or if the cutpoint vector is not sorted in
 * ascending order.
 * @throw std::invalid_argument If y and lambda are different
 * lengths.
 */
template <bool propto, typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_logistic_lpmf(const T_y& y,
                                                  const T_loc& lambda,
                                                  const T_cut& c) {
  static const char* function = "ordered_logistic";

  using T_partials_return = partials_return_t<T_loc, T_cut>;
  using T_partials_vec = typename Eigen::Matrix<T_partials_return, -1, 1>;

  scalar_seq_view<T_loc> lam_vec(lambda);
  scalar_seq_view<T_y> y_vec(y);
  vector_seq_view<T_cut> c_vec(c);

  int K = c_vec[0].size() + 1;
  int N = size(lambda);
  int C_l = size_mvt(c);

  check_consistent_sizes(function, "Integers", y, "Locations", lambda);
  if (C_l > 1) {
    check_size_match(function, "Length of location variables ", N,
                     "Number of cutpoint vectors ", C_l);
  }

  int size_c_old = c_vec[0].size();
  for (int i = 1; i < C_l; i++) {
    int size_c_new = c_vec[i].size();

    check_size_match(function, "Size of one of the vectors of cutpoints ",
                     size_c_new, "Size of another vector of the cutpoints ",
                     size_c_old);
  }

  check_bounded(function, "Random variable", y, 1, K);
  check_finite(function, "Location parameter", lambda);

  for (int i = 0; i < C_l; i++) {
    check_ordered(function, "Cut-points", c_vec[i]);
    check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0);
    check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1));
    check_finite(function, "First cut-point", c_vec[i](0));
  }

  operands_and_partials<T_loc, T_cut> ops_partials(lambda, c);

  T_partials_return logp(0.0);
  T_partials_vec c_dbl = value_of(c_vec[0]).template cast<T_partials_return>();

  for (int n = 0; n < N; ++n) {
    if (C_l > 1) {
      c_dbl = value_of(c_vec[n]).template cast<T_partials_return>();
    }
    T_partials_return lam_dbl = value_of(lam_vec[n]);

    if (y_vec[n] == 1) {
      logp -= log1p_exp(lam_dbl - c_dbl[0]);
      T_partials_return d = inv_logit(lam_dbl - c_dbl[0]);

      if (!is_constant_all<T_loc>::value) {
        ops_partials.edge1_.partials_[n] -= d;
      }

      if (!is_constant_all<T_cut>::value) {
        ops_partials.edge2_.partials_vec_[n](0) += d;
      }

    } else if (y_vec[n] == K) {
      logp -= log1p_exp(c_dbl[K - 2] - lam_dbl);
      T_partials_return d = inv_logit(c_dbl[K - 2] - lam_dbl);

      if (!is_constant_all<T_loc>::value) {
        ops_partials.edge1_.partials_[n] = d;
      }

      if (!is_constant_all<T_cut>::value) {
        ops_partials.edge2_.partials_vec_[n](K - 2) -= d;
      }

    } else {
      T_partials_return d1
          = inv(1 - exp(c_dbl[y_vec[n] - 1] - c_dbl[y_vec[n] - 2]))
            - inv_logit(c_dbl[y_vec[n] - 2] - lam_dbl);
      T_partials_return d2
          = inv(1 - exp(c_dbl[y_vec[n] - 2] - c_dbl[y_vec[n] - 1]))
            - inv_logit(c_dbl[y_vec[n] - 1] - lam_dbl);
      logp += log_inv_logit_diff(lam_dbl - c_dbl[y_vec[n] - 2],
                                 lam_dbl - c_dbl[y_vec[n] - 1]);

      if (!is_constant_all<T_loc>::value) {
        ops_partials.edge1_.partials_[n] -= d1 + d2;
      }

      if (!is_constant_all<T_cut>::value) {
        ops_partials.edge2_.partials_vec_[n](y_vec[n] - 2) += d1;
        ops_partials.edge2_.partials_vec_[n](y_vec[n] - 1) += d2;
      }
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_logistic_lpmf(const T_y& y,
                                                  const T_loc& lambda,
                                                  const T_cut& c) {
  return ordered_logistic_lpmf<false>(y, lambda, c);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

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;

vector<int> V[100010];
bool visited[100010];
int parents[100010];

typedef tuple<int, int, int> state; // now, d, from

int main () {
  int N;
  cin >> N;
  for (auto i = 0; i < N-1; ++i) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    V[a].push_back(b);
    V[b].push_back(a);
  }
  stack<state> S;
  S.push(state(0, 0, -1));
  int cut;
  int D;
  fill(visited, visited+N, false);
  while (!S.empty()) {
    int now = get<0>(S.top());
    int d = get<1>(S.top());
    int from = get<2>(S.top());
    S.pop();
    if (!visited[now]) {
      // cerr << "now = " << now << ", d = " << d << endl;
      visited[now] = true;
      parents[now] = from;
      if (now == N-1) {
        D = d;
        break;
      }
      for (auto x : V[now]) {
        if (!visited[x]) {
          S.push(state(x, d+1, now));
        }
      }
    }
  }
  stack<state> SS;
  SS.push(state(N-1, 0, parents[N-1]));
  int cnt = 0;
  cut = N-1;
  for (auto i = 0; i < (D-1)/2; ++i) {
    cut = parents[cut];
  }
  fill(visited, visited+N, false);
  while (!SS.empty()) {
    int now = get<0>(SS.top());
    int d = get<1>(SS.top());
    SS.pop();
    if (!visited[now]) {
      visited[now] = true;
      cnt++;
      for (auto x : V[now]) {
        if (!visited[x] && x != parents[cut]) {
          SS.push(state(x, d+1, now));
        }
      }
    }
  }
  int su = (D-1)/2 + cnt - 1;
  int fa = N - 2 - su;
  // cerr << "D = " << D << endl;
  // cerr << "cnt = " << cnt << endl;
  // cerr << "su = " << su << ", fa = " << fa << endl;
  if (fa > su) {
    cout << "Fennec" << endl;
  } else {
    cout << "Snuke" << endl;
  }
}
<commit_msg>submit D.cpp to 'D - Fennec VS. Snuke' (arc078) [C++14 (GCC 5.4.1)]<commit_after>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

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;

vector<int> V[100010];
bool visited[100010];
int parents[100010];

typedef tuple<int, int, int> state; // now, d, from

int main () {
  int N;
  cin >> N;
  for (auto i = 0; i < N-1; ++i) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    V[a].push_back(b);
    V[b].push_back(a);
  }
  stack<state> S;
  S.push(state(0, 0, -1));
  int cut;
  int D;
  fill(visited, visited+N, false);
  while (!S.empty()) {
    int now = get<0>(S.top());
    int d = get<1>(S.top());
    int from = get<2>(S.top());
    S.pop();
    if (!visited[now]) {
      // cerr << "now = " << now << ", d = " << d << endl;
      visited[now] = true;
      parents[now] = from;
      if (now == N-1) {
        D = d;
        break;
      }
      for (auto x : V[now]) {
        if (!visited[x]) {
          S.push(state(x, d+1, now));
        }
      }
    }
  }
  stack<state> SS;
  SS.push(state(N-1, 0, parents[N-1]));
  int cnt = 0;
  cut = N-1;
  for (auto i = 0; i < (D-1)/2; ++i) {
    cut = parents[cut];
  }
  fill(visited, visited+N, false);
  while (!SS.empty()) {
    int now = get<0>(SS.top());
    int d = get<1>(SS.top());
    SS.pop();
    if (!visited[now]) {
      visited[now] = true;
      cnt++;
      for (auto x : V[now]) {
        if (!visited[x] && x != parents[cut]) {
          SS.push(state(x, d+1, now));
        }
      }
    }
  }
  int su = cnt - 1;
  int fa = N - 2 - su;
  cerr << "D = " << D << endl;
  cerr << "cut = " << cut << endl;
  cerr << "cnt = " << cnt << endl;
  cerr << "su = " << su << ", fa = " << fa << endl;
  if (fa > su) {
    cout << "Fennec" << endl;
  } else {
    cout << "Snuke" << endl;
  }
}
<|endoftext|>


<commit_before>#include "MaterialTensorOnLine.h"
#include "SymmTensor.h"
#include "FEProblem.h"
#include <cmath>
#include <algorithm>
#include <set>

template<>
InputParameters validParams<MaterialTensorOnLine>()
{
  InputParameters params = validParams<ElementUserObject>();

  addMaterialTensorParams(params);

  params.addCoupledVar("element_line_id","Element line ID: if not zero, output stress at integration points");
  params.addRequiredParam<std::string>("filename","Output file name");
  params.addParam<int>("line_id",1,"ID of the line of elements to output stresses on");
  params.set<MooseEnum>("execute_on") = "timestep";

  return params;
}

MaterialTensorOnLine :: MaterialTensorOnLine(const std::string & name, InputParameters parameters) :
  ElementUserObject(name, parameters),

  _tensor( getMaterialProperty<SymmTensor>( getParam<std::string>("tensor") ) ),
  _index( getParam<int>("index") ),
  _quantity_moose_enum( getParam<MooseEnum>("quantity") ),
  _p1( getParam<RealVectorValue>("point1") ),
  _p2( getParam<RealVectorValue>("point2") ),
  _line_id( getParam<int>("line_id") ),
  _file_name( getParam<std::string>("filename") ),

  _stream_open(false),

  _elem_line_id(coupledValue("element_line_id"))

{

  MaterialTensorAux::checkMaterialTensorParams(_quantity,_quantity_moose_enum,_index,_name);

  if (!_stream_open && libMesh::processor_id() == 0)
  {
    _output_file.open(_file_name.c_str(), std::ios::trunc | std::ios::out);
    _stream_open = true;
  }

}

MaterialTensorOnLine::~MaterialTensorOnLine()
{
  if (_stream_open && libMesh::processor_id() == 0)
  {
    _output_file.close();
    _stream_open = false;
  }
}

void
MaterialTensorOnLine::initialize()
{
  _dist.clear();
  _value.clear();
}

void
MaterialTensorOnLine::execute()
{
  unsigned int qp(0); // all integration points have the same _elem_line_id, just use qp=0
  unsigned int id = _elem_line_id[qp] + .5;

  if (id == _line_id)
  {

    const Point line_vec(_p2-_p1);
    const Real length(line_vec.size());
    const Point line_unit_vec(line_vec/length);

    for ( qp = 0; qp < _qrule->n_points(); ++qp )
    {
      const Point qp_pos(_q_point[qp]);

      const Point line1_qp_vec(qp_pos-_p1);
      const Real proj(line1_qp_vec*line_unit_vec);
      const Point proj_vec(proj*line_unit_vec);

      const Point dist_vec(line1_qp_vec-proj_vec);
      const Real distance(dist_vec.size());

      const SymmTensor & tensor( _tensor[qp] );

//      _dist[_current_elem->id()] = distance;
//      _value[_current_elem->id()] = tensor.component(_index);
      _dist[std::make_pair(_current_elem->id(),qp)] = distance;
//      _value[std::make_pair(_current_elem->id(),qp)] = tensor.component(_index);
      _value[std::make_pair(_current_elem->id(),qp)] = MaterialTensorAux::getTensorQuantity(tensor,_quantity,_quantity_moose_enum,_index,&_q_point[qp],&_p1,&_p2);

    }
  }

}

void
MaterialTensorOnLine::threadJoin(const UserObject & u )
{
  const MaterialTensorOnLine & sp = dynamic_cast<const MaterialTensorOnLine &>(u);

  for ( std::map<std::pair<unsigned int, unsigned int>,Real>::const_iterator it = sp._dist.begin();
        it != sp._dist.end();
        ++it )
    _dist[it->first] = it->second;

  for ( std::map<std::pair<unsigned int, unsigned int>,Real>::const_iterator it = sp._value.begin();
        it != sp._value.end();
        ++it )
    _value[it->first] = it->second;
}

void
MaterialTensorOnLine::finalize()
{

    Parallel::set_union(_dist);
    Parallel::set_union(_value);

   if (libMesh::processor_id() == 0)
   {
     std::vector<std::pair<Real, Real> > table;
//     std::map<unsigned int, Real>::iterator id(_dist.begin());
//     std::map<unsigned int, Real>::iterator is(_value.begin());
     std::map<std::pair<unsigned int, unsigned int>, Real>::iterator id(_dist.begin());
     std::map<std::pair<unsigned int, unsigned int>, Real>::iterator is(_value.begin());

     while (id != _dist.end() && is != _value.end())
     {
       table.push_back(std::make_pair(id->second,is->second));
       id++;
       is++;
     }

     std::sort(table.begin(),table.end());

     _output_file << "time " << _fe_problem.time() << std::endl;
     for (std::vector<std::pair<Real, Real> >::iterator it = table.begin();
          it != table.end();
          ++it)
     {
       _output_file << it->first << "  " << it->second << std::endl;
     }
   }

}

<commit_msg>Fixing signed vs. unsigned integer comparison in ELK.<commit_after>#include "MaterialTensorOnLine.h"
#include "SymmTensor.h"
#include "FEProblem.h"
#include <cmath>
#include <algorithm>
#include <set>

template<>
InputParameters validParams<MaterialTensorOnLine>()
{
  InputParameters params = validParams<ElementUserObject>();

  addMaterialTensorParams(params);

  params.addCoupledVar("element_line_id","Element line ID: if not zero, output stress at integration points");
  params.addRequiredParam<std::string>("filename","Output file name");
  params.addParam<int>("line_id",1,"ID of the line of elements to output stresses on");
  params.set<MooseEnum>("execute_on") = "timestep";

  return params;
}

MaterialTensorOnLine :: MaterialTensorOnLine(const std::string & name, InputParameters parameters) :
  ElementUserObject(name, parameters),

  _tensor( getMaterialProperty<SymmTensor>( getParam<std::string>("tensor") ) ),
  _index( getParam<int>("index") ),
  _quantity_moose_enum( getParam<MooseEnum>("quantity") ),
  _p1( getParam<RealVectorValue>("point1") ),
  _p2( getParam<RealVectorValue>("point2") ),
  _line_id( getParam<int>("line_id") ),
  _file_name( getParam<std::string>("filename") ),

  _stream_open(false),

  _elem_line_id(coupledValue("element_line_id"))

{

  MaterialTensorAux::checkMaterialTensorParams(_quantity,_quantity_moose_enum,_index,_name);

  if (!_stream_open && libMesh::processor_id() == 0)
  {
    _output_file.open(_file_name.c_str(), std::ios::trunc | std::ios::out);
    _stream_open = true;
  }

}

MaterialTensorOnLine::~MaterialTensorOnLine()
{
  if (_stream_open && libMesh::processor_id() == 0)
  {
    _output_file.close();
    _stream_open = false;
  }
}

void
MaterialTensorOnLine::initialize()
{
  _dist.clear();
  _value.clear();
}

void
MaterialTensorOnLine::execute()
{
  unsigned int qp(0); // all integration points have the same _elem_line_id, just use qp=0
  int id = _elem_line_id[qp] + .5;

  if (id == _line_id)
  {

    const Point line_vec(_p2-_p1);
    const Real length(line_vec.size());
    const Point line_unit_vec(line_vec/length);

    for ( qp = 0; qp < _qrule->n_points(); ++qp )
    {
      const Point qp_pos(_q_point[qp]);

      const Point line1_qp_vec(qp_pos-_p1);
      const Real proj(line1_qp_vec*line_unit_vec);
      const Point proj_vec(proj*line_unit_vec);

      const Point dist_vec(line1_qp_vec-proj_vec);
      const Real distance(dist_vec.size());

      const SymmTensor & tensor( _tensor[qp] );

//      _dist[_current_elem->id()] = distance;
//      _value[_current_elem->id()] = tensor.component(_index);
      _dist[std::make_pair(_current_elem->id(),qp)] = distance;
//      _value[std::make_pair(_current_elem->id(),qp)] = tensor.component(_index);
      _value[std::make_pair(_current_elem->id(),qp)] = MaterialTensorAux::getTensorQuantity(tensor,_quantity,_quantity_moose_enum,_index,&_q_point[qp],&_p1,&_p2);

    }
  }

}

void
MaterialTensorOnLine::threadJoin(const UserObject & u )
{
  const MaterialTensorOnLine & sp = dynamic_cast<const MaterialTensorOnLine &>(u);

  for ( std::map<std::pair<unsigned int, unsigned int>,Real>::const_iterator it = sp._dist.begin();
        it != sp._dist.end();
        ++it )
    _dist[it->first] = it->second;

  for ( std::map<std::pair<unsigned int, unsigned int>,Real>::const_iterator it = sp._value.begin();
        it != sp._value.end();
        ++it )
    _value[it->first] = it->second;
}

void
MaterialTensorOnLine::finalize()
{

    Parallel::set_union(_dist);
    Parallel::set_union(_value);

   if (libMesh::processor_id() == 0)
   {
     std::vector<std::pair<Real, Real> > table;
//     std::map<unsigned int, Real>::iterator id(_dist.begin());
//     std::map<unsigned int, Real>::iterator is(_value.begin());
     std::map<std::pair<unsigned int, unsigned int>, Real>::iterator id(_dist.begin());
     std::map<std::pair<unsigned int, unsigned int>, Real>::iterator is(_value.begin());

     while (id != _dist.end() && is != _value.end())
     {
       table.push_back(std::make_pair(id->second,is->second));
       id++;
       is++;
     }

     std::sort(table.begin(),table.end());

     _output_file << "time " << _fe_problem.time() << std::endl;
     for (std::vector<std::pair<Real, Real> >::iterator it = table.begin();
          it != table.end();
          ++it)
     {
       _output_file << it->first << "  " << it->second << std::endl;
     }
   }

}

<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TFile.h>
#include <TH1F.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <TStyle.h>
#include <TGrid.h>
#include <TCanvas.h>
#include <TSystem.h>
#include <TLatex.h>
#include <TLegend.h>
#include <TLegendEntry.h>
#include <TObjArray.h>
#include "AliCDBEntry.h"
#include "AliITSCalibrationSDD.h"
#endif

/*  $Id: PlotCalibSDDVsTime.C 41568 2010-06-03 09:08:39Z prino $    */

// Macro to plot the calibration parameters from the OCDB files
// created from PEDESTAL and PULSER runs vs. Time
// Origin: F. Prino (prino@to.infn.it)

void PlotCalibSDDVsTime(Int_t year=2011, Int_t firstRun=142600,
			Int_t lastRun=999999999){

  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetPadLeftMargin(0.14);
  gStyle->SetTitleOffset(1.4,"Y");

  TGrid::Connect("alien:",0,0,"t");
  gSystem->Exec(Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/CalibSDD\" \"Run*.root\" > runCalibAlien.txt",year));
  FILE* listruns=fopen("runCalibAlien.txt","r");

  TH1F* hbase=new TH1F("hbase","",60,0.5,120.5);
  TH1F* hnoise=new TH1F("hnoise","",100,0.,7.);
  TH1F* hgain=new TH1F("hgain","",100,0.,4.);
  TH1F* hchstatus=new TH1F("hchstatus","",2,-0.5,1.5);
  TH1F* hchstatus3=new TH1F("hchstatus3","",2,-0.5,1.5);
  TH1F* hchstatus4=new TH1F("hchstatus4","",2,-0.5,1.5);
  TGraphErrors* gbasevstim=new TGraphErrors(0);
  TGraphErrors* gnoisevstim=new TGraphErrors(0);
  TGraphErrors* ggainvstim=new TGraphErrors(0);
  TGraphErrors* gstatvstim=new TGraphErrors(0);
  TGraphErrors* gfracvstim=new TGraphErrors(0);
  TGraphErrors* gfrac3vstim=new TGraphErrors(0);
  TGraphErrors* gfrac4vstim=new TGraphErrors(0);
  gbasevstim->SetName("gbasevstim");
  gnoisevstim->SetName("gnoisevstim");
  ggainvstim->SetName("ggainvstim");
  gstatvstim->SetName("gstatvstim");
  gfracvstim->SetName("gfracvstim");
  gfrac3vstim->SetName("gfrac3vstim");
  gfrac4vstim->SetName("gfrac4vstim");
  gbasevstim->SetTitle("Baseline vs. run");
  gnoisevstim->SetTitle("Noise vs. run");
  ggainvstim->SetTitle("Gain vs. run");
  gstatvstim->SetTitle("Good Anodes vs. run");
  gfracvstim->SetTitle("Fraction of Good Anodes vs. run");
  gfrac3vstim->SetTitle("Fraction of Good Anodes vs. run");
  gfrac4vstim->SetTitle("Fraction of Good Anodes vs. run");

  Char_t filnam[200],filnamalien[200];
  Int_t iPoint=0;
  Int_t nrun,nrun2,nv,ns;

  while(!feof(listruns)){
    hbase->Reset();
    hnoise->Reset();
    hgain->Reset();
    hchstatus->Reset();
    hchstatus3->Reset();
    hchstatus4->Reset();
    fscanf(listruns,"%s\n",filnam);
    Char_t directory[100];
    sprintf(directory,"/alice/data/%d",year);
    if(!strstr(filnam,directory)) continue;
    sscanf(filnam,"/alice/data/%d/OCDB/ITS/Calib/CalibSDD/Run%d_%d_v%d_s%d.root",&year,&nrun,&nrun2,&nv,&ns);
    if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; // protection for files with swapped ladders 4-5 of layer 3
    if(year==2009 && (nrun>100000 && nv< 184)) continue; // protection for files with swapped ladder 0-1 of layer 4
    if(year==2010 && (nrun>=114603 && nv< 98)) continue; // protection for files without treatment of masked hybrids
    if(nrun<firstRun) continue;
    if(nrun>lastRun) continue;
    sprintf(filnamalien,"alien://%s",filnam);
    printf("Open file: %s\n",filnam);
    TFile *f= TFile::Open(filnamalien);
    AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry");
    TObjArray *calSDD = (TObjArray *)ent->GetObject();
    printf("Run %d Entries in array=%d \n",nrun,calSDD->GetEntriesFast());

    AliITSCalibrationSDD *cal;
    for(Int_t iMod=0; iMod<260;iMod++){
      cal=(AliITSCalibrationSDD*)calSDD->At(iMod);
      if(cal==0) continue;
      for(Int_t iAn=0; iAn<512; iAn++){
	Int_t ic=cal->GetChip(iAn);
	Float_t base=cal->GetBaseline(iAn);
	Float_t noise=cal->GetNoiseAfterElectronics(iAn);
	Float_t gain=cal->GetChannelGain(iAn);
	if(cal->IsBadChannel(iAn)){
	  hchstatus->Fill(0);
	  if(iMod<84) hchstatus3->Fill(0);
	  else hchstatus4->Fill(0);
	}
	if(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){
	  hbase->Fill(base);
	  hchstatus->Fill(1);
	  if(iMod<84) hchstatus3->Fill(1);
	  else hchstatus4->Fill(1);
	  hnoise->Fill(noise);
	  hgain->Fill(gain);
	}
      }
    }
    printf("Run %d <Base> = %f <Noise> =%f Entries = %d\n",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries());
    if((Int_t)hbase->GetEntries()==0) continue;
    gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean());
    gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS());
    gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean());
    gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS());
    ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean());
    ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS());
    gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2));
    gfracvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)/260./512.);
    gfrac3vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus3->GetBinContent(2)/84./512.);
    gfrac4vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus4->GetBinContent(2)/176./512.);
    iPoint++;
    f->Close();
  }

  TFile *ofil=new TFile(Form("Calib%dVsTime.root",year),"recreate");
  gbasevstim->Write();
  gnoisevstim->Write();
  ggainvstim->Write();
  gstatvstim->Write();
  ofil->Close();

  TCanvas* cbase=new TCanvas("cbase","Baselines");
  gbasevstim->SetFillColor(kOrange-2);
  gbasevstim->SetMarkerStyle(20);
  gbasevstim->Draw("AP3");
  gbasevstim->Draw("PLXSAME");
  gbasevstim->SetMinimum(0.);
  gbasevstim->SetMaximum(70.);
  gbasevstim->GetXaxis()->SetTitle("Run number");
  gbasevstim->GetYaxis()->SetTitle("<Baseline> (ADC counts)");
  cbase->SaveAs(Form("BaseRun%d.gif",year));

  TCanvas* cnoise=new TCanvas("cnoise","Noise");
  gnoisevstim->SetFillColor(kOrange-2);
  gnoisevstim->SetMarkerStyle(20);
  gnoisevstim->Draw("AP3");
  gnoisevstim->Draw("PLXSAME");
  gnoisevstim->SetMinimum(0.);
  gnoisevstim->SetMaximum(4.);
  gnoisevstim->GetXaxis()->SetTitle("Run number");
  gnoisevstim->GetYaxis()->SetTitle("<Noise> (ADC counts)");
  cnoise->SaveAs(Form("NoiseRun%d.gif",year));

  TCanvas* cgain=new TCanvas("cgain","Gain");
  ggainvstim->SetFillColor(kOrange-2);
  ggainvstim->SetMarkerStyle(20);
  ggainvstim->Draw("AP3");
  ggainvstim->Draw("PLXSAME");
  ggainvstim->SetMinimum(0.);
  ggainvstim->SetMaximum(4.);
  ggainvstim->GetXaxis()->SetTitle("Run number");
  ggainvstim->GetYaxis()->SetTitle("<Gain> (ADC/DAC)");
  cgain->SaveAs(Form("GainRun%d.gif",year));

  TCanvas* cstatus=new TCanvas("cstatus","Good channels");
  gstatvstim->SetFillColor(kOrange-2);
  gstatvstim->SetMarkerStyle(20);
  gstatvstim->Draw("AP3");
  gstatvstim->Draw("PLXSAME");
  gstatvstim->SetMinimum(100000.);
  gstatvstim->SetMaximum(133000.);
  gstatvstim->GetXaxis()->SetTitle("Run number");
  gstatvstim->GetYaxis()->SetTitle("Number of good anodes in acquisition");
  cstatus->SaveAs(Form("GoodAnodesRun%d.gif",year));

  TCanvas* cfrac=new TCanvas("cfrac","Fraction of Good");
  gfracvstim->SetMarkerStyle(20);
  gfrac3vstim->SetMarkerStyle(22);
  gfrac3vstim->SetMarkerColor(2);
  gfrac3vstim->SetLineColor(2);
  gfrac4vstim->SetMarkerStyle(23);
  gfrac4vstim->SetMarkerColor(4);
  gfrac4vstim->SetLineColor(4);
  gfracvstim->Draw("APL");
  gfrac3vstim->Draw("PLSAME");
  gfrac4vstim->Draw("PLSAME");
  gfracvstim->SetMinimum(0.7);
  gfracvstim->SetMaximum(1.05);
  gfracvstim->GetXaxis()->SetTitle("Run number");
  gfracvstim->GetYaxis()->SetTitle("Fraction of good anodes in acquisition");
  TLegend* leg=new TLegend(0.2,0.15,0.45,0.35);
  leg->SetFillColor(0);
  TLegendEntry* entr=leg->AddEntry(gfrac3vstim,"Layer 3","P");
  entr->SetTextColor(2);
  entr=leg->AddEntry(gfrac4vstim,"Layer 4","P");
  entr->SetTextColor(4);
  entr=leg->AddEntry(gfracvstim,"All","P");
  entr->SetTextColor(1);
  leg->Draw();
  cfrac->SaveAs(Form("FractionGoodRun%d.gif",year));

}
<commit_msg>Added possibility to show the trend of calibrations of single SDD modules<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TFile.h>
#include <TH1F.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <TStyle.h>
#include <TGrid.h>
#include <TCanvas.h>
#include <TSystem.h>
#include <TLatex.h>
#include <TLegend.h>
#include <TLegendEntry.h>
#include <TObjArray.h>
#include "AliCDBEntry.h"
#include "AliITSCalibrationSDD.h"
#endif

/*  $Id: PlotCalibSDDVsTime.C 41568 2010-06-03 09:08:39Z prino $    */

// Macro to plot the calibration parameters from the OCDB files
// created from PEDESTAL and PULSER runs vs. Time
// Origin: F. Prino (prino@to.infn.it)

void PlotCalibSDDVsTime(Int_t year=2011, Int_t firstRun=142600,
			Int_t lastRun=999999999,
			Int_t selectedMod=-1){

  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetPadLeftMargin(0.14);
  gStyle->SetTitleOffset(1.4,"Y");

  TGrid::Connect("alien:",0,0,"t");
  gSystem->Exec(Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/CalibSDD\" \"Run*.root\" > runCalibAlien.txt",year));
  FILE* listruns=fopen("runCalibAlien.txt","r");

  TH1F* hbase=new TH1F("hbase","",60,0.5,120.5);
  TH1F* hnoise=new TH1F("hnoise","",100,0.,7.);
  TH1F* hgain=new TH1F("hgain","",100,0.,4.);
  TH1F* hchstatus=new TH1F("hchstatus","",2,-0.5,1.5);
  TH1F* hchstatus3=new TH1F("hchstatus3","",2,-0.5,1.5);
  TH1F* hchstatus4=new TH1F("hchstatus4","",2,-0.5,1.5);
  TGraphErrors* gbasevstim=new TGraphErrors(0);
  TGraphErrors* gnoisevstim=new TGraphErrors(0);
  TGraphErrors* ggainvstim=new TGraphErrors(0);
  TGraphErrors* gstatvstim=new TGraphErrors(0);
  TGraphErrors* gfracvstim=new TGraphErrors(0);
  TGraphErrors* gfrac3vstim=new TGraphErrors(0);
  TGraphErrors* gfrac4vstim=new TGraphErrors(0);
  gbasevstim->SetName("gbasevstim");
  gnoisevstim->SetName("gnoisevstim");
  ggainvstim->SetName("ggainvstim");
  gstatvstim->SetName("gstatvstim");
  gfracvstim->SetName("gfracvstim");
  gfrac3vstim->SetName("gfrac3vstim");
  gfrac4vstim->SetName("gfrac4vstim");
  gbasevstim->SetTitle("Baseline vs. run");
  gnoisevstim->SetTitle("Noise vs. run");
  ggainvstim->SetTitle("Gain vs. run");
  gstatvstim->SetTitle("Good Anodes vs. run");
  gfracvstim->SetTitle("Fraction of Good Anodes vs. run");
  gfrac3vstim->SetTitle("Fraction of Good Anodes vs. run");
  gfrac4vstim->SetTitle("Fraction of Good Anodes vs. run");

  Char_t filnam[200],filnamalien[200];
  Int_t iPoint=0;
  Int_t nrun,nrun2,nv,ns;

  while(!feof(listruns)){
    hbase->Reset();
    hnoise->Reset();
    hgain->Reset();
    hchstatus->Reset();
    hchstatus3->Reset();
    hchstatus4->Reset();
    fscanf(listruns,"%s\n",filnam);
    Char_t directory[100];
    sprintf(directory,"/alice/data/%d",year);
    if(!strstr(filnam,directory)) continue;
    sscanf(filnam,"/alice/data/%d/OCDB/ITS/Calib/CalibSDD/Run%d_%d_v%d_s%d.root",&year,&nrun,&nrun2,&nv,&ns);
    if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; // protection for files with swapped ladders 4-5 of layer 3
    if(year==2009 && (nrun>100000 && nv< 184)) continue; // protection for files with swapped ladder 0-1 of layer 4
    if(year==2010 && (nrun>=114603 && nv< 98)) continue; // protection for files without treatment of masked hybrids
    if(nrun<firstRun) continue;
    if(nrun>lastRun) continue;
    sprintf(filnamalien,"alien://%s",filnam);
    printf("Open file: %s\n",filnam);
    TFile *f= TFile::Open(filnamalien);
    AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry");
    TObjArray *calSDD = (TObjArray *)ent->GetObject();
    printf("Run %d Entries in array=%d \n",nrun,calSDD->GetEntriesFast());

    AliITSCalibrationSDD *cal;
    for(Int_t iMod=0; iMod<260;iMod++){
      if(selectedMod>=240 && (iMod+240)!=selectedMod) continue;
      cal=(AliITSCalibrationSDD*)calSDD->At(iMod);
      if(cal==0) continue;
      for(Int_t iAn=0; iAn<512; iAn++){
	Int_t ic=cal->GetChip(iAn);
	Float_t base=cal->GetBaseline(iAn);
	Float_t noise=cal->GetNoiseAfterElectronics(iAn);
	Float_t gain=cal->GetChannelGain(iAn);
	if(cal->IsBadChannel(iAn)){
	  hchstatus->Fill(0);
	  if(iMod<84) hchstatus3->Fill(0);
	  else hchstatus4->Fill(0);
	}
	if(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){
	  hbase->Fill(base);
	  hchstatus->Fill(1);
	  if(iMod<84) hchstatus3->Fill(1);
	  else hchstatus4->Fill(1);
	  hnoise->Fill(noise);
	  hgain->Fill(gain);
	}
      }
    }
    printf("Run %d <Base> = %f <Noise> =%f Entries = %d\n",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries());
    if(selectedMod==-1 && (Int_t)hbase->GetEntries()==0) continue;
    gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean());
    gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS());
    gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean());
    gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS());
    ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean());
    ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS());
    gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2));
    Float_t normMod=260.;
    if(selectedMod!=-1) normMod=1.;
    gfracvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)/normMod/512.);
    gfrac3vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus3->GetBinContent(2)/84./512.);
    gfrac4vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus4->GetBinContent(2)/176./512.);
    iPoint++;
    f->Close();
  }

  TFile *ofil=new TFile(Form("Calib%dVsTime.root",year),"recreate");
  gbasevstim->Write();
  gnoisevstim->Write();
  ggainvstim->Write();
  gstatvstim->Write();
  ofil->Close();

  TCanvas* cbase=new TCanvas("cbase","Baselines");
  gbasevstim->SetFillColor(kOrange-2);
  gbasevstim->SetMarkerStyle(20);
  gbasevstim->Draw("AP3");
  gbasevstim->Draw("PLXSAME");
  gbasevstim->SetMinimum(0.);
  gbasevstim->SetMaximum(70.);
  gbasevstim->GetXaxis()->SetTitle("Run number");
  gbasevstim->GetYaxis()->SetTitle("<Baseline> (ADC counts)");
  cbase->SaveAs(Form("BaseRun%d.gif",year));

  TCanvas* cnoise=new TCanvas("cnoise","Noise");
  gnoisevstim->SetFillColor(kOrange-2);
  gnoisevstim->SetMarkerStyle(20);
  gnoisevstim->Draw("AP3");
  gnoisevstim->Draw("PLXSAME");
  gnoisevstim->SetMinimum(0.);
  gnoisevstim->SetMaximum(4.);
  gnoisevstim->GetXaxis()->SetTitle("Run number");
  gnoisevstim->GetYaxis()->SetTitle("<Noise> (ADC counts)");
  cnoise->SaveAs(Form("NoiseRun%d.gif",year));

  TCanvas* cgain=new TCanvas("cgain","Gain");
  ggainvstim->SetFillColor(kOrange-2);
  ggainvstim->SetMarkerStyle(20);
  ggainvstim->Draw("AP3");
  ggainvstim->Draw("PLXSAME");
  ggainvstim->SetMinimum(0.);
  ggainvstim->SetMaximum(4.);
  ggainvstim->GetXaxis()->SetTitle("Run number");
  ggainvstim->GetYaxis()->SetTitle("<Gain> (ADC/DAC)");
  cgain->SaveAs(Form("GainRun%d.gif",year));

  TCanvas* cstatus=new TCanvas("cstatus","Good channels");
  gstatvstim->SetFillColor(kOrange-2);
  gstatvstim->SetMarkerStyle(20);
  gstatvstim->Draw("AP3");
  gstatvstim->Draw("PLXSAME");
  if(selectedMod==-1){
    gstatvstim->SetMinimum(100000.);
    gstatvstim->SetMaximum(133000.);
  }else{
    gstatvstim->SetMinimum(0.);
    gstatvstim->SetMaximum(512.);
  }
  gstatvstim->GetXaxis()->SetTitle("Run number");
  if(selectedMod==-1){
    gstatvstim->GetYaxis()->SetTitle("Number of good anodes in acquisition");
  }else{
    gstatvstim->GetYaxis()->SetTitle(Form("Number of good anodes in od %d",selectedMod));
  }
  cstatus->SaveAs(Form("GoodAnodesRun%d.gif",year));

  TCanvas* cfrac=new TCanvas("cfrac","Fraction of Good");
  gfracvstim->SetMarkerStyle(20);
  gfrac3vstim->SetMarkerStyle(22);
  gfrac3vstim->SetMarkerColor(2);
  gfrac3vstim->SetLineColor(2);
  gfrac4vstim->SetMarkerStyle(23);
  gfrac4vstim->SetMarkerColor(4);
  gfrac4vstim->SetLineColor(4);
  gfracvstim->Draw("APL");
  gfracvstim->SetMinimum(0.7);
  gfracvstim->SetMaximum(1.05);
  gfracvstim->GetXaxis()->SetTitle("Run number");
  if(selectedMod==-1){
    gfracvstim->GetYaxis()->SetTitle("Fraction of good anodes in acquisition");
    gfrac3vstim->Draw("PLSAME");
    gfrac4vstim->Draw("PLSAME");

    TLegend* leg=new TLegend(0.2,0.15,0.45,0.35);
    leg->SetFillColor(0);
    TLegendEntry* entr=leg->AddEntry(gfrac3vstim,"Layer 3","P");
    entr->SetTextColor(2);
    entr=leg->AddEntry(gfrac4vstim,"Layer 4","P");
    entr->SetTextColor(4);
    entr=leg->AddEntry(gfracvstim,"All","P");
    entr->SetTextColor(1);
    leg->Draw();
  }else{
    gfracvstim->GetYaxis()->SetTitle(Form("Fraction of good anodes in mod %d",selectedMod));
  }
  cfrac->SaveAs(Form("FractionGoodRun%d.gif",year));

}
<|endoftext|>


<commit_before>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

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 main () {
  ll K;
  cin >> K;
  if (K%2 != 0) {
    cout << 2 << endl;
    cout << (K+2)/2 << " " << (K+2) - (K+2)/2 << endl;
  }
  assert(false);
}
<commit_msg>submit D.cpp to 'D - Decrease (Contestant ver.)' (arc079) [C++14 (GCC 5.4.1)]<commit_after>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

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 main () {
  ll K;
  cin >> K;
  for (auto i = 2; ; ++i) {
    if (K%i != 0) {
      cout << i << endl;
      for (auto j = 0; j < i-1; ++j) {
        cout << (K+i)/i << " ";
      }
      cout << (K+i) - (K+i)/i * (i-1) << endl;
    }
  }
  assert(false);
}
<|endoftext|>