<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id$ */

//***********************************************************************
//
// It consist of a TClonesArray of
// AliITSpListItem objects
// This array can be accessed via 2 indexed
// it is used at digitization level by
// all the 3 ITS subdetectors
//
// ***********************************************************************

#include "AliITSpList.h"
#include "AliITSpListItem.h"

//______________________________________________________________________

ClassImp(AliITSpList)
//______________________________________________________________________
AliITSpList::AliITSpList(){
    // Default constructor
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    A zeroed/empty AliITSpList class.

    fNi = 0;
    fNj = 0;
    fa  = 0;
}
//______________________________________________________________________
AliITSpList::AliITSpList(Int_t imax,Int_t jmax){
    // Standard constructor
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    A setup AliITSpList class.

    fNi = imax;
    fNj = jmax;
    fEntries = 0;
    fa = new TClonesArray("AliITSpListItem",fNi*fNj);
}
//______________________________________________________________________
AliITSpList::~AliITSpList(){
    // Default destructor
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    a properly destroyed class

  if(fa){
    fa->Delete();
    delete fa;
    fa = 0;
  }
    fNi = 0;
    fNj = 0;

    fEntries = 0;
}

//______________________________________________________________________
void AliITSpList::ClearMap(){
    // Delete all AliITSpListItems and zero TClonesArray.
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    A zeroed AliITSpList class.

    fa->Delete();
    fEntries = 0;
}
//______________________________________________________________________
void AliITSpList::DeleteHit(Int_t i,Int_t j){
    // Delete a particular AliITSpListItems.
    // Inputs:
    //    Int_t i   Row number
    //    Int_t j   Columns number
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t k = GetIndex(i,j);

    if(fa->At(k)!=0){
      fa->RemoveAt(k);
    } // end for i && if
    if(k==fEntries-1) fEntries--;
}
//______________________________________________________________________
AliITSpList& AliITSpList::operator=(const AliITSpList &source){
    // = operator
    // Inputs:
    //    const AliITSpList &source    A AliITSpList object.
    // Outputs:
    //    none.
    // Return:
    //    A copied AliITSpList object.

    if(this == &source) return *this;

    if(this->fa!=0){ // if this->fa exists delete it first.
      fa->Delete();
      delete fa;
      fa = 0;
    } // end if this->fa!=0
    this->fNi = source.fNi;
    this->fNj = source.fNj;
    this->fa = new TClonesArray(*(source.fa));
    this->fEntries = source.fEntries;

    return *this;
}
//______________________________________________________________________
AliITSpList::AliITSpList(const AliITSpList &source) : AliITSMap(source){
    // Copy constructor

  fNi = source.fNi;
  fNj = source.fNj;
  fa = new TClonesArray(*(source.fa));
  fEntries = source.fEntries;
}
//______________________________________________________________________
void AliITSpList::AddItemTo(Int_t fileIndex, AliITSpListItem *pl) {
    // Adds the contents of pl to the list with track number off set given by
    // fileIndex.
    // Creates the AliITSpListItem if needed.
    // Inputs:
    //    Int_t fileIndex      track number offset value
    //    AliITSpListItem *pl  an AliITSpListItem to be added to this class.
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t index = pl->GetIndex();
    TClonesArray &rfa = *fa;
    if( fa->At( index ) == 0 ) { // most create AliITSpListItem
      new(rfa[index])AliITSpListItem(-2,-1,pl->GetModule(),index,0.0);
    } // end if

    ((AliITSpListItem*)(fa->At(index)))->AddTo( fileIndex,pl);
    if(index>=fEntries) fEntries = index +1;
}
//______________________________________________________________________
void AliITSpList::AddSignal(Int_t i,Int_t j,Int_t trk,Int_t ht,Int_t mod,
                       Double_t signal){
    // Adds a Signal value to the TClonesArray at i,j.
    // Creates the AliITSpListItem
    // if needed.
    // Inputs:
    //    Int_t i         Row number for this signal
    //    Int_t j         Column number for this signal
    //    Int_t trk       Track number creating this signal
    //    Int_t ht        Hit number creating this signal
    //    Int_t mod       The module where this signal is in
    //    Double_t signal The signal (ionization)
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t index = GetIndex(i,j);
    TClonesArray &rfa = *fa;
    if(GetpListItem(index)==0){ // must create AliITSpListItem
      new(rfa[index])AliITSpListItem(trk,ht,mod,index,signal);
    }else{ // AliITSpListItem exists, just add signal to it.
        GetpListItem(index)->AddSignal(trk,ht,mod,index,signal);
    } // end if
    if(index>=fEntries) fEntries = index +1;
}
//______________________________________________________________________
void AliITSpList::AddNoise(Int_t i,Int_t j,Int_t mod,Double_t noise){
    // Adds a noise value to the TClonesArray at i,j.
    // Creates the AliITSpListItem
    // if needed.
    // Inputs:
    //    Int_t i        Row number for this noise
    //    Int_t j        Column number for this noise
    //    Double_t noise The noise signal value.
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t index = GetIndex(i,j);
    TClonesArray &rfa = *fa;
    if(GetpListItem(index)==0){ // most create AliITSpListItem
      new(rfa[index]) AliITSpListItem(mod,index,noise);
    }else{ // AliITSpListItem exists, just add signal to it.
        GetpListItem(index)->AddNoise(mod,index,noise);
    } // end if
    if(index>=fEntries) fEntries = index +1;
}
//______________________________________________________________________
void AliITSpList::GetCell(Int_t index,Int_t &i,Int_t &j) const {
  // returns the i,j index numbers from the linearized index computed
  // with GetIndex
  if(index<0 || index>=fNi*fNj){
    Warning("GetCell","Index out of range 0<=index=%d<%d",
	    index,fNi*fNj);
    i=-1;j=-1;
    return;
  } // end if
  i = index/fNj;
  j = index - fNj*i;
  return;
}
//______________________________________________________________________
Int_t AliITSpList::GetIndex(Int_t i, Int_t j) const {
 // returns the TClonesArray index for a given set of map indexes.
  if(i<0||i>=fNi || j<0||j>=fNj){
    Warning("GetIndex","Index out of range 0<i=%d<%d and 0<0j=%d<%d",i,fNi,j,fNj);
    return -1;
  }
  else {
    return fNj*i+j;
  }
}
<commit_msg>Additional protection in case of negative indexes. More investigation is needed<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id$ */

//***********************************************************************
//
// It consist of a TClonesArray of
// AliITSpListItem objects
// This array can be accessed via 2 indexed
// it is used at digitization level by
// all the 3 ITS subdetectors
//
// ***********************************************************************

#include "AliITSpList.h"
#include "AliITSpListItem.h"

//______________________________________________________________________

ClassImp(AliITSpList)
//______________________________________________________________________
AliITSpList::AliITSpList(){
    // Default constructor
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    A zeroed/empty AliITSpList class.

    fNi = 0;
    fNj = 0;
    fa  = 0;
}
//______________________________________________________________________
AliITSpList::AliITSpList(Int_t imax,Int_t jmax){
    // Standard constructor
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    A setup AliITSpList class.

    fNi = imax;
    fNj = jmax;
    fEntries = 0;
    fa = new TClonesArray("AliITSpListItem",fNi*fNj);
}
//______________________________________________________________________
AliITSpList::~AliITSpList(){
    // Default destructor
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    a properly destroyed class

  if(fa){
    fa->Delete();
    delete fa;
    fa = 0;
  }
    fNi = 0;
    fNj = 0;

    fEntries = 0;
}

