<commit_before>/*****************************************************************************
 * gtk2_theme.cpp: GTK2 implementation of the Theme class
 *****************************************************************************
 * Copyright (C) 2003 VideoLAN
 * $Id: gtk2_theme.cpp,v 1.18 2003/04/19 11:16:17 asmax Exp $
 *
 * Authors: Cyril Deguet     <asmax@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111,
 * USA.
 *****************************************************************************/

#if !defined WIN32

//--- GTK2 -----------------------------------------------------------------
#include <gdk/gdk.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

//--- VLC -------------------------------------------------------------------
#include <vlc/intf.h>

//--- SKIN ------------------------------------------------------------------
#include "../os_api.h"
#include "../src/banks.h"
#include "../src/window.h"
#include "../os_window.h"
#include "../src/event.h"
#include "../os_event.h"
#include "../src/theme.h"
#include "../os_theme.h"
#include "../src/dialog.h"
#include "../os_dialog.h"
#include "../src/vlcproc.h"
#include "../src/skin_common.h"

//---------------------------------------------------------------------------
void SkinManage( intf_thread_t *p_intf );

//---------------------------------------------------------------------------
// THEME
//---------------------------------------------------------------------------
GTK2Theme::GTK2Theme( intf_thread_t *_p_intf ) : Theme( _p_intf )
{
/*
    // Get instance handle
    hinst = GetModuleHandle( NULL );

    // Create window class
    WNDCLASS SkinWindow;

    SkinWindow.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
    SkinWindow.lpfnWndProc = (WNDPROC) GTK2Proc;
    SkinWindow.lpszClassName = "SkinWindow";
    SkinWindow.lpszMenuName = NULL;
    SkinWindow.cbClsExtra = 0;
    SkinWindow.cbWndExtra = 0;
    SkinWindow.hbrBackground = HBRUSH (COLOR_WINDOW);
    SkinWindow.hCursor = LoadCursor( NULL , IDC_ARROW );
    SkinWindow.hIcon = LoadIcon( hinst, "VLC_ICON" );
    SkinWindow.hInstance = hinst;

    if( !RegisterClass( &SkinWindow ) )
    {
        WNDCLASS wndclass;

        // Check why it failed. If it's because the class already exists
        // then fine, otherwise return with an error.
        if( !GetClassInfo( hinst, "SkinWindow", &wndclass ) )
        {
            msg_Err( p_intf, "Cannot register window class" );
            return;
        }
    }
*/
    //Initialize value
    ParentWindow = NULL;

}

//---------------------------------------------------------------------------
GTK2Theme::~GTK2Theme()
{/*
    // Unregister the window class if needed
    WNDCLASS wndclass;
    if( GetClassInfo( hinst, "SkinWindow", &wndclass ) )
    {
        UnregisterClass( "SkinWindow", hinst );
    }
    if( GetClassInfo( hinst, "LogWindow", &wndclass ) )
    {
        UnregisterClass( "LogWindow", hinst );
    }
    if( GetClassInfo( hinst, "ParentWindow", &wndclass ) )
    {
        UnregisterClass( "ParentWindow", hinst );
    }

    // Delete tray icon if exists
    if( ShowInTray )
    {
        Shell_NotifyIcon( NIM_DELETE, &TrayIcon );
    }

    // Destroy parent window
    if( ParentWindow )
    {
        DestroyWindow( ParentWindow );
    }*/
}
//---------------------------------------------------------------------------
void GTK2Theme::OnLoadTheme()
{/*
    // Create window class
    WNDCLASS ParentClass;
    ParentClass.style = CS_VREDRAW|CS_HREDRAW|CS_DBLCLKS;
    ParentClass.lpfnWndProc = (WNDPROC) GTK2Proc;
    ParentClass.lpszClassName = "ParentWindow";
    ParentClass.lpszMenuName = NULL;
    ParentClass.cbClsExtra = 0;
    ParentClass.cbWndExtra = 0;
    ParentClass.hbrBackground = HBRUSH (COLOR_WINDOW);
    ParentClass.hCursor = LoadCursor( NULL , IDC_ARROW );
    ParentClass.hIcon = LoadIcon( hinst, "VLC_ICON" );
    ParentClass.hInstance = hinst;

    // register class and check it
    if( !RegisterClass( &ParentClass ) )
    {
        WNDCLASS wndclass;

        // Check why it failed. If it's because the class already exists
        // then fine, otherwise return with an error.
        if( !GetClassInfo( hinst, "ParentWindow", &wndclass ) )
        {
            msg_Err( p_intf, "Cannot register window class" );
            return;
        }
    }

    // Create Window
    ParentWindow = CreateWindowEx( WS_EX_LAYERED|WS_EX_TOOLWINDOW,
        "ParentWindow", "VLC Media Player",
        WS_SYSMENU,
        0, 0, 0, 0, 0, 0, hinst, NULL );

    // Store with it a pointer to the interface thread
    SetWindowLongPtr( ParentWindow, GWLP_USERDATA, (LONG_PTR)p_intf );
    ShowWindow( ParentWindow, SW_SHOW );

    // System tray icon
    TrayIcon.cbSize = sizeof( PNOTIFYICONDATA );
    TrayIcon.hWnd = ParentWindow;
    TrayIcon.uID = 42;
    TrayIcon.uFlags = NIF_ICON|NIF_TIP|NIF_MESSAGE;
    TrayIcon.uCallbackMessage = WM_RBUTTONDOWN;
    TrayIcon.hIcon = LoadIcon( hinst, "VLC_ICON" );
    strcpy( TrayIcon.szTip, "VLC Media Player" );

    // Remove default entries from system menu popup
    SysMenu = GetSystemMenu( ParentWindow, false );
    RemoveMenu( SysMenu, SC_RESTORE,  MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_MOVE,     MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_SIZE,     MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_MINIMIZE, MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_MAXIMIZE, MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_CLOSE,    MF_BYCOMMAND );
    RemoveMenu( SysMenu, 0,           MF_BYPOSITION );

    // The create menu
    CreateSystemMenu();
*/
    // Set the parent window attributes
    GdkWindowAttr attr;
    attr.title = "VLC Media Player";
    attr.event_mask = GDK_ALL_EVENTS_MASK;
    attr.x = 0;
    attr.y = 0;
    attr.width = 0;
    attr.height = 0;
    attr.window_type = GDK_WINDOW_TOPLEVEL;
    attr.wclass = GDK_INPUT_ONLY;
    attr.override_redirect = FALSE;

    gint mask = GDK_WA_TITLE|GDK_WA_X|GDK_WA_Y|GDK_WA_NOREDIR;

    // Create the parent window
    ParentWindow = gdk_window_new( NULL, &attr, mask);

//    gdk_window_show( ParentWindow );
}
//---------------------------------------------------------------------------
void GTK2Theme::AddSystemMenu( string name, Event *event )
{/*
    if( name == "SEPARATOR" )
    {
        AppendMenu( SysMenu, MF_SEPARATOR, 0, NULL );
    }
    else
    {
        AppendMenu( SysMenu, MF_STRING, (unsigned int)event,
                    (char *)name.c_str() );
    }*/
}
//---------------------------------------------------------------------------
void GTK2Theme::ChangeClientWindowName( string name )
{/*
    SetWindowText( ParentWindow, name.c_str() );*/
}
//---------------------------------------------------------------------------
void GTK2Theme::AddWindow( string name, int x, int y, bool visible,
    int fadetime, int alpha, int movealpha, bool dragdrop )
{/*
    HWND hwnd;

    hwnd = CreateWindowEx( WS_EX_LAYERED|WS_EX_TOOLWINDOW,
        "SkinWindow", name.c_str(), WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
        0, 0, ParentWindow, 0, hinst, NULL );

    if( !hwnd )
    {
        msg_Err( p_intf, "CreateWindow failed" );
        return;
    }

    SetWindowLongPtr( hwnd, GWLP_USERDATA, (LONG_PTR)p_intf );

    WindowList.push_back( (Window *)new OSWindow( p_intf, hwnd, x, y, visible,
        fadetime, alpha, movealpha, dragdrop ) ) ;*/

    GdkWindowAttr attr;
    attr.title = (gchar *)name.c_str();
    attr.event_mask = GDK_ALL_EVENTS_MASK;
    attr.width = 0;
    attr.height = 0;
    attr.window_type = GDK_WINDOW_TOPLEVEL;
    attr.wclass = GDK_INPUT_OUTPUT;
    attr.override_redirect = TRUE;

    gint mask = GDK_WA_NOREDIR;

    // Create the window
    GdkWindow *gwnd = gdk_window_new( NULL, &attr, mask );
    if( !gwnd )
    {
        msg_Err( p_intf, "CreateWindow failed" );
        return;
    }

    gdk_window_show( gwnd );

    WindowList.push_back( (Window *)new OSWindow( p_intf, gwnd, x, y, visible,
        fadetime, alpha, movealpha, dragdrop, name ) ) ;

}
//---------------------------------------------------------------------------
/*HWND GTK2Theme::GetLogHandle()
{
    if( Log != NULL )
        return ( (GTK2LogWindow *)Log )->GetWindow();
    else
        return NULL;
}*/
//---------------------------------------------------------------------------
void GTK2Theme::ChangeTray()
{/*
    if( ShowInTray )
    {
        Shell_NotifyIcon( NIM_DELETE, &TrayIcon );
        ShowInTray = false;
    }
    else
    {
        Shell_NotifyIcon( NIM_ADD, &TrayIcon );
        ShowInTray = true;
    }*/
}
//---------------------------------------------------------------------------
void GTK2Theme::ChangeTaskbar()
{/*
    if( ShowInTaskbar )
    {
        ShowWindow( ParentWindow, SW_HIDE );
        SetWindowLongPtr( ParentWindow, GWL_EXSTYLE,
                          WS_EX_LAYERED|WS_EX_TOOLWINDOW );
        ShowWindow( ParentWindow, SW_SHOW );
        ShowInTaskbar = false;
    }
    else
    {
        ShowWindow( ParentWindow, SW_HIDE );
        SetWindowLongPtr( ParentWindow, GWL_EXSTYLE,
                          WS_EX_LAYERED|WS_EX_APPWINDOW );
        ShowWindow( ParentWindow, SW_SHOW );
        ShowInTaskbar = true;
    }*/
}
//---------------------------------------------------------------------------

#endif
<commit_msg>* fixed the "always on top" bug<commit_after>/*****************************************************************************
 * gtk2_theme.cpp: GTK2 implementation of the Theme class
 *****************************************************************************
 * Copyright (C) 2003 VideoLAN
 * $Id: gtk2_theme.cpp,v 1.19 2003/04/20 16:16:34 asmax Exp $
 *
 * Authors: Cyril Deguet     <asmax@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111,
 * USA.
 *****************************************************************************/

#if !defined WIN32

//--- GTK2 -----------------------------------------------------------------
#include <gdk/gdk.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

//--- VLC -------------------------------------------------------------------
#include <vlc/intf.h>

//--- SKIN ------------------------------------------------------------------
#include "../os_api.h"
#include "../src/banks.h"
#include "../src/window.h"
#include "../os_window.h"
#include "../src/event.h"
#include "../os_event.h"
#include "../src/theme.h"
#include "../os_theme.h"
#include "../src/dialog.h"
#include "../os_dialog.h"
#include "../src/vlcproc.h"
#include "../src/skin_common.h"

//---------------------------------------------------------------------------
void SkinManage( intf_thread_t *p_intf );

