text:
package org.elasticsearch.action.search;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.elasticsearch.action.ValidateActions.addValidationError;

/**
 * A multi search API request.
 */
public class MultiSearchRequest extends ActionRequest implements CompositeIndicesRequest {

    private int maxConcurrentSearchRequests = 0;
    private List<SearchRequest> requests = new ArrayList<>();

    private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpenAndForbidClosed();

    /**
     * Add a search request to execute. Note, the order is important, the search response will be returned in the
     * same order as the search requests.
     */
    public MultiSearchRequest add(SearchRequestBuilder request) {
        requests.add(request.request());
        return this;
    }

    /**
     * Add a search request to execute. Note, the order is important, the search response will be returned in the
     * same order as the search requests.
     */
    public MultiSearchRequest add(SearchRequest request) {
        requests.add(request);
        return this;
    }

    /**
     * Returns the amount of search requests specified in this multi search requests are allowed to be ran concurrently.
     */
    public int maxConcurrentSearchRequests() {
        return maxConcurrentSearchRequests;
    }

    /**
     * Sets how many search requests specified in this multi search requests are allowed to be ran concurrently.
     */
    public MultiSearchRequest maxConcurrentSearchRequests(int maxConcurrentSearchRequests) {
        if (maxConcurrentSearchRequests < 1) {
            throw new IllegalArgumentException("maxConcurrentSearchRequests must be positive");
        }

        this.maxConcurrentSearchRequests = maxConcurrentSearchRequests;
        return this;
    }

    public List<SearchRequest> requests() {
        return this.requests;
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = null;
        if (requests.isEmpty()) {
            validationException = addValidationError("no requests added", validationException);
        }
        for (int i = 0; i < requests.size(); i++) {
            ActionRequestValidationException ex = requests.get(i).validate();
            if (ex != null) {
                if (validationException == null) {
                    validationException = new ActionRequestValidationException();
                }
                validationException.addValidationErrors(ex.validationErrors());
            }
        }

        return validationException;
    }

    public IndicesOptions indicesOptions() {
        return indicesOptions;
    }

    public MultiSearchRequest indicesOptions(IndicesOptions indicesOptions) {
        this.indicesOptions = indicesOptions;
        return this;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        maxConcurrentSearchRequests = in.readVInt();
        int size = in.readVInt();
        for (int i = 0; i < size; i++) {
            SearchRequest request = new SearchRequest();
            request.readFrom(in);
            requests.add(request);
        }
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeVInt(maxConcurrentSearchRequests);
        out.writeVInt(requests.size());
        for (SearchRequest request : requests) {
            request.writeTo(out);
        }
    }
}


text:
class StaticCylinder final
{

public:

  StaticCylinder( const Vector3s& x, const Vector3s& axis, const scalar& radius );
  explicit StaticCylinder( std::istream& input_stream );

  const Vector3s& x() const;

  void setOrientation( const Vector3s& axis, const scalar& theta );

  Quaternions R() const;

  const Vector3s& v() const;

  Vector3s& omega();
  const Vector3s& omega() const;

  const scalar& r() const;

  const Vector3s& axis() const;

  void serialize( std::ostream& output_stream ) const;
  void deserialize( std::istream& input_stream );

private:

  // Point on the cylinder's axis
  Vector3s m_x;
  // Cylinder's axis
  Vector3s m_n;
  // Rotation about the cylinder's axis
  scalar m_theta;
  // Linear velocity of point x
  Vector3s m_v;
  // Angular velocity about x
  Vector3s m_omega;
  // Radius of the cylinder.
  scalar m_r;

};

#endif

redpajama_set_name: RedPajamaGithub


text:
class SortAlgorithm {
public:
    int *bubleSort(int *num, int len);

    int *quickSort(int num[], int len);

};

#endif //CPPALGORITHM_SORTALGORITHM_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/kalite-stresstest.iml" filepath="$PROJECT_DIR$/kalite-stresstest.iml" />
    </modules>
  </component>
</project>


text:
import unittest
import os
import databaseservice

class PageVisitTest(unittest.TestCase):
  def setUp(self):
    self.visit = databaseservice.PageVisit(1, 12345)

  def test_visit_values(self):
    self.assertEquals(1, self.visit.get_for_page())
    self.assertEquals(12345, self.visit.get_time_visited())

class DatabaseServiceTest(unittest.TestCase):
  """
  These tests talk to an actual database, so they might run a bit slower.
  """
  def setUp(self):
    self.database_file = 'test.db'
    with open('schema.sql') as schema:
      databaseservice.initialize_database(self.database_file, schema)
    self.database_connection = \
        databaseservice.connect_database(self.database_file)
    self.database_cursor = self.database_connection.cursor()
    self.database = databaseservice.DatabaseService( \
        self.database_connection, self.database_cursor)

    # Test data
    self.first_url = 'first_url'
    self.first_shortened = 'first_shortened'

    self.second_url = 'second_url'
    self.second_shortened = 'second_shortened'

    self.first_url_first_visit_time = 12345
    self.first_url_second_visit_time = 2345

    self.second_url_first_visit_time = 9876
    self.second_url_second_visit_time = 9999

    self.test_user = databaseservice.User('rahulraj', 'fake_hash', 'fake_salt')
    self.second_user = databaseservice.User('second', 'fake_hash2', 'fake_salt2')

  def test_user_not_initially_in_database(self):
    self.assertFalse( \
        self.database.has_user_with_name(self.test_user.get_username()))

  def test_create_user_and_find(self):
    self.database.add_user(self.test_user)
    self.assertTrue(self.database.has_user_with_name( \
        self.test_user.get_username()))
    user = self.database.find_user_by_name(self.test_user.get_username())
    self.assertEquals(self.test_user.get_hashed_password(),
        user.get_hashed_password())
    self.assertEquals(self.test_user.get_salt(), user.get_salt())

  def test_last_row_id_is_correct(self):
    added_user = self.database.add_user(self.test_user)
    row_id = added_user.get_id()
    self.database_cursor.execute( \
        'select * from users where id=:id', {'id': row_id})
    result_row = self.database_cursor.fetchone()
    self.assertEquals(row_id, result_row[0])
    self.assertTrue(result_row[0] is not None)

  def test_create_pages_for_user(self):
    user = self.database.add_user(self.test_user)
    self.database.add_page_for_user(user, self.first_url, self.first_shortened)
    self.database.add_page_for_user(user, self.second_url,
        self.second_shortened)

    pages = list(self.database.find_pages_by_user(user))
    self.assertEquals(2, len(pages))
    self.assertEquals(self.first_url, pages[0].get_original_url())
    self.assertEquals(self.first_shortened, pages[0].get_shortened_url())
    self.assertEquals(self.second_url, pages[1].get_original_url())
    self.assertEquals(self.second_shortened, pages[1].get_shortened_url())

  def test_create_pages_multiple_users(self):
    first_user = self.database.add_user(self.test_user)
    second_user = self.database.add_user(self.second_user)

    self.database.add_page_for_user(first_user,
        self.first_url, self.first_shortened)
    self.database.add_page_for_user(second_user,
        self.second_url, self.second_shortened)

    first_pages = list(self.database.find_pages_by_user(first_user))
    self.assertEquals(1, len(first_pages))
    self.assertEquals(self.first_url, first_pages[0].get_original_url())
    self.assertEquals(self.first_shortened, first_pages[0].get_shortened_url())

    second_pages = list(self.database.find_pages_by_user(second_user))
    self.assertEquals(1, len(second_pages))
    self.assertEquals(self.second_url, second_pages[0].get_original_url())
    self.assertEquals(self.second_shortened,
        second_pages[0].get_shortened_url())

  def test_find_page_by_shortened_url(self):
    first_user = self.database.add_user(self.test_user)
    self.database.add_page_for_user(first_user,
        self.first_url, self.first_shortened)
    self.database.add_page_for_user(first_user,
        self.second_url, self.second_shortened)

    first_page = \
        self.database.find_page_by_shortened_url(self.first_shortened)
    self.assertEquals(self.first_shortened, first_page.get_shortened_url())

    second_page = \
        self.database.find_page_by_shortened_url(self.second_shortened)
    self.assertEquals(self.second_shortened, second_page.get_shortened_url())

  def test_visits_of_pages(self):
    user = self.database.add_user(self.test_user)

    first_page = self.database.add_page_for_user(user,
        self.first_url, self.first_shortened)
    second_page = self.database.add_page_for_user(user,
        self.second_url, self.second_shortened)

    self.database.add_visit_for_page(first_page,
        self.first_url_first_visit_time)
    self.database.add_visit_for_page(first_page,
        self.first_url_second_visit_time)

    self.database.add_visit_for_page(second_page,
        self.second_url_first_visit_time)
    self.database.add_visit_for_page(second_page,
        self.second_url_second_visit_time)

    first_visits = list(self.database.find_visits_of_page(first_page))
    self.assertEquals(2, len(first_visits))
    self.assertEquals(self.first_url_first_visit_time,
        first_visits[0].get_time_visited())
    self.assertEquals(self.first_url_second_visit_time,
        first_visits[1].get_time_visited())

    second_visits = list(self.database.find_visits_of_page(second_page))
    self.assertEquals(2, len(second_visits))
    self.assertEquals(self.second_url_first_visit_time,
        second_visits[0].get_time_visited())
    self.assertEquals(self.second_url_second_visit_time,
        second_visits[1].get_time_visited())

  def tearDown(self):
    os.unlink(self.database_file)