//______________________________________________________________________
void AliITSpList::ClearMap(){
    // Delete all AliITSpListItems and zero TClonesArray.
    // Inputs:
    //    none.
    // Outputs:
    //    none.
    // Return:
    //    A zeroed AliITSpList class.

    fa->Delete();
    fEntries = 0;
}
//______________________________________________________________________
void AliITSpList::DeleteHit(Int_t i,Int_t j){
    // Delete a particular AliITSpListItems.
    // Inputs:
    //    Int_t i   Row number
    //    Int_t j   Columns number
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t k = GetIndex(i,j);

    if(fa->At(k)!=0){
      fa->RemoveAt(k);
    } // end for i && if
    if(k==fEntries-1) fEntries--;
}
//______________________________________________________________________
AliITSpList& AliITSpList::operator=(const AliITSpList &source){
    // = operator
    // Inputs:
    //    const AliITSpList &source    A AliITSpList object.
    // Outputs:
    //    none.
    // Return:
    //    A copied AliITSpList object.

    if(this == &source) return *this;

    if(this->fa!=0){ // if this->fa exists delete it first.
      fa->Delete();
      delete fa;
      fa = 0;
    } // end if this->fa!=0
    this->fNi = source.fNi;
    this->fNj = source.fNj;
    this->fa = new TClonesArray(*(source.fa));
    this->fEntries = source.fEntries;

    return *this;
}
//______________________________________________________________________
AliITSpList::AliITSpList(const AliITSpList &source) : AliITSMap(source){
    // Copy constructor

  fNi = source.fNi;
  fNj = source.fNj;
  fa = new TClonesArray(*(source.fa));
  fEntries = source.fEntries;
}
//______________________________________________________________________
void AliITSpList::AddItemTo(Int_t fileIndex, AliITSpListItem *pl) {
    // Adds the contents of pl to the list with track number off set given by
    // fileIndex.
    // Creates the AliITSpListItem if needed.
    // Inputs:
    //    Int_t fileIndex      track number offset value
    //    AliITSpListItem *pl  an AliITSpListItem to be added to this class.
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t index = pl->GetIndex();
    TClonesArray &rfa = *fa;
    if( fa->At( index ) == 0 ) { // most create AliITSpListItem
      new(rfa[index])AliITSpListItem(-2,-1,pl->GetModule(),index,0.0);
    } // end if

    ((AliITSpListItem*)(fa->At(index)))->AddTo( fileIndex,pl);
    if(index>=fEntries) fEntries = index +1;
}
//______________________________________________________________________
void AliITSpList::AddSignal(Int_t i,Int_t j,Int_t trk,Int_t ht,Int_t mod,
                       Double_t signal){
    // Adds a Signal value to the TClonesArray at i,j.
    // Creates the AliITSpListItem
    // if needed.
    // Inputs:
    //    Int_t i         Row number for this signal
    //    Int_t j         Column number for this signal
    //    Int_t trk       Track number creating this signal
    //    Int_t ht        Hit number creating this signal
    //    Int_t mod       The module where this signal is in
    //    Double_t signal The signal (ionization)
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t index = GetIndex(i,j);
    if (index<0) return;
    TClonesArray &rfa = *fa;
    if(GetpListItem(index)==0){ // must create AliITSpListItem
      new(rfa[index])AliITSpListItem(trk,ht,mod,index,signal);
    }else{ // AliITSpListItem exists, just add signal to it.
        GetpListItem(index)->AddSignal(trk,ht,mod,index,signal);
    } // end if
    if(index>=fEntries) fEntries = index +1;
}
//______________________________________________________________________
void AliITSpList::AddNoise(Int_t i,Int_t j,Int_t mod,Double_t noise){
    // Adds a noise value to the TClonesArray at i,j.
    // Creates the AliITSpListItem
    // if needed.
    // Inputs:
    //    Int_t i        Row number for this noise
    //    Int_t j        Column number for this noise
    //    Double_t noise The noise signal value.
    // Outputs:
    //    none.
    // Return:
    //    none.
    Int_t index = GetIndex(i,j);
    TClonesArray &rfa = *fa;
    if(GetpListItem(index)==0){ // most create AliITSpListItem
      new(rfa[index]) AliITSpListItem(mod,index,noise);
    }else{ // AliITSpListItem exists, just add signal to it.
        GetpListItem(index)->AddNoise(mod,index,noise);
    } // end if
    if(index>=fEntries) fEntries = index +1;
}
//______________________________________________________________________
void AliITSpList::GetCell(Int_t index,Int_t &i,Int_t &j) const {
  // returns the i,j index numbers from the linearized index computed
  // with GetIndex
  if(index<0 || index>=fNi*fNj){
    Warning("GetCell","Index out of range 0<=index=%d<%d",
	    index,fNi*fNj);
    i=-1;j=-1;
    return;
  } // end if
  i = index/fNj;
  j = index - fNj*i;
  return;
}
//______________________________________________________________________
Int_t AliITSpList::GetIndex(Int_t i, Int_t j) const {
 // returns the TClonesArray index for a given set of map indexes.
  if(i<0||i>=fNi || j<0||j>=fNj){
    Warning("GetIndex","Index out of range 0<i=%d<%d and 0<0j=%d<%d",i,fNi,j,fNj);
    return -1;
  }
  else {
    return fNj*i+j;
  }
}
<|endoftext|>


<commit_before>#include<iostream>
using namespace std;
// Best case: O(n)
// Avg. case: O(n^2)
// Worst case: O(n^2)
// Sorts array A in increasing order
// Qualities:
// 1) Efficient - for small data sets and other quadratic algorithms
// 2) Stable - Doesn't change the relative order
// 3) Inplace - Doesn't need additional memory sorts as it receives online
void insertion_sort(int A[], int n);
void swap(int *n1, int *n2);

int main() {
    int A[] = {5, 6, 8, 1, -1, 0, 11, 100, -5, 0, 1, 0, 6, 1, 2, 3, 5, 10000};
    int size = sizeof(A)/sizeof(int);
    cout<<"Size = "<<size<<endl;
    cout<<"Input Array: \n";
    for (int i = 0; i < size; i++) {
        cout<<A[i]<<" ";
    }
    insertion_sort(A, size);
    cout<<"\nInsertion Sorted Array: \n";
    for (int i = 0; i < size; i++) {
        cout<<A[i]<<" ";
    }
    cout<<endl;
    return 0;
}

// Algorithm:
// 1) i = start/prev element, j = next element
// 2) A[j] < A[j] swap(A[j], A[i])
// 3) continue 1) untill all elements are sorted.
void insertion_sort(int A[], int size) {
    for (int i = 0; i < size; i++) {
        for (int j = i+1; j < size; j++) {
            if (A[j] < A[i]) {
                swap(A[j], A[i]);
            }
        }
    }
}

void swap(int *n1, int *n2) {
    int temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}
<commit_msg>Fix insertion sort<commit_after>#include<iostream>
using namespace std;
// Best case: O(n)
// Avg. case: O(n^2)
// Worst case: O(n^2)
// Sorts array A in increasing order
// Qualities:
// 1) Efficient - for small data sets and other quadratic algorithms
// 2) Stable - Doesn't change the relative order
// 3) Inplace - Doesn't need additional memory sorts as it receives online
void insertion_sort(int A[], int n);
void swap(int *n1, int *n2);

int main() {
    int A[] = {5, 6, 8, 1, -1, 0, 11, 100, -5, 0, 1, 0, 6, 1, 2, 3, 5, 10000};
    int size = sizeof(A)/sizeof(int);
    cout<<"Size = "<<size<<endl;
    cout<<"Input Array: \n";
    for (int i = 0; i < size; i++) {
        cout<<A[i]<<" ";
    }
    insertion_sort(A, size);
    cout<<"\nInsertion Sorted Array: \n";
    for (int i = 0; i < size; i++) {
        cout<<A[i]<<" ";
    }
    cout<<endl;
    return 0;
}

// Algorithm:
// 1) i = start/prev element, j = next element
// 2) A[j] < A[j] swap(A[j], A[i])
// 3) continue 1) untill all elements are sorted.
void insertion_sort(int A[], int size) {
    int i, j, key;
    for (i = 1; i < size; i++) {
        key = A[i];
        for (j = i - 1; j >= 0 && A[j] > key; j--) {
            A[j+1] = A[j];
        }
        A[j+1] = key;
    }
}

void swap(int *n1, int *n2) {
    int temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}
<|endoftext|>


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

#if defined(__APPLE__)
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#else
#include <AL/alc.h>
#endif

#include <Effekseer.h>
#include <EffekseerRendererGL.h>
#include <EffekseerSoundAL.h>

static ALCdevice* g_alcdev = nullptr;
static ALCcontext* g_alcctx = nullptr;
static ::EffekseerSound::Sound*			g_sound = NULL;

bool InitializeWindowAndDevice(int32_t windowWidth, int32_t windowHeight);
bool DoEvent();
void TerminateWindowAndDevice();
void ClearScreen();
void PresentDevice();

int main(int argc, char** argv)
{
	int32_t windowWidth = 1280;
	int32_t windowHeight = 720;
	InitializeWindowAndDevice(windowWidth, windowHeight);

	// Create a renderer of effects
	// エフェクトのレンダラーの作成
	auto renderer = ::EffekseerRendererGL::Renderer::Create(8000, EffekseerRendererGL::OpenGLDeviceType::OpenGL3);

	// Create a manager of effects
	// エフェクトのマネージャーの作成
	auto manager = ::Effekseer::Manager::Create(8000);

	// Sprcify rendering modules
	// 描画モジュールの設定
	manager->SetSpriteRenderer(renderer->CreateSpriteRenderer());
	manager->SetRibbonRenderer(renderer->CreateRibbonRenderer());
	manager->SetRingRenderer(renderer->CreateRingRenderer());
	manager->SetTrackRenderer(renderer->CreateTrackRenderer());
	manager->SetModelRenderer(renderer->CreateModelRenderer());

	// Specify a texture, model and material loader
	// It can be extended by yourself. It is loaded from a file on now.
	// テクスチャ、モデル、マテリアルローダーの設定する。
	// ユーザーが独自で拡張できる。現在はファイルから読み込んでいる。
	manager->SetTextureLoader(renderer->CreateTextureLoader());
	manager->SetModelLoader(renderer->CreateModelLoader());
	manager->SetMaterialLoader(renderer->CreateMaterialLoader());

	// Specify sound modules
	// サウンドモジュールの設定
	auto sound = EffekseerSound::Sound::Create(32);

	// Specify a metho to play sound from an instance of sound
	// 音再生用インスタンスから再生機能を指定
	manager->SetSoundPlayer(sound->CreateSoundPlayer());

	// Specify a sound data loader
	// It can be extended by yourself. It is loaded from a file on now.
	// サウンドデータの読込機能を設定する。
	// ユーザーが独自で拡張できる。現在はファイルから読み込んでいる。
	manager->SetSoundLoader(sound->CreateSoundLoader());

	// Specify a position of view
	// 視点位置を確定
	auto g_position = ::Effekseer::Vector3D(10.0f, 5.0f, 20.0f);

	// Specify a projection matrix
	// 投影行列を設定
	renderer->SetProjectionMatrix(::Effekseer::Matrix44().PerspectiveFovRH(
		90.0f / 180.0f * 3.14f, (float)windowWidth / (float)windowHeight, 1.0f, 500.0f));

	// Specify a camera matrix
	// カメラ行列を設定
	renderer->SetCameraMatrix(
		::Effekseer::Matrix44().LookAtRH(g_position, ::Effekseer::Vector3D(0.0f, 0.0f, 0.0f), ::Effekseer::Vector3D(0.0f, 1.0f, 0.0f)));

	// Load an effect
	// エフェクトの読込
	auto effect = Effekseer::Effect::Create(manager, EFK_EXAMPLE_ASSETS_DIR_U16 "Laser01.efk");

	int32_t time = 0;
	Effekseer::Handle handle = 0;

	while (DoEvent())
	{
		if (time % 120 == 0)
		{
			// Play an effect
			// エフェクトの再生
			handle = manager->Play(effect, 0, 0, 0);
		}

		if (time % 120 == 119)
		{
			// Stop effects
			// エフェクトの停止
			manager->StopEffect(handle);
		}

		// Move the effect
		// エフェクトの移動
		manager->AddLocation(handle, ::Effekseer::Vector3D(0.2f, 0.0f, 0.0f));

		// Update the manager
		// マネージャーの更新
		manager->Update();

		// Ececute functions about DirectX
		// DirectXの処理
		ClearScreen();

		// Begin to rendering effects
		// エフェクトの描画開始処理を行う。
		renderer->BeginRendering();

		// Render effects
		// エフェクトの描画を行う。
		manager->Draw();

		// Finish to rendering effects
		// エフェクトの描画終了処理を行う。
		renderer->EndRendering();

		// Ececute functions about DirectX
		// DirectXの処理
		PresentDevice();

		time++;
	}

	// Dispose the manager
	// マネージャーの破棄
	manager->Destroy();

	// Dispose the sound
	// サウンドの破棄
	sound->Destroy();

	// Dispose the renderer
	// レンダラーの破棄
	renderer->Destroy();

	TerminateWindowAndDevice();

	return 0;
}