//---------------------------------------------------------------------------
// THEME
//---------------------------------------------------------------------------
GTK2Theme::GTK2Theme( intf_thread_t *_p_intf ) : Theme( _p_intf )
{
/*
    // Get instance handle
    hinst = GetModuleHandle( NULL );

    // Create window class
    WNDCLASS SkinWindow;

    SkinWindow.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
    SkinWindow.lpfnWndProc = (WNDPROC) GTK2Proc;
    SkinWindow.lpszClassName = "SkinWindow";
    SkinWindow.lpszMenuName = NULL;
    SkinWindow.cbClsExtra = 0;
    SkinWindow.cbWndExtra = 0;
    SkinWindow.hbrBackground = HBRUSH (COLOR_WINDOW);
    SkinWindow.hCursor = LoadCursor( NULL , IDC_ARROW );
    SkinWindow.hIcon = LoadIcon( hinst, "VLC_ICON" );
    SkinWindow.hInstance = hinst;

    if( !RegisterClass( &SkinWindow ) )
    {
        WNDCLASS wndclass;

        // Check why it failed. If it's because the class already exists
        // then fine, otherwise return with an error.
        if( !GetClassInfo( hinst, "SkinWindow", &wndclass ) )
        {
            msg_Err( p_intf, "Cannot register window class" );
            return;
        }
    }
*/
    //Initialize value
    ParentWindow = NULL;

}

//---------------------------------------------------------------------------
GTK2Theme::~GTK2Theme()
{/*
    // Unregister the window class if needed
    WNDCLASS wndclass;
    if( GetClassInfo( hinst, "SkinWindow", &wndclass ) )
    {
        UnregisterClass( "SkinWindow", hinst );
    }
    if( GetClassInfo( hinst, "LogWindow", &wndclass ) )
    {
        UnregisterClass( "LogWindow", hinst );
    }
    if( GetClassInfo( hinst, "ParentWindow", &wndclass ) )
    {
        UnregisterClass( "ParentWindow", hinst );
    }

    // Delete tray icon if exists
    if( ShowInTray )
    {
        Shell_NotifyIcon( NIM_DELETE, &TrayIcon );
    }

    // Destroy parent window
    if( ParentWindow )
    {
        DestroyWindow( ParentWindow );
    }*/
}
//---------------------------------------------------------------------------
void GTK2Theme::OnLoadTheme()
{/*
    // Create window class
    WNDCLASS ParentClass;
    ParentClass.style = CS_VREDRAW|CS_HREDRAW|CS_DBLCLKS;
    ParentClass.lpfnWndProc = (WNDPROC) GTK2Proc;
    ParentClass.lpszClassName = "ParentWindow";
    ParentClass.lpszMenuName = NULL;
    ParentClass.cbClsExtra = 0;
    ParentClass.cbWndExtra = 0;
    ParentClass.hbrBackground = HBRUSH (COLOR_WINDOW);
    ParentClass.hCursor = LoadCursor( NULL , IDC_ARROW );
    ParentClass.hIcon = LoadIcon( hinst, "VLC_ICON" );
    ParentClass.hInstance = hinst;

    // register class and check it
    if( !RegisterClass( &ParentClass ) )
    {
        WNDCLASS wndclass;

        // Check why it failed. If it's because the class already exists
        // then fine, otherwise return with an error.
        if( !GetClassInfo( hinst, "ParentWindow", &wndclass ) )
        {
            msg_Err( p_intf, "Cannot register window class" );
            return;
        }
    }

    // Create Window
    ParentWindow = CreateWindowEx( WS_EX_LAYERED|WS_EX_TOOLWINDOW,
        "ParentWindow", "VLC Media Player",
        WS_SYSMENU,
        0, 0, 0, 0, 0, 0, hinst, NULL );

    // Store with it a pointer to the interface thread
    SetWindowLongPtr( ParentWindow, GWLP_USERDATA, (LONG_PTR)p_intf );
    ShowWindow( ParentWindow, SW_SHOW );

    // System tray icon
    TrayIcon.cbSize = sizeof( PNOTIFYICONDATA );
    TrayIcon.hWnd = ParentWindow;
    TrayIcon.uID = 42;
    TrayIcon.uFlags = NIF_ICON|NIF_TIP|NIF_MESSAGE;
    TrayIcon.uCallbackMessage = WM_RBUTTONDOWN;
    TrayIcon.hIcon = LoadIcon( hinst, "VLC_ICON" );
    strcpy( TrayIcon.szTip, "VLC Media Player" );

    // Remove default entries from system menu popup
    SysMenu = GetSystemMenu( ParentWindow, false );
    RemoveMenu( SysMenu, SC_RESTORE,  MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_MOVE,     MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_SIZE,     MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_MINIMIZE, MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_MAXIMIZE, MF_BYCOMMAND );
    RemoveMenu( SysMenu, SC_CLOSE,    MF_BYCOMMAND );
    RemoveMenu( SysMenu, 0,           MF_BYPOSITION );

    // The create menu
    CreateSystemMenu();
*/
    // Set the parent window attributes
    GdkWindowAttr attr;
    attr.title = "VLC Media Player";
    attr.event_mask = GDK_ALL_EVENTS_MASK;
    attr.x = 0;
    attr.y = 0;
    attr.width = 0;
    attr.height = 0;
    attr.window_type = GDK_WINDOW_TOPLEVEL;
    attr.wclass = GDK_INPUT_ONLY;
    attr.override_redirect = FALSE;

    gint mask = GDK_WA_TITLE|GDK_WA_X|GDK_WA_Y|GDK_WA_NOREDIR;

    // Create the parent window
    ParentWindow = gdk_window_new( NULL, &attr, mask);

//    gdk_window_show( ParentWindow );
}
//---------------------------------------------------------------------------
void GTK2Theme::AddSystemMenu( string name, Event *event )
{/*
    if( name == "SEPARATOR" )
    {
        AppendMenu( SysMenu, MF_SEPARATOR, 0, NULL );
    }
    else
    {
        AppendMenu( SysMenu, MF_STRING, (unsigned int)event,
                    (char *)name.c_str() );
    }*/
}
//---------------------------------------------------------------------------
void GTK2Theme::ChangeClientWindowName( string name )
{/*
    SetWindowText( ParentWindow, name.c_str() );*/
}
//---------------------------------------------------------------------------
void GTK2Theme::AddWindow( string name, int x, int y, bool visible,
    int fadetime, int alpha, int movealpha, bool dragdrop )
{/*
    HWND hwnd;

    hwnd = CreateWindowEx( WS_EX_LAYERED|WS_EX_TOOLWINDOW,
        "SkinWindow", name.c_str(), WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
        0, 0, ParentWindow, 0, hinst, NULL );

    if( !hwnd )
    {
        msg_Err( p_intf, "CreateWindow failed" );
        return;
    }

    SetWindowLongPtr( hwnd, GWLP_USERDATA, (LONG_PTR)p_intf );

    WindowList.push_back( (Window *)new OSWindow( p_intf, hwnd, x, y, visible,
        fadetime, alpha, movealpha, dragdrop ) ) ;*/

    GdkWindowAttr attr;
    attr.title = (gchar *)name.c_str();
    attr.event_mask = GDK_ALL_EVENTS_MASK;
    attr.width = 0;
    attr.height = 0;
    attr.window_type = GDK_WINDOW_TOPLEVEL;
    attr.wclass = GDK_INPUT_OUTPUT;
    attr.override_redirect = FALSE;

    gint mask = GDK_WA_NOREDIR;

    // Create the window
    GdkWindow *gwnd = gdk_window_new( NULL, &attr, mask );
    if( !gwnd )
    {
        msg_Err( p_intf, "CreateWindow failed" );
        return;
    }

    gdk_window_set_decorations( gwnd, (GdkWMDecoration)0 );

    gdk_window_show( gwnd );

    WindowList.push_back( (Window *)new OSWindow( p_intf, gwnd, x, y, visible,
        fadetime, alpha, movealpha, dragdrop, name ) ) ;

}
//---------------------------------------------------------------------------
/*HWND GTK2Theme::GetLogHandle()
{
    if( Log != NULL )
        return ( (GTK2LogWindow *)Log )->GetWindow();
    else
        return NULL;
}*/
//---------------------------------------------------------------------------
void GTK2Theme::ChangeTray()
{/*
    if( ShowInTray )
    {
        Shell_NotifyIcon( NIM_DELETE, &TrayIcon );
        ShowInTray = false;
    }
    else
    {
        Shell_NotifyIcon( NIM_ADD, &TrayIcon );
        ShowInTray = true;
    }*/
}
//---------------------------------------------------------------------------
void GTK2Theme::ChangeTaskbar()
{/*
    if( ShowInTaskbar )
    {
        ShowWindow( ParentWindow, SW_HIDE );
        SetWindowLongPtr( ParentWindow, GWL_EXSTYLE,
                          WS_EX_LAYERED|WS_EX_TOOLWINDOW );
        ShowWindow( ParentWindow, SW_SHOW );
        ShowInTaskbar = false;
    }
    else
    {
        ShowWindow( ParentWindow, SW_HIDE );
        SetWindowLongPtr( ParentWindow, GWL_EXSTYLE,
                          WS_EX_LAYERED|WS_EX_APPWINDOW );
        ShowWindow( ParentWindow, SW_SHOW );
        ShowInTaskbar = true;
    }*/
}
//---------------------------------------------------------------------------

#endif
<|endoftext|>


<commit_before>#include "PSFOutput.h"
#include "Molecules.h"
#include <cstdio>

using namespace mol_setup;

namespace{
    const char* remarkHeader = "!NTITLE";
    const char* remarkTag = " REMARKS ";
    const char* atomHeader = "!NATOM";
    const char* bondHeader = "!NBOND: bonds";
    const char* angleHeader = "!NTHETA: angles";
    const char* dihedralHeader = "!NPHI: dihedrals";

    const char* headerFormat = "%8d %s \n";
    //atom ID, segment name, residue ID, residue name,
    //atom name, atom type, charge, mass, and an unused 0
    //const char* atomFormat = "%8d%4s%3d%7s%4s%6s%12.6f%14.4f%12d\n";
    const char* atomFormat = "%8d %-5s%-5d%-5s%-5s%-3s%12.6f%14.4f%12d\n";

    const int bondPerLine = 4;
    const int anglePerLine = 3;
    const int dihPerLine = 2;
}

PSFOutput::PSFOutput(const Molecules& molecules, const System &sys,
		     mol_setup::MolMap& molMap,
                     const std::vector<std::string>& kindNames) :
  molecules(&molecules), molNames(kindNames),
  molLookRef(sys.molLookup)
{
    molKinds.resize(molMap.size());
    for(uint i = 0; i < kindNames.size(); ++i)
    {
        molKinds[i] = molMap[kindNames[i]];
    }
    CountMolecules();
}

void PSFOutput::CountMolecules()
{
    //count molecules of each kind
    std::vector<uint> molCounts(molKinds.size(), 0);

    for(uint i = 0; i < molecules->count; ++i)
    {
        ++molCounts[molecules->kIndex[i]];
    }
    totalAngles = 0;
    totalAtoms = 0;
    totalBonds = 0;
    totalDihs = 0;
    for(uint k = 0; k < molCounts.size(); ++k)
    {
      const MoleculeKind& molKind = molecules->GetKind(k);
      for(uint b = 0; b < BOX_TOTAL; b++)
      {
	totalAtoms += molKind.NumAtoms() * molLookRef.NumKindInBox(k, b);
	totalBonds += molKind.NumBonds() * molLookRef.NumKindInBox(k, b);
	totalAngles += molKind.NumAngles() * molLookRef.NumKindInBox(k, b);
	totalDihs += molKind.NumDihs() * molLookRef.NumKindInBox(k, b);
      }
    }
}

