<commit_before>/*
  This file is part of KOrganizer.
  Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
  Copyright (c) 2009 Allen Winter <winter@kde.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.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

// TODO: validate hand-entered email addresses
// TODO: don't allow duplicates; at least remove dupes when passing back
// TODO: the list in PublishDialog::addresses()

#include "publishdialog.h"

#include <kabc/addresseedialog.h>
#include <kcal/attendee.h>
#include <kcal/person.h>
#include <kpimutils/email.h>

#include <klineedit.h>
#include <klocale.h>

PublishDialog::PublishDialog( QWidget *parent )
  : KDialog( parent )
{
  setCaption( i18n( "Select Addresses" ) );
  setButtons( Ok|Cancel|Help );
  setHelp( "group-scheduling", "korganizer" );
  QWidget *widget = new QWidget( this );
  widget->setObjectName( "PublishFreeBusy" );
  mUI.setupUi( widget );
  setMainWidget( widget );
  mUI.mListWidget->setSelectionMode( QAbstractItemView::SingleSelection );
  mUI.mNameLineEdit->setEnabled( false );
  mUI.mEmailLineEdit->setEnabled( false );

  setButtonToolTip( Ok, i18n( "Send email to these recipients" ) );
  setButtonWhatsThis( Ok, i18n( "Clicking the Ok button will cause "
                                "an email to be sent to the recipients you "
                                "have entered." ) );
  setButtonToolTip( Cancel, i18n( "Cancel recipient selection and the email" ) );
  setButtonWhatsThis( Cancel, i18n( "Clicking the Cancel button will "
                                    "cause the email operation to be terminated." ) );

  setButtonWhatsThis( Help, i18n( "Click the Help button to read "
                                  "more information about Group Scheduling." ) );

  mUI.mNew->setIcon( KIcon( "list-add" ) );
  mUI.mRemove->setIcon( KIcon( "list-remove" ) );
  mUI.mRemove->setEnabled( false );
  mUI.mSelectAddressee->setIcon( KIcon( "view-pim-contacts" ) );

  connect( mUI.mListWidget, SIGNAL(itemSelectionChanged()),
           SLOT(updateInput()) );
  connect( mUI.mNew, SIGNAL(clicked()),
           SLOT(addItem()) );
  connect( mUI.mRemove, SIGNAL(clicked()),
           SLOT(removeItem()) );
  connect( mUI.mSelectAddressee, SIGNAL(clicked()),
           SLOT(openAddressbook()) );
  connect( mUI.mNameLineEdit, SIGNAL(textChanged(const QString &)),
           SLOT(updateItem()) );
  connect( mUI.mEmailLineEdit, SIGNAL(textChanged(const QString &)),
           SLOT(updateItem()) );
}

PublishDialog::~PublishDialog()
{
}

void PublishDialog::addAttendee( Attendee *attendee )
{
  mUI.mNameLineEdit->setEnabled( true );
  mUI.mEmailLineEdit->setEnabled( true );
  QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
  Person person( attendee->name(), attendee->email() );
  item->setText( person.fullName() );
  mUI.mListWidget->addItem( item );
  mUI.mRemove->setEnabled( true );
}

QString PublishDialog::addresses()
{
  QString to = "";
  QListWidgetItem *item;
  int i, count;
  count = mUI.mListWidget->count();
  for ( i=0; i<count; ++i ) {
    item = mUI.mListWidget->item( i );
    if( !item->text().isEmpty() ) {
      to += item->text();
      if ( i < count-1 ) {
        to += ", ";
      }
    }
  }
  return to;
}

void PublishDialog::addItem()
{
  mUI.mNameLineEdit->setEnabled( true );
  mUI.mEmailLineEdit->setEnabled( true );
  QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
  mUI.mListWidget->addItem( item );
  mUI.mListWidget->setItemSelected( item, true );
  mUI.mNameLineEdit->setText( i18n( "(EmptyName)" ) );
  mUI.mEmailLineEdit->setText( i18n( "(EmptyEmail)" ) );

  mUI.mRemove->setEnabled( true );
}

void PublishDialog::removeItem()
{
  if ( mUI.mListWidget->selectedItems().isEmpty() ) {
    return;
  }
  QListWidgetItem *item;
  item = mUI.mListWidget->selectedItems().first();

  int row = mUI.mListWidget->row( item );
  mUI.mListWidget->takeItem( row );

  if ( !mUI.mListWidget->count() ) {
    mUI.mNameLineEdit->setText( QString() );
    mUI.mNameLineEdit->setEnabled( false );
    mUI.mEmailLineEdit->setText( QString() );
    mUI.mEmailLineEdit->setEnabled( false );
    mUI.mRemove->setEnabled( false );
    return;
  }
  if ( row > 0 ) {
    row--;
  }

  mUI.mListWidget->setCurrentRow( row );
}

void PublishDialog::openAddressbook()
{
  KABC::Addressee::List addressList = KABC::AddresseeDialog::getAddressees( this );
  if( addressList.isEmpty() ) {
     return;
  }

  KABC::Addressee a = addressList.first();
  if ( !a.isEmpty() ) {
    int i;
    for ( i=0; i<addressList.size(); i++ ) {
      a = addressList[i];
      mUI.mNameLineEdit->setEnabled( true );
      mUI.mEmailLineEdit->setEnabled( true );
      QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
      mUI.mListWidget->setItemSelected( item, true );
      mUI.mNameLineEdit->setText( a.realName() );
      mUI.mEmailLineEdit->setText( a.preferredEmail() );
      mUI.mListWidget->addItem( item );
    }
    mUI.mRemove->setEnabled( true );
  }
}

void PublishDialog::updateItem()
{
  if ( !mUI.mListWidget->selectedItems().count() ) {
    return;
  }

  Person person( mUI.mNameLineEdit->text(), mUI.mEmailLineEdit->text() );
  QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
  item->setText( person.fullName() );
}

void PublishDialog::updateInput()
{
  if ( !mUI.mListWidget->selectedItems().count() ) {
    return;
  }

  mUI.mNameLineEdit->setEnabled( true );
  mUI.mEmailLineEdit->setEnabled( true );

  QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
  QString mail, name;
  KPIMUtils::extractEmailAddressAndName( item->text(), mail, name );
  mUI.mNameLineEdit->setText( name );
  mUI.mEmailLineEdit->setText( mail );
}

#include "publishdialog.moc"
<commit_msg>Fix enable/disable remove button<commit_after>/*
  This file is part of KOrganizer.
  Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
  Copyright (c) 2009 Allen Winter <winter@kde.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.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

// TODO: validate hand-entered email addresses
// TODO: don't allow duplicates; at least remove dupes when passing back
// TODO: the list in PublishDialog::addresses()

#include "publishdialog.h"

#include <kabc/addresseedialog.h>
#include <kcal/attendee.h>
#include <kcal/person.h>
#include <kpimutils/email.h>

#include <klineedit.h>
#include <klocale.h>

PublishDialog::PublishDialog( QWidget *parent )
  : KDialog( parent )
{
  setCaption( i18n( "Select Addresses" ) );
  setButtons( Ok|Cancel|Help );
  setHelp( "group-scheduling", "korganizer" );
  QWidget *widget = new QWidget( this );
  widget->setObjectName( "PublishFreeBusy" );
  mUI.setupUi( widget );
  setMainWidget( widget );
  mUI.mListWidget->setSelectionMode( QAbstractItemView::SingleSelection );
  mUI.mNameLineEdit->setEnabled( false );
  mUI.mEmailLineEdit->setEnabled( false );

  setButtonToolTip( Ok, i18n( "Send email to these recipients" ) );
  setButtonWhatsThis( Ok, i18n( "Clicking the Ok button will cause "
                                "an email to be sent to the recipients you "
                                "have entered." ) );
  setButtonToolTip( Cancel, i18n( "Cancel recipient selection and the email" ) );
  setButtonWhatsThis( Cancel, i18n( "Clicking the Cancel button will "
                                    "cause the email operation to be terminated." ) );

  setButtonWhatsThis( Help, i18n( "Click the Help button to read "
                                  "more information about Group Scheduling." ) );

  mUI.mNew->setIcon( KIcon( "list-add" ) );
  mUI.mRemove->setIcon( KIcon( "list-remove" ) );
  mUI.mRemove->setEnabled( false );
  mUI.mSelectAddressee->setIcon( KIcon( "view-pim-contacts" ) );

  connect( mUI.mListWidget, SIGNAL(itemSelectionChanged()),
           SLOT(updateInput()) );
  connect( mUI.mNew, SIGNAL(clicked()),
           SLOT(addItem()) );
  connect( mUI.mRemove, SIGNAL(clicked()),
           SLOT(removeItem()) );
  connect( mUI.mSelectAddressee, SIGNAL(clicked()),
           SLOT(openAddressbook()) );
  connect( mUI.mNameLineEdit, SIGNAL(textChanged(const QString &)),
           SLOT(updateItem()) );
  connect( mUI.mEmailLineEdit, SIGNAL(textChanged(const QString &)),
           SLOT(updateItem()) );
}

PublishDialog::~PublishDialog()
{
}

void PublishDialog::addAttendee( Attendee *attendee )
{
  mUI.mNameLineEdit->setEnabled( true );
  mUI.mEmailLineEdit->setEnabled( true );
  QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
  Person person( attendee->name(), attendee->email() );
  item->setText( person.fullName() );
  mUI.mListWidget->addItem( item );
  mUI.mRemove->setEnabled( !mUI.mListWidget->selectedItems().isEmpty() );
}

QString PublishDialog::addresses()
{
  QString to = "";
  QListWidgetItem *item;
  int i, count;
  count = mUI.mListWidget->count();
  for ( i=0; i<count; ++i ) {
    item = mUI.mListWidget->item( i );
    if( !item->text().isEmpty() ) {
      to += item->text();
      if ( i < count-1 ) {
        to += ", ";
      }
    }
  }
  return to;
}

void PublishDialog::addItem()
{
  mUI.mNameLineEdit->setEnabled( true );
  mUI.mEmailLineEdit->setEnabled( true );
  QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
  mUI.mListWidget->addItem( item );
  mUI.mListWidget->setItemSelected( item, true );
  mUI.mNameLineEdit->setText( i18n( "(EmptyName)" ) );
  mUI.mEmailLineEdit->setText( i18n( "(EmptyEmail)" ) );

  mUI.mRemove->setEnabled( true );
}

void PublishDialog::removeItem()
{
  if ( mUI.mListWidget->selectedItems().isEmpty() ) {
    return;
  }
  QListWidgetItem *item;
  item = mUI.mListWidget->selectedItems().first();

  int row = mUI.mListWidget->row( item );
  mUI.mListWidget->takeItem( row );

  if ( !mUI.mListWidget->count() ) {
    mUI.mNameLineEdit->setText( QString() );
    mUI.mNameLineEdit->setEnabled( false );
    mUI.mEmailLineEdit->setText( QString() );
    mUI.mEmailLineEdit->setEnabled( false );
    mUI.mRemove->setEnabled( false );
    return;
  }
  if ( row > 0 ) {
    row--;
  }

  mUI.mListWidget->setCurrentRow( row );
}

void PublishDialog::openAddressbook()
{
  KABC::Addressee::List addressList = KABC::AddresseeDialog::getAddressees( this );
  if( addressList.isEmpty() ) {
     return;
  }

  KABC::Addressee a = addressList.first();
  if ( !a.isEmpty() ) {
    int i;
    for ( i=0; i<addressList.size(); i++ ) {
      a = addressList[i];
      mUI.mNameLineEdit->setEnabled( true );
      mUI.mEmailLineEdit->setEnabled( true );
      QListWidgetItem *item = new QListWidgetItem( mUI.mListWidget );
      mUI.mListWidget->setItemSelected( item, true );
      mUI.mNameLineEdit->setText( a.realName() );
      mUI.mEmailLineEdit->setText( a.preferredEmail() );
      mUI.mListWidget->addItem( item );
    }
    mUI.mRemove->setEnabled( true );
  }
}

void PublishDialog::updateItem()
{
  if ( !mUI.mListWidget->selectedItems().count() ) {
    return;
  }

  Person person( mUI.mNameLineEdit->text(), mUI.mEmailLineEdit->text() );
  QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
  item->setText( person.fullName() );
}

void PublishDialog::updateInput()
{
  if ( !mUI.mListWidget->selectedItems().count() ) {
    return;
  }

  mUI.mNameLineEdit->setEnabled( true );
  mUI.mEmailLineEdit->setEnabled( true );

  QListWidgetItem *item = mUI.mListWidget->selectedItems().first();
  QString mail, name;
  KPIMUtils::extractEmailAddressAndName( item->text(), mail, name );
  mUI.mNameLineEdit->setText( name );
  mUI.mEmailLineEdit->setText( mail );
}

#include "publishdialog.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: reposy.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:14:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <reposy.hxx>

// NOT FULLY DECLARED SERVICES
#include <cpp_internalgate.hxx>
#include <idl_internalgate.hxx>

namespace ary
{

//*****************     Repository          ************//