// I use glfw to easy to write
// 簡単に書くために、glfwを使用します。
// https://www.glfw.org/
#include <GLFW/glfw3.h>
static GLFWwindow* glfwWindow = nullptr;

bool InitializeWindowAndDevice(int32_t windowWidth, int32_t windowHeight)
{
	// Initialize Window
	// ウインドウの初期化
	if (!glfwInit())
	{
		throw "Failed to initialize glfw";
	}

#if !_WIN32
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
		glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

	glfwWindow = glfwCreateWindow(windowWidth, windowHeight, "OpenGL", nullptr, nullptr);

	if (glfwWindow == nullptr)
	{
		glfwTerminate();
		throw "Failed to create an window.";
	}

	glfwMakeContextCurrent(glfwWindow);
	glfwSwapInterval(1);

	// OpenALデバイスを作成
	g_alcdev = alcOpenDevice(NULL);

	// OpenALコンテキストを作成
	g_alcctx = alcCreateContext(g_alcdev, NULL);

	alcMakeContextCurrent(g_alcctx);

	return true;
}

bool DoEvent()
{
	if (glfwWindowShouldClose(glfwWindow) == GL_TRUE)
	{
		return false;
	}

	glfwPollEvents();

	return true;
}

void TerminateWindowAndDevice()
{
	if (glfwWindow != nullptr)
	{
		glfwDestroyWindow(glfwWindow);
		glfwTerminate();
		glfwWindow = nullptr;
	}
}

void ClearScreen()
{
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void PresentDevice() { glfwSwapBuffers(glfwWindow); }<commit_msg>Fix a compile in OpenAL<commit_after>
#include <stdio.h>
#include <string>

#if defined(__APPLE__)
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#else
#include <AL/alc.h>
#endif

#include <Effekseer.h>
#include <EffekseerRendererGL.h>
#include <EffekseerSoundAL.h>

static ALCdevice* g_alcdev = nullptr;
static ALCcontext* g_alcctx = nullptr;
static ::EffekseerSound::Sound*			g_sound = NULL;

bool InitializeWindowAndDevice(int32_t windowWidth, int32_t windowHeight);
bool DoEvent();
void TerminateWindowAndDevice();
void ClearScreen();
void PresentDevice();

int main(int argc, char** argv)
{
	int32_t windowWidth = 1280;
	int32_t windowHeight = 720;
	InitializeWindowAndDevice(windowWidth, windowHeight);

	// Create a renderer of effects
	// エフェクトのレンダラーの作成
	auto renderer = ::EffekseerRendererGL::Renderer::Create(8000, EffekseerRendererGL::OpenGLDeviceType::OpenGL3);

	// Create a manager of effects
	// エフェクトのマネージャーの作成
	auto manager = ::Effekseer::Manager::Create(8000);

	// Sprcify rendering modules
	// 描画モジュールの設定
	manager->SetSpriteRenderer(renderer->CreateSpriteRenderer());
	manager->SetRibbonRenderer(renderer->CreateRibbonRenderer());
	manager->SetRingRenderer(renderer->CreateRingRenderer());
	manager->SetTrackRenderer(renderer->CreateTrackRenderer());
	manager->SetModelRenderer(renderer->CreateModelRenderer());

	// Specify a texture, model and material loader
	// It can be extended by yourself. It is loaded from a file on now.
	// テクスチャ、モデル、マテリアルローダーの設定する。
	// ユーザーが独自で拡張できる。現在はファイルから読み込んでいる。
	manager->SetTextureLoader(renderer->CreateTextureLoader());
	manager->SetModelLoader(renderer->CreateModelLoader());
	manager->SetMaterialLoader(renderer->CreateMaterialLoader());

	// Specify sound modules
	// サウンドモジュールの設定
	auto sound = EffekseerSound::Sound::Create(32);

	// Specify a metho to play sound from an instance of sound
	// 音再生用インスタンスから再生機能を指定
	manager->SetSoundPlayer(sound->CreateSoundPlayer());

	// Specify a sound data loader
	// It can be extended by yourself. It is loaded from a file on now.
	// サウンドデータの読込機能を設定する。
	// ユーザーが独自で拡張できる。現在はファイルから読み込んでいる。
	manager->SetSoundLoader(sound->CreateSoundLoader());

	// Specify a position of view
	// 視点位置を確定
	auto g_position = ::Effekseer::Vector3D(10.0f, 5.0f, 20.0f);

	// Specify a projection matrix
	// 投影行列を設定
	renderer->SetProjectionMatrix(::Effekseer::Matrix44().PerspectiveFovRH(
		90.0f / 180.0f * 3.14f, (float)windowWidth / (float)windowHeight, 1.0f, 500.0f));

	// Specify a camera matrix
	// カメラ行列を設定
	renderer->SetCameraMatrix(
		::Effekseer::Matrix44().LookAtRH(g_position, ::Effekseer::Vector3D(0.0f, 0.0f, 0.0f), ::Effekseer::Vector3D(0.0f, 1.0f, 0.0f)));

	// Load an effect
	// エフェクトの読込
	auto effect = Effekseer::Effect::Create(manager, EFK_EXAMPLE_ASSETS_DIR_U16 "Laser01.efk");

	int32_t time = 0;
	Effekseer::Handle handle = 0;

	while (DoEvent())
	{
		if (time % 120 == 0)
		{
			// Play an effect
			// エフェクトの再生
			handle = manager->Play(effect, 0, 0, 0);
		}

		if (time % 120 == 119)
		{
			// Stop effects
			// エフェクトの停止
			manager->StopEffect(handle);
		}

		// Move the effect
		// エフェクトの移動
		manager->AddLocation(handle, ::Effekseer::Vector3D(0.2f, 0.0f, 0.0f));

		// Update the manager
		// マネージャーの更新
		manager->Update();

		// Ececute functions about DirectX
		// DirectXの処理
		ClearScreen();

		// Begin to rendering effects
		// エフェクトの描画開始処理を行う。
		renderer->BeginRendering();

		// Render effects
		// エフェクトの描画を行う。
		manager->Draw();

		// Finish to rendering effects
		// エフェクトの描画終了処理を行う。
		renderer->EndRendering();

		// Ececute functions about DirectX
		// DirectXの処理
		PresentDevice();

		time++;
	}

	// Dispose the manager
	// マネージャーの破棄
	manager.Reset();

	// Dispose the sound
	// サウンドの破棄
	sound->Destroy();

	// Dispose the renderer
	// レンダラーの破棄
	renderer.Reset();

	TerminateWindowAndDevice();

	return 0;
}

// I use glfw to easy to write
// 簡単に書くために、glfwを使用します。
// https://www.glfw.org/
#include <GLFW/glfw3.h>
static GLFWwindow* glfwWindow = nullptr;

bool InitializeWindowAndDevice(int32_t windowWidth, int32_t windowHeight)
{
	// Initialize Window
	// ウインドウの初期化
	if (!glfwInit())
	{
		throw "Failed to initialize glfw";
	}

#if !_WIN32
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
		glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

	glfwWindow = glfwCreateWindow(windowWidth, windowHeight, "OpenGL", nullptr, nullptr);

	if (glfwWindow == nullptr)
	{
		glfwTerminate();
		throw "Failed to create an window.";
	}

	glfwMakeContextCurrent(glfwWindow);
	glfwSwapInterval(1);

	// OpenALデバイスを作成
	g_alcdev = alcOpenDevice(NULL);

	// OpenALコンテキストを作成
	g_alcctx = alcCreateContext(g_alcdev, NULL);

	alcMakeContextCurrent(g_alcctx);

	return true;
}

bool DoEvent()
{
	if (glfwWindowShouldClose(glfwWindow) == GL_TRUE)
	{
		return false;
	}

	glfwPollEvents();

	return true;
}

void TerminateWindowAndDevice()
{
	if (glfwWindow != nullptr)
	{
		glfwDestroyWindow(glfwWindow);
		glfwTerminate();
		glfwWindow = nullptr;
	}
}

void ClearScreen()
{
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void PresentDevice() { glfwSwapBuffers(glfwWindow); }<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTableShapeResizer.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2008-01-29 15:36:14 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _SC_XMLTABLESHAPERESIZER_HXX
#define _SC_XMLTABLESHAPERESIZER_HXX

#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEET_HPP_
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#endif
#include <list>

class ScXMLImport;
class ScChartListenerCollection;
class ScDocument;
class Rectangle;

struct ScMyToResizeShape
{
    com::sun::star::uno::Reference <com::sun::star::drawing::XShape> xShape;
    rtl::OUString* pRangeList;
    com::sun::star::table::CellAddress  aEndCell;
    com::sun::star::table::CellAddress  aStartCell;
    sal_Int32 nEndX;
    sal_Int32 nEndY;

    ScMyToResizeShape() : pRangeList(NULL) {}
};

typedef std::list<ScMyToResizeShape> ScMyToResizeShapes;

class ScMyShapeResizer
{
    ScXMLImport&                rImport;
    ScMyToResizeShapes          aShapes;
    ScChartListenerCollection*  pCollection;

    sal_Bool IsOLE(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape) const;
    void CreateChartListener(ScDocument* pDoc,
        const rtl::OUString& rName,
        const rtl::OUString* pRangeList);
    void GetNewShapeSizePos(ScDocument* pDoc, const Rectangle& rStartRect,
                            const com::sun::star::table::CellAddress& rEndCell,
                            com::sun::star::awt::Point& rPoint, com::sun::star::awt::Size& rSize,
                            sal_Int32& rEndX, sal_Int32& rEndY) const;
public:
    ScMyShapeResizer(ScXMLImport& rImport);
    ~ScMyShapeResizer();

    void    AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape,
                    rtl::OUString* pRangeList,
                    com::sun::star::table::CellAddress& rStartAddress,
                    com::sun::star::table::CellAddress& rEndAddress,
                    sal_Int32 nEndX, sal_Int32 nEndY);
    void    ResizeShapes();
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.12.88); FILE MERGED 2008/04/01 12:36:32 thb 1.12.88.2: #i85898# Stripping all external header guards 2008/03/31 17:14:56 rt 1.12.88.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: XMLTableShapeResizer.hxx,v $
 * $Revision: 1.13 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef _SC_XMLTABLESHAPERESIZER_HXX
#define _SC_XMLTABLESHAPERESIZER_HXX

#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/table/CellAddress.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <list>

class ScXMLImport;
class ScChartListenerCollection;
class ScDocument;
class Rectangle;

struct ScMyToResizeShape
{
    com::sun::star::uno::Reference <com::sun::star::drawing::XShape> xShape;
    rtl::OUString* pRangeList;
    com::sun::star::table::CellAddress  aEndCell;
    com::sun::star::table::CellAddress  aStartCell;
    sal_Int32 nEndX;
    sal_Int32 nEndY;

    ScMyToResizeShape() : pRangeList(NULL) {}
};

typedef std::list<ScMyToResizeShape> ScMyToResizeShapes;

class ScMyShapeResizer
{
    ScXMLImport&                rImport;
    ScMyToResizeShapes          aShapes;
    ScChartListenerCollection*  pCollection;

    sal_Bool IsOLE(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape) const;
    void CreateChartListener(ScDocument* pDoc,
        const rtl::OUString& rName,
        const rtl::OUString* pRangeList);
    void GetNewShapeSizePos(ScDocument* pDoc, const Rectangle& rStartRect,
                            const com::sun::star::table::CellAddress& rEndCell,
                            com::sun::star::awt::Point& rPoint, com::sun::star::awt::Size& rSize,
                            sal_Int32& rEndX, sal_Int32& rEndY) const;
public:
    ScMyShapeResizer(ScXMLImport& rImport);
    ~ScMyShapeResizer();

    void    AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape,
                    rtl::OUString* pRangeList,
                    com::sun::star::table::CellAddress& rStartAddress,
                    com::sun::star::table::CellAddress& rEndAddress,
                    sal_Int32 nEndX, sal_Int32 nEndY);
    void    ResizeShapes();
};