void PSFOutput::PrintPSF(const std::string& filename) const
{
    std::vector<std::string> remarks;
    //default file remarks
    remarks.push_back("Combined PSF produced by GOMC");
    remarks.push_back("Contains Geometry data for molecules in ALL boxes in the system");
    PrintPSF(filename, remarks);
}

void PSFOutput::PrintPSF(const std::string& filename,
			 const std::vector<std::string>& remarks) const
{
    FILE* outfile = fopen(filename.c_str(), "w");
    if (outfile == NULL)
    {
        fprintf(stderr, "Error opening PSF output file %s", filename.c_str());
        return;
    }

    fprintf(outfile, "PSF\n\n");
    PrintRemarks(outfile, remarks);
    PrintAtoms(outfile);
    PrintBonds(outfile);
    PrintAngles(outfile);
    PrintDihedrals(outfile);
    fclose(outfile);
}

void PSFOutput::PrintRemarks(FILE* outfile, const std::vector<std::string>& remarks) const
{
    fprintf(outfile, headerFormat, remarks.size(), remarkHeader);
    for(uint i = 0; i < remarks.size(); ++i)
    {
        fprintf(outfile, " REMARKS ");
        fprintf(outfile, "%s", remarks[i].c_str());
        fputc('\n', outfile);
    }
    fputc('\n', outfile);
}

void PSFOutput::PrintAtoms(FILE* outfile) const
{
    fprintf(outfile, headerFormat, totalAtoms, atomHeader);
    //silly psfs index from 1
    uint atomID = 1;
    uint molID = 1;
    for(uint mol = 0; mol < molecules->count; ++mol)
    {
        uint thisKind = molecules->kIndex[mol];
        uint nAtoms = molKinds[thisKind].atoms.size();
        for(uint at = 0; at < nAtoms; ++at)
        {
            const Atom* thisAtom = &molKinds[thisKind].atoms[at];
            //atom ID, segment name, residue ID, residue name,
            //atom name, atom type, charge, mass, and an unused 0
            fprintf(outfile, atomFormat, atomID, molNames[thisKind].c_str(), molID, molNames[thisKind].c_str(),
                thisAtom->name.c_str(), thisAtom->type.c_str(), thisAtom->charge, thisAtom->mass, 0);
            ++atomID;
        }
        ++molID;
    }
    fputc('\n', outfile);
}

void PSFOutput::PrintBonds(FILE* outfile) const
{
    fprintf(outfile, headerFormat, totalBonds, bondHeader);
    uint atomID = 1;
     uint lineEntry = 0;
     for(uint mol = 0; mol < molecules->count; ++mol)
     {
        const MolKind& thisKind = molKinds[molecules->kIndex[mol]];
         for(uint i = 0; i < thisKind.bonds.size(); ++i)
         {
             fprintf(outfile, "%8d%8d", thisKind.bonds[i].a0 + atomID,
                     thisKind.bonds[i].a1 + atomID);
             ++lineEntry;
             if(lineEntry == bondPerLine)
             {
                 lineEntry = 0;
                 fputc('\n', outfile);
             }
         }
         atomID += thisKind.atoms.size();
     }
     fputs("\n\n", outfile);
 }

 void PSFOutput::PrintAngles(FILE* outfile) const
 {
     fprintf(outfile, headerFormat, totalAngles, angleHeader);
     uint atomID = 1;
     uint lineEntry = 0;
     for(uint mol = 0; mol < molecules->count; ++mol)
     {
         const MolKind& thisKind = molKinds[molecules->kIndex[mol]];
         for(uint i = 0; i < thisKind.angles.size(); ++i)
         {
             fprintf(outfile, "%8d%8d%8d", thisKind.angles[i].a0 + atomID,
                     thisKind.angles[i].a1 + atomID,
                     thisKind.angles[i].a2 + atomID);
             ++lineEntry;
             if(lineEntry == anglePerLine)
             {
                 lineEntry = 0;
                 fputc('\n', outfile);
             }
         }
         atomID += thisKind.atoms.size();
     }
     fputs("\n\n", outfile);
 }
 void PSFOutput::PrintDihedrals(FILE* outfile) const
 {
     fprintf(outfile, headerFormat, totalDihs, dihedralHeader);
     uint atomID = 1;
     uint lineEntry = 0;
     for(uint mol = 0; mol < molecules->count; ++mol)
     {
         const MolKind& thisKind = molKinds[molecules->kIndex[mol]];
         for(uint i = 0; i < thisKind.dihedrals.size(); ++i)
         {
            fprintf(outfile, "%8d%8d%8d%8d", thisKind.dihedrals[i].a0 + atomID,
                    thisKind.dihedrals[i].a1 + atomID,
                    thisKind.dihedrals[i].a2 + atomID,
                    thisKind.dihedrals[i].a3 + atomID);
             ++lineEntry;
             if(lineEntry == dihPerLine)
             {
                 lineEntry = 0;
                 fputc('\n', outfile);
             }
         }
         atomID += thisKind.atoms.size();
     }
     fputs("\n\n", outfile);
 }

<commit_msg>Fix to the bug of printing merge PSF for binary system. Error was due to the logic of calculatinf number of atoms, bond, ...! molecules->GetKind() function works based on molecule index and the way it is been read from pdf file and not kind number.<commit_after>#include "PSFOutput.h"
#include "Molecules.h"
#include <cstdio>

using namespace mol_setup;

namespace{
    const char* remarkHeader = "!NTITLE";
    const char* remarkTag = " REMARKS ";
    const char* atomHeader = "!NATOM";
    const char* bondHeader = "!NBOND: bonds";
    const char* angleHeader = "!NTHETA: angles";
    const char* dihedralHeader = "!NPHI: dihedrals";

    const char* headerFormat = "%8d %s \n";
    //atom ID, segment name, residue ID, residue name,
    //atom name, atom type, charge, mass, and an unused 0
    //const char* atomFormat = "%8d%4s%3d%7s%4s%6s%12.6f%14.4f%12d\n";
    const char* atomFormat = "%8d %-5s%-5d%-5s%-5s%-3s%12.6f%14.4f%12d\n";

    const int bondPerLine = 4;
    const int anglePerLine = 3;
    const int dihPerLine = 2;
}

PSFOutput::PSFOutput(const Molecules& molecules, const System &sys,
		     mol_setup::MolMap& molMap,
                     const std::vector<std::string>& kindNames) :
  molecules(&molecules), molNames(kindNames),
  molLookRef(sys.molLookup)
{
    molKinds.resize(molMap.size());
    for(uint i = 0; i < kindNames.size(); ++i)
    {
        molKinds[i] = molMap[kindNames[i]];
    }
    CountMolecules();
}

void PSFOutput::CountMolecules()
{
    totalAngles = 0;
    totalAtoms = 0;
    totalBonds = 0;
    totalDihs = 0;
    uint atomT = 0;

    for(uint b = 0; b < BOX_TOTAL; b++)
    {
      for(uint k = 0; k < molKinds.size(); ++k)
      {
	const MoleculeKind& molKind = molecules->GetKind(atomT);

	totalAtoms += molKind.NumAtoms() * molLookRef.NumKindInBox(k, b);
	totalBonds += molKind.NumBonds() * molLookRef.NumKindInBox(k, b);
	totalAngles += molKind.NumAngles() * molLookRef.NumKindInBox(k, b);
	totalDihs += molKind.NumDihs() * molLookRef.NumKindInBox(k, b);

	atomT += molLookRef.NumKindInBox(k, b);
      }
    }
}

void PSFOutput::PrintPSF(const std::string& filename) const
{
    std::vector<std::string> remarks;
    //default file remarks
    remarks.push_back("Combined PSF produced by GOMC");
    remarks.push_back("Contains Geometry data for molecules in ALL boxes in the system");
    PrintPSF(filename, remarks);
}

void PSFOutput::PrintPSF(const std::string& filename,
			 const std::vector<std::string>& remarks) const
{
    FILE* outfile = fopen(filename.c_str(), "w");
    if (outfile == NULL)
    {
        fprintf(stderr, "Error opening PSF output file %s", filename.c_str());
        return;
    }

    fprintf(outfile, "PSF\n\n");
    PrintRemarks(outfile, remarks);
    PrintAtoms(outfile);
    PrintBonds(outfile);
    PrintAngles(outfile);
    PrintDihedrals(outfile);
    fclose(outfile);
}

void PSFOutput::PrintRemarks(FILE* outfile, const std::vector<std::string>& remarks) const
{
    fprintf(outfile, headerFormat, remarks.size(), remarkHeader);
    for(uint i = 0; i < remarks.size(); ++i)
    {
        fprintf(outfile, " REMARKS ");
        fprintf(outfile, "%s", remarks[i].c_str());
        fputc('\n', outfile);
    }
    fputc('\n', outfile);
}

void PSFOutput::PrintAtoms(FILE* outfile) const
{
    fprintf(outfile, headerFormat, totalAtoms, atomHeader);
    //silly psfs index from 1
    uint atomID = 1;
    uint molID = 1;
    for(uint mol = 0; mol < molecules->count; ++mol)
    {
        uint thisKind = molecules->kIndex[mol];
        uint nAtoms = molKinds[thisKind].atoms.size();
        for(uint at = 0; at < nAtoms; ++at)
        {
            const Atom* thisAtom = &molKinds[thisKind].atoms[at];
            //atom ID, segment name, residue ID, residue name,
            //atom name, atom type, charge, mass, and an unused 0
            fprintf(outfile, atomFormat, atomID, molNames[thisKind].c_str(), molID, molNames[thisKind].c_str(),
                thisAtom->name.c_str(), thisAtom->type.c_str(), thisAtom->charge, thisAtom->mass, 0);
            ++atomID;
        }
        ++molID;
    }
    fputc('\n', outfile);
}

void PSFOutput::PrintBonds(FILE* outfile) const
{
    fprintf(outfile, headerFormat, totalBonds, bondHeader);
    uint atomID = 1;
     uint lineEntry = 0;
     for(uint mol = 0; mol < molecules->count; ++mol)
     {
        const MolKind& thisKind = molKinds[molecules->kIndex[mol]];
         for(uint i = 0; i < thisKind.bonds.size(); ++i)
         {
             fprintf(outfile, "%8d%8d", thisKind.bonds[i].a0 + atomID,
                     thisKind.bonds[i].a1 + atomID);
             ++lineEntry;
             if(lineEntry == bondPerLine)
             {
                 lineEntry = 0;
                 fputc('\n', outfile);
             }
         }
         atomID += thisKind.atoms.size();
     }
     fputs("\n\n", outfile);
 }

 void PSFOutput::PrintAngles(FILE* outfile) const
 {
     fprintf(outfile, headerFormat, totalAngles, angleHeader);
     uint atomID = 1;
     uint lineEntry = 0;
     for(uint mol = 0; mol < molecules->count; ++mol)
     {
         const MolKind& thisKind = molKinds[molecules->kIndex[mol]];
         for(uint i = 0; i < thisKind.angles.size(); ++i)
         {
             fprintf(outfile, "%8d%8d%8d", thisKind.angles[i].a0 + atomID,
                     thisKind.angles[i].a1 + atomID,
                     thisKind.angles[i].a2 + atomID);
             ++lineEntry;
             if(lineEntry == anglePerLine)
             {
                 lineEntry = 0;
                 fputc('\n', outfile);
             }
         }
         atomID += thisKind.atoms.size();
     }
     fputs("\n\n", outfile);
 }
 void PSFOutput::PrintDihedrals(FILE* outfile) const
 {
     fprintf(outfile, headerFormat, totalDihs, dihedralHeader);
     uint atomID = 1;
     uint lineEntry = 0;
     for(uint mol = 0; mol < molecules->count; ++mol)
     {
         const MolKind& thisKind = molKinds[molecules->kIndex[mol]];
         for(uint i = 0; i < thisKind.dihedrals.size(); ++i)
         {
            fprintf(outfile, "%8d%8d%8d%8d", thisKind.dihedrals[i].a0 + atomID,
                    thisKind.dihedrals[i].a1 + atomID,
                    thisKind.dihedrals[i].a2 + atomID,
                    thisKind.dihedrals[i].a3 + atomID);
             ++lineEntry;
             if(lineEntry == dihPerLine)
             {
                 lineEntry = 0;
                 fputc('\n', outfile);
             }
         }
         atomID += thisKind.atoms.size();
     }
     fputs("\n\n", outfile);
 }