if __name__ == '__main__':
  unittest.main()


text:
class Appointment < ActiveRecord::Base
  include PublicActivity::Common
  include ActiveModel::Dirty

  belongs_to :patient
  belongs_to :medic

  just_define_datetime_picker :start
  just_define_datetime_picker :end
  validates :start, :presence => true

  def history
  	PublicActivity::Activity.where(trackable:self)
  end

  def title_calendar
    self.patient && "#{self.patient.title} #{self.patient.name}, #{self.patient.prename} #{self.title}"
  end

  def as_json(options={})
    h = super(
      :include => [:patient, :medic ,{:history => {include: [:owner]}}]
    )
    h[:allDay] = false
    h[:title_calendar] = title_calendar
    h[:waiting_persons] = 4
    h
  end

end


text:
using System;
using System.Reflection;

namespace Microsoft.NodejsTools.Parsing
{
    internal class BlockScope : ActivationObject
    {
        public BlockScope(Statement node, ActivationObject parent, ErrorSink errorSink)
            : base(node, parent, errorSink)
        {
        }

        #region scope setup methods

        /// <summary>
        /// Set up this scopes lexically-declared fields
        /// </summary>
        public override void DeclareScope(ResolutionVisitor resolutionVisitor)
        {
            // only bind lexical declarations
            DefineLexicalDeclarations(resolutionVisitor);
        }

        #endregion

        public override JSVariableField CreateField(string name)
        {
            return new JSVariableField(FieldType.Local, name);
        }
    }
}


text:
var Data = require('lib/Data');
var Link = require('components/Link');
var React = require('React');

var MakeSidebar = React.createClass({
  getInitialState: function() {
    return {
      hasData: false
    };
  },

  componentDidMount: function() {
    Data.fetch('makeentries', function() {
      if (this.isMounted()) {
        this.setState({hasData: true});
      }
    }.bind(this));
  },

  render: function() {
    var entryItems = null;
    if (this.state.hasData) {
      var entries = Data.get('makeentries');
      entryItems = entries.map(function(entry, ii) {
        var className = '';
        if (entry.url === this.props.entryurl) {
          className = 'sidebar-item-selected';
        }
        return (

            <Link path={'/make/' + entry.url} className={className}>{entry.title}</Link>

        );
      }, this);
    }

    return (

Make

          {entryItems}

    );
  }
});

module.exports = MakeSidebar;


text:
package main

import "net/http"

func main() {
	http.HandleFunc("/", HandleIndex)
	http.ListenAndServe(":10000", nil)
}

// HandleIndex renders the home page using our RenderIndex ego template.
func HandleIndex(w http.ResponseWriter, r *http.Request) {
	// Our list of available widgets.
	var widgets = []*Widget{
		{Name: "Blue Widget", Price: 100},
		{Name: "Red Widget", Price: 20},
	}

	// Generate the template and write it to the response.
	RenderIndex(w, widgets)
}

type Widget struct {
	Name  string
	Price int
}


text:
'use strict';

// Simulate a test service provider that submits duplicate usage for a
// resource and verifies the submission by retrieving a usage report.

const _ = require('underscore');
const extend = _.extend;
const map = _.map;
const omit = _.omit;

const request = require('abacus-request');
const commander = require('commander');
const clone = require('abacus-clone');
const oauth = require('abacus-oauth');
const dbclient = require('abacus-dbclient');

// Parse command line options
const argv = clone(process.argv);
argv.splice(1, 1, 'dupe');
commander
  .option('-c, --collector <uri>',
    'usage collector URL or domain name [http://localhost:9080]',
    'http://localhost:9080')
  .option('-r, --reporting <uri>',
    'usage reporting URL or domain name [http://localhost:9088]',
    'http://localhost:9088')
  .option('-a, --auth-server <uri>',
    'authentication server URL or domain name [http://localhost:9882]',
    'http://localhost:9882')
  .option('-t, --start-timeout <n>',
    'external processes start timeout in milliseconds', parseInt)
  .option('-u, --usage-time <n>',
    'submitted usage time', parseInt)
  .option('-d, --delay <n>',
    'delay between submissions', parseInt)
  .option('-n, --num <n>',
    'number of submissions', parseInt)
  .option('-o, --organization-guid <o>',
    'organization guid to submit duplicate usage for')
  .allowUnknownOption(true)
  .parse(argv);

// Collector service URL
const collector = /:/.test(commander.collector) ? commander.collector :
  'https://abacus-usage-collector.' + commander.collector;

// Reporting service URL
const reporting = /:/.test(commander.reporting) ? commander.reporting :
  'https://abacus-usage-reporting.' + commander.reporting;

// Auth server URL
const authServer = /:/.test(commander.authServer) ? commander.authServer :
'https://abacus-authserver-plugin.' + commander.authServer;

// External Abacus processes start timeout
const startTimeout = commander.startTimeout || 30000;

// Submitted usage time
const usageTime = commander.usageTime || Date.now();

// Delay in milliseconds between each submission
const delay = commander.delay || 20000;

// Total number of submissions to attempt
const num = commander.num || 7;

// Test organization guid
const organization = commander.organizationGuid || 'test-org';

// This test timeout
const totalTimeout = 60000 + delay * num;

// Use secure routes or not
const secured = () => process.env.SECURED === 'true' ? true : false;

// Token fetcher
const token = secured() ? oauth.cache(authServer,
  process.env.CLIENT_ID, process.env.CLIENT_SECRET,
  'abacus.usage.object-storage.write abacus.usage.object-storage.read') :
  undefined;

const authHeader = (token) => token ? {
  headers: {
    authorization: token()
  }
} : {};

const prune = (v, k) => {
  if(k === 'windows')
    map(v, (w) => {
      map(w, (tw) => {
        if(tw) {
          if(tw.charge)
            tw.charge = 0;
          if(tw.summary)
            tw.summary = 0;
        }
      });
    });
  return v;
};

describe('abacus-dupe', function() {
  const timeout = Math.max(totalTimeout, 40000);
  this.timeout(timeout);
  before((done) => {
    if (token)
      token.start();

    // Delete test dbs on the configured db server
    dbclient.drop(process.env.DB, /^abacus-/, done);
  });

  it('submits usage for a sample resource and retrieves an aggregated ' +
    'usage report', (done) => {

    // Configure the test timeout
    this.timeout(timeout);

    // Test usage to be submitted by the client
    const start = usageTime;
    const end = usageTime;

    const usage = {
      start: start,
      end: end,
      organization_id: organization,
      space_id: 'test-space',
      consumer_id: 'test-consumer',
      resource_id: 'test-resource',
      plan_id: 'basic',
      resource_instance_id: 'test-instance',
      measured_usage: [
        {
          measure: 'previous_instance_memory',
          quantity: 536870912
        },
        {
          measure: 'previous_running_instances',
          quantity: 0
        },
        {
          measure: 'current_instance_memory',
          quantity: 536870912
        },
        {
          measure: 'current_running_instances',
          quantity: 1
        }
      ]
    };

    // Submit usage for sample resource with 10 GB, 1000 light API calls,
    // and 100 heavy API calls
    let posts = 0;
    let previousReport;
    const post = (u, done) => {
      console.log('Posting document', posts + 1);

      const cb = () => {
        posts++;
        done();
      };

      request.post(collector + '/v1/metering/collected/usage',
        extend({ body: u }, authHeader(token)), (err, val) => {
          if(organization === 'test_status_code_502') {
            expect(err).to.not.equal(undefined);
            expect(val).to.equal(undefined);
          }
          else {
            expect(err).to.equal(undefined);
            if(organization !== 'test_status_code_404') {
              expect(val.statusCode).to.equal(201);
              expect(val.headers.location).to.not.equal(undefined);
            }
            else
              expect(val.statusCode).to.equal(404);
          }
          // Expect a 201 with the location of the accumulated usage
          cb();
        });
    };

    // Get a usage report for the test organization
    const get = (u, done) => {
      console.log('Retrieving Usage Report');
      request.get([
        reporting,
        'v1/metering/organizations',
        organization,
        'aggregated/usage'
      ].join('/'), extend({}, authHeader(token)), (err, val) => {
        if(organization === 'test_status_code_502')
          expect(err).to.not.equal(undefined);
        else if(organization === 'test_status_code_404') {
          expect(err).to.equal(undefined);
          expect(val.statusCode).to.equal(404);
        }
        else {
          expect(err).to.equal(undefined);
          expect(val.statusCode).to.equal(200);

          // Only check the previous report if it exists
          if(!previousReport) {
            console.log('Setting report');
            previousReport = clone(omit(val.body,
              'id', 'processed', 'processed_id', 'start', 'end'), prune);
          }
          else {
            expect(previousReport).to.deep.equal(clone(omit(val.body,
              'id', 'processed', 'processed_id', 'start', 'end'), prune));
            console.log('No change in report');
          }
        }

        // Exit if all submissions are done, otherwise wait and post again
        if(posts === num) {
          console.log('No duplicates aggregated. Ending test.');
          done();
        }
        else {
          console.log('Waiting', delay, ' milliseconds before submitting');
          setTimeout(() => post(u, () => get(u, done)), delay);
        }
      });
    };

    // Wait for usage reporter to start
    request.waitFor(reporting + '/batch', {}, startTimeout, (err, value) => {
      // Failed to ping usage reporter before timing out
      if (err) throw err;

      // Run the above steps
      post(usage, () => get(usage, done));
    });
  });
});