#endif
<|endoftext|>


<commit_before>#include <Arduino.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>
#include "PWM.h"

static uint16_t timer1[2] = {0,0};
static uint16_t timer2[2] = {0,0};
static struct {
	uint8_t duty12[2];
	uint8_t duty4[2];
	uint8_t lag[2];
} timer2_state;
static uint8_t timer2ctr = 0;
static uint8_t timer2cmpa = 0, timer2cmpb = 0;

void setTimer1PWM() {
	/* Timer 1: Pins 9 and 10.
	 * Uses CTC mode and a 12 bit timer.
	 */

	TCCR1A = 0;

	if(timer1[0] > 0) {
		TCCR1A |= (1<<COM1A1) | (1<<COM1A0);
	} else {
		PORTB |= (1<<1);
	}

	if(timer1[1] > 0) {
		TCCR1A |= (1<<COM1B1) | (1<<COM1B0);
	} else {
		PORTB |= (1<<2);
	}

	TCCR1A |= (1<<WGM11);
	TIMSK1 |= (1<<TOIE1);
}

void setTimer2PWM() {
	/* Timer 2: Pins 3 and 11
	 * If one of the PWM values is <64, the overflow ISR will use an
	 * additional counter (4 bits) to switch between two OCR values
	 */

	// Disable the overflow interrupt first
	TIMSK2 &= ~(1<<TOIE2);

	// phase-correct PWM
	TCCR2A = (1<<WGM21) | (1<<WGM20);

	if(timer2[0] > 0) {
		// Inverting mode
		TCCR2A |= (1<<COM2A1) | (1<<COM2A0);
		OCR2A = (timer2[0] >> 4);
	} else {
		PORTB |= (1<<3);
	}

	if(timer2[1] > 0) {
		// Inverting mode
		TCCR2A |= (1<<COM2B1) | (1<<COM2B0);
		OCR2B = (timer2[1] >> 4);
	} else {
		PORTD |= (1<<3);
	}

	if((timer2[0] > 0 && timer2[0] < 64) || (timer2[1] > 0 && timer2[1] < 64)) {
		timer2_state.duty12[0] = (timer2[0] >> 4);
		timer2_state.duty4 [0] = (timer2[0]     ) & 0x0F;
		timer2_state.lag   [0] = 0;
		timer2_state.duty12[1] = (timer2[1] >> 4);
		timer2_state.duty4 [1] = (timer2[1]     ) & 0x0F;
		timer2_state.lag   [1] = 0;
		TIMSK2 |= (1<<TOIE2);
	}
}

void setPWM(uint8_t color, uint16_t value) {
	uint8_t pin = colorToPin[color];
	switch(pin) {
	case 3:
		if(value > 0x0FF0) value &= ~0xF;
		timer2[1] = value;
		setTimer2PWM();
		break;
	case 9:
		timer1[0] = value;
		setTimer1PWM();
		break;
	case 10:
		timer1[1] = value;
		setTimer1PWM();
		break;
	case 11:
		if(value > 0x0FF0) value &= ~0xF;
		timer2[0] = value;
		setTimer2PWM();
		break;
	}
}

void setPWMs(uint16_t white, uint16_t red, uint16_t green, uint16_t blue) {
	timer1[0] = blue;
	timer1[1] = green;
	timer2[0] = red;
	timer2[1] = white;
	setTimer1PWM();
	setTimer2PWM();
}

void initPWM() {
	pinMode(PIN_W, OUTPUT);
	pinMode(PIN_R, OUTPUT);
	pinMode(PIN_G, OUTPUT);
	pinMode(PIN_B, OUTPUT);

	TCCR1B = (1<<WGM13) | (1<<CS10);
	ICR1 = 0x0FFF;

	TCCR2B = (1<<CS20);

	setTimer1PWM();
	setTimer2PWM();
}

ISR(TIMER2_OVF_vect) {
	register uint8_t reg;
	timer2_state.lag[0] += timer2_state.duty4[0];
	reg = timer2_state.duty12[0];
	if(timer2_state.lag[0] & 0x10) {
		reg++;
	}

	if(reg == 0) {
		TCCR2A &= ~(3<<COM2A0);
	} else {
		OCR2A = reg;
		TCCR2A |= 3<<COM2A0;
	}
	timer2_state.lag[0] &= 0x0F;

	timer2_state.lag[1] += timer2_state.duty4[1];
	reg = timer2_state.duty12[1];
	if(timer2_state.lag[1] & 0x10) {
		reg++;
	}

	if(reg == 0) {
		TCCR2A &= ~(3<<COM2B0);
	} else {
		OCR2B = reg;
		TCCR2A |= 3<<COM2B0;
	}
	timer2_state.lag[1] &= 0x0F;
}

ISR(TIMER1_OVF_vect) {
	OCR1A = timer1[0];
	OCR1B = timer1[1];
	TIMSK1 &= ~(1<<TOIE1);
}
<commit_msg>Bugfix in timer2 pwm handling: Set SDM state in any case.<commit_after>#include <Arduino.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>
#include "PWM.h"

static uint16_t timer1[2] = {
    0,0};
static uint16_t timer2[2] = {
    0,0};
static struct {
    uint8_t duty12[2];
    uint8_t duty4[2];
    uint8_t lag[2];
}
timer2_state;
static uint8_t timer2ctr = 0;
static uint8_t timer2cmpa = 0, timer2cmpb = 0;

void setTimer1PWM() {
    /* Timer 1: Pins 9 and 10.
     	 * Uses CTC mode and a 12 bit timer.
     	 */

    TCCR1A = 0;

    if(timer1[0] > 0) {
        TCCR1A |= (1<<COM1A1) | (1<<COM1A0);
    }
    else {
        PORTB |= (1<<1);
    }

    if(timer1[1] > 0) {
        TCCR1A |= (1<<COM1B1) | (1<<COM1B0);
    }
    else {
        PORTB |= (1<<2);
    }

    TCCR1A |= (1<<WGM11);
    TIMSK1 |= (1<<TOIE1);
}