<|endoftext|>


<commit_before>#include <iostream>
#include "flight_manager.h"

void addFlight(FlightManager &manager){
  int    flight_id;
  char   flight_authority[1];
  double flight_fuel;

  cout << "Flight id:                               "; cin >> flight_id;
  cout << "Flight is from national authority? (y/n) "; cin >> flight_authority;
  cout << "Flight fuel quantity:                    "; cin >> flight_fuel;

  Flight flight;
  flight.id = flight_id;
  flight.national_authority = tolower(flight_authority[0]) == 'y';
  flight.fuel_quantity = flight_fuel;

  manager.addFlight(flight);

  cout << "\nSuccessfully added flight.\n";
}

void deleteFirstFlight(FlightManager &manager){
  char option;

  cout << "\nAre you sure? (y/n) ";
  cin >> option;

  if (tolower(option) != 'y'){
    cout << "\nNothing to do.";
    return;
  }

  if (!manager.deleteFirstFlight()){
    cout << "\nCannot remove first flight! :(";
  } else {
    cout << "\nSuccessfully removed first flight.";
  }
}

void deleteLastFlight(FlightManager &manager){
  char option;

  cout << "\nAre you sure? (y/n) ";
  cin >> option;

  if (tolower(option) != 'y'){
    cout << "\nNothing to do.";
    return;
  }

  if (!manager.deleteLastFlight()){
    cout << "\nCannot remove last flight! :(";
  } else {
    cout << "\nSuccessfully removed last flight.";
  }
}

void deleteFlight(FlightManager &manager){
  int flight_id;

  cout << "\nEnter flight id: "; cin >> flight_id;

  if (manager.deleteFlight(flight_id))
    cout << "\nSuccessfully deleted flight.";
  else
    cout << "\nFlight not found.";
}

void showFlights(FlightManager &manager){
  manager.showFlights();
}

void showMenu(){
  cout << "\n------------------------";
  cout << "\n1 - Add flight";
  cout << "\n2 - Show flights";
  cout << "\n3 - Delete flight";
  cout << "\n4 - Delete first flight";
  cout << "\n5 - Delete last flight";
  cout << "\n9 - Exit";
  cout << "\n-----------------------";
  cout << "\n";
  cout << "\nEnter a option:  ";
}

int main(){
  FlightManager manager;
  int option;

  do {
    showMenu();

    cin >> option; cout << "\n";

    switch (option){
      case 1:
        addFlight(manager);
        break;

      case 2:
        showFlights(manager);
        break;

      case 3:
        deleteFlight(manager);
        break;

      case 4:
        deleteFirstFlight(manager);
        break;

      case 5:
        deleteLastFlight(manager);
        break;

      case 9:
        break;

      default:
        char dummy[255];

        cin.clear();
        cin >> dummy;

        cout << "\nInvalid option, try again.\n";
    }
  } while (option != 9);

  cin.ignore();
}

<commit_msg>Finally fixed broken int read for flight ids.<commit_after>#include <iostream>
#include "flight_manager.h"

using namespace std;

void addFlight(FlightManager &manager){
  int    flight_id;
  char   flight_authority[1];
  double flight_fuel;
  Flight flight;

  cout << "Flight id:                               "; cin >> flight_id;
  flight.id = flight_id;

  cout << "Flight fuel quantity:                    "; cin >> flight_fuel;
  flight.fuel_quantity = flight_fuel;

  cout << "Flight is from national authority? (y/n) "; cin >> flight_authority;
  flight.national_authority = tolower(flight_authority[0]) == 'y';

  manager.addFlight(flight);

  cout << "\nSuccessfully added flight.\n";
}

void deleteFirstFlight(FlightManager &manager){
  if (manager.noFlights()){
    cout << "\nNo flights available.\n";
    return;
  }

  char option;

  cout << "\nAre you sure? (y/n) ";
  cin >> option;

  if (tolower(option) != 'y'){
    cout << "\nNothing to do.";
    return;
  }

  if (!manager.deleteFirstFlight()){
    cout << "\nCannot remove first flight! :(";
  } else {
    cout << "\nSuccessfully removed first flight.";
  }
}

void deleteLastFlight(FlightManager &manager){
  if (manager.noFlights()){
    cout << "\nNo flights available.\n";
    return;
  }

  char option;

  cout << "\nAre you sure? (y/n) ";
  cin >> option;

  if (tolower(option) != 'y'){
    cout << "\nNothing to do.";
    return;
  }

  if (!manager.deleteLastFlight()){
    cout << "\nCannot remove last flight! :(";
  } else {
    cout << "\nSuccessfully removed last flight.";
  }
}

void deleteFlight(FlightManager &manager){
  if (manager.noFlights()){
    cout << "\nNo flights available.\n";
    return;
  }

  int flight_id;

  cout << "\nEnter flight id: "; cin >> flight_id;

  if (manager.deleteFlight(flight_id))
    cout << "Successfully deleted flight.";
  else
    cout << "Flight not found.\n";
}

void showFlights(FlightManager &manager){
  manager.showFlights();
}

void showMenu(){
  cout << "\n------------------------";
  cout << "\n1 - Add flight";
  cout << "\n2 - Show flights";
  cout << "\n3 - Delete flight";
  cout << "\n4 - Delete first flight";
  cout << "\n5 - Delete last flight";
  cout << "\n9 - Exit";
  cout << "\n-----------------------";
  cout << "\n";
  cout << "\nEnter a option:  ";
}

int main(){
  FlightManager manager;
  int option;

  do {
    showMenu();

    cin >> option; cout << "\n";

    switch (option){
      case 1:
        addFlight(manager);
        break;

      case 2:
        showFlights(manager);
        break;

      case 3:
        deleteFlight(manager);
        break;

      case 4:
        deleteFirstFlight(manager);
        break;

      case 5:
        deleteLastFlight(manager);
        break;

      case 9:
        break;

      default:
        if (cin.fail()){
          char dummy[255];
          cin.clear();
          cin >> dummy;
        }

        cout << "\nInvalid option, try again.\n";
    }
  } while (option != 9);

  cin.ignore();
}

<|endoftext|>


<commit_before>/**
 * @file Dtw.cpp
 *
 * An implementation of the Dynamic Time Warping algorithm.
 *
 * This file is part of the Aquila DSP library.
 * Aquila is free software, licensed under the MIT/X11 License. A copy of
 * the license is provided with the library in the LICENSE file.
 *
 * @package Aquila
 * @version 3.0.0-dev
 * @author Zbigniew Siciarz
 * @date 2007-2013
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @since 0.5.7
 */

#include "Dtw.h"

namespace Aquila
{
    /**
     * Computes the distance between two sets of data.
     *
     * @param from first vector of features
     * @param to second vector of features
     * @return double DTW distance
     */
    double Dtw::getDistance(const DtwDataType& from, const DtwDataType& to)
    {
        m_fromSize = from.size();
        m_toSize = to.size();

        // fill the local distances array
        m_points.clear();
        m_points.resize(m_fromSize);
        for (std::size_t i = 0; i < m_fromSize; ++i)
        {
            m_points[i].reserve(m_toSize);
            for (std::size_t j = 0; j < m_toSize; ++j)
            {
                // use emplace_back, once all compilers support it correctly
                m_points[i].push_back(
                    DtwPoint(i, j, m_distanceFunction(from[i], to[j])
                ));
            }
        }

        // the actual pathfinding algorithm
        DtwPoint *top = 0, *center = 0, *bottom = 0, *previous = 0;
        for (std::size_t i = 1; i < m_fromSize; ++i)
        {
            for (std::size_t j = 1; j < m_toSize; ++j)
            {
                center = &m_points[i - 1][j - 1];
                if (Neighbors == m_passType)
                {
                    top = &m_points[i - 1][j];
                    bottom = &m_points[i][j - 1];
                }
                else // Diagonals
                {
                    if (i > 1 && j > 1)
                    {
                        top = &m_points[i - 2][j - 1];
                        bottom = &m_points[i - 1][j - 2];
                    }
                    else
                    {
                        top = &m_points[i - 1][j];
                        bottom = &m_points[i][j - 1];
                    }
                }

                if (top->dAccumulated < center->dAccumulated)
                    previous = top;
                else
                    previous = center;

                if (bottom->dAccumulated < previous->dAccumulated)
                    previous = bottom;

                m_points[i][j].dAccumulated = m_points[i][j].dLocal + previous->dAccumulated;
                m_points[i][j].previous = previous;
            }
        }

        return getFinalPoint().dAccumulated;
    }

    /**
     * Returns the lowest-cost path in the DTW array.
     *
     * @return path
     */
    DtwPathType Dtw::getPath() const
    {
        DtwPathType path;
        DtwPoint finalPoint = getFinalPoint();
        DtwPoint* point = &finalPoint;

        path.push_back(std::make_pair(point->x, point->y));
        while(point->previous != 0)
        {
            point = point->previous;
            path.push_back(std::make_pair(point->x, point->y));
        }

        return path;
    }
}
<commit_msg>Code style fixes in Dtw::getDistance.<commit_after>/**
 * @file Dtw.cpp
 *
 * An implementation of the Dynamic Time Warping algorithm.
 *
 * This file is part of the Aquila DSP library.
 * Aquila is free software, licensed under the MIT/X11 License. A copy of
 * the license is provided with the library in the LICENSE file.
 *
 * @package Aquila
 * @version 3.0.0-dev
 * @author Zbigniew Siciarz
 * @date 2007-2013
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @since 0.5.7
 */

#include "Dtw.h"

namespace Aquila
{
    /**
     * Computes the distance between two sets of data.
     *
     * @param from first vector of features
     * @param to second vector of features
     * @return double DTW distance
     */
    double Dtw::getDistance(const DtwDataType& from, const DtwDataType& to)
    {
        m_fromSize = from.size();
        m_toSize = to.size();

        // fill the local distances array
        m_points.clear();
        m_points.resize(m_fromSize);
        for (std::size_t i = 0; i < m_fromSize; ++i)
        {
            m_points[i].reserve(m_toSize);
            for (std::size_t j = 0; j < m_toSize; ++j)
            {
                // use emplace_back, once all compilers support it correctly
                m_points[i].push_back(
                    DtwPoint(i, j, m_distanceFunction(from[i], to[j])
                ));
            }
        }

        // the actual pathfinding algorithm
        DtwPoint *top = 0, *center = 0, *bottom = 0, *previous = 0;
        for (std::size_t i = 1; i < m_fromSize; ++i)
        {
            for (std::size_t j = 1; j < m_toSize; ++j)
            {
                center = &m_points[i - 1][j - 1];
                if (Neighbors == m_passType)
                {
                    top = &m_points[i - 1][j];
                    bottom = &m_points[i][j - 1];
                }
                else // Diagonals
                {
                    if (i > 1 && j > 1)
                    {
                        top = &m_points[i - 2][j - 1];
                        bottom = &m_points[i - 1][j - 2];
                    }
                    else
                    {
                        top = &m_points[i - 1][j];
                        bottom = &m_points[i][j - 1];
                    }
                }

                if (top->dAccumulated < center->dAccumulated)
                {
                    previous = top;
                }
                else
                {
                    previous = center;
                }

                if (bottom->dAccumulated < previous->dAccumulated)
                {
                    previous = bottom;
                }

                m_points[i][j].dAccumulated = m_points[i][j].dLocal + previous->dAccumulated;
                m_points[i][j].previous = previous;
            }
        }

        return getFinalPoint().dAccumulated;
    }