text:
#include "mitkNodeDepententPointSetInteractor.h"
#include "mitkPointSet.h"
#include "mitkPositionEvent.h"
#include "mitkVtkPropRenderer.h"
#include "mitkStateEvent.h"
#include "mitkInteractionConst.h"
#include "mitkGlobalInteraction.h"
#include "mitkPointOperation.h"
#include "mitkTestingMacros.h"
#include "mitkStandaloneDataStorage.h"
#include "mitkDataNodeFactory.h"
#include "mitkStandardFileLocations.h"
#include "mitkNodePredicateDataType.h"

void SendPositionEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, const mitk::Point3D& worldPosition)
{
  mitk::Event *posEvent = new mitk::PositionEvent(sender, type, button, buttonState, key, displPosition, worldPosition);
  mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(posEvent);
  delete posEvent;
}

//test related to tutorial Step5.cpp
int mitkNodeDependentPointSetInteractorTest(int argc, char* argv[])
{
  MITK_TEST_BEGIN("NodeDependentPointSetInteractor");

  // Global interaction must(!) be initialized if used
  mitk::GlobalInteraction::GetInstance()->Initialize("global");

  // Create a DataStorage
  mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
  MITK_TEST_CONDITION_REQUIRED(ds.IsNotNull(),"Instantiating DataStorage");

  //read two images and store to datastorage
  //these two images are used as node the interactors depend on. If the visibility property of one node if false, the
  //associated interactor may not change the data
  mitk::DataNode::Pointer node1, node2;
  mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New();

  MITK_TEST_CONDITION_REQUIRED(argc >= 3, "Test if a files to load has been specified");

  try
  {
    //file 1
    const std::string filename1 = argv[1];
    nodeReader->SetFileName(filename1);
    nodeReader->Update();
    node1 = nodeReader->GetOutput();
    ds->Add(node1);

    //file 2
    const std::string filename2 = argv[2];
    nodeReader->SetFileName(filename2);
    nodeReader->Update();
    node2 = nodeReader->GetOutput();
    ds->Add(node2);
  }
  catch(...) {
    MITK_TEST_FAILED_MSG(<< "Could not read file for testing");
    return EXIT_FAILURE;
  }

  //check for the two images
  mitk::NodePredicateDataType::Pointer predicate(mitk::NodePredicateDataType::New("Image"));
  mitk::DataStorage::SetOfObjects::ConstPointer allImagesInDS = ds->GetSubset(predicate);
  MITK_TEST_CONDITION_REQUIRED(allImagesInDS->Size()==2,"load images to data storage");

  // Create PointSet and a node for it
  mitk::PointSet::Pointer pointSet1 = mitk::PointSet::New();
  mitk::DataNode::Pointer pointSetNode1 = mitk::DataNode::New();
  pointSetNode1->AddProperty( "unselectedcolor", mitk::ColorProperty::New(0.0f, 1.0f, 0.0f));
  pointSetNode1->SetData(pointSet1);
  mitk::NodeDepententPointSetInteractor::Pointer interactor1 = mitk::NodeDepententPointSetInteractor::New("pointsetinteractor", pointSetNode1, node1);
  MITK_TEST_CONDITION_REQUIRED(interactor1.IsNotNull(),"Instanciating NodeDependentPointSetInteractor");
  // Add the node to the tree
  ds->Add(pointSetNode1);
  mitk::GlobalInteraction::GetInstance()->AddInteractor(interactor1);

  mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New();
  mitk::DataNode::Pointer pointSetNode2 = mitk::DataNode::New();
  pointSetNode2->AddProperty( "unselectedcolor", mitk::ColorProperty::New(0.0f, 0.0f, 1.0f));
  pointSetNode2->SetData(pointSet2);
  mitk::NodeDepententPointSetInteractor::Pointer interactor2 = mitk::NodeDepententPointSetInteractor::New("pointsetinteractor", pointSetNode2, node2);
  MITK_TEST_CONDITION_REQUIRED(interactor2.IsNotNull(),"Instanciating NodeDependentPointSetInteractor");
  // Add the node to the tree
  ds->Add(pointSetNode2);
  mitk::GlobalInteraction::GetInstance()->AddInteractor(interactor2);

  //check for the two pointsets
  mitk::NodePredicateDataType::Pointer predicatePS(mitk::NodePredicateDataType::New("PointSet"));
  mitk::DataStorage::SetOfObjects::ConstPointer allImagesInDSPS = ds->GetSubset(predicatePS);
  MITK_TEST_CONDITION_REQUIRED(allImagesInDSPS->Size()==2,"create associated pointsets to data storage");

  //create two RenderWindows
  mitk::RenderingManager::Pointer myRenderingManager = mitk::RenderingManager::New();
  vtkRenderWindow* vtkRenWin1 = vtkRenderWindow::New();
  mitk::VtkPropRenderer::Pointer br1 = mitk::VtkPropRenderer::New("testingBR1", vtkRenWin1, myRenderingManager);
  mitk::BaseRenderer::AddInstance(vtkRenWin1,br1);
  myRenderingManager->AddRenderWindow(vtkRenWin1);
  mitk::BaseRenderer::Pointer renderer1 = mitk::BaseRenderer::GetInstance(vtkRenWin1);

  vtkRenderWindow* vtkRenWin2 = vtkRenderWindow::New();
  mitk::VtkPropRenderer::Pointer br2 = mitk::VtkPropRenderer::New("testingBR2", vtkRenWin2, myRenderingManager);
  mitk::BaseRenderer::AddInstance(vtkRenWin2,br2);
  myRenderingManager->AddRenderWindow(vtkRenWin2);
  mitk::BaseRenderer::Pointer renderer2 = mitk::BaseRenderer::GetInstance(vtkRenWin2);

  //set properties for renderWindow 1 and 2
  //1:
  node1->SetBoolProperty("visible", true, renderer1);
  node2->SetBoolProperty("visible", false, renderer1);
  //2:
  node1->SetBoolProperty("visible", false, renderer2);
  node2->SetBoolProperty("visible", true, renderer2);

  //***************************************************
  //now start to test if only an event send from renderwindow 1 can interact with interactor 1 and vice versa

  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==0,"Checking empty pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==0,"Checking empty pointset 2.");

  //sending an event to interactor1
  mitk::Point3D pos3D;
  mitk::Point2D pos2D;
  pos3D[0]= 10.0;  pos3D[1]= 20.0;  pos3D[2]= 30.0;
  pos2D[0]= 100;  pos2D[0]= 200;

  //add to pointset 1
  SendPositionEvent(renderer1, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"1 Checking addition of point to pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==0,"2 Checking empty pointset 2");

  //add to pointset 2
  SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"3 Checking untouched state of pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==1,"4 Checking addition of point to pointset 2");

  //add to pointset 2
  SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"5 Checking untouched state of pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"6 Checking addition of point to pointset 2");

  //add to pointset 2
  SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"7 Checking untouched state of pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==3,"8 Checking addition of point to pointset 2");

  //add to pointset 1
  SendPositionEvent(renderer1, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==2,"9 Checking addition of point to pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==3,"10 Checking untouched state of pointset 2");

  //trying to delete points
  mitk::Event* delEvent1 = new mitk::Event(renderer1, mitk::Type_KeyPress, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_Delete);
  mitk::Event* delEvent2 = new mitk::Event(renderer2, mitk::Type_KeyPress, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_Delete);

  mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent2);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==2,"11 Checking untouched state of pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"12 Checking detected point in pointset 2");

  mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent1);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"11 Checking deleted point in pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"12 Checking untouched state of pointset 2");

  mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent2);
  MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"13 Checking untouched state of pointset 1");
  MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==1,"14 Checking detected point in pointset 2");

  mitk::GlobalInteraction::GetInstance()->RemoveInteractor(interactor1);
  mitk::GlobalInteraction::GetInstance()->RemoveInteractor(interactor2);
  delete delEvent1;
  delete delEvent2;

  myRenderingManager->RemoveRenderWindow(vtkRenWin1);
  myRenderingManager->RemoveRenderWindow(vtkRenWin2);
  vtkRenWin1->Delete();
  vtkRenWin2->Delete();

  //destroy RenderingManager
  myRenderingManager = NULL;

  MITK_TEST_END()
}


text:
// ========================================================================
// SproutCore
// copyright 2006-2008 Sprout Systems, Inc.
// ========================================================================

require('controllers/controller') ;
require('mixins/array') ;
require('mixins/selection_support') ;
require('foundation/binding') ;