void setTimer2PWM() {
    /* Timer 2: Pins 3 and 11
     	 * If one of the PWM values is <64, the overflow ISR will use an
     	 * additional counter (4 bits) to switch between two OCR values
     	 */

    // Disable the overflow interrupt first
    TIMSK2 &= ~(1<<TOIE2);

    // phase-correct PWM
    TCCR2A = (1<<WGM21) | (1<<WGM20);

    // Update SDM state __in any case__
    timer2_state.duty12[0] = (timer2[0] >> 4);
    timer2_state.duty4 [0] = (timer2[0]     ) & 0x0F;
    timer2_state.lag   [0] = 0;
    timer2_state.duty12[1] = (timer2[1] >> 4);
    timer2_state.duty4 [1] = (timer2[1]     ) & 0x0F;
    timer2_state.lag   [1] = 0;

    if(timer2[0] > 0) {
        // Inverting mode
        TCCR2A |= (1<<COM2A1) | (1<<COM2A0);
        OCR2A = timer2_state.duty12[0];
    }
    else {
        PORTB |= (1<<3);
    }

    if(timer2[1] > 0) {
        // Inverting mode
        TCCR2A |= (1<<COM2B1) | (1<<COM2B0);
        OCR2B = timer2_state.duty12[1];
    }
    else {
        PORTD |= (1<<3);
    }

    // Enable timer 2 overflow interrupt if SDM is used
    if((timer2[0] > 0 && timer2[0] < 64) || (timer2[1] > 0 && timer2[1] < 64)) {
        TIMSK2 |= (1<<TOIE2);
    }
}

void setPWM(uint8_t color, uint16_t value) {
    uint8_t pin = colorToPin[color];
    switch(pin) {
    case 3:
        if(value > 0x0FF0) value &= ~0xF;
        timer2[1] = value;
        setTimer2PWM();
        break;
    case 9:
        timer1[0] = value;
        setTimer1PWM();
        break;
    case 10:
        timer1[1] = value;
        setTimer1PWM();
        break;
    case 11:
        if(value > 0x0FF0) value &= ~0xF;
        timer2[0] = value;
        setTimer2PWM();
        break;
    }
}

void setPWMs(uint16_t white, uint16_t red, uint16_t green, uint16_t blue) {
    timer1[0] = blue;
    timer1[1] = green;
    timer2[0] = red;
    timer2[1] = white;
    setTimer1PWM();
    setTimer2PWM();
}

void initPWM() {
    pinMode(PIN_W, OUTPUT);
    pinMode(PIN_R, OUTPUT);
    pinMode(PIN_G, OUTPUT);
    pinMode(PIN_B, OUTPUT);

    TCCR1B = (1<<WGM13) | (1<<CS10);
    ICR1 = 0x0FFF;

    TCCR2B = (1<<CS20);

    setTimer1PWM();
    setTimer2PWM();
}

ISR(TIMER2_OVF_vect) {
    register uint8_t reg;
    timer2_state.lag[0] += timer2_state.duty4[0];
    reg = timer2_state.duty12[0];
    if(timer2_state.lag[0] & 0x10) {
        reg++;
    }

    if(reg == 0) {
        TCCR2A &= ~(3<<COM2A0);
    }
    else {
        OCR2A = reg;
        TCCR2A |= 3<<COM2A0;
    }
    timer2_state.lag[0] &= 0x0F;

    timer2_state.lag[1] += timer2_state.duty4[1];
    reg = timer2_state.duty12[1];
    if(timer2_state.lag[1] & 0x10) {
        reg++;
    }

    if(reg == 0) {
        TCCR2A &= ~(3<<COM2B0);
    }
    else {
        OCR2B = reg;
        TCCR2A |= 3<<COM2B0;
    }
    timer2_state.lag[1] &= 0x0F;
}

ISR(TIMER1_OVF_vect) {
    OCR1A = timer1[0];
    OCR1B = timer1[1];
    TIMSK1 &= ~(1<<TOIE1);
}

<|endoftext|>


<commit_before><commit_msg>Reduce indentation by early bail-out.<commit_after><|endoftext|>


<commit_before><commit_msg>minor comment change<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <vector>

std::vector<int> generate_range(int lowerbound, int upperbound) {
	int length = upperbound - lowerbound;
	std::vector<int> range;
	for(int i = lowerbound; i <= upperbound; i++) {
		range.push_back(i);
	}
	return range;
}

void mark_composites_in_range(int prime, std::vector<int> &range, int lowerbound, int upperbound) {
	// Determine smallest composite in range (start)
	int lb_mod_p = (lowerbound % prime);
	int start = (lb_mod_p == 0) ? lowerbound : lowerbound - lb_mod_p + prime;

	// Determine largest composite in range (stop)
	int ub_mod_p = (upperbound % prime);
	int stop = upperbound - ub_mod_p;

	// Adjust for appropriate index range
	start = start - lowerbound;
	stop = stop - lowerbound;
	for(int index = start; index <= stop; index += prime) {
		std::cout << "\tMarking " << index + lowerbound << " as 0 at position " << index << "\n";
		range.at(index) = 0;
	}
}

void apply_sieve(std::vector<int> &range, std::vector<int> primes) {
	int lowerbound = range.front();
	int upperbound = range.back();
	for(std::vector<int>::iterator it = primes.begin(); it != primes.end(); ++it) {
		int p = *it;
		std::cout << "Attempting to sieve for prime " << p << "\n";
		mark_composites_in_range(p, range, lowerbound, upperbound);
	}
}

void capture_primes_from_range(std::vector<int> &range, std::vector<int> &primes) {
	for(std::vector<int>::iterator it = range.begin(); it != range.end(); ++it) {
		if(*it != 0) {
			primes.push_back(*it);
		}
	}
}

void print_list(std::vector<int> &list) {
	for(std::vector<int>::iterator it = list.begin(); it != list.end(); ++it) {
		std::cout << *it << ",";
	}
	std::cout << "\n";
}

#define MAX_PRIME 5000
int main(int argc, char** argv) {
	std::cout << "Finding all primes less than " << MAX_PRIME << "\n";

	// Initialize Primes
	std::vector<int> primes;
	primes.push_back(2);
	primes.push_back(3);
	primes.push_back(5);

	bool perform_another_sieve = (primes.back() < MAX_PRIME);
	while(perform_another_sieve) {
		int start = primes.back() + 1;
		int stop = primes.back() * primes.back();
		if (stop >= MAX_PRIME) {
			stop = MAX_PRIME;
		}
		std::vector<int> range = generate_range(start, stop);
		apply_sieve(range, primes);
		capture_primes_from_range(range, primes);
		print_list(primes);
		perform_another_sieve = (stop < MAX_PRIME);
	}

	return 0;
}
<commit_msg>Using unsigned 64-bit ints<commit_after>#include <iostream>
#include <vector>
#include <cstdint>
#include <string>

std::vector<uint64_t> generate_range(uint64_t lowerbound, uint64_t upperbound) {
	uint64_t length = upperbound - lowerbound;
	std::vector<uint64_t> range;
	for(uint64_t i = lowerbound; i <= upperbound; i++) {
		range.push_back(i);
	}
	return range;
}

void mark_composites_in_range(uint64_t prime, std::vector<uint64_t> &range, uint64_t lowerbound, uint64_t upperbound) {
	// Determine smallest composite in range (start)
	uint64_t lb_mod_p = (lowerbound % prime);
	uint64_t start = (lb_mod_p == 0) ? lowerbound : lowerbound - lb_mod_p + prime;

	// Determine largest composite in range (stop)
	uint64_t ub_mod_p = (upperbound % prime);
	uint64_t stop = upperbound - ub_mod_p;

	// Adjust for appropriate index range
	start = start - lowerbound;
	stop = stop - lowerbound;
	for(uint64_t index = start; index <= stop; index += prime) {
		range.at(index) = 0;
	}
}

void apply_sieve(std::vector<uint64_t> &range, std::vector<uint64_t> primes) {
	uint64_t lowerbound = range.front();
	uint64_t upperbound = range.back();
	for(std::vector<uint64_t>::iterator it = primes.begin(); it != primes.end(); ++it) {
		uint64_t p = *it;
		std::cout << "Marking composites of " << p << std::endl;
		mark_composites_in_range(p, range, lowerbound, upperbound);
	}
}

void capture_primes_from_range(std::vector<uint64_t> &range, std::vector<uint64_t> &primes) {
	for(std::vector<uint64_t>::iterator it = range.begin(); it != range.end(); ++it) {
		if(*it != 0) {
			primes.push_back(*it);
		}
	}
}

void pruint64_t_list(std::vector<uint64_t> &list) {
	for(std::vector<uint64_t>::iterator it = list.begin(); it != list.end(); ++it) {
		std::cout << *it << ",";
	}
	std::cout << "\n";
}

int main(int argc, char** argv) {
	uint64_t MAX_PRIME = std::stoull(argv[1]);
	std::cout << "Finding all primes less than " << MAX_PRIME << "\n";

	// Initialize Primes
	std::vector<uint64_t> primes;
	primes.push_back(2);
	primes.push_back(3);
	primes.push_back(5);

	bool perform_another_sieve = (primes.back() < MAX_PRIME);
	while(perform_another_sieve) {
		uint64_t start = primes.back() + 1;
		uint64_t stop = primes.back() * primes.back();
		if (stop >= MAX_PRIME) {
			stop = MAX_PRIME;
		}
		std::vector<uint64_t> range = generate_range(start, stop);
		apply_sieve(range, primes);
		capture_primes_from_range(range, primes);
		std::cout << "There are " << primes.size() << " primes below " << stop << "\n";
		perform_another_sieve = (stop < MAX_PRIME);
	}

	return 0;
}
<|endoftext|>


<commit_before>//
//  nthRoot.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "nthRoot.h"
#include "Integer.h"
#include <array>
using namespace std;
nthRoot::nthRoot(int root, int operand, int coefficient) {
    this->type = "nthRoot";
    this->operand = operand;
    this->root = root;
    this->coefficient = coefficient;
    this->simplify();

    if ((root % 2) == 0 && operand < 0) {
        throw runtime_error("unreal answer");
    }
}