    /**
     * Returns the lowest-cost path in the DTW array.
     *
     * @return path
     */
    DtwPathType Dtw::getPath() const
    {
        DtwPathType path;
        DtwPoint finalPoint = getFinalPoint();
        DtwPoint* point = &finalPoint;

        path.push_back(std::make_pair(point->x, point->y));
        while(point->previous != 0)
        {
            point = point->previous;
            path.push_back(std::make_pair(point->x, point->y));
        }

        return path;
    }
}
<|endoftext|>


<commit_before>#include "jakmuse_common.h"

#ifndef VERSION
# error "VERSION is not defined."
#endif

#include <cstdio>
#include <cassert>
#include <cstdlib>
#include <cstring>

#include <vector>
#include <string>

size_t g_maxChannelLen = 0;
channels_t g_channels;
generators_t g_generators;

#define PRINT(WHAT, VAR) printf(#WHAT "\n"); \
for(size_t i = 0; i < JAKMUSE_NUMCHANNELS; ++i) {\
    printf("channel %ld:\n", i); \
    for(size_t j = 0; j < g_channels[i].size(); ++j) { \
        printf("%5d", g_channels[i][j].VAR); \
        if(j % 16 == 15 && j != g_channels[i].size() - 1) printf("\n"); \
    } \
    printf("\n"); \
}

int main(int argc, char* argv[])
{
    if(argc > 1 && strcmp(argv[1], "-v") == 0) {
        printf("JakMuse v%s, Copyright Vlad Mesco 2014\n", VERSION);
        printf("  available under the terms of the Simplified BSD License");
        exit(255);
    }

    extern void init_generators();
    init_generators();

    extern void parse();
    parse();

    extern void mix();
    mix();

    std::string filename("jakmuse.wav");
    if(argc > 1 && strcmp(argv[1], "-w") == 0) {
        if(argc > 2) {
            filename.assign(argv[2]);
        }

        extern bool wav_write_file(std::string const&, std::vector<short> const&, unsigned);
        extern std::vector<short> g_wav;
        auto hr = wav_write_file(filename, g_wav, JAKMUSE_SAMPLES_PER_SECOND);

        if(hr) {
            printf("Wrote %s\n", filename.c_str());
            exit(0);
        } else {
            printf("Could not write %s\n", filename.c_str());
            exit(hr);
        }
    } else {
        extern void play_music();
        play_music();
    }

    return 0;
}

<commit_msg>fix -v output (missing EOL)<commit_after>#include "jakmuse_common.h"

#ifndef VERSION
# error "VERSION is not defined."
#endif

#include <cstdio>
#include <cassert>
#include <cstdlib>
#include <cstring>

#include <vector>
#include <string>

size_t g_maxChannelLen = 0;
channels_t g_channels;
generators_t g_generators;

#define PRINT(WHAT, VAR) printf(#WHAT "\n"); \
for(size_t i = 0; i < JAKMUSE_NUMCHANNELS; ++i) {\
    printf("channel %ld:\n", i); \
    for(size_t j = 0; j < g_channels[i].size(); ++j) { \
        printf("%5d", g_channels[i][j].VAR); \
        if(j % 16 == 15 && j != g_channels[i].size() - 1) printf("\n"); \
    } \
    printf("\n"); \
}

int main(int argc, char* argv[])
{
    if(argc > 1 && strcmp(argv[1], "-v") == 0) {
        printf("JakMuse v%s, Copyright Vlad Mesco 2014\n", VERSION);
        printf("  available under the terms of the Simplified BSD License\n");
        exit(255);
    }

    extern void init_generators();
    init_generators();

    extern void parse();
    parse();

    extern void mix();
    mix();

    std::string filename("jakmuse.wav");
    if(argc > 1 && strcmp(argv[1], "-w") == 0) {
        if(argc > 2) {
            filename.assign(argv[2]);
        }

        extern bool wav_write_file(std::string const&, std::vector<short> const&, unsigned);
        extern std::vector<short> g_wav;
        auto hr = wav_write_file(filename, g_wav, JAKMUSE_SAMPLES_PER_SECOND);

        if(hr) {
            printf("Wrote %s\n", filename.c_str());
            exit(0);
        } else {
            printf("Could not write %s\n", filename.c_str());
            exit(hr);
        }
    } else {
        extern void play_music();
        play_music();
    }

    return 0;
}

<|endoftext|>


<commit_before>// Filename: config_ptloader.cxx
// Created by:  drose (26Apr01)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////

#include "config_ptloader.h"
#include "loaderFileTypePandatool.h"

#include "config_lwo.h"
#include "fltToEggConverter.h"
#include "config_flt.h"
#include "lwoToEggConverter.h"

#ifdef HAVE_DX
#include "config_xfile.h"
#include "xFileToEggConverter.h"
#endif

#ifdef HAVE_MAYA
#include "config_mayaegg.h"
#include "mayaToEggConverter.h"
#endif

#include "dconfig.h"
#include "loaderFileTypeRegistry.h"
#include "eggData.h"

ConfigureDef(config_ptloader);

ConfigureFn(config_ptloader) {
  init_libptloader();
}

////////////////////////////////////////////////////////////////////
//     Function: init_libptloader
//  Description: Initializes the library.  This must be called at
//               least once before any of the functions or classes in
//               this library can be used.  Normally it will be
//               called by the static initializers and need not be
//               called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libptloader() {
  static bool initialized = false;
  if (initialized) {
    return;
  }
  initialized = true;

  LoaderFileTypePandatool::init_type();

  LoaderFileTypeRegistry *reg = LoaderFileTypeRegistry::get_ptr();

  init_liblwo();
  FltToEggConverter *flt = new FltToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(flt));

  init_libflt();
  LwoToEggConverter *lwo = new LwoToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(lwo));

#ifdef HAVE_DX
  init_libxfile();
  XFileToEggConverter *xfile = new XFileToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(xfile));
#endif

#ifdef HAVE_MAYA
  init_libmayaegg();
  MayaToEggConverter *maya = new MayaToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(maya));
#endif
}
<commit_msg>remove xfile<commit_after>// Filename: config_ptloader.cxx
// Created by:  drose (26Apr01)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////

#include "config_ptloader.h"
#include "loaderFileTypePandatool.h"

#include "config_lwo.h"
#include "fltToEggConverter.h"
#include "config_flt.h"
#include "lwoToEggConverter.h"

/*
#ifdef HAVE_DX
#include "config_xfile.h"
#include "xFileToEggConverter.h"
#endif
*/

#ifdef HAVE_MAYA
#include "config_mayaegg.h"
#include "mayaToEggConverter.h"
#endif

#include "dconfig.h"
#include "loaderFileTypeRegistry.h"
#include "eggData.h"

ConfigureDef(config_ptloader);

ConfigureFn(config_ptloader) {
  init_libptloader();
}

////////////////////////////////////////////////////////////////////
//     Function: init_libptloader
//  Description: Initializes the library.  This must be called at
//               least once before any of the functions or classes in
//               this library can be used.  Normally it will be
//               called by the static initializers and need not be
//               called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libptloader() {
  static bool initialized = false;
  if (initialized) {
    return;
  }
  initialized = true;

  LoaderFileTypePandatool::init_type();

  LoaderFileTypeRegistry *reg = LoaderFileTypeRegistry::get_ptr();

  init_liblwo();
  FltToEggConverter *flt = new FltToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(flt));

  init_libflt();
  LwoToEggConverter *lwo = new LwoToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(lwo));

  /*
#ifdef HAVE_DX
  init_libxfile();
  XFileToEggConverter *xfile = new XFileToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(xfile));
#endif
  */

#ifdef HAVE_MAYA
  init_libmayaegg();
  MayaToEggConverter *maya = new MayaToEggConverter;
  reg->register_type(new LoaderFileTypePandatool(maya));
#endif
}
<|endoftext|>