/** @class

An Array Controller provides a way to project the contents of an array
out to a view.  You can use this object any place you might use an
array.  Changes to the array will not propogate to the content array
until you call commitChanges().

@extends SC.Controller
@extends SC.Array
@extends SC.SelectionSupport
@since SproutCore 1.0

*/
SC.ArrayController = SC.Controller.extend(SC.Array, SC.SelectionSupport,
/** @scope SC.ArrayController.prototype */
{

  /**
    If YES the will return controllers for content objects.

    If you want to use an array controller to edit an array contents directly
    but you do not want to wrap the values of the array in controller objects
    then you should set this property to NO.

    @field
    @type {Boolean}
  */
  useControllersForContent: NO,

  /**
    Provides compatibility with CollectionControllers.
    @field
    @type {SC.ArrayController}
  */
  arrangedObjects: function() { return this; }.property('content'),

  /**
    The content array managed by this controller.

    In general you can treat an instance of ArrayController as if it were
    the array held in this property.  Any changes you make to the controller
    that are not specifically implemented in the controller will pass through
    to the Array.

    Also if you set commitsChangesImmediately to false, the controller will
    buffer changes against this.

    @property
    @type {Array}
  */
  content: null,
  contentBindingDefault: SC.Binding.Multiple,

  /**
    Set to true if the controller has any content, even an empty array.
  */
  hasContent: function() {
    return this.get('content') != null ;
  }.property('content'),

  /**
    Set to true if you want objects removed from the array to also be
    deleted.  This is a convenient way to manage lists of items owned
    by a parent record object.

    Note that even if this is set to NO, calling destroyObject() instead of
    removeObject() will still destroy the object in question as well as
    removing it from the parent array.

    @field
    @type {Boolean}
  */
  destroyOnRemoval: NO,

  /**
    Defines the default class to use when creating new content.

    This property should either contains a class or a string that resolves
    to a class that responds to the newRecord() method.

    @property
    @type {Class}
  */
  exampleContentObject: null,

  /**
    Creates a new record instance and adds it to the end of the current array.

    This method works just like insertNewObjectAt() but always appends.

    @param attributes {Hash} optional hash of attributes to pass to the new obejct.
    @param objectType {Class} optional class of object to create.
    @returns {Object} the newly created object (also added to the array)
  */
  newObject: function(attributes, objectType) {
    return this.insertNewObjectAt(null, attributes, objectType) ;
  },

  /**
    Creates a new content object and inserts it at the passed index or appends
    it at the end of the array if you pass null.

    This method takes an optional hash of attributes which will be set on
    the new record.  You can also pass an optional objectType.  If you do
    not pass the objectType, you must instead set the exampleContentObject to
    the class of the object you want to use.  The object can be of any type
    but it must respond to the newRecord() method.

    Objects created using this method will be destroyed automatically if you
    have set commitsChangesImmediately to false and call discardChanges().

    @param index {Number} the index to insert at or null to append.
    @param attributes {Hash} optional hash of attributes to pass to the new obejct.
    @param objectType {Class} optional class of object to create.
    @returns {Object} the newly created object (also added to the array)
  */
  insertNewObjectAt: function(index, attributes, objectType) {

    // compute the objectType
    if (!objectType) objectType = this.get('exampleContentObject') ;
    if ($type(objectType) === T_STRING) {
      objectType = SC.Object.objectForPropertyPath(objectType) ;
    }
    if (objectType == null) {
      throw "Invalid object type was provided" ;
    }

    if ($type(objectType.newObject) !== T_FUNCTION) {
      throw "content object type does not support newRecord()" ;
    }

    // Create a new object...
    var obj = objectType.newObject(attributes) ;
    if (!this._createdObjects) this._createdObjects = [] ;
    this._createdObjects.push(obj) ; // save for discard...

    // Add to array.
    if (index) {
      this.insertAt(index, obj) ;
    } else this.pushObject(obj) ;

    return obj ;
  },

  /**
    Watches changes to the content property updates the contentClone.
    @private
    @observes content
  */
  _contentObserver: function() {
    var content = this.get('content') ;
    if (SC.isEqual(content, this._content)) return ; // nothing to do

    if (!this._boundContentPropertyObserver) {
      this._boundContentPropertyObserver = this._contentPropertyObserver.bind(this) ;
    }
    var func = this._boundContentPropertyObserver ;

    // remove old observer, add new observer, and trigger content property change
    if (this._content && this._content.removeObserver) this._content.removeObserver('[]', func) ;
    if (content && content.addObserver) content.addObserver('[]', func) ;
    this._content = content; //cache
    this._contentPropertyRevision = null ;

    var rev = (content) ? content.propertyRevision : -1 ;
    this._contentPropertyObserver(this, '[]', content, rev) ;
  }.observes('content'),

  _contentPropertyObserver: function(target, key, value, rev) {

    if (!this._updatingContent && (!rev || (rev != this._contentPropertyRevision))) {
      this._contentPropertyRevision = rev ;

      this._updatingContent = true ;

      this.beginPropertyChanges();
      this.contentCloneReset();
      this.enumerableContentDidChange() ;
      this.notifyPropertyChange('length') ;
      this.updateSelectionAfterContentChange();
      this.endPropertyChanges() ;

      this._updatingContent = false ;

    }
  },

  /**
    The array content that (when committed) will be merged back into the
    content property. All array methods will take place on this object.

    @field
    @type {SC.Array}
  */
  contentClone: null,

  /**
    Clones the content property into the contentClone property.
    @private
  */
  contentCloneReset: function() {
    this._changelog = [];
    this.set('contentClone', null);
  },

  /**
   SC.Array interface implimentation.

   @param idx {Number} Starting index in the array to replace.  If idx >=
     length, then append to the end of the array.

   @param amt {Number} Number of elements that should be removed from the
     array, starting at *idx*.

   @param objects {Array} An array of zero or more objects that should be
     inserted into the array at *idx*
  */
  replace: function(idx, amt, objects) {

    var content = this.get('content') ;

    // in case the passed objects are controllers, convert to source objects.
    var copyIdx = objects.length ;
    var sourceObjects = objects ;
    if (copyIdx > 0) {
      sourceObjects = [] ;
      while(--copyIdx >= 0) {
        sourceObjects[copyIdx] = this._sourceObjectFor(objects[copyIdx]) ;
      }
    }

    // create clone of content array if needed
    var contentClone = this.get('contentClone') ;
    if (!contentClone) {
      this.set('contentClone', contentClone = content.clone()) ;
    }

    // now, record the removed objects.  This may be used later.
    if (this.get('destroyOnRemoval')) {
      if (!this._deletions) this._deletions = [] ;
      for (var i=0; i < amt; i++) {
        this._deletions.push(content.objectAt(idx + i));
      }
    }

    // and record additions
    if (!this._changelog) this._changelog = [];
    this._changelog.push({ idx: idx, amt: amt, objects: sourceObjects });

    // then actually perform the edit on the contentClone
    contentClone.replace(idx, amt, sourceObjects);

    this.editorDidChange() ;
    this.enumerableContentDidChange();
    this.updateSelectionAfterContentChange();

    return this;
  },

  /**
    SC.Array interface implimentation.
    @param idx {Number} The index of the item to return.  If idx exceeds the
      current length, return null.
  */
  objectAt: function(idx) {
    var obj = this._getSourceContent() ;
    obj = (obj && obj.objectAt) ? obj.objectAt(idx) : null;
    return this._objectControllerFor(obj) ;
  },
  /**
    SC.Array interface implimentation.
    @property
    @type {integer}
  */
  length: function( key, value ) {
    var ret = this._getSourceContent() ;
    return (ret && ret.get) ? (ret.get('length') || 0) : 0 ;
  }.property(),

  /**
    Returns the index in the array of the specified object.

    This can handle both controller wrapper objects and source content objects.
  */
  indexOf: function( obj ) {
    return this._getSourceContent().indexOf(this._sourceObjectFor(obj)) ;
  },

  _getSourceContent: function() {
    return this.get('contentClone') || this.get('content') || [];
  },

  /**
  * @private
  */
  performCommitChanges: function()
  {
    var content = this.get('content');
    var ret     = true;

    // cannot commit changes to null content.  Return an error.
    if (!content) {
      return $error("No Content");
    }

    if (content.beginPropertyChanges) content.beginPropertyChanges();

    // apply all the changes made to the clone
    if (this._changelog) {
      var changelog = this._changelog ;
      var max = changelog.length;
      for(var idx=0;idx<max;idx++) {
        var change = changelog[idx];
        content.replace(change.idx, change.amt, change.objects) ;
      }
      this._changelog.length = 0 ; // reset changelog
    }

    // finally, destroy any removed objects if necessary.  Make
    // sure the objects have not been re-added before doing this.
    if (this.get('destroyOnRemoval') && this._deletions && this._deletions.length>0) {
      var idx = this._deletions.length;
      while(--idx >= 0) {
        var obj = this._deletions[idx] ;
        if (obj && obj.destroy && (content.indexOf(obj) < 0)) {
          obj.destroy() ;
        }
      }
      this._deletions.length = 0; // clear array
    }

    // changes commited, clear any created objects from the internal array
    if (this._createdObjects) this._createdObjects.length = 0 ;

     // finish commiting changes.
    if (content.endPropertyChanges) content.endPropertyChanges();
    if (content.commitChanges) ret = content.commitChanges();

    if ($ok(ret)) {
      this.contentCloneReset();
      this.editorDidClearChanges();
    }

    return ret;
  },
  /**
  * @private
  */
  performDiscardChanges: function()
  {
    this.contentCloneReset();
    this.editorDidClearChanges();

    // if any objects were created before the commit, destroy the objects
    // and reset the array.
    if (this._createdObjects && this._createdObjects.length > 0) {
      var idx = this._createdObjects.length ;
      while(--idx >= 0) {
        var obj = this._createdObjects[idx] ;
        if ($type(obj.destroy) === T_FUNCTION) obj.destroy() ;
      }
      this._createdObjects.length = 0 ;
    }

    return true;
  },

  /** @private
    Returns the object controller for a source value.
  */
  _objectControllerFor: function(obj) {
    if (!this.useControllersForContent) return obj;

    var controllers = this._objControllers = this._objControllers || {} ;
    var guid = SC.getGUID(obj) ;
    var ret = controllers[guid] ;
    if (!ret) {
      ret = controllers[guid] = this.controllerForValue(obj) ;
      if (ret) ret.__isArrayController = true ;
    }
    return ret ;
  },

  /** @private
    Returns the source object for the passed value.  If the passed value is a
    controller, this will map back to the sourceo object.  Otherwise the object itself
    will be returned.
  */
  _sourceObjectFor: function(obj) {
    return (obj && obj.kindOf && obj.kindOf(SC.Controller)) ? obj.get('content') : obj ;
  },

  init: function() {
    sc_super() ;
    if (this.get('content')) this._contentObserver() ;
  }

});