DYN Repository &
Repository::Create_()
{
    return *new RepositoryCenter;
}

RepositoryCenter::RepositoryCenter()
    :   sDisplayedName(),
        aLocation(),
        pCppPartition(0),
        pIdlPartition(0)
{
    pCppPartition = & cpp::InternalGate::Create_Partition_(*this);
    pIdlPartition = & idl::InternalGate::Create_Partition_(*this);
}

RepositoryCenter::~RepositoryCenter()
{
}

const ::ary::cpp::Gate &
RepositoryCenter::Gate_Cpp() const
{
    csv_assert(pCppPartition);
    return *pCppPartition;
}

const ::ary::idl::Gate &
RepositoryCenter::Gate_Idl() const
{
    csv_assert(pIdlPartition);
    return *pIdlPartition;
}

const String &
RepositoryCenter::Title() const
{
    return sDisplayedName;
}

::ary::cpp::Gate &
RepositoryCenter::Gate_Cpp()
{
    csv_assert(pCppPartition);
    return *pCppPartition;
}

::ary::idl::Gate &
RepositoryCenter::Gate_Idl()
{
    csv_assert(pIdlPartition);
    return *pIdlPartition;
}

void
RepositoryCenter::Set_Title(const String & i_sName)
{
    sDisplayedName = i_sName;
}

//*********************     Repository Type Info Data       ****************//

// !!! IMPORTANT - NEVER DELETE OR CHANGE - ADDING ALLOWED

/*  ClassType-Ids
    -------------

    cpp                 1000
    idl                 2000
    corba               3000
    java                4000
    information         5000
    logic location      6000
    phys location       7000
    sec. prod.          8000

    cpp
    ---
    Namespace           1000
    Class               1001
    Enum                1002
    Typedef             1003
    Function            1004
    Variable            1005
    EnumValue           1006
    NamespaceAlias      1007

    BuiltInType         1200
    CeType_Final        1201
    CeType_Extern       1202
    UsedType            1203
    PtrType             1211
    RefType             1212
    ConstType           1221
    VolatileType        1222
    ArrayType           1230
    TemplateInstance    1235
    FunctionPtr         1240
    DataMemberPtr       1250
    OperationMemberPtr  1260

    TplParam_Type       1301
    TplParam_Value      1302

    OpSignature         1400

    Define              1601
    Macro               1602

    ProjectGroup        1901
    FileGroup           1902

    TopProject          1921

    idl
    ---

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004
    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009
    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016

    BuiltInType         2200
    CeType              2201
    Sequence            2202
    ExplicitType        2203
    ExplicitNameRoom    2204
    TemplateParamType   2205

    java
    ----
    Package             4000
    Interface           4001
    Class               4002

    physical location
    -----------------
    Root                7000
    Directory           7030
    File                7100

    info
    ----
    CodeInformation
        (IDL)          11002
*/

}   // namespace ary
<commit_msg>INTEGRATION: CWS changefileheader (1.10.22); FILE MERGED 2008/03/28 16:01:53 rt 1.10.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: reposy.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <precomp.h>
#include <reposy.hxx>

// NOT FULLY DECLARED SERVICES
#include <cpp_internalgate.hxx>
#include <idl_internalgate.hxx>

namespace ary
{

//*****************     Repository          ************//

DYN Repository &
Repository::Create_()
{
    return *new RepositoryCenter;
}

RepositoryCenter::RepositoryCenter()
    :   sDisplayedName(),
        aLocation(),
        pCppPartition(0),
        pIdlPartition(0)
{
    pCppPartition = & cpp::InternalGate::Create_Partition_(*this);
    pIdlPartition = & idl::InternalGate::Create_Partition_(*this);
}

RepositoryCenter::~RepositoryCenter()
{
}

const ::ary::cpp::Gate &
RepositoryCenter::Gate_Cpp() const
{
    csv_assert(pCppPartition);
    return *pCppPartition;
}

const ::ary::idl::Gate &
RepositoryCenter::Gate_Idl() const
{
    csv_assert(pIdlPartition);
    return *pIdlPartition;
}

const String &
RepositoryCenter::Title() const
{
    return sDisplayedName;
}

::ary::cpp::Gate &
RepositoryCenter::Gate_Cpp()
{
    csv_assert(pCppPartition);
    return *pCppPartition;
}

::ary::idl::Gate &
RepositoryCenter::Gate_Idl()
{
    csv_assert(pIdlPartition);
    return *pIdlPartition;
}

void
RepositoryCenter::Set_Title(const String & i_sName)
{
    sDisplayedName = i_sName;
}

//*********************     Repository Type Info Data       ****************//

// !!! IMPORTANT - NEVER DELETE OR CHANGE - ADDING ALLOWED

/*  ClassType-Ids
    -------------

    cpp                 1000
    idl                 2000
    corba               3000
    java                4000
    information         5000
    logic location      6000
    phys location       7000
    sec. prod.          8000

    cpp
    ---
    Namespace           1000
    Class               1001
    Enum                1002
    Typedef             1003
    Function            1004
    Variable            1005
    EnumValue           1006
    NamespaceAlias      1007

    BuiltInType         1200
    CeType_Final        1201
    CeType_Extern       1202
    UsedType            1203
    PtrType             1211
    RefType             1212
    ConstType           1221
    VolatileType        1222
    ArrayType           1230
    TemplateInstance    1235
    FunctionPtr         1240
    DataMemberPtr       1250
    OperationMemberPtr  1260

    TplParam_Type       1301
    TplParam_Value      1302

    OpSignature         1400

    Define              1601
    Macro               1602

    ProjectGroup        1901
    FileGroup           1902

    TopProject          1921

    idl
    ---

    Module              2000
    Interface           2001
    Function            2002
    Service             2003
    Property            2004
    Enum                2005
    EnumValue           2006
    Typedef             2007
    Struct              2008
    StructElement       2009
    Exception           2010
    ConstantGroup       2011
    Constant            2012
    Singleton           2013
    Attribute           2014
    SglIfcService       2015
    SglIfcSingleton     2016

    BuiltInType         2200
    CeType              2201
    Sequence            2202
    ExplicitType        2203
    ExplicitNameRoom    2204
    TemplateParamType   2205

    java
    ----
    Package             4000
    Interface           4001
    Class               4002

    physical location
    -----------------
    Root                7000
    Directory           7030
    File                7100

    info
    ----
    CodeInformation
        (IDL)          11002
*/

}   // namespace ary
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mysql.h"
#include "cJSON/cJSON.h"

#define LEN 20
#define GENE_LEN 80000000
#define PAM_LEN 20

int check_pam(const char *str,const char *pam){
    for(;*pam;pam++,str++){
        if(*pam=='R' && (*str=='A' || *str=='G')) continue;
        if(*pam=='M' && (*str=='A' || *str=='C')) continue;
        if(*pam=='W' && (*str=='A' || *str=='T')) continue;
        if(*pam=='S' && (*str=='C' || *str=='G')) continue;
        if(*pam=='K' && (*str=='G' || *str=='T')) continue;
        if(*pam=='Y' && (*str=='C' || *str=='T')) continue;
        if(*pam=='H' && (*str=='A' || *str=='C' || *str=='T')) continue;
        if(*pam=='V' && (*str=='A' || *str=='C' || *str=='G')) continue;
        if(*pam=='B' && (*str=='C' || *str=='G' || *str=='T')) continue;
        if(*pam=='D' && (*str=='A' || *str=='G' || *str=='T')) continue;
        if(*pam=='N' || *pam=='n') continue;
        if(*pam==*str) continue;
        return 0;
    }
    return 1;
}

char dna_rev_char(char ch){
    if(ch=='A' || ch=='a') return 'T';
    if(ch=='T' || ch=='t') return 'A';
    if(ch=='C' || ch=='c') return 'G';
    if(ch=='G' || ch=='g') return 'C';
    return 'N';
}

char *dna_rev(char *sr,const char *s,int len){
    int i;
    for(i=0;i<len;i++){
        sr[i]=dna_rev_char(s[len-i-1]);
    }
    sr[i]=0;
    return sr;
}

int readLine(FILE *file){
    char ch;
    while(fscanf(file,"%c",&ch)==1) if(ch=='\n') return 1;
    return 0;
}

char *_tos(char *str){
    for(char *p=str;*p;p++){
        if(*p=='_') *p++=' ';
    }
    return str;
}

char str[GENE_LEN];
char buffer[9182];

MYSQL *my_conn;
MYSQL_RES *result;
MYSQL_ROW sql_row;

void get_pam_info(char pam_id[],const char pam[]){
    sprintf(buffer,"SELECT pam_id FROM Table_PAM WHERE pam_PAM='%s'; ",pam);
    mysql_query(my_conn,buffer);
    result=mysql_store_result(my_conn);
    sql_row=mysql_fetch_row(result);
    strcpy(pam_id,sql_row[0]);
}

int sum=0;
char sql[500000]="";
void add(char *str){
    if(sum==0){
        strcat(sql,"INSERT INTO Table_sgRNA (Chr_No, sgrna_start, sgrna_end, sgrna_strand, sgrna_seq, sgrna_PAM, pam_id) VALUES \n");
    }else{
        strcat(sql,",\n");
    }
    strcat(sql,str);
    sum=(sum+1)%500;
    if(sum==0){
        strcat(sql,"; \n");
        int res=mysql_query(my_conn,sql);
        if(res){
            printf("%s\n",mysql_error(my_conn));
        }
        sql[0]=0;
    }
}
void finish(){
    if(sum!=0){
        strcat(sql,"; \n");
        int res=mysql_query(my_conn,sql);
        if(res){
            printf("%s\n",mysql_error(my_conn));
            printf("%s\n",sql);
        }
        sql[0]=0;
    }
}