<commit_before><commit_msg>Fix in THStack drawing option "pads" (#9438)<commit_after><|endoftext|>


<commit_before>// todo:
// ir controll
// autonomous drive

#define VERSION "mBot Hackaton"
#define DISTANCECMCRITICAL 20
#define PUBLSIHINTERVAL 1000
#define WAITINTERVAL 5000
#define MOVESPEEDMAX 230

#include <Arduino.h>

#include <Streaming.h>
#include <MeMCore.h>

MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_1, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;

int moveSpeed = 100;
int lineFollowFlag = 0;
double distanceCm = 0.0;
uint8_t readSensors = 0;
bool start = false;
bool moveBot = false;
uint8_t randNumber;

unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();
bool makeNoise = false;

void Forward() {
  moveBot = true;
  motorL.run(-moveSpeed);
  motorR.run(moveSpeed);
}

void Backward() {
  moveBot = true;
  motorL.run(moveSpeed);
  motorR.run(-moveSpeed);
}

void TurnLeft() {
  moveBot = true;
  motorL.run(-moveSpeed / 10);
  motorR.run(moveSpeed);
}

void TurnRight() {
  moveBot = true;
  motorL.run(-moveSpeed);
  motorR.run(moveSpeed / 10);
}

void Stop() {
  moveBot = false;
  motorL.run(0);
  motorR.run(0);
}

void Autonomous() {
    randomSeed(analogRead(6));
    randNumber = random(2);
    if (distanceCm > 15 || distanceCm == 0) {
      Forward();
    } else if (distanceCm > 10) {
      switch (randNumber)
      {
        case 0:
          TurnLeft();
          delay(200);
          break;
        case 1:
          TurnRight();
          delay(200);
          break;
      }
    } else {
      Backward();
      delay(400);
    }
    delay(100);
}

void bottomPressed() {
    start = !start;
    if (start) {
      rgbLed.setColor(1, 0, 10, 0);
      rgbLed.show();
    } else {
      rgbLed.setColor(1, 0, 0, 0);
      rgbLed.show();
      Stop();
    }
    delay(250);
}

void bottomCheck() {
  if (analogRead(A7) == 0) {
    bottomPressed();
  }
}

bool irControl() {
  uint32_t value;

  if (ir.decode()) {
    value = ir.value;
    switch (value >> 16 & 0xff) {
      case IR_BUTTON_LEFT:
      TurnLeft();
      break;
      case IR_BUTTON_RIGHT:
      TurnRight();
      break;
      case IR_BUTTON_DOWN:
      Backward();
      break;
      case IR_BUTTON_UP:
      Forward();
      break;
      case IR_BUTTON_SETTING:
      Stop();
      break;
      case IR_BUTTON_A:
      bottomPressed();
      break;
    }
  }
}

void noise() {
  if (!moveBot and start) {
    if (wait == false) {
      wait = true;
      waitTimer = millis();
    }
    if (wait and millis() - waitTimer > WAITINTERVAL) {
      makeNoise = true;
      //buzzer.tone(262, 100);
      rgbLed.setColor(2, 10, 0, 0);
      rgbLed.show();
    } else {
      rgbLed.setColor(2, 0, 0, 10);
      rgbLed.show();
    }
  } else {
    wait = false;
    makeNoise = false;
    buzzer.noTone();
    rgbLed.setColor(2, 0, 0, 0);
    rgbLed.show();
  }
}

void readData() {
  readSensors = lineFollower.readSensors();
  distanceCm = ultrasonicSensor.distanceCm();
}

void sendData() {
  if (millis() - publishTimer > PUBLSIHINTERVAL) {
    publishTimer = millis();
    Serial << endl << "start: " << start << endl;
    Serial << "moveBot: " << moveBot << endl;
    Serial << "tryFollowLine: " << tryFollowLine << endl;
    Serial << "makeNoise: " << makeNoise << endl;
    Serial << "readSensors: " << readSensors << endl;
    Serial << "temperature: " << temperature.temperature() << endl;
    Serial << "lightSensor: " << lightSensor.read() << endl;
    Serial << "distanceCm: " << distanceCm << endl;
  }
}

void setup() {
  Serial.begin(115200);
  Serial << endl << VERSION << endl << endl;
  pinMode(A7, INPUT);
  ir.begin();
  rgbLed.setColor(0, 0, 0, 0);
  rgbLed.show();
}

void loop() {
  bottomCheck();
  irControl();
  readData();
  sendData();
  noise();
  if (start) {
    if (distanceCm < DISTANCECMCRITICAL and distanceCm > 0) {
      Stop();
      tryFollowLine = true;
    } else {
      moveBot = true;
      if (moveSpeed > MOVESPEEDMAX) {
        moveSpeed = 230;
      }
      switch (readSensors) {
        case S1_IN_S2_IN:
          tryFollowLine = true;
          Forward();
          lineFollowFlag = 10;
          break;
        case S1_IN_S2_OUT:
          tryFollowLine = true;
          Forward();
          if (lineFollowFlag > 1) lineFollowFlag--;
          break;
        case S1_OUT_S2_IN:
          tryFollowLine = true;
          Forward();
          if (lineFollowFlag < 20) lineFollowFlag++;
          break;
        case S1_OUT_S2_OUT:
          if (tryFollowLine) {
            tryFollowLine = !tryFollowLine;
            tryFollowLineTimer = millis();
          }
          if (millis() - tryFollowLineTimer < 3000) {
            if (lineFollowFlag == 10) Backward();
            if (lineFollowFlag < 10) TurnLeft();
            if (lineFollowFlag > 10) TurnRight();
          } else {
            Stop();
//            Autonomous();
          }
          break;
      }
    }
  }
}
<commit_msg>removed return value<commit_after>// todo:
// autonomous drive

#define VERSION "mBot Hackaton"
#define DISTANCECMCRITICAL 20
#define PUBLSIHINTERVAL 1000
#define WAITINTERVAL 5000
#define MOVESPEEDMAX 230

#include <Arduino.h>

#include <Streaming.h>
#include <MeMCore.h>

MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_1, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;

int moveSpeed = 100;
int lineFollowFlag = 0;
double distanceCm = 0.0;
uint8_t readSensors = 0;
bool start = false;
bool moveBot = false;
uint8_t randNumber;

unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();
bool makeNoise = false;

void Forward() {
  moveBot = true;
  motorL.run(-moveSpeed);
  motorR.run(moveSpeed);
}

void Backward() {
  moveBot = true;
  motorL.run(moveSpeed);
  motorR.run(-moveSpeed);
}

void TurnLeft() {
  moveBot = true;
  motorL.run(-moveSpeed / 10);
  motorR.run(moveSpeed);
}

void TurnRight() {
  moveBot = true;
  motorL.run(-moveSpeed);
  motorR.run(moveSpeed / 10);
}

void Stop() {
  moveBot = false;
  motorL.run(0);
  motorR.run(0);
}

void Autonomous() {
    randomSeed(analogRead(6));
    randNumber = random(2);
    if (distanceCm > 15 || distanceCm == 0) {
      Forward();
    } else if (distanceCm > 10) {
      switch (randNumber)
      {
        case 0:
          TurnLeft();
          delay(200);
          break;
        case 1:
          TurnRight();
          delay(200);
          break;
      }
    } else {
      Backward();
      delay(400);
    }
    delay(100);
}

void bottomPressed() {
    start = !start;
    if (start) {
      rgbLed.setColor(1, 0, 10, 0);
      rgbLed.show();
    } else {
      rgbLed.setColor(1, 0, 0, 0);
      rgbLed.show();
      Stop();
    }
    delay(250);
}

void bottomCheck() {
  if (analogRead(A7) == 0) {
    bottomPressed();
  }
}

void irControl() {
  uint32_t value;

  if (ir.decode()) {
    value = ir.value;
    switch (value >> 16 & 0xff) {
      case IR_BUTTON_LEFT:
      TurnLeft();
      break;
      case IR_BUTTON_RIGHT:
      TurnRight();
      break;
      case IR_BUTTON_DOWN:
      Backward();
      break;
      case IR_BUTTON_UP:
      Forward();
      break;
      case IR_BUTTON_SETTING:
      Stop();
      break;
      case IR_BUTTON_A:
      bottomPressed();
      break;
    }
  }
}

void noise() {
  if (!moveBot and start) {
    if (wait == false) {
      wait = true;
      waitTimer = millis();
    }
    if (wait and millis() - waitTimer > WAITINTERVAL) {
      makeNoise = true;
      //buzzer.tone(262, 100);
      rgbLed.setColor(2, 10, 0, 0);
      rgbLed.show();
    } else {
      rgbLed.setColor(2, 0, 0, 10);
      rgbLed.show();
    }
  } else {
    wait = false;
    makeNoise = false;
    buzzer.noTone();
    rgbLed.setColor(2, 0, 0, 0);
    rgbLed.show();
  }
}

void readData() {
  readSensors = lineFollower.readSensors();
  distanceCm = ultrasonicSensor.distanceCm();
}

void sendData() {
  if (millis() - publishTimer > PUBLSIHINTERVAL) {
    publishTimer = millis();
    Serial << endl << "start: " << start << endl;
    Serial << "moveBot: " << moveBot << endl;
    Serial << "tryFollowLine: " << tryFollowLine << endl;
    Serial << "makeNoise: " << makeNoise << endl;
    Serial << "readSensors: " << readSensors << endl;
    Serial << "temperature: " << temperature.temperature() << endl;
    Serial << "lightSensor: " << lightSensor.read() << endl;
    Serial << "distanceCm: " << distanceCm << endl;
  }
}

void setup() {
  Serial.begin(115200);
  Serial << endl << VERSION << endl << endl;
  pinMode(A7, INPUT);
  ir.begin();
  rgbLed.setColor(0, 0, 0, 0);
  rgbLed.show();
}

void loop() {
  bottomCheck();
  irControl();
  readData();
  sendData();
  noise();
  if (start) {
    if (distanceCm < DISTANCECMCRITICAL and distanceCm > 0) {
      Stop();
      tryFollowLine = true;
    } else {
      moveBot = true;
      if (moveSpeed > MOVESPEEDMAX) {
        moveSpeed = 230;
      }
      switch (readSensors) {
        case S1_IN_S2_IN:
          tryFollowLine = true;
          Forward();
          lineFollowFlag = 10;
          break;
        case S1_IN_S2_OUT:
          tryFollowLine = true;
          Forward();
          if (lineFollowFlag > 1) lineFollowFlag--;
          break;
        case S1_OUT_S2_IN:
          tryFollowLine = true;
          Forward();
          if (lineFollowFlag < 20) lineFollowFlag++;
          break;
        case S1_OUT_S2_OUT:
          if (tryFollowLine) {
            tryFollowLine = !tryFollowLine;
            tryFollowLineTimer = millis();
          }
          if (millis() - tryFollowLineTimer < 3000) {
            if (lineFollowFlag == 10) Backward();
            if (lineFollowFlag < 10) TurnLeft();
            if (lineFollowFlag > 10) TurnRight();
          } else {
            Stop();
//            Autonomous();
          }
          break;
      }
    }
  }
}
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <unistd.h>
#include "fnord/base/io/filerepository.h"
#include "fnord/base/io/fileutil.h"
#include "fnord/base/application.h"
#include "fnord/base/logging.h"
#include "fnord/base/random.h"
#include "fnord/base/thread/eventloop.h"
#include "fnord/base/thread/threadpool.h"
#include "fnord/base/wallclock.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord/cli/flagparser.h"
#include "fnord/json/json.h"
#include "fnord/json/jsonrpc.h"
#include "fnord/net/http/httprouter.h"
#include "fnord/net/http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord/stats/statsdagent.h"
#include "fnord-mdb/MDB.h"
#include "cm-common/CustomerNamespace.h"
#include "cm-logjoin/LogJoin.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "statefile",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "statefile",
      "<filename>");

  flags.defineFlag(
      "batch_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "2048",
      "batch_size",
      "<num>");

  flags.defineFlag(
      "buffer_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8192",
      "buffer_size",
      "<num>");

  flags.defineFlag(
      "commit_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "1024",
      "commit_size",
      "<num>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* start event loop */
  fnord::thread::EventLoop ev;

  auto evloop_thread = std::thread([&ev] {
    ev.run();
  });

  /* set up rpc client */
  HTTPRPCClient rpc_client(&ev);

  size_t batch_size = flags.getInt("batch_size");
  size_t buffer_size = flags.getInt("buffer_size");
  size_t commit_size = flags.getInt("commit_size");

  /* set up input feed reader */
  feeds::RemoteFeedReader feed_reader(&rpc_client);

  /* get source urls */
  Vector<String> uris = flags.getArgv();
  if (flags.isSet("statefile")) {
    auto statefile = FileUtil::read(flags.getString("statefile")).toString();
    for (const auto& uri : StringUtil::split(statefile, "\n")) {
      if (uri.size() > 0) {
        uris.emplace_back(uri);
      }
    }
  }

  HashMap<String, String> feed_urls;
  for (const auto& uri_raw : uris) {
    URI uri(uri_raw);
    const auto& params = uri.queryParams();

    std::string feed;
    if (!URI::getParam(params, "feed", &feed)) {
      RAISE(kIllegalArgumentError, "feed url missing ?feed query param");
    }

    feed_urls.emplace(feed, uri_raw.substr(0, uri_raw.find("?")));

    std::string offset_str;
    uint64_t offset = 0;
    if (URI::getParam(params, "offset", &offset_str)) {
      if (offset_str == "HEAD") {
        offset = std::numeric_limits<uint64_t>::max();
      } else {
        offset = std::stoul(offset_str);
      }
    }

    feed_reader.addSourceFeed(
        uri,
        feed,
        offset,
        batch_size,
        buffer_size);
  }

  DateTime last_iter;
  uint64_t rate_limit_micros = 1 * kMicrosPerSecond;

  for (int i = 0; i < commit_size; ++i) {
    last_iter = WallClock::now();
    feed_reader.waitForNextEntry();

    for (;;) {
      auto entry = feed_reader.fetchNextEntry();

      if (entry.isEmpty()) {
        break;
      }

      fnord::iputs("$0", entry.get().data);
    }

    if (flags.isSet("statefile")) {
      auto stream_offsets = feed_reader.streamOffsets();
      Buffer statefile;

      for (const auto& soff : stream_offsets) {
        statefile.append(
            StringUtil::format(
                "$0?feed=$1&offset=$2\n",
                feed_urls[soff.first],
                soff.first,
                soff.second));
      }

      FileUtil::write(flags.getString("statefile") + "~", statefile);
      FileUtil::mv(
          flags.getString("statefile") + "~",
          flags.getString("statefile"));
    }

    auto etime = WallClock::now().unixMicros() - last_iter.unixMicros();
    if (etime < rate_limit_micros) {
      usleep(rate_limit_micros - etime);
    }
  }

  evloop_thread.join();
  return 0;
}