text:
function varargout = synth(varargin)
% SYNTH M-file for synth.fig
%      SYNTH, by itself, creates a new SYNTH or raises the existing
%      singleton*.
%
%      H = SYNTH returns the handle to a new SYNTH or the handle to
%      the existing singleton*.
%
%      SYNTH('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SYNTH.M with the given input arguments.
%
%      SYNTH('Property','Value',...) creates a new SYNTH or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before synth_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to synth_OpeningFcn via varargin.
%
% Created by: Daniel Houwen (danhouwen@gmail.com)
% Last Modified by GUIDE v2.5 20-Aug-2013 22:24:55

% Initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @synth_OpeningFcn, ...
                   'gui_OutputFcn',  @synth_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before synth is made visible.
function synth_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to synth (see VARARGIN)

% choose default command line output for synth
handles.output = hObject;

% set default values / initialize variables
set(handles.octaveMenu,'Value',5);
set(handles.valueMenu,'Value',5);
handles.wavCount = 0;

% grey out non-active text boxes
set(handles.freqText,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.tone1,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone2,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone3,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone4,'BackgroundColor',[0.8 0.8 0.8]);

% generate empty notes
handles.wave1Note = zeros(1,88200);
handles.wave2Note = zeros(1,88200);
handles.wave3Note = zeros(1,88200);
handles.wave4Note = zeros(1,88200);
handles.wave5Note = zeros(1,88200);

% create location for note .wav files
handles.files=dir('wavs/note_*.wav');

% generate startup sine wave
handles.finalNote = generateWave(261.6,0.5,1,0,1);
plot(handles.axes1,handles.finalNote(1:2000))
title('First 2000 Samples of generated sound')

% Update handles structure
guidata(hObject, handles);

% --- Outputs from this function are returned to the command line.
function varargout = synth_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in generateButton.
function generateButton_Callback(hObject, eventdata, handles)
% hObject    handle to generateButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% set note as 'generated'
set(handles.playButton,'userData',1);

% get note and octave from menus
    note = get(handles.noteMenu,'Value');
    octave = get(handles.octaveMenu,'Value')-1;

    % if 'Triad Chord' is selected (bold), use preset chords
    if strcmp(get(handles.chordText,'FontWeight'),'bold')
        % based on chord/single note selection
        switch get(handles.chordMenu,'Value')
            case 1 % single note
                trueFreq=0;
            case 2 % major
                note = [note note+4 note+7]; % create chord
                trueFreq=[0 0 0];
            case 3 % minor
                note = [note note+3 note+7];
                trueFreq=[0 0 0];
            case 4 % augmented
                note = [note note+4 note+8];
                trueFreq=[0 0 0];
            case 5 % diminished
                note = [note note+3 note+6];
                trueFreq=[0 0 0];
            case 6 % suspended second
                note = [note note+2 note+7];
                trueFreq=[0 0 0];
            case 7 % suspended fourth
                note = [note note+5 note+7];
                trueFreq=[0 0 0];
        end

        % add minor seventh (10 semitones)
        if get(handles.chordButton,'Value')
            note = [note note(1)+10];
        end
    else % if 'Custom Semitones' is selected, use entered numbers
        tone1 = str2double(get(handles.tone1,'String'));
        tone2 = str2double(get(handles.tone2,'String'));
        tone3 = str2double(get(handles.tone3,'String'));
        tone4 = str2double(get(handles.tone4,'String'));
        note = [note tone1 tone2 tone3 tone4];
    end

    % assign note value (in terms of measures)
    switch get(handles.valueMenu,'Value')
        case 1
            noteValue = 16; % Ionga
        case 2
            noteValue = 8; % Double Whole
        case 3
            noteValue = 4; % Whole
        case 4
            noteValue = 2; % Half
        case 5
            noteValue = 1; % Quarter
        case 6
            noteValue = 0.5; % Eighth
        case 7
            noteValue = 0.25; % Sixteenth
        case 8
            noteValue = 0.125; % Thirty-second
    end

    % check for dotted notes
    if get(handles.dotted,'Value')
        noteValue = noteValue + noteValue/2;
    end

    % set duration based on tempo or custom duration based on selection
    if strcmp(get(handles.tempoText,'FontWeight'), 'bold') % tempo
        tempo = str2double(get(handles.editTempo,'String'));
        duration = 60/tempo*noteValue; % resultant duration
        set(handles.freqText,'String',duration);
    else % custom duration
        duration = str2double(get(handles.freqText,'String'));
        tempo = 60/duration*noteValue; % resultant tempo
        set(handles.editTempo,'String',tempo);
        set(handles.tempoSlider,'Value',tempo);
    end

    % get wave shape, width/duty, and volume from selection
    wave = get(handles.waveMenu,'Value');
    width = str2double(get(handles.editWidth,'String'));
    volume = str2double(get(handles.editVolume,'String'))/100;

    % CHORD LOOP
    % initialize variables
    prevNote = zeros(1,floor(duration*44100));
    trueFreq = zeros(1,length(note));
    % repeat for each note in the chord
    for i=1:length(note)
        switch note(i)
            case 1
                baseFreq = 16.35; % C
            case 2
                baseFreq = 17.325; % C#
            case 3
                baseFreq = 18.355; % D
            case 4
                baseFreq = 19.45; % D#
            case 5
                baseFreq = 20.60; % E
            case 6
                baseFreq = 21.825; % F
            case 7
                baseFreq = 23.125; % F#
            case 8
                baseFreq = 24.50; % G
            case 9
                baseFreq = 25.955; % G#
            case 10
                baseFreq = 27.50; % A
            case 11
                baseFreq = 29.135; % A#
            case 12
                baseFreq = 30.87; % B
            case 13
                baseFreq = 32.70; % C
            case 14
                baseFreq = 34.65; % C#
            case 15
                baseFreq = 36.71; % D
            case 16
                baseFreq = 38.89; % D#
            case 17
                baseFreq = 41.20; % E
            case 18
                baseFreq = 43.65; % F
            case 19
                baseFreq = 46.25; % F#
            case 20
                baseFreq = 49.00; % G
        end
        trueFreq(i)=baseFreq*2^octave; % find true frequency
        % create current note based on selected parameters
        currentNote = generateWave(trueFreq(i),duration,wave,width,volume);

        finalNote = prevNote + currentNote; % additive chord synthesis
        prevNote = finalNote; % update previous note for chord synthesis
    end

    % save generated note to the selected wave (1-5)
    if get(handles.wave1Button,'Value')
        handles.wave1Note=generateWave(trueFreq(1),2,wave,width,1);
    elseif get(handles.wave2Button,'Value')
        handles.wave2Note=generateWave(trueFreq(1),2,wave,width,1);
    elseif get(handles.wave3Button,'Value')
        handles.wave3Note=generateWave(trueFreq(1),2,wave,width,1);
    elseif get(handles.wave4Button,'Value')
        handles.wave4Note=generateWave(trueFreq(1),2,wave,width,1);
    elseif get(handles.wave5Button,'Value')
        handles.wave5Note=generateWave(trueFreq(1),2,wave,width,1);
    end

    % plot the first 2000 samples of the note (for readability)
    if length(finalNote) > 2000
        plot(handles.axes1,finalNote(1:2000))
    else
        plot(handles.axes1,finalNote)
    end
    axes(handles.axes1)
    title('First 2000 Samples of generated sound')

    % update global variables
    handles.finalNote = finalNote;
    guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function noteMenu_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function octaveMenu_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in waveMenu.
function waveMenu_Callback(hObject, eventdata, handles)

% turn additional menus on/off depending on wave type
waveChoice = get(handles.waveMenu,'Value');
if  waveChoice == 1 % if sine, no additional menu needed
    set(handles.dutyText,'Visible','off');
    set(handles.widthText,'Visible','off');
    set(handles.editWidth,'Visible','off');
elseif waveChoice == 2 % show duty menu for square wave
    set(handles.dutyText,'Visible','on');
    set(handles.widthText,'Visible','off');
    set(handles.editWidth,'Visible','on');
else % show width menu for sawtooth wave
    set(handles.dutyText,'Visible','off');
    set(handles.widthText,'Visible','on');
    set(handles.editWidth,'Visible','on');
end

% --- Executes during object creation, after setting all properties.
function waveMenu_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function tempoSlider_Callback(hObject, eventdata, handles)

% if tempo slider is used, show updated values in tempo text and duration
sliderValue = get(handles.tempoSlider,'Value');
set(handles.editTempo,'String',num2str(sliderValue));
set(handles.freqText,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.editTempo,'BackgroundColor',[1,1,1]);
set(handles.tempoText,'FontWeight','bold');
set(handles.durationText,'FontWeight','normal');

% --- Executes during object creation, after setting all properties.
function tempoSlider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on selection change in editTempo.
function editTempo_Callback(hObject, eventdata, handles)
% if tempo text is used, show updated values in tempo slider and duration
sliderValue = str2double(get(handles.editTempo,'String'));
% if blank or incorrect text is given, set to default
if (isempty(sliderValue) || sliderValue < 40 || sliderValue > 240)
    set(handles.tempoSlider,'Value',120);
    set(handles.editTempo,'String','120');
else
    set(handles.tempoSlider,'Value',sliderValue);
end

set(handles.freqText,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.editTempo,'BackgroundColor',[1,1,1]);
set(handles.tempoText,'FontWeight','bold');
set(handles.durationText,'FontWeight','normal');

% --- Executes during object creation, after setting all properties.
function editTempo_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function valueMenu_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in playButton.
function playButton_Callback(hObject, eventdata, handles)
% normalize signal to prevent clipping
finalNote = handles.finalNote/max(abs(handles.finalNote));
% play note
sound(finalNote,44100);

% --- Executes on change to editWidth.
function editWidth_Callback(hObject, eventdata, handles)

% if an invalid point is entered, set to default
widthValue = str2double(get(handles.editWidth,'String'));
if (isempty(widthValue) || widthValue < 0 || widthValue > 1)
   set(handles.editWidth,'String','0.5');
end

% --- Executes during object creation, after setting all properties.
function editWidth_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function volumeSlider_Callback(hObject, eventdata, handles)

% set the volume text to the position of the volume slider
sliderValue = get(handles.volumeSlider,'Value');
set(handles.editVolume,'String',num2str(sliderValue));

% --- Executes during object creation, after setting all properties.
function volumeSlider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on change to editVolume.
function editVolume_Callback(hObject, eventdata, handles)

% set the position of the slider based on the input volume text
% if invalid volume is given, set to default value
sliderValue = str2num(get(handles.editVolume,'String'));
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 100)
    set(handles.volumeSlider,'Value',100);
    set(handles.editVolume,'String','100');