nthRoot::nthRoot(int root, Expression* eoperand, int coefficient) {
    this->type = "nthRoot";
    this->eoperand = eoperand;
    this->root = root;
    this->coefficient = coefficient;

    if ((root % 2) == 0 && eoperand->type == "integer") {
        Integer *a = (Integer *)eoperand;
        if (a->getValue() < 0) {
            throw runtime_error("unreal answer");
        }
    }

    if ((root % 2) == 0 && eoperand->type == "Rational"){
        Rational *b = (Rational*)eoperand;
        if ((b->getNumerator() < 0 || b->getDenominator() < 0)
             && !(b->getNumerator() < 0 && b->getDenominator() < 0)) {
             throw runtime_error("unreal answer");
        }
    }
}

nthRoot::~nthRoot() {

}

 int* nthRoot::primeFactorization(int n, int div, int k) {
    if (n % div == 0) {
        factors[k] = div;
        if (div == n) {
            factors[k+1] = 0; //the zero works as a stopping point later on
            return factors;
        }
        else {
            primeFactorization((n / div), div, (k + 1));
        }
    }
    else if (div <= n) {
        primeFactorization(n, (div + 1), k);
    }
    return factors;
}

int nthRoot::localExponentiate(int under, int locExponent) {
    for (int i = 1; i < locExponent; i++) {
        under *= under;
    }
//    cout << under << "\n";
    return under;
}
/*int* nthRoot::primeFactorization(int n, int num, int number) {    //non-recursive version
    int k = 0;
    int* factors;
    while (n%2 == 0) {
        factors[k] = 2;
        k++;
        n = n/2;
    }
    for (int i = 3; i <= sqrt(n); i = i + 2) {
//        if (n%i == 0) {
            while (n%i == 0) {
                factors[k] = i;
                k++;
                n = n/i;
            }
//        }
    }
    if (n > 2) {
        factors[k] = n;
    }
    n = 3;
    return factors;
    // added bonus: factors should be sorted already
} */

Expression* nthRoot::simplify(){
    //if coefficient == 0 then return 0?
    //if operand < 0 throw an error
    if ((root % 2) == 0 && operand < 0) {
        throw runtime_error("unreal answer");
    }
//    int *factorsCopy = this->primeFactorization(operand, 2, 0);
      this->primeFactorization(operand, 2, 0);
//    copy(this->primeFactorization(operand, 2, 0)+50, factors);
    int i = 0;
    int factorsSize = sizeof(factors)/sizeof(factors[0]);

    while (i <= factorsSize && factors[i] != 0) {   //all this takes unnecessary factors out of the operand
        int j = i;               //and puts them into the coefficient
        int count = 1;
        while (j <= factorsSize && factors[j + 1] == factors[j] && factors[j] != 0) {
            count++;
            j++;
        }
        if (count >= root) {

            coefficient = coefficient * localExponentiate(factors[i], (count/root));
            operand = (operand / localExponentiate(factors[i], (count - (count % root))));
        }
        i = j + 1;
    }
    if (operand == 1) {
        Integer* newInt = new Integer(coefficient);
        return newInt;
    }
    else {
        Expression* newRoot = new nthRoot(root, operand, coefficient);
        delete this;  //is this necessary?
        return newRoot;
    }

}