<commit_msg>better error msg<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <unistd.h>
#include "fnord/base/io/filerepository.h"
#include "fnord/base/io/fileutil.h"
#include "fnord/base/application.h"
#include "fnord/base/logging.h"
#include "fnord/base/random.h"
#include "fnord/base/thread/eventloop.h"
#include "fnord/base/thread/threadpool.h"
#include "fnord/base/wallclock.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord/cli/flagparser.h"
#include "fnord/json/json.h"
#include "fnord/json/jsonrpc.h"
#include "fnord/net/http/httprouter.h"
#include "fnord/net/http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord/stats/statsdagent.h"
#include "fnord-mdb/MDB.h"
#include "cm-common/CustomerNamespace.h"
#include "cm-logjoin/LogJoin.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "statefile",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "statefile",
      "<filename>");

  flags.defineFlag(
      "batch_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "2048",
      "batch_size",
      "<num>");

  flags.defineFlag(
      "buffer_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8192",
      "buffer_size",
      "<num>");

  flags.defineFlag(
      "commit_size",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "1024",
      "commit_size",
      "<num>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* start event loop */
  fnord::thread::EventLoop ev;

  auto evloop_thread = std::thread([&ev] {
    ev.run();
  });

  /* set up rpc client */
  HTTPRPCClient rpc_client(&ev);

  size_t batch_size = flags.getInt("batch_size");
  size_t buffer_size = flags.getInt("buffer_size");
  size_t commit_size = flags.getInt("commit_size");

  /* set up input feed reader */
  feeds::RemoteFeedReader feed_reader(&rpc_client);

  /* get source urls */
  Vector<String> uris = flags.getArgv();
  if (flags.isSet("statefile")) {
    auto statefile = FileUtil::read(flags.getString("statefile")).toString();
    for (const auto& uri : StringUtil::split(statefile, "\n")) {
      if (uri.size() > 0) {
        uris.emplace_back(uri);
      }
    }
  }

  HashMap<String, String> feed_urls;
  for (const auto& uri_raw : uris) {
    URI uri(uri_raw);
    const auto& params = uri.queryParams();

    std::string feed;
    if (!URI::getParam(params, "feed", &feed)) {
      RAISEF(
          kIllegalArgumentError,
          "feed url missing ?feed query param: $0",
          uri_raw);
    }

    feed_urls.emplace(feed, uri_raw.substr(0, uri_raw.find("?")));

    std::string offset_str;
    uint64_t offset = 0;
    if (URI::getParam(params, "offset", &offset_str)) {
      if (offset_str == "HEAD") {
        offset = std::numeric_limits<uint64_t>::max();
      } else {
        offset = std::stoul(offset_str);
      }
    }

    feed_reader.addSourceFeed(
        uri,
        feed,
        offset,
        batch_size,
        buffer_size);
  }

  DateTime last_iter;
  uint64_t rate_limit_micros = 1 * kMicrosPerSecond;

  for (int i = 0; i < commit_size; ++i) {
    last_iter = WallClock::now();
    feed_reader.waitForNextEntry();

    for (;;) {
      auto entry = feed_reader.fetchNextEntry();

      if (entry.isEmpty()) {
        break;
      }

      fnord::iputs("$0", entry.get().data);
    }

    if (flags.isSet("statefile")) {
      auto stream_offsets = feed_reader.streamOffsets();
      Buffer statefile;

      for (const auto& soff : stream_offsets) {
        statefile.append(
            StringUtil::format(
                "$0?feed=$1&offset=$2\n",
                feed_urls[soff.first],
                soff.first,
                soff.second));
      }

      FileUtil::write(flags.getString("statefile") + "~", statefile);
      FileUtil::mv(
          flags.getString("statefile") + "~",
          flags.getString("statefile"));
    }

    auto etime = WallClock::now().unixMicros() - last_iter.unixMicros();
    if (etime < rate_limit_micros) {
      usleep(rate_limit_micros - etime);
    }
  }

  evloop_thread.join();
  return 0;
}

<|endoftext|>


<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include <tev/ImageViewer.h>
#include <tev/Ipc.h>
#include <tev/SharedQueue.h>
#include <tev/ThreadPool.h>

#include <args.hxx>
#include <ImfThreading.h>

#include <utf8.h>

#include <iostream>
#include <thread>

using namespace args;
using namespace filesystem;
using namespace std;

TEV_NAMESPACE_BEGIN

int mainFunc(const vector<string>& arguments) {
    ArgumentParser parser{
        "Inspection tool for images with a high dynamic range.",
        "",
    };

    HelpFlag helpFlag{
        parser,
        "help",
        "Display this help menu",
        {'h', "help"},
    };

    Flag newWindowFlag{
        parser,
        "new window",
        "Opens a new window of tev, even if one exists already.",
        {'n', "new"},
    };

    ValueFlag<float> exposureFlag{
        parser,
        "exposure",
        "Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. "
        "It can be controlled via the GUI, or by pressing E/Shift+E.",
        {'e', "exposure"},
    };

    ValueFlag<string> filterFlag{
        parser,
        "filter",
        "Filters visible images and layers according to a supplied string. "
        "The string must have the format 'image:layer'. "
        "Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.",
        {'f', "filter"},
    };

    ValueFlag<bool> maximizeFlag{
        parser,
        "maximize",
        "Whether to maximize the window on startup or not. "
        "If no images were supplied via the command line, then the default is false. "
        "Otherwise, the default is true.",
        {"max", "maximize"},
    };

    ValueFlag<string> metricFlag{
        parser,
        "metric",
        "The metric to use when comparing two images. "
        R"(
        The available metrics are:
        E   - Error
        AE  - Absolute Error
        SE  - Squared Error
        RAE - Relative Absolute Error
        RSE - Relative Squared Error
        )"
        "Default is E.",
        {'m', "metric"},
    };

    ValueFlag<float> offsetFlag{
        parser,
        "offset",
        "The offset is added to the image after exposure has been applied. "
        "It can be controlled via the GUI, or by pressing O/Shift+O.",
        {'o', "offset"},
    };

    ValueFlag<string> tonemapFlag{
        parser,
        "tonemap",
        "The tonemapping algorithm to use. "
        R"(
        The available tonemaps are:
        sRGB   - sRGB
        Gamma  - Gamma curve (2.2)
        FC     - False Color
        PN     - Positive=Green, Negative=Red
        )"
        "Default is sRGB.",
        {'t', "tonemap"},
    };

    PositionalList<string> imageFiles{
        parser,
        "images or channel selectors",
        "The image files to be opened by the viewer. "
        "If a filename starting with a ':' is encountered, "
        "then this filename is not treated as an image file "
        "but as a comma-separated channel selector. Until the next channel "
        "selector is encountered only channels containing "
        "elements from the current selector will be loaded. This is "
        "especially useful for selectively loading a specific "
        "part of a multi-part EXR file.",
    };

    // Parse command line arguments and react to parsing
    // errors using exceptions.
    try {
        parser.ParseArgs(arguments);
    } catch (Help) {
        std::cout << parser;
        return 0;
    } catch (ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -1;
    } catch (ValidationError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -2;
    }

    auto ipc = make_shared<Ipc>();

    // If we're not the primary instance and did not request to open a new window,
    // simply send the to-be-opened images to the primary instance.
    if (!ipc->isPrimaryInstance() && !newWindowFlag) {
        string channelSelector;
        for (auto imageFile : get(imageFiles)) {
            if (!imageFile.empty() && imageFile[0] == ':') {
                channelSelector = imageFile.substr(1);
                continue;
            }

            try {
                ipc->sendToPrimaryInstance(path{imageFile}.make_absolute().str() + ":" + channelSelector);
            } catch (runtime_error e) {
                cerr << "Invalid file '" << imageFile << "': " << e.what() << endl;
            }
        }

        return 0;
    }

    Imf::setGlobalThreadCount(thread::hardware_concurrency());

    cout << "Loading window..." << endl;

    // Load images passed via command line in the background prior to
    // creating our main application such that they are not stalled
    // by the potentially slow initialization of opengl / glfw.
    shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();
    string channelSelector;
    for (auto imageFile : get(imageFiles)) {
        if (!imageFile.empty() && imageFile[0] == ':') {
            channelSelector = imageFile.substr(1);
            continue;
        }

        ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {
            auto image = tryLoadImage(imageFile, channelSelector);
            if (image) {
                imagesToAdd->push({false, image});
            }
        });
    }

    // Init nanogui application
    nanogui::init();

    {
        auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd, !imageFiles}};
        app->drawAll();
        app->setVisible(true);

        // Do what the maximize flag tells us---if it exists---and
        // maximize if we have images otherwise.
        if (maximizeFlag ? get(maximizeFlag) : imageFiles) {
            app->maximize();
        }

        // Apply parameter flags
        if (exposureFlag) { app->setExposure(get(exposureFlag)); }
        if (filterFlag)   { app->setFilter(get(filterFlag)); }
        if (metricFlag)   { app->setMetric(toMetric(get(metricFlag))); }
        if (offsetFlag)   { app->setOffset(get(offsetFlag)); }
        if (tonemapFlag)  { app->setTonemap(toTonemap(get(tonemapFlag))); }

        // Refresh only every 250ms if there are no user interactions.
        // This makes an idling tev surprisingly energy-efficient. :)
        nanogui::mainloop(250);
    }

    // On some linux distributions glfwTerminate() (which is called by
    // nanogui::shutdown()) causes segfaults. Since we are done with our
    // program here anyways, let's let the OS clean up after us.
    //nanogui::shutdown();

    // Let all threads gracefully terminate.
    ThreadPool::shutdown();

    return 0;
}

TEV_NAMESPACE_END