else
    set(handles.volumeSlider,'Value',sliderValue);
end

% --- Executes during object creation, after setting all properties.
function editVolume_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in chordMenu.
function chordMenu_Callback(hObject, eventdata, handles)

% if chordMenu is changed, grey out 'Custom Semitones'
set(handles.chordMenu,'BackgroundColor',[1,1,1]);
set(handles.chordText,'FontWeight','bold');
set(handles.tone1,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone2,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone3,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone4,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.toneText,'FontWeight','normal');

% --- Executes during object creation, after setting all properties.
function chordMenu_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in chordButton.
function chordButton_Callback(hObject, eventdata, handles)

% if chordButton is changed, grey out 'Custom Semitones'
set(handles.chordMenu,'BackgroundColor',[1,1,1]);
set(handles.chordText,'FontWeight','bold');
set(handles.tone1,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone2,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone3,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.tone4,'BackgroundColor',[0.8 0.8 0.8]);
set(handles.toneText,'FontWeight','normal');

% --- Executes on change in text to tone1.
function tone1_Callback(hObject, eventdata, handles)

% if semitones are edited, grey out 'Triad Chord' menu
set(handles.chordMenu,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.chordText,'FontWeight','normal');
set(handles.tone1,'BackgroundColor',[1 1 1]);
set(handles.tone2,'BackgroundColor',[1 1 1]);
set(handles.tone3,'BackgroundColor',[1 1 1]);
set(handles.tone4,'BackgroundColor',[1 1 1]);
set(handles.toneText,'FontWeight','bold');

% if invalid tone is entered, set tone to 0
tone = str2double(get(handles.tone1,'String'));
if (isempty(tone) || tone < 0 || tone > 20)
    set(handles.tone1,'String','0');
else % ensure all tones are integers
    set(handles.tone1,'String',num2str(round(tone)));
end

% --- Executes during object creation, after setting all properties.
function tone1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change in text to tone2.
function tone2_Callback(hObject, eventdata, handles)

% if semitones are edited, grey out 'Triad Chord' menu
set(handles.chordMenu,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.chordText,'FontWeight','normal');
set(handles.tone1,'BackgroundColor',[1 1 1]);
set(handles.tone2,'BackgroundColor',[1 1 1]);
set(handles.tone3,'BackgroundColor',[1 1 1]);
set(handles.tone4,'BackgroundColor',[1 1 1]);
set(handles.toneText,'FontWeight','bold');

% if invalid tone is entered, set tone to 0
tone = str2double(get(handles.tone2,'String'));
if (isempty(tone) || tone < 0 || tone > 20)
    set(handles.tone2,'String','0');
else % ensure all tones are integers
    set(handles.tone2,'String',num2str(round(tone)));
end

% --- Executes during object creation, after setting all properties.
function tone2_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change in text to tone3.
function tone3_Callback(hObject, eventdata, handles)

% if semitones are edited, grey out 'Triad Chord' menu
set(handles.chordMenu,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.chordText,'FontWeight','normal');
set(handles.tone1,'BackgroundColor',[1 1 1]);
set(handles.tone2,'BackgroundColor',[1 1 1]);
set(handles.tone3,'BackgroundColor',[1 1 1]);
set(handles.tone4,'BackgroundColor',[1 1 1]);
set(handles.toneText,'FontWeight','bold');

% if invalid tone is entered, set tone to 0
tone = str2double(get(handles.tone3,'String'));
if (isempty(tone) || tone < 0 || tone > 20)
    set(handles.tone3,'String','0');
else % ensure all tones are integers
    set(handles.tone3,'String',num2str(round(tone)));
end

% --- Executes during object creation, after setting all properties.
function tone3_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change in text to tone4.
function tone4_Callback(hObject, eventdata, handles)

% if semitones are edited, grey out 'Triad Chord' menu
set(handles.chordMenu,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.chordText,'FontWeight','normal');
set(handles.tone1,'BackgroundColor',[1 1 1]);
set(handles.tone2,'BackgroundColor',[1 1 1]);
set(handles.tone3,'BackgroundColor',[1 1 1]);
set(handles.tone4,'BackgroundColor',[1 1 1]);
set(handles.toneText,'FontWeight','bold');

% if invalid tone is entered, set tone to 0
tone = str2double(get(handles.tone4,'String'));
if (isempty(tone) || tone < 0 || tone > 20)
    set(handles.tone4,'String','0');
else % ensure all tones are integers
    set(handles.tone4,'String',num2str(round(tone)));
end

% --- Executes during object creation, after setting all properties.
function tone4_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function freqText_Callback(hObject, eventdata, handles)

% if invalid duration is entered, set duration to 1
duration = str2double(get(handles.freqText,'String'));
if (isnan(duration) || duration < 0.01 || duration > 10)
    set(handles.freqText,'String','1');
end

% grey out tempo text and slider if duration is activated
set(handles.editTempo,'BackgroundColor',[0.8,0.8,0.8]);
set(handles.freqText,'BackgroundColor',[1,1,1]);
set(handles.durationText,'FontWeight','bold');
set(handles.tempoText,'FontWeight','normal');

% --- Executes during object creation, after setting all properties.
function freqText_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on slider movement.
function wave1Slider_Callback(hObject, eventdata, handles)
% update wave1 text if slider is changed
sliderValue = get(handles.wave1Slider,'Value');
set(handles.wave1Edit,'String',num2str(sliderValue));

% --- Executes during object creation, after setting all properties.
function wave1Slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function wave2Slider_Callback(hObject, eventdata, handles)
% update wave2 text if slider is changed
sliderValue = get(handles.wave2Slider,'Value');
set(handles.wave2Edit,'String',num2str(sliderValue));