int getFileID(const char *user_ID,const char *fileName){
    char sql[1024];
    sprintf(sql,"SELECT upload_ID FROM user_upload WHERE user_id=%s AND upload_filename='%s'; ",user_ID,fileName);
    int res=mysql_query(my_conn,sql);
    if(res){
        return -1;
    }
    result=mysql_store_result(my_conn);
    if(result){
        sql_row=mysql_fetch_row(result);
        return atoi(sql_row[0]);
    }else{
        return -1;
    }
    return -1;
}

//char def1[]="{\"specie\":\"kkkk\",\"files\":[{\"fileName\":\"NC_01297\"}],\"PAM\":\"NGG\"}";
//char def2[]="8"
int main(int args, char *argv[]){
    if(args!=3){
        printf("N3");
        return 1;
    }

    int count=0;

    my_bool mb=false;
    my_conn=mysql_init(NULL);
    mysql_options(my_conn,MYSQL_SECURE_AUTH,&mb);
#ifdef  _WIN32
    if(mysql_real_connect(my_conn,"127.0.0.1","root","zy19930108","CasDB",3306,NULL,0)){
#endif
#ifdef  __linux
    if(mysql_real_connect(my_conn,"127.0.0.1","igem","uestc2014!","CasDB",3306,NULL,0)){
#endif
        cJSON *root=cJSON_Parse(argv[1]);
        if(root==NULL){
            printf("N4");
            return 1;
        }

        char Sno[15],SName[100+1];
        strcpy(SName,cJSON_GetObjectItem(root,"specie")->valuestring);
		if(strcmp(argv[2],"0")==0) sprintf(buffer,"INSERT INTO Table_Specie(SName) VALUES('%s-%s'); ",argv[2],SName);
        else sprintf(buffer,"INSERT INTO Table_Specie(SName,user_id) VALUES('%s-%s',%s); ",argv[2],SName,argv[2]);
        printf("%s-%s",argv[2],SName);
        mysql_query(my_conn,buffer);
        result=mysql_store_result(my_conn);
        mysql_free_result(result);
        mysql_query(my_conn,"SELECT LAST_INSERT_ID(); ");
        result=mysql_store_result(my_conn);
        sql_row=mysql_fetch_row(result);
        strcpy(Sno,sql_row[0]);
        mysql_free_result(result);
printf("\n%s\n",Sno);
        char pam[20+1],pam_id[15];
        strcpy(pam,cJSON_GetObjectItem(root,"PAM")->valuestring);
        get_pam_info(pam_id,pam);
        int req_pam_len=strlen(pam);

        cJSON *files=cJSON_GetObjectItem(root,"files");
        int len=cJSON_GetArraySize(files);

        for(int k=0;k<len;k++){
            char Chr_No[15];
            cJSON *node=cJSON_GetArrayItem(files,k);
            sprintf(buffer,"INSERT INTO Table_chromosome(SNo,Chr_Name) VALUES('%s','%s'); ",Sno,cJSON_GetObjectItem(node,"fileName")->valuestring);
            mysql_query(my_conn,buffer);
            mysql_query(my_conn,"SELECT LAST_INSERT_ID(); ");
            result=mysql_store_result(my_conn);
            sql_row=mysql_fetch_row(result);
            strcpy(Chr_No,sql_row[0]);
            mysql_free_result(result);

                if(strcmp(argv[2],"0")==0 && cJSON_GetObjectItem(node,"filePath")) sprintf(buffer,cJSON_GetObjectItem(node,"filePath")-valuestring);
                else sprintf(buffer,"../uploaddata/%d",getFileID(argv[2],cJSON_GetObjectItem(node,"fileName")->valuestring));
printf("%s\n",buffer);
                FILE *ff=fopen(buffer,"r");
                readLine(ff);
                int i=1,j;
                int len;
                char ch;
                while(fscanf(ff,"%c",&ch)==1){
                    if(ch==10) continue;
                    str[i++]=ch;
                }
                str[i]=0;
                len=i;
                fclose(ff);

                char thispam[20],nt[LEN+1];
                for(i=LEN;i<len-req_pam_len;i++){       // All possible gRNAs, +direction
                    if(check_pam(str+i,pam)){
                        for(j=0;j<LEN;j++) nt[j]=(str+i-LEN)[j];
                        nt[j]=0;
                        for(j=0;j<req_pam_len;j++) thispam[j]=(str+i)[j];
                        thispam[j]=0;   //(Chr_No, sgrna_start, sgrna_end, sgrna_strand, sgrna_seq, sgrna_PAM, pam_id)
                        sprintf(buffer,"(%s, %d, %d, '%c', '%s', '%s', %s)",Chr_No,i-LEN,i-1+req_pam_len,'+',nt,thispam,pam_id);
                        add(buffer);
                        count++;
                    }
                }
                char req_pam_rev[PAM_LEN];
                dna_rev(req_pam_rev,pam,req_pam_len);
                for(i=0;i<len-LEN-req_pam_len;i++){     // All possible gRNAs, -direction
                    if(check_pam(str+i,req_pam_rev)){
                        for(j=0;j<LEN;j++) nt[j]=dna_rev_char((str+i+req_pam_len)[LEN-j-1]);
                        nt[j]=0;
                        for(j=0;j<req_pam_len;j++) thispam[j]=dna_rev_char((str+i)[req_pam_len-j-1]);
                        thispam[j]=0;
                        sprintf(buffer,"(%s, %d, %d, '%c', '%s', '%s', %s)",Chr_No,i,i+req_pam_len+LEN-1,'-',nt,thispam,pam_id);
                        add(buffer);
                        count++;
                    }
                }
        }
        finish();
    }
    mysql_close(my_conn);

    return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mysql.h"
#include "cJSON/cJSON.h"

#define LEN 20
#define GENE_LEN 80000000
#define PAM_LEN 20

int check_pam(const char *str,const char *pam){
    for(;*pam;pam++,str++){
        if(*pam=='R' && (*str=='A' || *str=='G')) continue;
        if(*pam=='M' && (*str=='A' || *str=='C')) continue;
        if(*pam=='W' && (*str=='A' || *str=='T')) continue;
        if(*pam=='S' && (*str=='C' || *str=='G')) continue;
        if(*pam=='K' && (*str=='G' || *str=='T')) continue;
        if(*pam=='Y' && (*str=='C' || *str=='T')) continue;
        if(*pam=='H' && (*str=='A' || *str=='C' || *str=='T')) continue;
        if(*pam=='V' && (*str=='A' || *str=='C' || *str=='G')) continue;
        if(*pam=='B' && (*str=='C' || *str=='G' || *str=='T')) continue;
        if(*pam=='D' && (*str=='A' || *str=='G' || *str=='T')) continue;
        if(*pam=='N' || *pam=='n') continue;
        if(*pam==*str) continue;
        return 0;
    }
    return 1;
}

char dna_rev_char(char ch){
    if(ch=='A' || ch=='a') return 'T';
    if(ch=='T' || ch=='t') return 'A';
    if(ch=='C' || ch=='c') return 'G';
    if(ch=='G' || ch=='g') return 'C';
    return 'N';
}

char *dna_rev(char *sr,const char *s,int len){
    int i;
    for(i=0;i<len;i++){
        sr[i]=dna_rev_char(s[len-i-1]);
    }
    sr[i]=0;
    return sr;
}

int readLine(FILE *file){
    char ch;
    while(fscanf(file,"%c",&ch)==1) if(ch=='\n') return 1;
    return 0;
}

char *_tos(char *str){
    for(char *p=str;*p;p++){
        if(*p=='_') *p++=' ';
    }
    return str;
}

char str[GENE_LEN];
char buffer[9182];

MYSQL *my_conn;
MYSQL_RES *result;
MYSQL_ROW sql_row;

void get_pam_info(char pam_id[],const char pam[]){
    sprintf(buffer,"SELECT pam_id FROM Table_PAM WHERE pam_PAM='%s'; ",pam);
    mysql_query(my_conn,buffer);
    result=mysql_store_result(my_conn);
    sql_row=mysql_fetch_row(result);
    strcpy(pam_id,sql_row[0]);
}

int sum=0;
char sql[500000]="";
void add(char *str){
    if(sum==0){
        strcat(sql,"INSERT INTO Table_sgRNA (Chr_No, sgrna_start, sgrna_end, sgrna_strand, sgrna_seq, sgrna_PAM, pam_id) VALUES \n");
    }else{
        strcat(sql,",\n");
    }
    strcat(sql,str);
    sum=(sum+1)%500;
    if(sum==0){
        strcat(sql,"; \n");
        int res=mysql_query(my_conn,sql);
        if(res){
            printf("%s\n",mysql_error(my_conn));
        }
        sql[0]=0;
    }
}
void finish(){
    if(sum!=0){
        strcat(sql,"; \n");
        int res=mysql_query(my_conn,sql);
        if(res){
            printf("%s\n",mysql_error(my_conn));
            printf("%s\n",sql);
        }
        sql[0]=0;
    }
}

int getFileID(const char *user_ID,const char *fileName){
    char sql[1024];
    sprintf(sql,"SELECT upload_ID FROM user_upload WHERE user_id=%s AND upload_filename='%s'; ",user_ID,fileName);
    int res=mysql_query(my_conn,sql);
    if(res){
        return -1;
    }
    result=mysql_store_result(my_conn);
    if(result){
        sql_row=mysql_fetch_row(result);
        return atoi(sql_row[0]);
    }else{
        return -1;
    }
    return -1;
}

//char def1[]="{\"specie\":\"kkkk\",\"files\":[{\"fileName\":\"NC_01297\"}],\"PAM\":\"NGG\"}";
//char def2[]="8"
int main(int args, char *argv[]){
    if(args!=3){
        printf("N3");
        return 1;
    }

    int count=0;

    my_bool mb=false;
    my_conn=mysql_init(NULL);
    mysql_options(my_conn,MYSQL_SECURE_AUTH,&mb);
#ifdef  _WIN32
    if(mysql_real_connect(my_conn,"127.0.0.1","root","zy19930108","CasDB",3306,NULL,0)){
#endif
#ifdef  __linux
    if(mysql_real_connect(my_conn,"127.0.0.1","igem","uestc2014!","CasDB",3306,NULL,0)){
#endif
        cJSON *root=cJSON_Parse(argv[1]);
        if(root==NULL){
            printf("N4");
            return 1;
        }

        char Sno[15],SName[100+1];
        strcpy(SName,cJSON_GetObjectItem(root,"specie")->valuestring);
		if(strcmp(argv[2],"0")==0) sprintf(buffer,"INSERT INTO Table_Specie(SName) VALUES('%s-%s'); ",argv[2],SName);
        else sprintf(buffer,"INSERT INTO Table_Specie(SName,user_id) VALUES('%s-%s',%s); ",argv[2],SName,argv[2]);
        printf("%s-%s",argv[2],SName);
        mysql_query(my_conn,buffer);
        result=mysql_store_result(my_conn);
        mysql_free_result(result);
        mysql_query(my_conn,"SELECT LAST_INSERT_ID(); ");
        result=mysql_store_result(my_conn);
        sql_row=mysql_fetch_row(result);
        strcpy(Sno,sql_row[0]);
        mysql_free_result(result);
printf("\n%s\n",Sno);
        char pam[20+1],pam_id[15];
        strcpy(pam,cJSON_GetObjectItem(root,"PAM")->valuestring);
        get_pam_info(pam_id,pam);
        int req_pam_len=strlen(pam);

        cJSON *files=cJSON_GetObjectItem(root,"files");
        int len=cJSON_GetArraySize(files);

        for(int k=0;k<len;k++){
            char Chr_No[15];
            cJSON *node=cJSON_GetArrayItem(files,k);
            sprintf(buffer,"INSERT INTO Table_chromosome(SNo,Chr_Name) VALUES('%s','%s'); ",Sno,cJSON_GetObjectItem(node,"fileName")->valuestring);
            mysql_query(my_conn,buffer);
            mysql_query(my_conn,"SELECT LAST_INSERT_ID(); ");
            result=mysql_store_result(my_conn);
            sql_row=mysql_fetch_row(result);
            strcpy(Chr_No,sql_row[0]);
            mysql_free_result(result);

                if(strcmp(argv[2],"0")==0 && cJSON_GetObjectItem(node,"filePath")) sprintf(buffer,cJSON_GetObjectItem(node,"filePath")->valuestring);
                else sprintf(buffer,"../uploaddata/%d",getFileID(argv[2],cJSON_GetObjectItem(node,"fileName")->valuestring));
printf("%s\n",buffer);
                FILE *ff=fopen(buffer,"r");
                readLine(ff);
                int i=1,j;
                int len;
                char ch;
                while(fscanf(ff,"%c",&ch)==1){
                    if(ch==10) continue;
                    str[i++]=ch;
                }
                str[i]=0;
                len=i;
                fclose(ff);

                char thispam[20],nt[LEN+1];
                for(i=LEN;i<len-req_pam_len;i++){       // All possible gRNAs, +direction
                    if(check_pam(str+i,pam)){
                        for(j=0;j<LEN;j++) nt[j]=(str+i-LEN)[j];
                        nt[j]=0;
                        for(j=0;j<req_pam_len;j++) thispam[j]=(str+i)[j];
                        thispam[j]=0;   //(Chr_No, sgrna_start, sgrna_end, sgrna_strand, sgrna_seq, sgrna_PAM, pam_id)
                        sprintf(buffer,"(%s, %d, %d, '%c', '%s', '%s', %s)",Chr_No,i-LEN,i-1+req_pam_len,'+',nt,thispam,pam_id);
                        add(buffer);
                        count++;
                    }
                }
                char req_pam_rev[PAM_LEN];
                dna_rev(req_pam_rev,pam,req_pam_len);
                for(i=0;i<len-LEN-req_pam_len;i++){     // All possible gRNAs, -direction
                    if(check_pam(str+i,req_pam_rev)){
                        for(j=0;j<LEN;j++) nt[j]=dna_rev_char((str+i+req_pam_len)[LEN-j-1]);
                        nt[j]=0;
                        for(j=0;j<req_pam_len;j++) thispam[j]=dna_rev_char((str+i)[req_pam_len-j-1]);
                        thispam[j]=0;
                        sprintf(buffer,"(%s, %d, %d, '%c', '%s', '%s', %s)",Chr_No,i,i+req_pam_len+LEN-1,'-',nt,thispam,pam_id);
                        add(buffer);
                        count++;
                    }
                }
        }
        finish();
    }
    mysql_close(my_conn);

    return 0;
}
<|endoftext|>


<commit_before>/*
exception.cpp
*/
/*
Copyright © 2016 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// BUGBUG
#include "platform.headers.hpp"

// Self:
#include "exception.hpp"

// Internal:
#include "imports.hpp"
#include "encoding.hpp"
#include "log.hpp"

// Platform:
#include "platform.debug.hpp"

// Common:
#include "common/string_utils.hpp"

// External:
#include "format.hpp"

//----------------------------------------------------------------------------

error_state last_error()
{
	return
	{
		errno,
		GetLastError(),
		os::get_last_nt_status(),
	};
}

string error_state::ErrnoStr() const
{
	return os::format_errno(Errno);
}

string error_state::Win32ErrorStr() const
{
	return os::format_error(Win32Error);
}

string error_state::NtErrorStr() const
{
	return os::format_ntstatus(NtError);
}

std::array<string, 3> error_state::format_errors() const
{
	return
	{
		ErrnoStr(),
		Win32ErrorStr(),
		NtErrorStr()
	};
}

string error_state::to_string() const
{
	const auto Errors = format_errors();
	return format(FSTR(L"Errno: {}, Win32 error: {}, NT error: {}"sv), Errors[0], Errors[1], Errors[2]);
}

namespace detail
{
	string far_base_exception::to_string() const
	{
		return any()?
			format(FSTR(L"far_base_exception: {}, Error: {}"sv), full_message(), error_state_ex::to_string()) :
			format(FSTR(L"far_base_exception: {}"sv), full_message());
	}

	far_base_exception::far_base_exception(bool const CaptureErrors, string_view const Message, std::string_view const Function, std::string_view const File, int const Line):
		error_state_ex(CaptureErrors? last_error(): error_state{}, Message),
		m_Function(Function),
		m_Location(format(FSTR(L"{}({})"sv), encoding::utf8::get_chars(File), Line)),
		m_FullMessage(format(FSTR(L"{} ({}, {})"sv), Message, encoding::utf8::get_chars(m_Function), m_Location))
	{
		LOGTRACE(L"{}"sv, *this);
	}

	std::string far_std_exception::convert_message() const
	{
		return encoding::utf8::get_bytes(full_message());
	}

	break_into_debugger::break_into_debugger()
	{
		os::debug::breakpoint(false);
	}
}

string error_state_ex::format_error() const
{
	if (!any())
		return What;

	auto Str = What;

	if (!Str.empty())
		append(Str, L": "sv);

	constexpr auto UseNtMessages = false;

	return Str + (UseNtMessages? NtErrorStr() : Win32ErrorStr());
}

string error_state_ex::to_string() const
{
	return any()?
		format(FSTR(L"Message: {}, Error: {}"sv), What, error_state::to_string()) :
		format(FSTR(L"Message: {}"sv), What);
}

string formattable<std::exception>::to_string(std::exception const& e)
{
	return ::format(FSTR(L"std::exception: {}"sv), encoding::utf8::get_chars(e.what()));
}

<commit_msg>Build<commit_after>/*
exception.cpp
*/
/*
Copyright © 2016 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// BUGBUG
#include "platform.headers.hpp"

// Self:
#include "exception.hpp"

// Internal:
#include "imports.hpp"
#include "encoding.hpp"
#include "log.hpp"

// Platform:
#include "platform.debug.hpp"

// Common:
#include "common/string_utils.hpp"

// External:
#include "format.hpp"

//----------------------------------------------------------------------------

error_state last_error()
{
	return
	{
		errno,
		GetLastError(),
		os::get_last_nt_status(),
	};
}

string error_state::ErrnoStr() const
{
	return os::format_errno(Errno);
}

string error_state::Win32ErrorStr() const
{
	return os::format_error(Win32Error);
}

string error_state::NtErrorStr() const
{
	return os::format_ntstatus(NtError);
}

std::array<string, 3> error_state::format_errors() const
{
	return
	{
		ErrnoStr(),
		Win32ErrorStr(),
		NtErrorStr()
	};
}

string error_state::to_string() const
{
	const auto Errors = format_errors();
	return format(FSTR(L"Errno: {}, Win32 error: {}, NT error: {}"sv), Errors[0], Errors[1], Errors[2]);
}

namespace detail
{
	string far_base_exception::to_string() const
	{
		return any()?
			format(FSTR(L"far_base_exception: {}, Error: {}"sv), full_message(), error_state_ex::to_string()) :
			format(FSTR(L"far_base_exception: {}"sv), full_message());
	}

	far_base_exception::far_base_exception(bool const CaptureErrors, string_view const Message, std::string_view const Function, std::string_view const File, int const Line):
		error_state_ex(CaptureErrors? last_error(): error_state{}, Message),
		m_Function(Function),
		m_Location(format(FSTR(L"{}({})"sv), encoding::utf8::get_chars(File), Line)),
		m_FullMessage(format(FSTR(L"{} ({}, {})"sv), Message, encoding::utf8::get_chars(m_Function), m_Location))
	{
		LOGTRACE(L"{}"sv, *this);
	}

	std::string far_std_exception::convert_message() const
	{
		return encoding::utf8::get_bytes(full_message());
	}

	break_into_debugger::break_into_debugger()
	{
		os::debug::breakpoint(false);
	}
}

string error_state_ex::format_error() const
{
	if (!any())
		return What;

	auto Str = What;

	if (!Str.empty())
		append(Str, L": "sv);

	constexpr auto UseNtMessages = false;

	return Str + (UseNtMessages? NtErrorStr() : Win32ErrorStr());
}

string error_state_ex::to_string() const
{
	return any()?
		format(FSTR(L"Message: {}, Error: {}"sv), What, error_state::to_string()) :
		format(FSTR(L"Message: {}"sv), What);
}

string formattable<std::exception>::to_string(std::exception const& e)
{
	return ::format(FSTR(L"std::exception: {}"sv), encoding::utf8::get_chars(e.what()));
}
<|endoftext|>


<commit_before>#include "Machine.hpp"
#include "registerAddr.hpp"
#include <unistd.h>

#define DEBUG_LOOP 1
#define DEBUG_ROM 1
#define DEBUG_GPU

htype	Machine::_hardware = AUTO;

/*
** ############################################################################
** PUBLIC Function
** ############################################################################
*/
Machine::Machine(void) :
	_memory(new Memory()),
	_cyclesMax(Cpu_z80::getClockSpeed()),
	_cyclesAcc(0)
{
	_cpu = new Cpu_z80(_memory);
	_gpu = new Gpu(_memory);
	_clock = new Timer(_memory);
	this->_cpu->init();
}

bool Machine::step(void)
{
	this->_cpu->execInterrupt();
	if (!this->_cpu->getHalt() && !this->_cpu->getStop())
	{
		unsigned int cycles = this->_cpu->executeNextOpcode();
		_cyclesAcc += cycles;

		this->_clock->step(cycles);
		this->_gpu->step();
		this->_gpu->accClock(cycles);
		this->_cpu->execInterrupt();

		if (_cyclesAcc >= _cyclesMax / 60)
		{
			_cyclesAcc -= _cyclesMax / 60;
			usleep(16000);
		}
	}
	return (true);
}

void Machine::run(void)
{
	this->step();
	this->run();
}

void Machine::setHardware(htype hardware)
{
	_hardware = hardware;
}
<commit_msg>comment usleep<commit_after>#include "Machine.hpp"
#include "registerAddr.hpp"
#include <unistd.h>

#define DEBUG_LOOP 1
#define DEBUG_ROM 1
#define DEBUG_GPU

htype	Machine::_hardware = AUTO;

/*
** ############################################################################
** PUBLIC Function
** ############################################################################
*/
Machine::Machine(void) :
	_memory(new Memory()),
	_cyclesMax(Cpu_z80::getClockSpeed()),
	_cyclesAcc(0)
{
	_cpu = new Cpu_z80(_memory);
	_gpu = new Gpu(_memory);
	_clock = new Timer(_memory);
	this->_cpu->init();
}

bool Machine::step(void)
{
	this->_cpu->execInterrupt();
	if (!this->_cpu->getHalt() && !this->_cpu->getStop())
	{
		unsigned int cycles = this->_cpu->executeNextOpcode();
		_cyclesAcc += cycles;

		this->_clock->step(cycles);
		this->_gpu->step();
		this->_gpu->accClock(cycles);
		this->_cpu->execInterrupt();

		if (_cyclesAcc >= _cyclesMax / 60)
		{
			_cyclesAcc -= _cyclesMax / 60;
			// TODO: usleep(16000);
		}
	}
	return (true);
}

void Machine::run(void)
{
	this->step();
	this->run();
}

void Machine::setHardware(htype hardware)
{
	_hardware = hardware;
}
<|endoftext|>


<commit_before>/*
  aimcontact.cpp  -  Oscar Protocol Plugin

  Copyright (c) 2003 by Will Stephenson
  Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.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.                                   *
  *                                                                       *
  *************************************************************************
*/

#include <time.h>

#include <qapplication.h>
#include <qregexp.h>

#include <kactionclasses.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>

#include "kopeteaway.h"
#include "kopetemessagemanager.h"
#include "kopeteuiglobal.h"
#include "kopetemetacontact.h"
#include "aimprotocol.h"
#include "aimcontact.h"
#include "aimaccount.h"
#include "aimuserinfo.h"
#include "aim.h" //for tocNormalize

AIMContact::AIMContact(const QString name, const QString displayName, AIMAccount *acc, KopeteMetaContact *parent)
	 : OscarContact(name, displayName, acc, parent)
{
	mProtocol=static_cast<AIMProtocol *>(protocol());
	setOnlineStatus(mProtocol->statusOffline);

	mUserProfile="";
	infoDialog=0L;

	// Contact changed his online status
	QObject::connect(
		acc->engine(), SIGNAL(gotContactChange(const UserInfo &)),
		this, SLOT(slotContactChanged(const UserInfo &)));

	// Incoming minitype notification
	QObject::connect(
		acc->engine(), SIGNAL(gotMiniTypeNotification(const QString &, OscarConnection::TypingNotify)),
		this, SLOT(slotGotMiniType(const QString &, OscarConnection::TypingNotify)));

	// received userprofile
	QObject::connect(
		acc->engine(), SIGNAL(gotUserProfile(const UserInfo &, const QString &, const QString &)),
		this, SLOT(slotGotProfile(const UserInfo &, const QString &, const QString &)));

	/*kdDebug(14190) << k_funcinfo <<
		"contactName()='" << contactName() <<
		"', displayName()='" << displayName << "'" << endl;*/
	actionRequestAuth = 0L;
}

AIMContact::~AIMContact()
{
}

void AIMContact::setOwnProfile(const QString &profile)
{
	kdDebug(14200) << k_funcinfo << "Called." << endl;
	if(this == account()->myself())
	{
		mUserProfile = profile;
		if(mAccount->isConnected())
			mAccount->engine()->sendLocationInfo(mUserProfile);
	}
}

void AIMContact::slotGotProfile(const UserInfo &user, const QString &profile, const QString &away)
{
	if(tocNormalize(user.sn) != contactName())
		return;
	kdDebug(14200) << k_funcinfo << "Called for contact '" << displayName() << "'" << endl;
	mUserProfile = profile;
	setAwayMessage(away);
	if ( metaContact()->isTemporary() && onlineStatus().internalStatus() == OSCAR_OFFLINE && user.onlinesince.isValid() )
	{
		kdDebug(14150) << k_funcinfo << "Attempting to set status to online for temp contact" << endl;
		setStatus(OSCAR_ONLINE);
	}

	emit updatedProfile();
}

bool AIMContact::isReachable()
{
	return true;
	//return isOnline();
}

QPtrList<KAction> *AIMContact::customContextMenuActions()
{
	QPtrList<KAction> *actionCollection = new QPtrList<KAction>();

	if(!actionRequestAuth)
	{
		actionRequestAuth = new KAction(i18n("&Request Authorization"), "mail_reply", 0,
			this, SLOT(slotRequestAuth()), this, "actionRequestAuth");
		actionSendAuth = new KAction(i18n("&Send Authorization"), "mail_forward", 0,
			this, SLOT(slotSendAuth()), this, "actionSendAuth");
		actionWarn = new KAction(i18n("&Warn"), 0,
			this, SLOT(slotWarn()), this, "actionWarn");
		actionInvisibleTo = new KToggleAction(i18n("&Block"), "", 0,
			this, SLOT(slotInvisibleTo()), this, "actionInvisibleTo");
		/*KAction* actionDirectConnect = new KAction(i18n("&Direct IM"), 0,
			this, SLOT(slotDirectConnect()), this, "actionDirectConnect");*/
	}

	actionRequestAuth->setEnabled(isOnline());
	actionSendAuth->setEnabled(isOnline());
	actionWarn->setEnabled(isOnline());

	actionCollection->append(actionRequestAuth);
	actionCollection->append(actionSendAuth);
	actionCollection->append(actionWarn);
	actionCollection->append(actionInvisibleTo);
	//actionCollection->insert(actionDirectConnect);

	return actionCollection;
}

KopeteMessageManager* AIMContact::manager(bool)
{
	//kdDebug(14190) << k_funcinfo << "called" << endl;
	// Check to see if we already have a message manager
	if (!mMsgManager)
	{
		// The true flag here is to tell OscarContact that
		// it can create the message mananger if it
		// doesn't exist, which is the case here.
		OscarContact::manager(true);

		// Connect the typing signal to the slot here
		QObject::connect(mMsgManager, SIGNAL(typingMsg(bool)),
			this, SLOT(slotTyping(bool)));
	}

	// Return the message manager
	return mMsgManager;
}

void AIMContact::setStatus(const unsigned int newStatus)
{
	if(onlineStatus().internalStatus() == newStatus)
		return;

	switch(newStatus)
	{
		case OSCAR_OFFLINE:
			setOnlineStatus(mProtocol->statusOffline);
			break;
		case OSCAR_AWAY:
			setOnlineStatus(mProtocol->statusAway);
			break;
		case OSCAR_CONNECTING:
			setOnlineStatus(mProtocol->statusConnecting);
			break;
		default: // emergency choose, also OSCAR_ONLINE
			setOnlineStatus(mProtocol->statusOnline);
	}

//	kdDebug(14190) << k_funcinfo << "'" << displayName() << "' is now " <<
//		onlineStatus().description() << endl;
}

void AIMContact::slotTyping(bool typing)
{
//	kdDebug(14190) << k_funcinfo << "Typing: " << typing << endl;
	mAccount->engine()->sendMiniTypingNotify(contactName(),
		typing ? OscarSocket::TypingBegun : OscarSocket::TypingFinished );
}

// Called when we get a minityping notification
void AIMContact::slotGotMiniType(const QString &screenName, OscarConnection::TypingNotify type)
{
	// Check to see if it's us
	if(tocNormalize(screenName) != contactName())
		return;

//	kdDebug(14190) << k_funcinfo << "Got minitype notification for " << contactName() << endl;

	// Only if we already have a message manager
	if(mMsgManager == 0L)
		return;

	switch(type)
	{
		case (OscarConnection::TypingFinished):
		case (OscarConnection::TextTyped): // Both of these are types of "not typing"
			mMsgManager->receivedTypingMsg(this, false);
			break;
		case (OscarConnection::TypingBegun): // Typing started
			mMsgManager->receivedTypingMsg(this, true);
			break;
		default:
			break;
	}
}

void AIMContact::slotContactChanged(const UserInfo &u)
{
	if (tocNormalize(u.sn) != contactName())
		return;

	// update mInfo and general stuff from OscarContact
	slotParseUserInfo(u);

	/*kdDebug(14190) << k_funcinfo << "Called for '"
		<< displayName() << "', contactName()=" << contactName() << endl;*/
	QStringList capList;
	// Append client name and version in case we found one
	if (!mInfo.clientName.isEmpty())
	{
		if (!mInfo.clientVersion.isEmpty())
		{
			capList << i18n("Translators: client-name client-version",
				"%1 %2").arg(mInfo.clientName, mInfo.clientVersion);
		}
		else
		{
			capList << mInfo.clientName;
		}
	}
	// and now for some general informative capabilities
	if (hasCap(CAP_BUDDYICON))
		capList << i18n("Buddyicons");
	if (hasCap(CAP_UTF8))
		capList << i18n("UTF-8");
	if (hasCap(CAP_RTFMSGS))
		capList << i18n("RTF-Messages");
	if (hasCap(CAP_CHAT))
		capList << i18n("Groupchat");
	if (hasCap(CAP_VOICE))
		capList << i18n("Voicechat");
	if (hasCap(CAP_IMIMAGE))
		capList << i18n("DirectIM/IMImage");
	if (hasCap(CAP_SENDBUDDYLIST))
		capList << i18n("Send Buddylist");
	if (hasCap(CAP_SENDFILE))
		capList << i18n("Send Files");
	if (hasCap(CAP_GETFILE))
		capList << i18n("Receive Files");

	if (capList.count() > 0)
		setProperty(mProtocol->clientFeatures, capList.join(", "));
	else
		removeProperty(mProtocol->clientFeatures);

	if(u.userclass & CLASS_AWAY)
	{
		if((this != account()->myself()) &&
		(account()->myself()->onlineStatus().status() != KopeteOnlineStatus::Connecting))
		{
			// request away message
			mAccount->engine()->sendUserLocationInfoRequest(contactName(),
				AIM_LOCINFO_AWAYMESSAGE);
		}
		setStatus(OSCAR_AWAY);
	}
	else
	{
		setStatus(OSCAR_ONLINE);
	}
}

void AIMContact::slotOffgoingBuddy(QString sn)
{
	if(tocNormalize(sn) != contactName())
		return;

	removeProperty(mProtocol->clientFeatures);
	removeProperty(mProtocol->awayMessage);

	setStatus(OSCAR_OFFLINE);
}

void AIMContact::slotSendMsg(KopeteMessage& message, KopeteMessageManager *)
{
	if (message.plainBody().isEmpty()) // no text, do nothing
		return;

	// ===================================================================================

	QString finalMessage = "";
	if(message.bg().isValid())
		finalMessage += "";
	else
		finalMessage += "";
	if(message.fg().isValid())
		finalMessage += "";
	if(!message.font().family().isEmpty())
		finalMessage += "";

	finalMessage += message.escapedBody().replace("
" , "
");

	if(!message.font().family().isEmpty())
		finalMessage += "";
	if(message.fg().isValid())
		finalMessage += "";
	finalMessage += "";
	finalMessage.replace(" ", " ");

	// ===================================================================================

	// Check to see if we're even online
	if(!mAccount->isConnected())
	{
		KMessageBox::sorry(Kopete::UI::Global::mainWidget(),
			i18n("<qt>You must be logged on to AIM before you can send a message to a user.</qt>"),
			i18n("Not Signed On"));
		return;
	}

	// Check to see if the person we're sending the message to is online

	if( onlineStatus().status() == KopeteOnlineStatus::Offline )
	{
		KMessageBox::sorry(Kopete::UI::Global::mainWidget(),
			i18n("<qt>This user is not online at the moment for you to message them. "
				"AIM users must be online for you to be able to message them.</qt>"),
			i18n("User Not Online"));
		return;
	}

	// FIXME: We don't do HTML in ICQ
	// we might be able to do that in AIM and we might also convert
	// HTML to RTF for ICQ type-2 messages  [mETz]
	// Will asks: Does this still apply in AIM?
	mAccount->engine()->sendIM(finalMessage, this, false);

	// Show the message we just sent in the chat window
	manager()->appendMessage(message);
	manager()->messageSucceeded();
}

void AIMContact::slotUserInfo()
{
	if (!infoDialog)
	{
		infoDialog = new AIMUserInfoDialog(this, static_cast<AIMAccount*>(account()),
			false, 0L, ( displayName() + "_userInfoDialog" ).latin1() );
		if(!infoDialog)
			return;
		connect(infoDialog, SIGNAL(closing()), this, SLOT(slotCloseUserInfoDialog()));
		infoDialog->show();
	}
	else
	{
		infoDialog->raise();
	}
}

void AIMContact::slotCloseUserInfoDialog()
{
	infoDialog->delayedDestruct();
	infoDialog = 0L;
}

void AIMContact::slotWarn()
{
	QString message = i18n( "<qt>Would you like to warn %1 anonymously or with your name?
" \
		"(Warning a user on AIM will result in a \"Warning Level\"" \
		" increasing for the user you warn. Once this level has reached a" \
		" certain point, they will not be able to sign on. Please do not abuse" \
		" this function, it is meant for legitimate practices.)</qt>" ).arg(displayName());

	int result = KMessageBox::questionYesNoCancel(
		Kopete::UI::Global::mainWidget(),
		message,
		i18n("Warn User %1?").arg(displayName()),
		i18n("Warn Anonymously"),
		i18n("Warn"));

	if (result == KMessageBox::Yes)
		mAccount->engine()->sendWarning(contactName(), true);
	else if (result == KMessageBox::No)
		mAccount->engine()->sendWarning(contactName(), false);
}

const QString AIMContact::awayMessage()
{
	return property(mProtocol->awayMessage).value().toString();
}

void AIMContact::setAwayMessage(const QString &message)
{
	/*kdDebug(14150) << k_funcinfo <<
		"Called for '" << displayName() << "', away msg='" << message << "'" << endl;*/
	setProperty(mProtocol->awayMessage, message);
	emit awayMessageChanged();
}

#include "aimcontact.moc"
<commit_msg>Show if AIM contacts are using a wireless client, do not display the normal client detection in this case<commit_after>/*
  aimcontact.cpp  -  Oscar Protocol Plugin

  Copyright (c) 2003 by Will Stephenson
  Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.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.                                   *
  *                                                                       *
  *************************************************************************
*/

#include <time.h>

#include <qapplication.h>
#include <qregexp.h>

#include <kactionclasses.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>

#include "kopeteaway.h"
#include "kopetemessagemanager.h"
#include "kopeteuiglobal.h"
#include "kopetemetacontact.h"
#include "aimprotocol.h"
#include "aimcontact.h"
#include "aimaccount.h"
#include "aimuserinfo.h"
#include "aim.h" //for tocNormalize

AIMContact::AIMContact(const QString name, const QString displayName, AIMAccount *acc, KopeteMetaContact *parent)
	 : OscarContact(name, displayName, acc, parent)
{
	mProtocol=static_cast<AIMProtocol *>(protocol());
	setOnlineStatus(mProtocol->statusOffline);

	mUserProfile="";
	infoDialog=0L;

	// Contact changed his online status
	QObject::connect(
		acc->engine(), SIGNAL(gotContactChange(const UserInfo &)),
		this, SLOT(slotContactChanged(const UserInfo &)));

	// Incoming minitype notification
	QObject::connect(
		acc->engine(), SIGNAL(gotMiniTypeNotification(const QString &, OscarConnection::TypingNotify)),
		this, SLOT(slotGotMiniType(const QString &, OscarConnection::TypingNotify)));

	// received userprofile
	QObject::connect(
		acc->engine(), SIGNAL(gotUserProfile(const UserInfo &, const QString &, const QString &)),
		this, SLOT(slotGotProfile(const UserInfo &, const QString &, const QString &)));

	/*kdDebug(14190) << k_funcinfo <<
		"contactName()='" << contactName() <<
		"', displayName()='" << displayName << "'" << endl;*/
	actionRequestAuth = 0L;
}

AIMContact::~AIMContact()
{
}

void AIMContact::setOwnProfile(const QString &profile)
{
	kdDebug(14200) << k_funcinfo << "Called." << endl;
	if(this == account()->myself())
	{
		mUserProfile = profile;
		if(mAccount->isConnected())
			mAccount->engine()->sendLocationInfo(mUserProfile);
	}
}

void AIMContact::slotGotProfile(const UserInfo &user, const QString &profile, const QString &away)
{
	if(tocNormalize(user.sn) != contactName())
		return;
	kdDebug(14200) << k_funcinfo << "Called for contact '" << displayName() << "'" << endl;
	mUserProfile = profile;
	setAwayMessage(away);
	if ( metaContact()->isTemporary() && onlineStatus().internalStatus() == OSCAR_OFFLINE && user.onlinesince.isValid() )
	{
		kdDebug(14150) << k_funcinfo << "Attempting to set status to online for temp contact" << endl;
		setStatus(OSCAR_ONLINE);
	}

	emit updatedProfile();
}

bool AIMContact::isReachable()
{
	return true;
	//return isOnline();
}

QPtrList<KAction> *AIMContact::customContextMenuActions()
{
	QPtrList<KAction> *actionCollection = new QPtrList<KAction>();

	if(!actionRequestAuth)
	{
		actionRequestAuth = new KAction(i18n("&Request Authorization"), "mail_reply", 0,
			this, SLOT(slotRequestAuth()), this, "actionRequestAuth");
		actionSendAuth = new KAction(i18n("&Send Authorization"), "mail_forward", 0,
			this, SLOT(slotSendAuth()), this, "actionSendAuth");
		actionWarn = new KAction(i18n("&Warn"), 0,
			this, SLOT(slotWarn()), this, "actionWarn");
		actionInvisibleTo = new KToggleAction(i18n("&Block"), "", 0,
			this, SLOT(slotInvisibleTo()), this, "actionInvisibleTo");
		/*KAction* actionDirectConnect = new KAction(i18n("&Direct IM"), 0,
			this, SLOT(slotDirectConnect()), this, "actionDirectConnect");*/
	}

	actionRequestAuth->setEnabled(isOnline());
	actionSendAuth->setEnabled(isOnline());
	actionWarn->setEnabled(isOnline());

	actionCollection->append(actionRequestAuth);
	actionCollection->append(actionSendAuth);
	actionCollection->append(actionWarn);
	actionCollection->append(actionInvisibleTo);
	//actionCollection->insert(actionDirectConnect);

	return actionCollection;
}

KopeteMessageManager* AIMContact::manager(bool)
{
	//kdDebug(14190) << k_funcinfo << "called" << endl;
	// Check to see if we already have a message manager
	if (!mMsgManager)
	{
		// The true flag here is to tell OscarContact that
		// it can create the message mananger if it
		// doesn't exist, which is the case here.
		OscarContact::manager(true);

		// Connect the typing signal to the slot here
		QObject::connect(mMsgManager, SIGNAL(typingMsg(bool)),
			this, SLOT(slotTyping(bool)));
	}

	// Return the message manager
	return mMsgManager;
}

void AIMContact::setStatus(const unsigned int newStatus)
{
	if(onlineStatus().internalStatus() == newStatus)
		return;

	switch(newStatus)
	{
		case OSCAR_OFFLINE:
			setOnlineStatus(mProtocol->statusOffline);
			break;
		case OSCAR_AWAY:
			setOnlineStatus(mProtocol->statusAway);
			break;
		case OSCAR_CONNECTING:
			setOnlineStatus(mProtocol->statusConnecting);
			break;
		default: // emergency choose, also OSCAR_ONLINE
			setOnlineStatus(mProtocol->statusOnline);
	}

//	kdDebug(14190) << k_funcinfo << "'" << displayName() << "' is now " <<
//		onlineStatus().description() << endl;
}

void AIMContact::slotTyping(bool typing)
{
//	kdDebug(14190) << k_funcinfo << "Typing: " << typing << endl;
	mAccount->engine()->sendMiniTypingNotify(contactName(),
		typing ? OscarSocket::TypingBegun : OscarSocket::TypingFinished );
}

// Called when we get a minityping notification
void AIMContact::slotGotMiniType(const QString &screenName, OscarConnection::TypingNotify type)
{
	// Check to see if it's us
	if(tocNormalize(screenName) != contactName())
		return;

//	kdDebug(14190) << k_funcinfo << "Got minitype notification for " << contactName() << endl;

	// Only if we already have a message manager
	if(mMsgManager == 0L)
		return;

	switch(type)
	{
		case (OscarConnection::TypingFinished):
		case (OscarConnection::TextTyped): // Both of these are types of "not typing"
			mMsgManager->receivedTypingMsg(this, false);
			break;
		case (OscarConnection::TypingBegun): // Typing started
			mMsgManager->receivedTypingMsg(this, true);
			break;
		default:
			break;
	}
}

void AIMContact::slotContactChanged(const UserInfo &u)
{
	if (tocNormalize(u.sn) != contactName())
		return;

	// update mInfo and general stuff from OscarContact
	slotParseUserInfo(u);

	/*kdDebug(14190) << k_funcinfo << "Called for '"
		<< displayName() << "', contactName()=" << contactName() << endl;*/
	QStringList capList;
	// Append client name and version in case we found one
	if(u.userclass & CLASS_WIRELESS)
		capList << i18n("Mobile AIM Client");
	else
	{
		if (!mInfo.clientName.isEmpty())
		{
			if (!mInfo.clientVersion.isEmpty())
			{
				capList << i18n("Translators: client-name client-version",
					"%1 %2").arg(mInfo.clientName, mInfo.clientVersion);
			}
			else
			{
				capList << mInfo.clientName;
			}
		}
	}
	// and now for some general informative capabilities
	if (hasCap(CAP_BUDDYICON))
		capList << i18n("Buddyicons");
	if (hasCap(CAP_UTF8))
		capList << i18n("UTF-8");
	if (hasCap(CAP_RTFMSGS))
		capList << i18n("RTF-Messages");
	if (hasCap(CAP_CHAT))
		capList << i18n("Groupchat");
	if (hasCap(CAP_VOICE))
		capList << i18n("Voicechat");
	if (hasCap(CAP_IMIMAGE))
		capList << i18n("DirectIM/IMImage");
	if (hasCap(CAP_SENDBUDDYLIST))
		capList << i18n("Send Buddylist");
	if (hasCap(CAP_SENDFILE))
		capList << i18n("Send Files");
	if (hasCap(CAP_GETFILE))
		capList << i18n("Receive Files");

	if (capList.count() > 0)
		setProperty(mProtocol->clientFeatures, capList.join(", "));
	else
		removeProperty(mProtocol->clientFeatures);

	if(u.userclass & CLASS_AWAY)
	{
		if((this != account()->myself()) &&
		(account()->myself()->onlineStatus().status() != KopeteOnlineStatus::Connecting))
		{
			// request away message
			mAccount->engine()->sendUserLocationInfoRequest(contactName(),
				AIM_LOCINFO_AWAYMESSAGE);
		}
		setStatus(OSCAR_AWAY);
	}
	else
	{
		setStatus(OSCAR_ONLINE);
	}
}

void AIMContact::slotOffgoingBuddy(QString sn)
{
	if(tocNormalize(sn) != contactName())
		return;

	removeProperty(mProtocol->clientFeatures);
	removeProperty(mProtocol->awayMessage);

	setStatus(OSCAR_OFFLINE);
}

void AIMContact::slotSendMsg(KopeteMessage& message, KopeteMessageManager *)
{
	if (message.plainBody().isEmpty()) // no text, do nothing
		return;

	// ===================================================================================

	QString finalMessage = "";
	if(message.bg().isValid())
		finalMessage += "";
	else
		finalMessage += "";
	if(message.fg().isValid())
		finalMessage += "";
	if(!message.font().family().isEmpty())
		finalMessage += "";

	finalMessage += message.escapedBody().replace("
" , "
");

	if(!message.font().family().isEmpty())
		finalMessage += "";
	if(message.fg().isValid())
		finalMessage += "";
	finalMessage += "";
	finalMessage.replace(" ", " ");

	// ===================================================================================

	// Check to see if we're even online
	if(!mAccount->isConnected())
	{
		KMessageBox::sorry(Kopete::UI::Global::mainWidget(),
			i18n("<qt>You must be logged on to AIM before you can send a message to a user.</qt>"),
			i18n("Not Signed On"));
		return;
	}

	// Check to see if the person we're sending the message to is online

	if( onlineStatus().status() == KopeteOnlineStatus::Offline )
	{
		KMessageBox::sorry(Kopete::UI::Global::mainWidget(),
			i18n("<qt>This user is not online at the moment for you to message them. "
				"AIM users must be online for you to be able to message them.</qt>"),
			i18n("User Not Online"));
		return;
	}

	// FIXME: We don't do HTML in ICQ
	// we might be able to do that in AIM and we might also convert
	// HTML to RTF for ICQ type-2 messages  [mETz]
	// Will asks: Does this still apply in AIM?
	mAccount->engine()->sendIM(finalMessage, this, false);

	// Show the message we just sent in the chat window
	manager()->appendMessage(message);
	manager()->messageSucceeded();
}

void AIMContact::slotUserInfo()
{
	if (!infoDialog)
	{
		infoDialog = new AIMUserInfoDialog(this, static_cast<AIMAccount*>(account()),
			false, 0L, ( displayName() + "_userInfoDialog" ).latin1() );
		if(!infoDialog)
			return;
		connect(infoDialog, SIGNAL(closing()), this, SLOT(slotCloseUserInfoDialog()));
		infoDialog->show();
	}
	else
	{
		infoDialog->raise();
	}
}

void AIMContact::slotCloseUserInfoDialog()
{
	infoDialog->delayedDestruct();
	infoDialog = 0L;
}

void AIMContact::slotWarn()
{
	QString message = i18n( "<qt>Would you like to warn %1 anonymously or with your name?
" \
		"(Warning a user on AIM will result in a \"Warning Level\"" \
		" increasing for the user you warn. Once this level has reached a" \
		" certain point, they will not be able to sign on. Please do not abuse" \
		" this function, it is meant for legitimate practices.)</qt>" ).arg(displayName());

	int result = KMessageBox::questionYesNoCancel(
		Kopete::UI::Global::mainWidget(),
		message,
		i18n("Warn User %1?").arg(displayName()),
		i18n("Warn Anonymously"),
		i18n("Warn"));

	if (result == KMessageBox::Yes)
		mAccount->engine()->sendWarning(contactName(), true);
	else if (result == KMessageBox::No)
		mAccount->engine()->sendWarning(contactName(), false);
}

const QString AIMContact::awayMessage()
{
	return property(mProtocol->awayMessage).value().toString();
}

void AIMContact::setAwayMessage(const QString &message)
{
	/*kdDebug(14150) << k_funcinfo <<
		"Called for '" << displayName() << "', away msg='" << message << "'" << endl;*/
	setProperty(mProtocol->awayMessage, message);
	emit awayMessageChanged();
}

#include "aimcontact.moc"
<|endoftext|>


<commit_before>/// DAC router
///
/// (c) Koheron

#ifndef __DRIVERS_LIB_DAC_ROUTER_HPP__
#define __DRIVERS_LIB_DAC_ROUTER_HPP__

#include "memory_manager.hpp"

constexpr uint32_t get_width(uint32_t n_dac_bram) {
    return ceil(log(float(n_dac_bram)) / log(2.));
}
static_assert(get_width(8) == 3, "get_width test failed");
static_assert(get_width(9) == 4, "get_width test failed");

template<uint32_t n_dac, uint32_t n_dac_bram>
class DacRouter
{
  public:
    DacRouter(MemoryManager& mm)
    : cfg(mm.get<mem::config>())
    , dac_map(mm.get<mem::dac>())
    {}

    void set_config_reg(uint32_t dac_select_off_, uint32_t addr_select_off_) {
        dac_select_off = dac_select_off_;
        addr_select_off = addr_select_off_;
        init_dac_brams();
    }

    template<size_t N>
    std::array<uint32_t, N>& get_data(uint32_t channel) {
        return dac_map.read_array<uint32_t, N>(bram_index[channel]);
    }

    /// /!\ Array is of size 1/2 of the number of samples in the waveform
    template<size_t N>
    void set_data(uint32_t channel, const std::array<uint32_t, N> arr) {
        uint32_t old_idx = bram_index[channel];
        uint32_t new_idx = get_first_empty_bram_index();
        dac_map.set_ptr(arr.data(), N, new_idx);
        switch_interconnect(channel, old_idx, new_idx);
    }

  private:
    Memory<mem::config>& cfg;
    uint32_t dac_select_off;
    uint32_t addr_select_off;
    Memory<mem::dac>& dac_map;
    std::array<uint32_t, n_dac> bram_index;
    std::array<bool, n_dac_bram> connected_bram;

    void init_dac_brams() {
        // Use BRAM0 for DAC0, BRAM1 for DAC1 ...
        for (uint32_t i=0; i < n_dac; i++) {
            bram_index[i] = i;
            connected_bram[i] = true;
        }
        for (uint32_t i=n_dac; i < n_dac_bram; i++) {
            connected_bram[i] = false;
        }
        update_dac_routing();
    }

    void update_dac_routing() {
        // dac_select defines the connection between BRAMs and DACs
        uint32_t dac_select = 0;
        for (uint32_t i=0; i < n_dac_bram; i++) {
            dac_select += bram_index[i] << (get_width(n_dac_bram) * i);
        }
        cfg.write_reg(dac_select_off, dac_select);

        // addr_select defines the connection between address generators and BRAMs
        uint32_t addr_select = 0;
        for (uint32_t j=0; j < n_dac_bram; j++) {
            addr_select += j << (get_width(n_dac) * bram_index[j]);
        }
        cfg.write_reg(addr_select_off, addr_select);
    }

    uint32_t get_first_empty_bram_index() {
        for (uint32_t i=0; i < n_dac_bram; i++) {
            // Check if the BRAM is connected to no
            bool empty = true;
            for (uint32_t j=0; j < n_dac; j++) {
                if (bram_index[j] == i) {
                    empty = false;
                    break;
                }
            }
            if (empty) {
                return i;
            }
        }
        return -1;
    }

    void switch_interconnect(uint32_t channel, uint32_t old_idx, uint32_t new_idx) {
        bram_index[channel] = new_idx;
        connected_bram[new_idx] = true;
        update_dac_routing();
        connected_bram[old_idx] = false;
    }

};

#endif // __DRIVERS_LIB_DAC_ROUTER_HPP__
<commit_msg>clean dac_router (#323)<commit_after>/// DAC router
///
/// (c) Koheron

#ifndef __DRIVERS_LIB_DAC_ROUTER_HPP__
#define __DRIVERS_LIB_DAC_ROUTER_HPP__

#include "memory_manager.hpp"

constexpr uint32_t get_width(uint32_t n_dac_bram) {
    return ceil(log(float(n_dac_bram)) / log(2.));
}
static_assert(get_width(8) == 3, "get_width test failed");
static_assert(get_width(9) == 4, "get_width test failed");

template<uint32_t n_dac, uint32_t n_dac_bram>
class DacRouter
{
  public:
    DacRouter(MemoryManager& mm)
    : cfg(mm.get<mem::config>())
    , dac_map(mm.get<mem::dac>())
    {}

    void set_config_reg(uint32_t dac_select_off_, uint32_t addr_select_off_) {
        dac_select_off = dac_select_off_;
        addr_select_off = addr_select_off_;
        init_dac_brams();
    }

    template<size_t N>
    std::array<uint32_t, N>& get_data(uint32_t channel) {
        return dac_map.read_array<uint32_t, N>(bram_index[channel]);
    }

    /// /!\ Array is of size 1/2 of the number of samples in the waveform
    template<size_t N>
    void set_data(uint32_t channel, const std::array<uint32_t, N> arr) {
        uint32_t new_idx = get_first_empty_bram();
        dac_map.set_ptr(arr.data(), N, new_idx);
        bram_index[channel] = new_idx;
        update_dac_routing();
    }

  private:
    Memory<mem::config>& cfg;
    uint32_t dac_select_off;
    uint32_t addr_select_off;
    Memory<mem::dac>& dac_map;
    std::array<uint32_t, n_dac> bram_index;

    void init_dac_brams() {
        // Use BRAM0 for DAC0, BRAM1 for DAC1 ...
        for (uint32_t i=0; i < n_dac; i++) {
            bram_index[i] = i;
        }
        update_dac_routing();
    }

    void update_dac_routing() {
        // dac_select defines the connection between BRAMs and DACs
        uint32_t dac_select = 0;
        for (uint32_t i=0; i < n_dac; i++) {
            dac_select += bram_index[i] << (get_width(n_dac_bram) * i);
        }
        cfg.write_reg(dac_select_off, dac_select);

        // addr_select defines the connection between address generators and BRAMs
        uint32_t addr_select = 0;
        for (uint32_t j=0; j < n_dac_bram; j++) {
            addr_select += get_addr_index(j) << (get_width(n_dac) * j);
        }
        cfg.write_reg(addr_select_off, addr_select);
    }

    uint32_t get_addr_index(uint32_t i) {
        for (uint32_t j=0; j < n_dac; j++) {
            if (bram_index[j] == i) {
                return j;
            }
        }
        return 0;
    }

    uint32_t get_first_empty_bram() {
        for (uint32_t i=0; i < n_dac_bram; i++) {
            // Check if the BRAM is connected to no
            bool empty = true;
            for (uint32_t j=0; j < n_dac; j++) {
                if (bram_index[j] == i) {
                    empty = false;
                    break;
                }
            }
            if (empty) {
                return i;
            }
        }
        return -1;
    }

};

#endif // __DRIVERS_LIB_DAC_ROUTER_HPP__
<|endoftext|>


<commit_before>
#include <stdarg.h>
#include <stdio.h>

#include "../imgui/imgui.h"

#if defined _WIN32 || defined __CYGWIN__
#define API __declspec(dllexport)
#else
#define API
#endif

extern "C" API ImGuiIO* ImGui_GetIO()
{
	return &ImGui::GetIO();
}

extern "C" API void ImGui_Shutdown()
{
	ImGui::Shutdown();
}

extern "C" API void ImGui_NewFrame()
{
	ImGui::NewFrame();
}

extern "C" API void ImGui_Render()
{
	ImGui::Render();
}

extern "C" API bool ImGui_Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
{
	return ImGui::Begin(name, p_opened, flags);
}

extern "C" API void ImGui_End()
{
	ImGui::End();
}

extern "C" API void ImGui_Text(const char* text, ...)
{
	char buffer[256];
  	va_list args;
  	va_start (args, text);
  	vsprintf (buffer, text, args);
  	va_end (args);

	ImGui::Text(buffer);
}

extern "C" API bool ImGui_ColorEdit3(const char* label, float col[3])
{
	return ImGui::ColorEdit3(label,col);
}

extern "C" API void ImGui_SetNextWindowSize(const ImVec2 size, ImGuiSetCond cond)
{
	ImGui::SetNextWindowSize(size, cond);
}

extern "C" API void ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
	ImGui::SliderFloat(label,v,v_min,v_max,display_format,power);
}

extern "C" API bool ImGui_Button(const char* label, const ImVec2& size, bool repeat_when_held)
{
	return ImGui::Button(label,size,repeat_when_held);
}

extern "C" API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* atlas, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
	atlas->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel);
}

extern "C" API void ImFontAtlas_SetTexID(ImFontAtlas* atlas, void* tex)
{
	atlas->TexID = tex;
}

extern "C" API int ImDrawList_GetVertexBufferSize(ImDrawList* list)
{
	return list->vtx_buffer.size();
}

extern "C" API ImDrawVert* ImDrawList_GetVertexPtr(ImDrawList* list, int n)
{
	return &list->vtx_buffer[n];
}

extern "C" API int ImDrawList_GetCmdSize(ImDrawList* list)
{
	return list->commands.size();
}

extern "C" API ImDrawCmd* ImDrawList_GetCmdPtr(ImDrawList* list, int n)
{
	return &list->commands[n];
}

extern "C" API void ImGuiIO_AddInputCharacter(unsigned short c)
{
	ImGui::GetIO().AddInputCharacter(c);
}
<commit_msg>support more methods<commit_after>
#include <stdarg.h>
#include <stdio.h>

#include "../imgui/imgui.h"

#if defined _WIN32 || defined __CYGWIN__
#define API __declspec(dllexport)
#else
#define API
#endif

extern "C" API ImGuiIO* ImGui_GetIO()
{
	return &ImGui::GetIO();
}

extern "C" API void ImGui_Shutdown()
{
	ImGui::Shutdown();
}

extern "C" API void ImGui_NewFrame()
{
	ImGui::NewFrame();
}

extern "C" API void ImGui_Render()
{
	ImGui::Render();
}

extern "C" API void ImGui_ShowTestWindow(bool* opened)
{
	ImGui::ShowTestWindow(opened);
}

extern "C" API bool ImGui_Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
{
	return ImGui::Begin(name, p_opened, flags);
}

extern "C" API void ImGui_End()
{
	ImGui::End();
}

extern "C" API void ImGui_Text(const char* text, ...)
{
	char buffer[256];
  	va_list args;
  	va_start (args, text);
  	vsprintf (buffer, text, args);
  	va_end (args);

	ImGui::Text(buffer);
}

extern "C" API bool ImGui_ColorEdit3(const char* label, float col[3])
{
	return ImGui::ColorEdit3(label,col);
}

extern "C" API void ImGui_SetNextWindowPos(const ImVec2 pos, ImGuiSetCond cond)
{
	ImGui::SetNextWindowPos(pos,cond);
}

extern "C" API void ImGui_SetNextWindowSize(const ImVec2 size, ImGuiSetCond cond)
{
	ImGui::SetNextWindowSize(size, cond);
}

extern "C" API void ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
	ImGui::SliderFloat(label,v,v_min,v_max,display_format,power);
}

extern "C" API bool ImGui_Button(const char* label, const ImVec2& size, bool repeat_when_held)
{
	return ImGui::Button(label,size,repeat_when_held);
}

extern "C" API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* atlas, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
	atlas->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel);
}

extern "C" API void ImFontAtlas_SetTexID(ImFontAtlas* atlas, void* tex)
{
	atlas->TexID = tex;
}

extern "C" API int ImDrawList_GetVertexBufferSize(ImDrawList* list)
{
	return list->vtx_buffer.size();
}

extern "C" API ImDrawVert* ImDrawList_GetVertexPtr(ImDrawList* list, int n)
{
	return &list->vtx_buffer[n];
}

extern "C" API int ImDrawList_GetCmdSize(ImDrawList* list)
{
	return list->commands.size();
}

extern "C" API ImDrawCmd* ImDrawList_GetCmdPtr(ImDrawList* list, int n)
{
	return &list->commands[n];
}

extern "C" API void ImGuiIO_AddInputCharacter(unsigned short c)
{
	ImGui::GetIO().AddInputCharacter(c);
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_L2_HH
#define DUNE_GDT_FUNCTIONALS_L2_HH

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/localfunctional/codim0.hh>
#include <dune/gdt/localfunctional/codim1.hh>
#include <dune/gdt/localevaluation/product.hh>
#include <dune/gdt/assembler/system.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace Functionals {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType>
class L2Volume;

namespace internal {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2VolumeTraits
{
  static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface<
                                    typename FunctionType::EntityType, typename FunctionType::DomainFieldType,
                                    FunctionType::dimDomain, typename FunctionType::RangeFieldType,
                                    FunctionType::dimRange, FunctionType::dimRangeCols>,
                                FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Volume<FunctionType, VectorImp, SpaceImp, GridViewImp> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2VolumeTraits

} // namespace internal

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2Volume
    : public Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>,
      public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>
      FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;

  typedef LocalFunctional::Codim0Integral<LocalEvaluation::Product<FunctionType>> LocalFunctionalType;
  typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp> Traits;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw)
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc)
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  virtual void assemble() DS_OVERRIDE DS_FINAL
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup()
  {
    this->add(local_assembler_, this->vector());
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Volume

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType>
class L2Face;

namespace internal {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2FaceTraits
{
  static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface<
                                    typename FunctionType::EntityType, typename FunctionType::DomainFieldType,
                                    FunctionType::dimDomain, typename FunctionType::RangeFieldType,
                                    FunctionType::dimRange, FunctionType::dimRangeCols>,
                                FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Face<FunctionType, VectorImp, SpaceImp, GridViewImp> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2FaceTraits

} // namespace internal

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2Face : public Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>,
               public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>
      FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;

  typedef LocalFunctional::Codim1Integral<LocalEvaluation::Product<FunctionType>> LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp> Traits;

  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw,
         const GDT::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new GDT::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc,
         const GDT::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new GDT::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  virtual void assemble() DS_OVERRIDE DS_FINAL
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup(const GDT::ApplyOn::WhichIntersection<GridViewType>* which_intersections)
  {
    this->add(local_assembler_, this->vector(), which_intersections);
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Face

} // namespace Functionals
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_L2_HH
<commit_msg>allows injecting evaluation type into L2 functional<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_L2_HH
#define DUNE_GDT_FUNCTIONALS_L2_HH

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/localfunctional/codim0.hh>
#include <dune/gdt/localfunctional/codim1.hh>
#include <dune/gdt/localevaluation/product.hh>
#include <dune/gdt/assembler/system.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace Functionals {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,
          class LocalEvaluationType                                              = LocalEvaluation::Product<FunctionType>>
class L2Volume;

namespace internal {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType>
class L2VolumeTraits
{
  static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface<
                                    typename FunctionType::EntityType, typename FunctionType::DomainFieldType,
                                    FunctionType::dimDomain, typename FunctionType::RangeFieldType,
                                    FunctionType::dimRange, FunctionType::dimRangeCols>,
                                FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Volume<FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2VolumeTraits

} // namespace internal

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType>
class L2Volume : public Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp,
                                                                          GridViewImp, LocalEvaluationType>>,
                 public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp,
                                                            LocalEvaluationType>> FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;

  typedef LocalFunctional::Codim0Integral<LocalEvaluationType> LocalFunctionalType;
  typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2VolumeTraits<FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType> Traits;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw)
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc)
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  virtual void assemble() DS_OVERRIDE DS_FINAL
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup()
  {
    this->add(local_assembler_, this->vector());
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Volume

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType>
class L2Face;

namespace internal {

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2FaceTraits
{
  static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface<
                                    typename FunctionType::EntityType, typename FunctionType::DomainFieldType,
                                    FunctionType::dimDomain, typename FunctionType::RangeFieldType,
                                    FunctionType::dimRange, FunctionType::dimRangeCols>,
                                FunctionType>::value,
                "FunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");

public:
  typedef L2Face<FunctionType, VectorImp, SpaceImp, GridViewImp> derived_type;
  typedef VectorImp VectorType;
  typedef SpaceImp SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class L2FaceTraits

} // namespace internal

template <class FunctionType, class VectorImp, class SpaceImp, class GridViewImp>
class L2Face : public Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>,
               public SystemAssembler<SpaceImp, GridViewImp, SpaceImp>
{
  typedef Functionals::VectorBased<internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp>>
      FunctionalBaseType;
  typedef SystemAssembler<SpaceImp, GridViewImp, SpaceImp> AssemblerBaseType;

  typedef LocalFunctional::Codim1Integral<LocalEvaluation::Product<FunctionType>> LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType;

public:
  typedef internal::L2FaceTraits<FunctionType, VectorImp, SpaceImp, GridViewImp> Traits;

  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw,
         const GDT::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new GDT::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc, grd_vw)
    , AssemblerBaseType(spc, grd_vw)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  L2Face(const FunctionType& function, VectorType& vec, const SpaceType& spc,
         const GDT::ApplyOn::WhichIntersection<GridViewType>* which_intersections =
             new GDT::ApplyOn::AllIntersections<GridViewType>())
    : FunctionalBaseType(vec, spc)
    , AssemblerBaseType(spc)
    , function_(function)
    , local_functional_(function_)
    , local_assembler_(local_functional_)
  {
    setup(which_intersections);
  }

  virtual void assemble() DS_OVERRIDE DS_FINAL
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup(const GDT::ApplyOn::WhichIntersection<GridViewType>* which_intersections)
  {
    this->add(local_assembler_, this->vector(), which_intersections);
  }

  const FunctionType& function_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class L2Face

} // namespace Functionals
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_L2_HH
<|endoftext|>