#ifdef _WIN32
int wmain(int argc, wchar_t* argv[]) {
#else
int main(int argc, char* argv[]) {
#endif
    try {
        vector<string> arguments;
        for (int i = 1; i < argc; ++i) {
#ifdef _WIN32
            arguments.emplace_back(tev::utf16to8(argv[i]));
#else
            string arg = argv[i];
            // OSX sometimes (seemingly sporadically) passes the
            // process serial number via a command line parameter.
            // We would like to ignore this.
            if (arg.find("-psn") != 0) {
                arguments.emplace_back(tev::ensureUtf8(argv[i]));
            }
#endif
        }

        tev::mainFunc(arguments);
    } catch (const runtime_error& e) {
        cerr << "Uncaught exception: " << e.what() << endl;
        return 1;
    }
}
<commit_msg>Print uncaught std::exception rather than std::runtime_error<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include <tev/ImageViewer.h>
#include <tev/Ipc.h>
#include <tev/SharedQueue.h>
#include <tev/ThreadPool.h>

#include <args.hxx>
#include <ImfThreading.h>

#include <utf8.h>

#include <iostream>
#include <thread>

using namespace args;
using namespace filesystem;
using namespace std;

TEV_NAMESPACE_BEGIN

int mainFunc(const vector<string>& arguments) {
    ArgumentParser parser{
        "Inspection tool for images with a high dynamic range.",
        "",
    };

    HelpFlag helpFlag{
        parser,
        "help",
        "Display this help menu",
        {'h', "help"},
    };

    Flag newWindowFlag{
        parser,
        "new window",
        "Opens a new window of tev, even if one exists already.",
        {'n', "new"},
    };

    ValueFlag<float> exposureFlag{
        parser,
        "exposure",
        "Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. "
        "It can be controlled via the GUI, or by pressing E/Shift+E.",
        {'e', "exposure"},
    };

    ValueFlag<string> filterFlag{
        parser,
        "filter",
        "Filters visible images and layers according to a supplied string. "
        "The string must have the format 'image:layer'. "
        "Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.",
        {'f', "filter"},
    };

    ValueFlag<bool> maximizeFlag{
        parser,
        "maximize",
        "Whether to maximize the window on startup or not. "
        "If no images were supplied via the command line, then the default is false. "
        "Otherwise, the default is true.",
        {"max", "maximize"},
    };

    ValueFlag<string> metricFlag{
        parser,
        "metric",
        "The metric to use when comparing two images. "
        R"(
        The available metrics are:
        E   - Error
        AE  - Absolute Error
        SE  - Squared Error
        RAE - Relative Absolute Error
        RSE - Relative Squared Error
        )"
        "Default is E.",
        {'m', "metric"},
    };

    ValueFlag<float> offsetFlag{
        parser,
        "offset",
        "The offset is added to the image after exposure has been applied. "
        "It can be controlled via the GUI, or by pressing O/Shift+O.",
        {'o', "offset"},
    };

    ValueFlag<string> tonemapFlag{
        parser,
        "tonemap",
        "The tonemapping algorithm to use. "
        R"(
        The available tonemaps are:
        sRGB   - sRGB
        Gamma  - Gamma curve (2.2)
        FC     - False Color
        PN     - Positive=Green, Negative=Red
        )"
        "Default is sRGB.",
        {'t', "tonemap"},
    };

    PositionalList<string> imageFiles{
        parser,
        "images or channel selectors",
        "The image files to be opened by the viewer. "
        "If a filename starting with a ':' is encountered, "
        "then this filename is not treated as an image file "
        "but as a comma-separated channel selector. Until the next channel "
        "selector is encountered only channels containing "
        "elements from the current selector will be loaded. This is "
        "especially useful for selectively loading a specific "
        "part of a multi-part EXR file.",
    };

    // Parse command line arguments and react to parsing
    // errors using exceptions.
    try {
        parser.ParseArgs(arguments);
    } catch (Help) {
        std::cout << parser;
        return 0;
    } catch (ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -1;
    } catch (ValidationError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -2;
    }

    auto ipc = make_shared<Ipc>();

    // If we're not the primary instance and did not request to open a new window,
    // simply send the to-be-opened images to the primary instance.
    if (!ipc->isPrimaryInstance() && !newWindowFlag) {
        string channelSelector;
        for (auto imageFile : get(imageFiles)) {
            if (!imageFile.empty() && imageFile[0] == ':') {
                channelSelector = imageFile.substr(1);
                continue;
            }

            try {
                ipc->sendToPrimaryInstance(path{imageFile}.make_absolute().str() + ":" + channelSelector);
            } catch (runtime_error e) {
                cerr << "Invalid file '" << imageFile << "': " << e.what() << endl;
            }
        }

        return 0;
    }

    Imf::setGlobalThreadCount(thread::hardware_concurrency());

    cout << "Loading window..." << endl;

    // Load images passed via command line in the background prior to
    // creating our main application such that they are not stalled
    // by the potentially slow initialization of opengl / glfw.
    shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();
    string channelSelector;
    for (auto imageFile : get(imageFiles)) {
        if (!imageFile.empty() && imageFile[0] == ':') {
            channelSelector = imageFile.substr(1);
            continue;
        }

        ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {
            auto image = tryLoadImage(imageFile, channelSelector);
            if (image) {
                imagesToAdd->push({false, image});
            }
        });
    }

    // Init nanogui application
    nanogui::init();

    {
        auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd, !imageFiles}};
        app->drawAll();
        app->setVisible(true);

        // Do what the maximize flag tells us---if it exists---and
        // maximize if we have images otherwise.
        if (maximizeFlag ? get(maximizeFlag) : imageFiles) {
            app->maximize();
        }

        // Apply parameter flags
        if (exposureFlag) { app->setExposure(get(exposureFlag)); }
        if (filterFlag)   { app->setFilter(get(filterFlag)); }
        if (metricFlag)   { app->setMetric(toMetric(get(metricFlag))); }
        if (offsetFlag)   { app->setOffset(get(offsetFlag)); }
        if (tonemapFlag)  { app->setTonemap(toTonemap(get(tonemapFlag))); }

        // Refresh only every 250ms if there are no user interactions.
        // This makes an idling tev surprisingly energy-efficient. :)
        nanogui::mainloop(250);
    }

    // On some linux distributions glfwTerminate() (which is called by
    // nanogui::shutdown()) causes segfaults. Since we are done with our
    // program here anyways, let's let the OS clean up after us.
    //nanogui::shutdown();

    // Let all threads gracefully terminate.
    ThreadPool::shutdown();

    return 0;
}

TEV_NAMESPACE_END

#ifdef _WIN32
int wmain(int argc, wchar_t* argv[]) {
#else
int main(int argc, char* argv[]) {
#endif
    try {
        vector<string> arguments;
        for (int i = 1; i < argc; ++i) {
#ifdef _WIN32
            arguments.emplace_back(tev::utf16to8(argv[i]));
#else
            string arg = argv[i];
            // OSX sometimes (seemingly sporadically) passes the
            // process serial number via a command line parameter.
            // We would like to ignore this.
            if (arg.find("-psn") != 0) {
                arguments.emplace_back(tev::ensureUtf8(argv[i]));
            }
#endif
        }

        tev::mainFunc(arguments);
    } catch (const exception& e) {
        cerr << "Uncaught exception: " << e.what() << endl;
        return 1;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

using namespace std;

int main()
{
        string user_stream;
        const char * commands;
        char * parsed;
        const char * parser = " ;";
        char * username = getlogin();

        char host[1024];
        gethostname(host, 1024);

        //Introductory Message to make sure shell is running.
        cout << "Hello, and welcome to Kevin's shell." << endl;

        while(1){

                // Prints out the username and hostname if it exists.
                if (username && host){
                        cout << username << "@" << host;
                }
                cout << "$ ";

                //Gets line for user stream.
                getline(cin, user_stream);

                //Parsing the string using strdup to change from const char* to char*
                parsed = strdup(user_stream.c_str());

                //Tokenizes the first one in the array.
                commands = strtok(parsed, parser);

                /* walk through to check if commands are null terminated.
                while( commands != NULL )
                {
                        printf( " %s\n", commands );
                        commands = strtok(NULL, parser );
                }

                if (user_stream == "exit"){
                        cout << "Shell will be terminated now." << endl;
                        exit(0);
                }
                */

                //Creating a fork process
                int pid = fork();

                if (pid == -1){

                        //PID will return -1 when an error occurs.
                        cout << "Fork broke. Shell will now exit." << endl;
                        exit(1);
                }

        }
        /*
	if (pid == 0){
		cout << "I'm a child process. " << endl;
		//PID returns 0 when you have nothing left to execute.

		char *argv[3];
                strcpy(argv[0], "ls");
                argv[1] = "-a";
                argv[2] = "-l";
                cout << "before" << endl;
                execvp ("ls", argv);
                cout << "after" << endl; // Nothing after execvp will ever be run.
        }
        else{
                wait(NULL);
                cout << "I'm a parent process." << endl;
        }*/

        return 0;

}
<commit_msg>Made some more changes<commit_after>#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

using namespace std;

char ** changeToArray(char ** commandList, char* commands, const char* parser){
        int i;
        char* parsingKey = strtok(commands, parser);

        for (i = 0; parsingKey != NULL; parsingKey = strtok(NULL, parser) ){
                commandList[i] = parsingKey;
                ++i;
        }

        commandList[i] = NULL;
        return commandList;
}

int main()
{
        string user_stream;
        const char * parser = " ;";
        char * parsedString;
        char * username = getlogin();
        char ** commandstream = NULL;

        char host[1024];
        gethostname(host, 1024);

        //Introductory Message to make sure shell is running.
        cout << "Hello, and welcome to Kevin's shell." << endl;

        while(1){

                // Prints out the username and hostname if it exists.
                if (username && host){
                        cout << username << "@" << host;
                }
                cout << "$ ";

                //Gets line for user stream.
                getline(cin, user_stream);

                //Parsing the string using strdup to change from const char* to char*
                parsedString = strdup(user_stream.c_str());

                changeToArray(commandstream, parsedString, parser);

                execvp(parsedString, commandstream);

                //walk through to check if commands are null terminated.

                /*
                if (user_stream == "exit"){
                        cout << "Shell will be terminated now." << endl;
                        exit(0);
                }
                */

                //Creating a fork process
                /*
                int pid = fork();

                if (pid == -1){

                        //PID will return -1 when an error occurs.
                        cout << "Fork broke. Shell will now exit." << endl;
                        exit(1);
                }
                else if (pid == 0){

                }

                else{
                        wait(NULL);
                        cout << "I'm done." << endl;
                }
                */

        }
        /*
	if (pid == 0){
		cout << "I'm a child process. " << endl;
		//PID returns 0 when you have nothing left to execute.

		char *argv[3];
                strcpy(argv[0], "ls");
                argv[1] = "-a";
                argv[2] = "-l";
                cout << "before" << endl;
                execvp ("ls", argv);
                cout << "after" << endl; // Nothing after execvp will ever be run.
        }
        else{
                wait(NULL);
                cout << "I'm a parent process." << endl;
        }*/

        return 0;

}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include "juuhcode.hpp"
#include "mainfunctions.cpp"

int main(int argc, char *argv[]) {
  if (argc < 2 || isatty(0)) {
    // if there's no argument(s) or we're not getting piped anything
    printUsage();
    return 2;
  }

  // gather everything from stdin
  const std::string s{std::istreambuf_iterator<char>(std::cin),
                std::istreambuf_iterator<char>()};

  const std::string argument = argv[1];

  auto const j = JuuhCode(s);

  switch (getOptionForArgument(argument)) {
  case PRINT_CODES:
    j.printCodes();
    break;
  case PRINT_ENCODED:
    j.printEncodedString();
    break;
  case PRINT_STATS:
    j.printStats();
    break;
  case UNDEFINED:
    printUsage();
    return 2;
  }

  return 0;
}
<commit_msg>add consistency<commit_after>#include <string>
#include <iostream>
#include "juuhcode.hpp"
#include "mainfunctions.cpp"

int main(int argc, char *argv[]) {
  if (argc < 2 || isatty(0)) {
    // if there's no argument(s) or we're not getting piped anything
    printUsage();
    return 2;
  }

  // gather everything from stdin
  const std::string s{std::istreambuf_iterator<char>(std::cin),
                std::istreambuf_iterator<char>()};

  const std::string argument = argv[1];

  const JuuhCode j = JuuhCode(s);

  switch (getOptionForArgument(argument)) {
  case PRINT_CODES:
    j.printCodes();
    break;
  case PRINT_ENCODED:
    j.printEncodedString();
    break;
  case PRINT_STATS:
    j.printStats();
    break;
  case UNDEFINED:
    printUsage();
    return 2;
  }

  return 0;
}
<|endoftext|>