% --- Executes during object creation, after setting all properties.
function wave2Slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function wave3Slider_Callback(hObject, eventdata, handles)
% update wave3 text if slider is changed
sliderValue = get(handles.wave3Slider,'Value');
set(handles.wave3Edit,'String',num2str(sliderValue));

% --- Executes during object creation, after setting all properties.
function wave3Slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function wave4Slider_Callback(hObject, eventdata, handles)
% update wave4 text if slider is changed
sliderValue = get(handles.wave4Slider,'Value');
set(handles.wave4Edit,'String',num2str(sliderValue));

% --- Executes during object creation, after setting all properties.
function wave4Slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function wave5Slider_Callback(hObject, eventdata, handles)
% update wave5 text if slider is changed
sliderValue = get(handles.wave5Slider,'Value');
set(handles.wave5Edit,'String',num2str(sliderValue));

% --- Executes during object creation, after setting all properties.
function wave5Slider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on button press in wave1Button.
function wave1Button_Callback(hObject, eventdata, handles)
% turn all other wave buttons off
set(handles.wave2Button,'Value',0.0)
set(handles.wave3Button,'Value',0.0)
set(handles.wave4Button,'Value',0.0)
set(handles.wave5Button,'Value',0.0)

% --- Executes on button press in wave5Button.
function wave5Button_Callback(hObject, eventdata, handles)
% turn all other wave buttons off
set(handles.wave2Button,'Value',0.0)
set(handles.wave3Button,'Value',0.0)
set(handles.wave4Button,'Value',0.0)
set(handles.wave1Button,'Value',0.0)

% --- Executes on button press in wave4Button.
function wave4Button_Callback(hObject, eventdata, handles)
% turn all other wave buttons off
set(handles.wave2Button,'Value',0.0)
set(handles.wave3Button,'Value',0.0)
set(handles.wave1Button,'Value',0.0)
set(handles.wave5Button,'Value',0.0)

% --- Executes on button press in wave3Button.
function wave3Button_Callback(hObject, eventdata, handles)
% turn all other wave buttons off
set(handles.wave2Button,'Value',0.0)
set(handles.wave1Button,'Value',0.0)
set(handles.wave4Button,'Value',0.0)
set(handles.wave5Button,'Value',0.0)

% --- Executes on button press in wave2Button.
function wave2Button_Callback(hObject, eventdata, handles)
% turn all other wave buttons off
set(handles.wave1Button,'Value',0.0)
set(handles.wave3Button,'Value',0.0)
set(handles.wave4Button,'Value',0.0)
set(handles.wave5Button,'Value',0.0)

% --- Executes on change to wave1 text.
function wave1Edit_Callback(hObject, eventdata, handles)
% set wave1 slider to match text. if invalid input, set to default
sliderValue = str2double(get(handles.wave1Edit,'String'));
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 120)
    set(handles.wave1Slider,'Value',100);
    set(handles.wave1Edit,'String','100');
else
    set(handles.wave1Slider,'Value',sliderValue);
end

% --- Executes during object creation, after setting all properties.
function wave1Edit_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change to wave2 text.
function wave2Edit_Callback(hObject, eventdata, handles)
% set wave2 slider to match text. if invalid input, set to default
sliderValue = str2double(get(handles.wave2Edit,'String'));
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 120)
    set(handles.wave2Slider,'Value',100);
    set(handles.wave2Edit,'String','100');
else
    set(handles.wave2Slider,'Value',sliderValue);
end

% --- Executes during object creation, after setting all properties.
function wave2Edit_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change to wave3 text.
function wave3Edit_Callback(hObject, eventdata, handles) %#ok<DEFNU>
% set wave3 slider to match text. if invalid input, set to default
sliderValue = str2double(get(handles.wave3Edit,'String'));
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 120)
    set(handles.wave3Slider,'Value',100);
    set(handles.wave3Edit,'String','100');
else
    set(handles.wave3Slider,'Value',sliderValue);
end

% --- Executes during object creation, after setting all properties.
function wave3Edit_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change to wave4 text.
function wave4Edit_Callback(hObject, eventdata, handles)
% set wave4 slider to match text. if invalid input, set to default
sliderValue = str2double(get(handles.wave4Edit,'String'));
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 120)
    set(handles.wave4Slider,'Value',100);
    set(handles.wave4Edit,'String','100');
else
    set(handles.wave4Slider,'Value',sliderValue);
end

% --- Executes during object creation, after setting all properties.
function wave4Edit_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on change to wave5 text.
function wave5Edit_Callback(hObject, eventdata, handles)
% set wave5 slider to match text. if invalid input, set to default
sliderValue = str2double(get(handles.wave5Edit,'String'));
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 120)
    set(handles.wave5Slider,'Value',100);
    set(handles.wave5Edit,'String','100');
else
    set(handles.wave5Slider,'Value',sliderValue);
end

% --- Executes during object creation, after setting all properties.
function wave5Edit_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% compile all the waves into one signal through additive synthesis
function fullNote = additiveSynthesis(handles)
wav1 = get(handles.wave1Slider,'Value')*handles.wave1Note/100;
wav2 = get(handles.wave2Slider,'Value')*handles.wave2Note/100;
wav3 = get(handles.wave3Slider,'Value')*handles.wave3Note/100;
wav4 = get(handles.wave4Slider,'Value')*handles.wave4Note/100;
wav5 = get(handles.wave5Slider,'Value')*handles.wave5Note/100;

fullNote = wav1+wav2+wav3+wav4+wav5;

% --- Executes on button press in allButton.
function allButton_Callback(hObject, eventdata, handles)
% compile all waves into one signal and play
fullNote = additiveSynthesis(handles);
soundsc(fullNote,44100);

function fileName = wavCounter(hObject,eventdata,handles)
% create local variable for faster execution
wavCount = handles.wavCount;

% if wavCount has not been established, find current note count
if (wavCount==0)
    if(exist('wavs','dir')~=7) % does the directory exist?
        mkdir('wavs') % create directory named 'wavs'
    else % directory already exists
        if(~isempty(handles.files)) % are there files in the directory?
            prevCount = 0; % establish previous count for comp.
            for x=1:length(handles.files) % cycle through files
                % extract the note count from filename
                wavCount = str2double(handles.files(x).name(6:8));
                if (prevCount < wavCount) % compare current and previous
                    prevCount = wavCount;
                end
            end
        end
    end
end
wavCount = wavCount + 1; % increment global wavCount

% create file name by string concatenation
if (wavCount<10)
    fileName = ['wavs/note_00',num2str(wavCount),'.wav'];
elseif (wavCount<100)
    fileName = ['wavs/note_0',num2str(wavCount),'.wav'];
else
    fileName = ['wavs/note_',num2str(wavCount),'.wav'];
end

% update global variable
handles.wavCount = wavCount;
guidata(hObject,handles);

% --- Executes on button press in saveWaveButton.
function saveWaveButton_Callback(hObject, eventdata, handles)
% perform additive synthesis to find complete signal
fullNote = additiveSynthesis(handles);
% create file name based on current wav# in folder
fileName = wavCounter(hObject,eventdata,handles);

% normalize the note to prevent clipping
saveNote = 0.9999*fullNote/max(abs(fullNote));

% save file as .wav and alert user
wavwrite(saveNote,44100,fileName);
msgbox(['File "', fileName(6:17), '" has been created.']);

function noteMenu_Callback(hObject, eventdata, handles)
% empty function, no action to be taken during change in noteMenu

function octaveMenu_Callback(hObject, eventdata, handles)
% empty function, no action to be taken during change in octaveMenu

function valueMenu_Callback(hObject, eventdata, handles)
% empty function, no action to be taken during change in valueMenu

% --- Executes on button press in waveButton.
function waveButton_Callback(hObject, eventdata, handles)
% play the wave that is currently selected
if get(handles.wave1Button,'Value')
        sound(handles.wave1Note*get(handles.wave1Slider,'Value')/100,44100);
    elseif get(handles.wave2Button,'Value')
        sound(handles.wave2Note*get(handles.wave2Slider,'Value')/100,44100);
    elseif get(handles.wave3Button,'Value')
        sound(handles.wave3Note*get(handles.wave3Slider,'Value')/100,44100);
    elseif get(handles.wave4Button,'Value')
        sound(handles.wave4Note*get(handles.wave4Slider,'Value')/100,44100);
    elseif get(handles.wave5Button,'Value')
        sound(handles.wave5Note*get(handles.wave5Slider,'Value')/100,44100);
end

% --- Executes on button press in plotWaveButton.
function plotWaveButton_Callback(hObject, eventdata, handles)
% plot the output of all waves after additive synthesis
fullNote = additiveSynthesis(handles);
plot(handles.axes1,fullNote(1:2000))
title('First 2000 Samples of the addition of all waves')

% --- Executes on button press in saveNoteButton.
function saveNoteButton_Callback(hObject, eventdata, handles)
% generate file name based on the current wav# in the folder
fileName = wavCounter(hObject,eventdata,handles);
finalNote = handles.finalNote; % import global variable

% normalize the note to prevent clipping
finalNote = 0.9999*finalNote/max(abs(finalNote));

% save file as .wav and alert user
wavwrite(finalNote,44100,fileName);
msgbox(['File "', fileName(6:17), '" has been created.']);