Expression* nthRoot::add(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = asCoefficient + coefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::subtract(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = coefficient - asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::multiply(Expression* a) {
    if (a->type == "integer") {
        Integer *b = (Integer*)a;
        int asValue = b->getValue();
        int newCoefficient = asValue * coefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    if (a->type == "nthRoot") {
        nthRoot *b = (nthRoot *)a;
        int asCoefficient = b->getCoefficient();
        int asOperand = b->getOperand();
        int asRoot = b->getRoot();
        if (root == asRoot) {
            int newCoefficient = asCoefficient * coefficient;
            int newOperand = operand * asOperand;       //asOperand doesnt exist?
            nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
            nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
            return simplifiedVersion;
        }
    }
    else {
        return this;
    }
    return this;
}

Expression* nthRoot::divide(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asRoot = b->getRoot();
    int asOperand = b->getOperand();
    int asCoefficient = b->getCoefficient();
    if (root == asRoot && fmod( ((double)coefficient / (double)asCoefficient), 1) == 0 && fmod(((double)operand / (double)asOperand), 1) == 0) {
        int newCoefficient = coefficient / asCoefficient;
        int newOperand = operand / asOperand;
        nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
   else if (fmod( ((double)coefficient / (double)asCoefficient),1) == 0) {
        int newCoefficient = coefficient / asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

int nthRoot::getRoot() {
    return root;
}

int nthRoot::getOperand() {
    return operand;
}

int nthRoot::getCoefficient() {
    return coefficient;
}

void nthRoot::setCoefficient(int n) {
    this->coefficient = n;
}

void nthRoot::setOperand(int n) {
    this->operand = n;
}

void nthRoot::setRoot(int n) {
    this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
    if (this->operand == 1) {
        output << this->coefficient;
    }else{
        output << this->coefficient  << "*" << this->root << "rt:" << this->operand;
    }
    return output;
}

string nthRoot::toString() {
    stringstream s;
    if (this->operand == 1) {
        s << this->coefficient;
    }else{
        s << this->coefficient  << "*" << this->root << "rt:" << this->operand;
    }
    return s.str();
}

bool nthRoot::canAdd(Expression* b){     //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)

    if (this->type == b->type && this->type != "logarithm") {
        if (this->type == "nthRoot") {
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool nthRoot::canSubtract(Expression* b){
    if (this->type == b->type) {
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool nthRoot::canMultiply(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer" && b->type == "rational") return true;
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;

}
bool nthRoot::canDivide(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer"){
        if( b->type == "rational") return true;
    }
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
<commit_msg>put in a localExp that works (maybe)<commit_after>//
//  nthRoot.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "nthRoot.h"
#include "Integer.h"
#include <array>
using namespace std;
nthRoot::nthRoot(int root, int operand, int coefficient) {
    this->type = "nthRoot";
    this->operand = operand;
    this->root = root;
    this->coefficient = coefficient;
    this->simplify();

    if ((root % 2) == 0 && operand < 0) {
        throw runtime_error("unreal answer");
    }
}

nthRoot::nthRoot(int root, Expression* eoperand, int coefficient) {
    this->type = "nthRoot";
    this->eoperand = eoperand;
    this->root = root;
    this->coefficient = coefficient;

    if ((root % 2) == 0 && eoperand->type == "integer") {
        Integer *a = (Integer *)eoperand;
        if (a->getValue() < 0) {
            throw runtime_error("unreal answer");
        }
    }

    if ((root % 2) == 0 && eoperand->type == "Rational"){
        Rational *b = (Rational*)eoperand;
        if ((b->getNumerator() < 0 || b->getDenominator() < 0)
             && !(b->getNumerator() < 0 && b->getDenominator() < 0)) {
             throw runtime_error("unreal answer");
        }
    }
}

nthRoot::~nthRoot() {

}

 int* nthRoot::primeFactorization(int n, int div, int k) {
    if (n % div == 0) {
        factors[k] = div;
        if (div == n) {
            factors[k+1] = 0; //the zero works as a stopping point later on
            return factors;
        }
        else {
            primeFactorization((n / div), div, (k + 1));
        }
    }
    else if (div <= n) {
        primeFactorization(n, (div + 1), k);
    }
    return factors;
}

int nthRoot::localExponentiate(int base, int locExponent) {
    if (locExponent >= 1)
        return base * (localExponentiate(base, locExponent - 1));
    else return 1;
}

/*
int nthRoot::localExponentiate(int under, int locExponent) {
    for (int i = 1; i < locExponent; i++) {
        under *= under;
    }
//    cout << under << "\n";
    return under;
}
*/
/*int* nthRoot::primeFactorization(int n, int num, int number) {    //non-recursive version
    int k = 0;
    int* factors;
    while (n%2 == 0) {
        factors[k] = 2;
        k++;
        n = n/2;
    }
    for (int i = 3; i <= sqrt(n); i = i + 2) {
//        if (n%i == 0) {
            while (n%i == 0) {
                factors[k] = i;
                k++;
                n = n/i;
            }
//        }
    }
    if (n > 2) {
        factors[k] = n;
    }
    n = 3;
    return factors;
    // added bonus: factors should be sorted already
} */

Expression* nthRoot::simplify(){
    //if coefficient == 0 then return 0?
    //if operand < 0 throw an error
    if ((root % 2) == 0 && operand < 0) {
        throw runtime_error("unreal answer");
    }
//    int *factorsCopy = this->primeFactorization(operand, 2, 0);
      this->primeFactorization(operand, 2, 0);
//    copy(this->primeFactorization(operand, 2, 0)+50, factors);
    int i = 0;
    int factorsSize = sizeof(factors)/sizeof(factors[0]);

    while (i <= factorsSize && factors[i] != 0) {   //all this takes unnecessary factors out of the operand
        int j = i;               //and puts them into the coefficient
        int count = 1;
        while (j <= factorsSize && factors[j + 1] == factors[j] && factors[j] != 0) {
            count++;
            j++;
        }
        if (count >= root) {

            coefficient = coefficient * localExponentiate(factors[i], (count/root));
            operand = (operand / localExponentiate(factors[i], (count - (count % root))));
        }
        i = j + 1;
    }
    if (operand == 1) {
        Integer* newInt = new Integer(coefficient);
        return newInt;
    }
    else {
        Expression* newRoot = new nthRoot(root, operand, coefficient);
        delete this;  //is this necessary?
        return newRoot;
    }

}

Expression* nthRoot::add(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = asCoefficient + coefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::subtract(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = coefficient - asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::multiply(Expression* a) {
    if (a->type == "integer") {
        Integer *b = (Integer*)a;
        int asValue = b->getValue();
        int newCoefficient = asValue * coefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    if (a->type == "nthRoot") {
        nthRoot *b = (nthRoot *)a;
        int asCoefficient = b->getCoefficient();
        int asOperand = b->getOperand();
        int asRoot = b->getRoot();
        if (root == asRoot) {
            int newCoefficient = asCoefficient * coefficient;
            int newOperand = operand * asOperand;       //asOperand doesnt exist?
            nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
            nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
            return simplifiedVersion;
        }
    }
    else {
        return this;
    }
    return this;
}

Expression* nthRoot::divide(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asRoot = b->getRoot();
    int asOperand = b->getOperand();
    int asCoefficient = b->getCoefficient();
    if (root == asRoot && fmod( ((double)coefficient / (double)asCoefficient), 1) == 0 && fmod(((double)operand / (double)asOperand), 1) == 0) {
        int newCoefficient = coefficient / asCoefficient;
        int newOperand = operand / asOperand;
        nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
   else if (fmod( ((double)coefficient / (double)asCoefficient),1) == 0) {
        int newCoefficient = coefficient / asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

int nthRoot::getRoot() {
    return root;
}

int nthRoot::getOperand() {
    return operand;
}

int nthRoot::getCoefficient() {
    return coefficient;
}

void nthRoot::setCoefficient(int n) {
    this->coefficient = n;
}

void nthRoot::setOperand(int n) {
    this->operand = n;
}

void nthRoot::setRoot(int n) {
    this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
    if (this->operand == 1) {
        output << this->coefficient;
    }else{
        output << this->coefficient  << "*" << this->root << "rt:" << this->operand;
    }
    return output;
}

string nthRoot::toString() {
    stringstream s;
    if (this->operand == 1) {
        s << this->coefficient;
    }else{
        s << this->coefficient  << "*" << this->root << "rt:" << this->operand;
    }
    return s.str();
}

bool nthRoot::canAdd(Expression* b){     //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)

    if (this->type == b->type && this->type != "logarithm") {
        if (this->type == "nthRoot") {
        }
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool nthRoot::canSubtract(Expression* b){
    if (this->type == b->type) {
        return true;
    }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
        return true;
    }else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
bool nthRoot::canMultiply(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer" && b->type == "rational") return true;
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;

}
bool nthRoot::canDivide(Expression* b){
    if (this->type == b->type) {
        return true;
    }
    else if(this->type == "integer"){
        if( b->type == "rational") return true;
    }
    else if(this->type == "rational" && b->type == "integer") return true;
    else if(this->type == "multiple" && b->type == "multiple"){
        MultipleExpressions *t = (MultipleExpressions *)this;
        MultipleExpressions *m = (MultipleExpressions *)b;
        if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
            return true;
        }
    }else if(this->type == "multiple" || b->type == "multiple") return true;
    return false;
}
<|endoftext|>


<commit_before>/*++

Module Name:

    AlignerOptions.cpp

Abstract:

    Common parameters for running single & paired alignment.

Authors:

    Ravi Pandya, May, 2012

Environment:
`
    User mode service.

Revision History:

    Integrated from SingleAligner.cpp & PairedAligner.cpp

--*/

#include "stdafx.h"
#include "options.h"
#include "AlignerOptions.h"

AlignerOptions::AlignerOptions(
    const char* i_commandLine,
    bool forPairedEnd)
    :
    commandLine(i_commandLine),
    indexDir(NULL),
    numThreads(1),
    computeError(false),
    bindToProcessors(false),
    ignoreMismatchedIDs(false),
    selectivity(1),
    samFileTemplate(NULL),
    doAlignerPrefetch(false),
    inputFilename(NULL),
    inputFileIsFASTQ(true),
    clipping(ClipBack),
    sortOutput(false),
    sortMemory(0),
    filterFlags(0),
    explorePopularSeeds(false),
    stopOnFirstHit(false),
	useM(false),
	extra(NULL),
    rgLineContents(NULL)
{
    if (forPairedEnd) {
        maxDist             = 15;
        numSeeds            = 25;
        maxHits             = 250;
        confDiff            = 1;
        adaptiveConfDiff    = 7;
    } else {
        maxDist             = 8;
        numSeeds            = 25;
        maxHits             = 250;
        confDiff            = 2;
        adaptiveConfDiff    = 4;
    }
}

    void
AlignerOptions::usage()
{
    usageMessage();
    exit(1);
}

    void
AlignerOptions::usageMessage()
{
    fprintf(stderr,
        "Usage: %s\n"
        "Options:\n"
        "  -o   output alignments to a given SAM file\n"
#ifndef _MSC_VER
        "       (note: will create one output file per thread)\n"  // Linux guys: you should fix up your SAM writer!
#endif  // _MSC_VER
        "  -d   maximum edit distance allowed per read or pair (default: %d)\n"
        "  -n   number of seeds to use per read (default: %d)\n"
        "  -h   maximum hits to consider per seed (default: %d)\n"
        "  -c   confidence threshold (default: %d)\n"
        "  -a   confidence adaptation threshold (default: %d)\n"
        "  -t   number of threads\n"
        "  -b   bind each thread to its processor (off by default)\n"
        "  -e   compute error rate assuming wgsim-generated reads\n"
        "  -P   disables cache prefetching in the genome; may be helpful for machines\n"
        "       with small caches or lots of cores/cache\n"
        "  -so  sort output file by alignment location\n"
        "  -sm  memory to use for sorting in Gb\n"
        "  -x   explore some hits of overly popular seeds (useful for filtering)\n"
        "  -f   stop on first match within edit distance limit (filtering mode)\n"
        "  -F   filter output (a=aligned only, s=single hit only, u=unaligned only)\n"
#if     USE_DEVTEAM_OPTIONS
        "  -I   ignore IDs that don't match in the paired-end aligner\n"
        "  -S   selectivity; randomly choose 1/selectivity of the reads to score\n"
#endif  // USE_DEVTEAM_OPTIONS
        "  -Cxx must be followed by two + or - symbols saying whether to clip low-quality\n"
        "       bases from front and back of read respectively; default: back only (-C-+)\n"
		"  -M   indicates that CIGAR strings in the generated SAM file should use M (alignment\n"
		"       match) rather than = and X (sequence (mis-)match)\n"
// not written yet        "  -r   Specify the content of the @RG line in the SAM header.\n"
            ,
            commandLine,
            maxDist.start,
            numSeeds.start,
            maxHits.start,
            confDiff.start,
            adaptiveConfDiff.start);
    if (extra != NULL) {
        extra->usageMessage();
    }
}

    bool
AlignerOptions::parse(
    const char** argv,
    int argc,
    int& n)
{
    if (strcmp(argv[n], "-d") == 0) {
        if (n + 1 < argc) {
            maxDist = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-n") == 0) {
        if (n + 1 < argc) {
            numSeeds = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-h") == 0) {
        if (n + 1 < argc) {
            maxHits = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-c") == 0) {
        if (n + 1 < argc) {
            confDiff = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-a") == 0) {
        if (n + 1 < argc) {
            adaptiveConfDiff = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-t") == 0) {
        if (n + 1 < argc) {
            numThreads = atoi(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-o") == 0) {
        if (n + 1 < argc) {
            samFileTemplate = argv[n+1];
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-e") == 0) {
        computeError = true;
        return true;
    } else if (strcmp(argv[n], "-P") == 0) {
        doAlignerPrefetch = false;
        return true;
    } else if (strcmp(argv[n], "-b") == 0) {
        bindToProcessors = true;
        return true;
    } else if (strcmp(argv[n], "-so") == 0) {
        sortOutput = true;
        return true;
    } else if (strcmp(argv[n], "-sm") == 0) {
        if (n + 1 < argc) {
            sortMemory = atoi(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-F") == 0) {
        if (n + 1 < argc) {
            n++;
            if (strcmp(argv[n], "a") == 0) {
                filterFlags = FilterSingleHit | FilterMultipleHits;
            } else if (strcmp(argv[n], "s") == 0) {
                filterFlags = FilterSingleHit;
            } else if (strcmp(argv[n], "u") == 0) {
                filterFlags = FilterUnaligned;
            } else {
                return false;
            }
            return true;
        }
    } else if (strcmp(argv[n], "-x") == 0) {
        explorePopularSeeds = true;
        return true;
    } else if (strcmp(argv[n], "-f") == 0) {
        stopOnFirstHit = true;
        return true;
#if     USE_DEVTEAM_OPTIONS
    } else if (strcmp(argv[n], "-I") == 0) {
        ignoreMismatchedIDs = true;
        return true;
    } else if (strcmp(argv[n], "-S") == 0) {
        if (n + 1 < argc) {
            selectivity = atoi(argv[n+1]);
            if (selectivity < 2) {
                fprintf(stderr,"Selectivity must be at least 2.\n");
                exit(1);
            }
            n++;
            return true;
        } else {
            fprintf(stderr,"Must have the selectivity value after -S\n");
        }
#endif  // USE_DEVTEAM_OPTIONS
	} else if (strcmp(argv[n], "-M") == 0) {
		useM = true;
		return true;
    } else if (strcmp(argv[n], "-r") == 0) {
#if 0   // This isn't ready yet.
        if (n + 1 < argc) {
            //
            // Check the line for sanity.  It must consist either of @RG\t<fields> or just <fields> (in which
            // case we add the @RG part).  It must contain a field called ID. Fields are separated by tabs.
            // We don't require that the fields be things that are listed in the SAM spec, however, because
            // new ones might be added.
            //
            const char *parsePointer = argv[n+1];
            if (*parsePointer == '@') {
            }

            rgLineContents = argv[n+1];
            n++;
            return true;
        }
#endif  // 0
    } else if (strlen(argv[n]) >= 2 && '-' == argv[n][0] && 'C' == argv[n][1]) {
        if (strlen(argv[n]) != 4 || '-' != argv[n][2] && '+' != argv[n][2] ||
            '-' != argv[n][3] && '+' != argv[n][3]) {

            fprintf(stderr,"Invalid -C argument.\n\n");
            return false;
        }

        if ('-' == argv[n][2]) {
            if ('-' == argv[n][3]) {
                clipping = NoClipping;
            } else {
                clipping = ClipBack;
            }
        } else {
            if ('-' == argv[n][3]) {
                clipping = ClipFront;
            } else {
                clipping = ClipFrontAndBack;
            }
        }
        return true;
    } else if (extra != NULL) {
        return extra->parse(argv, argc, n);
    }
    return false;
}

    bool
AlignerOptions::passFilter(
    Read* read,
    AlignmentResult result)
{
    if (filterFlags == 0) {
        return true;
    }
    switch (result) {
    case NotFound:
    case UnknownAlignment:
        return (filterFlags & FilterUnaligned) != 0;
    case SingleHit:
    case CertainHit:
        return (filterFlags & FilterSingleHit) != 0;
    case MultipleHits:
        return (filterFlags & FilterMultipleHits) != 0;
    default:
        return false; // shouldn't happen!
    }
}
<commit_msg>Require -sm to have a numeric value<commit_after>/*++

Module Name:

    AlignerOptions.cpp

Abstract:

    Common parameters for running single & paired alignment.

Authors:

    Ravi Pandya, May, 2012

Environment:
`
    User mode service.

Revision History:

    Integrated from SingleAligner.cpp & PairedAligner.cpp

--*/

#include "stdafx.h"
#include "options.h"
#include "AlignerOptions.h"

AlignerOptions::AlignerOptions(
    const char* i_commandLine,
    bool forPairedEnd)
    :
    commandLine(i_commandLine),
    indexDir(NULL),
    numThreads(1),
    computeError(false),
    bindToProcessors(false),
    ignoreMismatchedIDs(false),
    selectivity(1),
    samFileTemplate(NULL),
    doAlignerPrefetch(false),
    inputFilename(NULL),
    inputFileIsFASTQ(true),
    clipping(ClipBack),
    sortOutput(false),
    sortMemory(0),
    filterFlags(0),
    explorePopularSeeds(false),
    stopOnFirstHit(false),
	useM(false),
	extra(NULL),
    rgLineContents(NULL)
{
    if (forPairedEnd) {
        maxDist             = 15;
        numSeeds            = 25;
        maxHits             = 250;
        confDiff            = 1;
        adaptiveConfDiff    = 7;
    } else {
        maxDist             = 8;
        numSeeds            = 25;
        maxHits             = 250;
        confDiff            = 2;
        adaptiveConfDiff    = 4;
    }
}

    void
AlignerOptions::usage()
{
    usageMessage();
    exit(1);
}

    void
AlignerOptions::usageMessage()
{
    fprintf(stderr,
        "Usage: %s\n"
        "Options:\n"
        "  -o   output alignments to a given SAM file\n"
#ifndef _MSC_VER
        "       (note: will create one output file per thread)\n"  // Linux guys: you should fix up your SAM writer!
#endif  // _MSC_VER
        "  -d   maximum edit distance allowed per read or pair (default: %d)\n"
        "  -n   number of seeds to use per read (default: %d)\n"
        "  -h   maximum hits to consider per seed (default: %d)\n"
        "  -c   confidence threshold (default: %d)\n"
        "  -a   confidence adaptation threshold (default: %d)\n"
        "  -t   number of threads\n"
        "  -b   bind each thread to its processor (off by default)\n"
        "  -e   compute error rate assuming wgsim-generated reads\n"
        "  -P   disables cache prefetching in the genome; may be helpful for machines\n"
        "       with small caches or lots of cores/cache\n"
        "  -so  sort output file by alignment location\n"
        "  -sm  memory to use for sorting in Gb\n"
        "  -x   explore some hits of overly popular seeds (useful for filtering)\n"
        "  -f   stop on first match within edit distance limit (filtering mode)\n"
        "  -F   filter output (a=aligned only, s=single hit only, u=unaligned only)\n"
#if     USE_DEVTEAM_OPTIONS
        "  -I   ignore IDs that don't match in the paired-end aligner\n"
        "  -S   selectivity; randomly choose 1/selectivity of the reads to score\n"
#endif  // USE_DEVTEAM_OPTIONS
        "  -Cxx must be followed by two + or - symbols saying whether to clip low-quality\n"
        "       bases from front and back of read respectively; default: back only (-C-+)\n"
		"  -M   indicates that CIGAR strings in the generated SAM file should use M (alignment\n"
		"       match) rather than = and X (sequence (mis-)match)\n"
// not written yet        "  -r   Specify the content of the @RG line in the SAM header.\n"
            ,
            commandLine,
            maxDist.start,
            numSeeds.start,
            maxHits.start,
            confDiff.start,
            adaptiveConfDiff.start);
    if (extra != NULL) {
        extra->usageMessage();
    }
}

    bool
AlignerOptions::parse(
    const char** argv,
    int argc,
    int& n)
{
    if (strcmp(argv[n], "-d") == 0) {
        if (n + 1 < argc) {
            maxDist = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-n") == 0) {
        if (n + 1 < argc) {
            numSeeds = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-h") == 0) {
        if (n + 1 < argc) {
            maxHits = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-c") == 0) {
        if (n + 1 < argc) {
            confDiff = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-a") == 0) {
        if (n + 1 < argc) {
            adaptiveConfDiff = Range::parse(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-t") == 0) {
        if (n + 1 < argc) {
            numThreads = atoi(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-o") == 0) {
        if (n + 1 < argc) {
            samFileTemplate = argv[n+1];
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-e") == 0) {
        computeError = true;
        return true;
    } else if (strcmp(argv[n], "-P") == 0) {
        doAlignerPrefetch = false;
        return true;
    } else if (strcmp(argv[n], "-b") == 0) {
        bindToProcessors = true;
        return true;
    } else if (strcmp(argv[n], "-so") == 0) {
        sortOutput = true;
        return true;
    } else if (strcmp(argv[n], "-sm") == 0) {
        if (n + 1 < argc && argv[n+1][0] >= '0' && argv[n+1][0] <= '9') {
            sortMemory = atoi(argv[n+1]);
            n++;
            return true;
        }
    } else if (strcmp(argv[n], "-F") == 0) {
        if (n + 1 < argc) {
            n++;
            if (strcmp(argv[n], "a") == 0) {
                filterFlags = FilterSingleHit | FilterMultipleHits;
            } else if (strcmp(argv[n], "s") == 0) {
                filterFlags = FilterSingleHit;
            } else if (strcmp(argv[n], "u") == 0) {
                filterFlags = FilterUnaligned;
            } else {
                return false;
            }
            return true;
        }
    } else if (strcmp(argv[n], "-x") == 0) {
        explorePopularSeeds = true;
        return true;
    } else if (strcmp(argv[n], "-f") == 0) {
        stopOnFirstHit = true;
        return true;
#if     USE_DEVTEAM_OPTIONS
    } else if (strcmp(argv[n], "-I") == 0) {
        ignoreMismatchedIDs = true;
        return true;
    } else if (strcmp(argv[n], "-S") == 0) {
        if (n + 1 < argc) {
            selectivity = atoi(argv[n+1]);
            if (selectivity < 2) {
                fprintf(stderr,"Selectivity must be at least 2.\n");
                exit(1);
            }
            n++;
            return true;
        } else {
            fprintf(stderr,"Must have the selectivity value after -S\n");
        }
#endif  // USE_DEVTEAM_OPTIONS
	} else if (strcmp(argv[n], "-M") == 0) {
		useM = true;
		return true;
    } else if (strcmp(argv[n], "-r") == 0) {
#if 0   // This isn't ready yet.
        if (n + 1 < argc) {
            //
            // Check the line for sanity.  It must consist either of @RG\t<fields> or just <fields> (in which
            // case we add the @RG part).  It must contain a field called ID. Fields are separated by tabs.
            // We don't require that the fields be things that are listed in the SAM spec, however, because
            // new ones might be added.
            //
            const char *parsePointer = argv[n+1];
            if (*parsePointer == '@') {
            }

            rgLineContents = argv[n+1];
            n++;
            return true;
        }
#endif  // 0
    } else if (strlen(argv[n]) >= 2 && '-' == argv[n][0] && 'C' == argv[n][1]) {
        if (strlen(argv[n]) != 4 || '-' != argv[n][2] && '+' != argv[n][2] ||
            '-' != argv[n][3] && '+' != argv[n][3]) {

            fprintf(stderr,"Invalid -C argument.\n\n");
            return false;
        }

        if ('-' == argv[n][2]) {
            if ('-' == argv[n][3]) {
                clipping = NoClipping;
            } else {
                clipping = ClipBack;
            }
        } else {
            if ('-' == argv[n][3]) {
                clipping = ClipFront;
            } else {
                clipping = ClipFrontAndBack;
            }
        }
        return true;
    } else if (extra != NULL) {
        return extra->parse(argv, argc, n);
    }
    return false;
}

    bool
AlignerOptions::passFilter(
    Read* read,
    AlignmentResult result)
{
    if (filterFlags == 0) {
        return true;
    }
    switch (result) {
    case NotFound:
    case UnknownAlignment:
        return (filterFlags & FilterUnaligned) != 0;
    case SingleHit:
    case CertainHit:
        return (filterFlags & FilterSingleHit) != 0;
    case MultipleHits:
        return (filterFlags & FilterMultipleHits) != 0;
    default:
        return false; // shouldn't happen!
    }
}
<|endoftext|>