% --- Executes on button press in dotted.
function dotted_Callback(hObject, eventdata, handles)
% empty function, no action to be taken during change in dotted


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.18.1: http://docutils.sourceforge.net/" />

    <title>monty — monty 2022.9.9 documentation</title>
    <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="_static/flasky.css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />

  <link media="only screen and (max-device-width: 480px)" href="_static/small_flask.css" type= "text/css" rel="stylesheet" />
  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">

Navigation

          index

          modules |

monty 2022.9.9 documentation »

monty

monty¶

monty package

Subpackages

monty.os package

Submodules

monty.os.path module

Module contents

Submodules

monty.bisect module

monty.collections module

monty.design_patterns module

monty.dev module

monty.fnmatch module

monty.fractions module

monty.functools module

monty.inspect module

monty.io module

monty.itertools module

monty.json module

monty.logging module

monty.math module

monty.msgpack module

monty.multiprocessing module

monty.operator module

monty.pprint module

monty.re module

monty.serialization module

monty.shutil module

monty.string module

monty.subprocess module

monty.tempfile module

monty.termcolor module

Module contents

Related Topics

Documentation overview

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

      © Copyright 2014, Shyue Ping Ong.


text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/declarative/deduping_factory.h"

#include <memory>

#include "base/values.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

const char kTypeName[] = "Foo";
const char kTypeName2[] = "Foo2";

// This serves as an example how to use the DedupingFactory.
class BaseClass : public base::RefCounted<BaseClass> {
 public:
  // The type is introduced so that we can compare derived classes even though
  // Equals takes a parameter of type BaseClass. Each derived class gets an
  // entry in Type.
  enum Type { FOO };

  explicit BaseClass(Type type) : type_(type) {}

  Type type() const { return type_; }

  // For BaseClassT template:
  virtual bool Equals(const BaseClass* other) const = 0;

 protected:
  friend class base::RefCounted<BaseClass>;
  virtual ~BaseClass() {}

 private:
  const Type type_;
};

class Foo : public BaseClass {
 public:
  explicit Foo(int parameter) : BaseClass(FOO), parameter_(parameter) {}
  Foo(const Foo&) = delete;
  Foo& operator=(const Foo&) = delete;
  bool Equals(const BaseClass* other) const override {
    return other->type() == type() &&
           static_cast<const Foo*>(other)->parameter_ == parameter_;
  }
  int parameter() const {
    return parameter_;
  }

 private:
  friend class base::RefCounted<BaseClass>;
  ~Foo() override {}

  // Note that this class must be immutable.
  const int parameter_;
};

scoped_refptr<const BaseClass> CreateFoo(const std::string& /*instance_type*/,
                                         const base::Value* value,
                                         std::string* error,
                                         bool* bad_message) {
  CHECK(value->is_dict());
  absl::optional<int> parameter = value->GetDict().FindInt("parameter");
  if (!parameter) {
    *error = "No parameter";
    *bad_message = true;
    return nullptr;
  }
  return scoped_refptr<const BaseClass>(new Foo(*parameter));
}

base::Value CreateDictWithParameter(int parameter) {
  base::Value::Dict dict;
  dict.Set("parameter", parameter);
  return base::Value(std::move(dict));
}

}  // namespace

namespace extensions {

using FactoryT = DedupingFactory<BaseClass, const base::Value*>;

TEST(DedupingFactoryTest, InstantiationParameterized) {
  FactoryT factory(2);
  factory.RegisterFactoryMethod(kTypeName, FactoryT::IS_PARAMETERIZED,
                                &CreateFoo);

  base::Value d1 = CreateDictWithParameter(1);
  base::Value d2 = CreateDictWithParameter(2);
  base::Value d3 = CreateDictWithParameter(3);
  base::Value d4 = CreateDictWithParameter(4);

  std::string error;
  bool bad_message = false;

  // Fill factory with 2 different types.
  scoped_refptr<const BaseClass> c1(
      factory.Instantiate(kTypeName, &d1, &error, &bad_message));
  scoped_refptr<const BaseClass> c2(
      factory.Instantiate(kTypeName, &d2, &error, &bad_message));
  ASSERT_TRUE(c1.get());
  ASSERT_TRUE(c2.get());
  EXPECT_EQ(1, static_cast<const Foo*>(c1.get())->parameter());
  EXPECT_EQ(2, static_cast<const Foo*>(c2.get())->parameter());

  // This one produces an overflow, now the cache contains [2, 3]
  scoped_refptr<const BaseClass> c3(
      factory.Instantiate(kTypeName, &d3, &error, &bad_message));
  ASSERT_TRUE(c3.get());
  EXPECT_EQ(3, static_cast<const Foo*>(c3.get())->parameter());

  // Reuse 2, this should give the same instance as c2.
  scoped_refptr<const BaseClass> c2_b(
      factory.Instantiate(kTypeName, &d2, &error, &bad_message));
  EXPECT_EQ(2, static_cast<const Foo*>(c2_b.get())->parameter());
  EXPECT_EQ(c2, c2_b);

  // Also check that the reuse of 2 moved it to the end, so that the cache is
  // now [3, 2] and 3 is discarded before 2.
  // This discards 3, so the cache becomes [2, 1]
  scoped_refptr<const BaseClass> c1_b(
      factory.Instantiate(kTypeName, &d1, &error, &bad_message));

  scoped_refptr<const BaseClass> c2_c(
      factory.Instantiate(kTypeName, &d2, &error, &bad_message));
  EXPECT_EQ(2, static_cast<const Foo*>(c2_c.get())->parameter());
  EXPECT_EQ(c2, c2_c);
}

TEST(DedupingFactoryTest, InstantiationNonParameterized) {
  FactoryT factory(2);
  factory.RegisterFactoryMethod(kTypeName, FactoryT::IS_NOT_PARAMETERIZED,
                                &CreateFoo);

  base::Value d1 = CreateDictWithParameter(1);
  base::Value d2 = CreateDictWithParameter(2);

  std::string error;
  bool bad_message = false;

  // We create two instances with different dictionaries but because the type is
  // declared to be not parameterized, we should get the same instance.
  scoped_refptr<const BaseClass> c1(
      factory.Instantiate(kTypeName, &d1, &error, &bad_message));
  scoped_refptr<const BaseClass> c2(
      factory.Instantiate(kTypeName, &d2, &error, &bad_message));
  ASSERT_TRUE(c1.get());
  ASSERT_TRUE(c2.get());
  EXPECT_EQ(1, static_cast<const Foo*>(c1.get())->parameter());
  EXPECT_EQ(1, static_cast<const Foo*>(c2.get())->parameter());
  EXPECT_EQ(c1, c2);
}

TEST(DedupingFactoryTest, TypeNames) {
  FactoryT factory(2);
  factory.RegisterFactoryMethod(kTypeName, FactoryT::IS_PARAMETERIZED,
                                &CreateFoo);
  factory.RegisterFactoryMethod(kTypeName2, FactoryT::IS_PARAMETERIZED,
                                &CreateFoo);

  base::Value d1 = CreateDictWithParameter(1);

  std::string error;
  bool bad_message = false;

  scoped_refptr<const BaseClass> c1_a(
      factory.Instantiate(kTypeName, &d1, &error, &bad_message));
  scoped_refptr<const BaseClass> c1_b(
      factory.Instantiate(kTypeName2, &d1, &error, &bad_message));

  ASSERT_TRUE(c1_a.get());
  ASSERT_TRUE(c1_b.get());
  EXPECT_NE(c1_a, c1_b);
}

TEST(DedupingFactoryTest, Clear) {
  FactoryT factory(2);
  factory.RegisterFactoryMethod(kTypeName, FactoryT::IS_PARAMETERIZED,
                                &CreateFoo);

  base::Value d1 = CreateDictWithParameter(1);

  std::string error;
  bool bad_message = false;

  scoped_refptr<const BaseClass> c1_a(
      factory.Instantiate(kTypeName, &d1, &error, &bad_message));

  factory.ClearPrototypes();

  scoped_refptr<const BaseClass> c1_b(
      factory.Instantiate(kTypeName, &d1, &error, &bad_message));

  ASSERT_TRUE(c1_a.get());
  ASSERT_TRUE(c1_b.get());
  EXPECT_NE(c1_a, c1_b);
}

}  // namespace extensions


text:
experimental
============

This repository contains code testing out new language features


text:
//  Copyright 2010 Vicente J. Botet Escriba

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

#ifndef BOOST_DETAIL_WIN_PROCESS_HPP
#define BOOST_DETAIL_WIN_PROCESS_HPP

#include <boost/detail/win/basic_types.hpp>
#include <boost/detail/win/GetCurrentProcess.hpp>

namespace boost {
namespace detail {
namespace win32 {
#if defined( BOOST_USE_WINDOWS_H )
    using ::GetCurrentProcessId;
#else
# ifndef UNDER_CE
extern "C" {
    __declspec(dllimport) unsigned long __stdcall
        GetCurrentProcessId(void);
}
# else
    using ::GetCurrentProcessId;
# endif
#endif
}
}
}
#endif // BOOST_DETAIL_WIN_PROCESS_HPP