<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperInputFilenameListParameter.h"

namespace otb
{
namespace Wrapper
{

class TestApplication : public Application
{
public:
  /** Standard class typedefs. */
  typedef TestApplication               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(TestApplication, otb::Application);

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("TestApplication");
    SetDescription("This application helps developers to test parameters types");

    SetDocName("Test");
    SetDocLongDescription("The purpose of this application is to test parameters types.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag("Test");

    //std::cout << "TestApplication::DoInit" << std::endl;
    AddParameter(ParameterType_Empty, "boolean", "Boolean");
    AddParameter(ParameterType_Int, "int", "Integer");
    MandatoryOff("int");
    AddParameter(ParameterType_Float, "float", "Float");
    MandatoryOff("float");
    AddParameter(ParameterType_String, "string", "String");
    AddParameter(ParameterType_InputFilename, "filename", "File name");
    AddParameter(ParameterType_OutputFilename, "outfilename", "Output Filename");
    AddParameter(ParameterType_Directory, "directory", "Directory name");

    AddParameter(ParameterType_Choice, "choice", "Choice");
    AddChoice("choice.choice1", "Choice 1");
    AddChoice("choice.choice2", "Choice 2");
    AddChoice("choice.choice3", "Choice 3");
    AddParameter(ParameterType_Float,  "choice.choice1.floatchoice1", "Float of choice1");
    SetDefaultParameterFloat("choice.choice1.floatchoice1",   0.125);
    AddParameter(ParameterType_Float,  "choice.choice3.floatchoice3", "Float of choice3");
    SetDefaultParameterFloat("choice.choice3.floatchoice3",   5.0);

    AddParameter(ParameterType_Group, "ingroup", "Input Group");
    MandatoryOff("ingroup");
    AddParameter(ParameterType_Float,  "ingroup.integer", "Integer of Group");
    AddParameter(ParameterType_Group, "ingroup.images", "Input Images Group");
    AddParameter(ParameterType_InputImage, "ingroup.images.inputimage", "Input Image");

    AddParameter(ParameterType_Group, "outgroup", "Output Group");
    AddParameter(ParameterType_OutputImage, "outgroup.outputimage", "Output Image");

    AddParameter(ParameterType_InputImageList,  "il",   "Input image list");
    MandatoryOff("il");

    AddParameter( ParameterType_InputFilenameList, "fl", "Input filename list" );
    MandatoryOff( "fl" );

    AddParameter( ParameterType_InputVectorDataList, "vdl", "Input vector-data list" );
    MandatoryOff( "vdl" );

    AddParameter( ParameterType_StringList, "sl", "Input string list" );
    MandatoryOff( "sl" );

    AddParameter(ParameterType_ListView,  "cl", "Output Image channels");
    AddChoice("cl.choice1", "Choice1");
    AddChoice("cl.choice2", "Choice2");
    MandatoryOff("cl");

    AddParameter(ParameterType_ComplexInputImage,  "cin", "Input Complex Image");
    AddParameter(ParameterType_ComplexOutputImage,  "cout", "Output Complex Image");

    // Doc example parameter settings
    SetDocExampleParameterValue("boolean", "true");
    SetDocExampleParameterValue("filename", "myFilename.foo");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {}

  void DoExecute() ITK_OVERRIDE
  {
    if( HasValue("il") && IsParameterEnabled("il") )
      {
      FloatVectorImageListType * imgList = GetParameterImageList( "il" );
      SetParameterOutputImage(
        "outgroup.outputimage",
        imgList->GetNthElement( 0 )
      );
      }
    else if (HasValue("ingroup.images.inputimage") &&
      IsParameterEnabled("ingroup.images.inputimage",true) )
      {
      SetParameterOutputImage("outgroup.outputimage",
        GetParameterImage("ingroup.images.inputimage"));
      }
    else
      {
      otbAppLogFATAL("Waiting at least one input image");
      }

    SetParameterComplexOutputImage(
      "cout",
      GetParameterComplexImage( "cin" )
    );

    PrintStrings( "fl" );
  }

private:
  void PrintStrings( const std::string & key ) const
  {
    if( !IsParameterEnabled(key) )
      return;

    const Parameter * p = GetParameterByKey( key );
    assert( p!=nullptr );
    const StringListInterface * sli =
      dynamic_cast< const StringListInterface * >(p);
    assert( sli!=nullptr );

    StringListInterface::StringVector strings;

    sli->GetStrings( strings );

    std::cout << "{" << std::endl;
    {
      for( auto s : strings )
        std::cout << "'" << s << "'" << std::endl;
    }
    std::cout << "}"<< std::endl;
  }
};

} // end of namespace Wrapper
} // end of namespace otb

OTB_APPLICATION_EXPORT( otb::Wrapper::TestApplication )
<commit_msg>TEST: fix TestApplication<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWrapperInputFilenameListParameter.h"

namespace otb
{
namespace Wrapper
{

class TestApplication : public Application
{
public:
  /** Standard class typedefs. */
  typedef TestApplication               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(TestApplication, otb::Application);

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("TestApplication");
    SetDescription("This application helps developers to test parameters types");

    SetDocName("Test");
    SetDocLongDescription("The purpose of this application is to test parameters types.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag("Test");

    //std::cout << "TestApplication::DoInit" << std::endl;
    AddParameter(ParameterType_Empty, "boolean", "Boolean");
    AddParameter(ParameterType_Int, "int", "Integer");
    MandatoryOff("int");
    AddParameter(ParameterType_Float, "float", "Float");
    MandatoryOff("float");
    AddParameter(ParameterType_String, "string", "String");
    AddParameter(ParameterType_InputFilename, "filename", "File name");
    AddParameter(ParameterType_OutputFilename, "outfilename", "Output Filename");
    AddParameter(ParameterType_Directory, "directory", "Directory name");

    AddParameter(ParameterType_Choice, "choice", "Choice");
    AddChoice("choice.choice1", "Choice 1");
    AddChoice("choice.choice2", "Choice 2");
    AddChoice("choice.choice3", "Choice 3");
    AddParameter(ParameterType_Float,  "choice.choice1.floatchoice1", "Float of choice1");
    SetDefaultParameterFloat("choice.choice1.floatchoice1",   0.125);
    AddParameter(ParameterType_Float,  "choice.choice3.floatchoice3", "Float of choice3");
    SetDefaultParameterFloat("choice.choice3.floatchoice3",   5.0);

    AddParameter(ParameterType_Group, "ingroup", "Input Group");
    MandatoryOff("ingroup");
    AddParameter(ParameterType_Float,  "ingroup.integer", "Integer of Group");
    AddParameter(ParameterType_Group, "ingroup.images", "Input Images Group");
    AddParameter(ParameterType_InputImage, "ingroup.images.inputimage", "Input Image");

    AddParameter(ParameterType_Group, "outgroup", "Output Group");
    AddParameter(ParameterType_OutputImage, "outgroup.outputimage", "Output Image");

    AddParameter(ParameterType_InputImageList,  "il",   "Input image list");
    MandatoryOff("il");

    AddParameter( ParameterType_InputFilenameList, "fl", "Input filename list" );
    MandatoryOff( "fl" );

    AddParameter( ParameterType_InputVectorDataList, "vdl", "Input vector-data list" );
    MandatoryOff( "vdl" );

    AddParameter( ParameterType_StringList, "sl", "Input string list" );
    MandatoryOff( "sl" );

    AddParameter(ParameterType_ListView,  "cl", "Output Image channels");
    AddChoice("cl.choice1", "Choice1");
    AddChoice("cl.choice2", "Choice2");
    MandatoryOff("cl");

    AddParameter(ParameterType_ComplexInputImage,  "cin", "Input Complex Image");
    AddParameter(ParameterType_ComplexOutputImage,  "cout", "Output Complex Image");

    // Doc example parameter settings
    SetDocExampleParameterValue("boolean", "true");
    SetDocExampleParameterValue("filename", "myFilename.foo");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {}

  void DoExecute() ITK_OVERRIDE
  {
    if( HasValue("il") && IsParameterEnabled("il") )
      {
      FloatVectorImageListType * imgList = GetParameterImageList( "il" );
      SetParameterOutputImage(
        "outgroup.outputimage",
        imgList->GetNthElement( 0 )
      );
      }
    else if (HasValue("ingroup.images.inputimage") && IsParameterEnabled("ingroup") )
      {
      SetParameterOutputImage("outgroup.outputimage",
        GetParameterImage("ingroup.images.inputimage"));
      }
    else
      {
      otbAppLogFATAL("Waiting at least one input image");
      }

    SetParameterComplexOutputImage(
      "cout",
      GetParameterComplexImage( "cin" )
    );

    PrintStrings( "fl" );
  }

private:
  void PrintStrings( const std::string & key ) const
  {
    if( !IsParameterEnabled(key) )
      return;

    const Parameter * p = GetParameterByKey( key );
    assert( p!=nullptr );
    const StringListInterface * sli =
      dynamic_cast< const StringListInterface * >(p);
    assert( sli!=nullptr );

    StringListInterface::StringVector strings;

    sli->GetStrings( strings );

    std::cout << "{" << std::endl;
    {
      for( auto s : strings )
        std::cout << "'" << s << "'" << std::endl;
    }
    std::cout << "}"<< std::endl;
  }
};

} // end of namespace Wrapper
} // end of namespace otb

OTB_APPLICATION_EXPORT( otb::Wrapper::TestApplication )
<|endoftext|>


<commit_before>#include "group_flux_checker_sequential.h"

namespace bart {

namespace convergence {

GroupFluxCheckerSequential::GroupFluxCheckerSequential(
    std::unique_ptr<FluxCheckerI> &tester)
    : tester_(std::move(tester)) {}

bool GroupFluxCheckerSequential::CheckIfConverged(data::ScalarGroupFluxPtrs &current,
                                                  data::ScalarGroupFluxPtrs &last) {
  AssertThrow(current.size() > 0,
              dealii::ExcMessage("Current iteration group fluxes has 0 groups"));
  AssertThrow(last.size() > 0,
              dealii::ExcMessage("Last iteration group fluxes has 0 groups"));
  AssertThrow(last.size() == current.size(),
              dealii::ExcMessage("Current & last group iteration fluxes have"
                                 "different sizes"));

  for (auto current_pair = current.cbegin(), last_pair = last.cbegin();
       current_pair != current.cend(), last_pair != last.cend();
       ++current_pair, ++last_pair) {

    auto &[current_group_number, current_group_flux_ptr] = *current_pair;
    auto &[last_group_number, last_group_flux_ptr] = *last_pair;

    AssertThrow(current_group_number == last_group_number,
                dealii::ExcMessage("Current & last group numbers mismatched"));

    if (!tester_->CheckIfConverged(*current_group_flux_ptr,
                                   *last_group_flux_ptr)) {
      failed_group_ = current_group_number;
      return false;
    }
  }
  return true;
}

bool GroupFluxCheckerSequential::CheckIfConverged(data::AngularGroupFluxPtrs &current,
                                                  data::AngularGroupFluxPtrs &last) {
  AssertThrow(current.size() > 0,
              dealii::ExcMessage("Current iteration group fluxes has 0 groups & angles"));
  AssertThrow(last.size() > 0,
              dealii::ExcMessage("Last iteration group fluxes has 0 groups & angles"));
  AssertThrow(last.size() == current.size(),
              dealii::ExcMessage("Current & last group iteration fluxes have"
                                 "different sizes"));

  for (auto current_pair = current.cbegin(), last_pair = last.cbegin();
       current_pair != current.cend(), last_pair != last.cend();
       ++current_pair, ++last_pair) {

    auto &[current_dof_pair, current_group_flux_ptr] = *current_pair;
    auto &[last_dof_pair, last_group_flux_ptr] = *last_pair;
    auto &[current_group_number, current_direction] = current_dof_pair;
    auto &[last_group_number, last_direction] = last_dof_pair;

    AssertThrow(current_group_number == last_group_number,
                dealii::ExcMessage("Current & last group numbers mismatched"));
    AssertThrow(current_direction == last_direction,
                dealii::ExcMessage("Current & last directions mismatched"));

    if (!tester_->CheckIfConverged(*current_group_flux_ptr,
                                   *last_group_flux_ptr)) {
      failed_group_ = current_group_number;
      failed_angle_ = current_direction;
      return false;
    }
  }
  return true;

}

} // namespace convergence

} // namespace bart
<commit_msg>removed extraneous white space<commit_after>#include "group_flux_checker_sequential.h"

namespace bart {

namespace convergence {

GroupFluxCheckerSequential::GroupFluxCheckerSequential(
    std::unique_ptr<FluxCheckerI> &tester)
    : tester_(std::move(tester)) {}

bool GroupFluxCheckerSequential::CheckIfConverged(data::ScalarGroupFluxPtrs &current,
                                                  data::ScalarGroupFluxPtrs &last) {
  AssertThrow(current.size() > 0,
              dealii::ExcMessage("Current iteration group fluxes has 0 groups"));
  AssertThrow(last.size() > 0,
              dealii::ExcMessage("Last iteration group fluxes has 0 groups"));
  AssertThrow(last.size() == current.size(),
              dealii::ExcMessage("Current & last group iteration fluxes have"
                                 "different sizes"));

  for (auto current_pair = current.cbegin(), last_pair = last.cbegin();
       current_pair != current.cend(), last_pair != last.cend();
       ++current_pair, ++last_pair) {

    auto &[current_group_number, current_group_flux_ptr] = *current_pair;
    auto &[last_group_number, last_group_flux_ptr] = *last_pair;

    AssertThrow(current_group_number == last_group_number,
                dealii::ExcMessage("Current & last group numbers mismatched"));

    if (!tester_->CheckIfConverged(*current_group_flux_ptr,
                                   *last_group_flux_ptr)) {
      failed_group_ = current_group_number;
      return false;
    }
  }
  return true;
}

bool GroupFluxCheckerSequential::CheckIfConverged(data::AngularGroupFluxPtrs &current,
                                                  data::AngularGroupFluxPtrs &last) {
  AssertThrow(current.size() > 0,
              dealii::ExcMessage("Current iteration group fluxes has 0 groups & angles"));
  AssertThrow(last.size() > 0,
              dealii::ExcMessage("Last iteration group fluxes has 0 groups & angles"));
  AssertThrow(last.size() == current.size(),
              dealii::ExcMessage("Current & last group iteration fluxes have"
                                 "different sizes"));

  for (auto current_pair = current.cbegin(), last_pair = last.cbegin();
       current_pair != current.cend(), last_pair != last.cend();
       ++current_pair, ++last_pair) {

    auto &[current_dof_pair, current_group_flux_ptr] = *current_pair;
    auto &[last_dof_pair, last_group_flux_ptr] = *last_pair;
    auto &[current_group_number, current_direction] = current_dof_pair;
    auto &[last_group_number, last_direction] = last_dof_pair;

    AssertThrow(current_group_number == last_group_number,
                dealii::ExcMessage("Current & last group numbers mismatched"));
    AssertThrow(current_direction == last_direction,
                dealii::ExcMessage("Current & last directions mismatched"));

    if (!tester_->CheckIfConverged(*current_group_flux_ptr,
                                   *last_group_flux_ptr)) {
      failed_group_ = current_group_number;
      failed_angle_ = current_direction;
      return false;
    }
  }
  return true;
}

} // namespace convergence

} // namespace bart
<|endoftext|>


<commit_before>//
// Copyright 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "Firebase.h"

// Detect whether stable version of HTTP library is installed instead of
// master branch and patch in missing status and methods.
#ifndef HTTP_CODE_TEMPORARY_REDIRECT
#define HTTP_CODE_TEMPORARY_REDIRECT 307
#define USE_ESP_ARDUINO_CORE_2_0_0
#endif

namespace {
const char* kFirebaseFingerprint = "7A 54 06 9B DC 7A 25 B3 86 8D 66 53 48 2C 0B 96 42 C7 B3 0A";
const uint16_t kFirebasePort = 443;

String makeFirebaseURL(const String& path, const String& auth) {
  String url;
  if (path[0] != '/') {
    url = "/";
  }
  url += path + ".json";
  if (auth.length() > 0) {
    url += "?auth=" + auth;
  }
  return url;
}

}  // namespace

Firebase::Firebase(const String& host) : host_(host) {
  http_.setReuse(true);
}

Firebase& Firebase::auth(const String& auth) {
  auth_ = auth;
  return *this;
}

FirebaseGet Firebase::get(const String& path) {
  return FirebaseGet(host_, auth_, path, &http_);
}

FirebaseSet Firebase::set(const String& path, const String& value) {
  return FirebaseSet(host_, auth_, path, value, &http_);
}

FirebasePush Firebase::push(const String& path, const String& value) {
  return FirebasePush(host_, auth_, path, value, &http_);
}

FirebaseRemove Firebase::remove(const String& path) {
  return FirebaseRemove(host_, auth_, path, &http_);
}

FirebaseStream Firebase::stream(const String& path) {
  // TODO: create new client dedicated to stream.
  return FirebaseStream(host_, auth_, path, &http_);
}

// FirebaseCall
FirebaseCall::FirebaseCall(const String& host, const String& auth,
                           const char* method, const String& path,
                           const String& data, HTTPClient* http) : http_(http) {
  String url = makeFirebaseURL(path, auth);
  http_->setReuse(true);
  http_->begin(host, kFirebasePort, url, true, kFirebaseFingerprint);

  bool followRedirect = false;
  if (method == "STREAM") {
    method = "GET";
    http_->addHeader("Accept", "text/event-stream");
    followRedirect = true;
  }

  if (followRedirect) {
    const char* headers[] = {"Location"};
    http_->collectHeaders(headers, 1);
  }

  int status = http_->sendRequest(method, (uint8_t*)data.c_str(), data.length());

  // TODO: Add a max redirect check
  if (followRedirect) {
    while (status == HTTP_CODE_TEMPORARY_REDIRECT) {
      String location = http_->header("Location");
      http_->setReuse(false);
      http_->end();
      http_->setReuse(true);
      http_->begin(location, kFirebaseFingerprint);
      status = http_->sendRequest("GET", (uint8_t*)NULL, 0);
    }
  }

  if (status != 200) {
#ifdef USE_ESP_ARDUINO_CORE_2_0_0
    error_ = FirebaseError(status, String(method) + " " + url + ": " + status);
#else
    error_ = FirebaseError(status, String(method) + " " + url + ": " + HTTPClient::errorToString(status));
#endif
  }

  // if not streaming.
  if (!followRedirect) {
    response_ = http_->getString();
  }
}

const JsonObject& FirebaseCall::json() {
  //TODO(edcoyne): This is not efficient, we should do something smarter with
  //the buffers.
  buffer_ = DynamicJsonBuffer();
  return buffer_.parseObject(response());
}

// FirebaseGet
FirebaseGet::FirebaseGet(const String& host, const String& auth,
                         const String& path,
                         HTTPClient* http)
  : FirebaseCall(host, auth, "GET", path, "", http) {
}

// FirebaseSet
FirebaseSet::FirebaseSet(const String& host, const String& auth,
       const String& path, const String& value,
       HTTPClient* http)
  : FirebaseCall(host, auth, "PUT", path, value, http) {
  if (!error()) {
    // TODO: parse json
    json_ = response();
  }
}
// FirebasePush
FirebasePush::FirebasePush(const String& host, const String& auth,
                           const String& path, const String& value,
                           HTTPClient* http)
  : FirebaseCall(host, auth, "POST", path, value, http) {
  if (!error()) {
    name_ = parseResponse()["name"].as<const char*>();
  }
}

// FirebasePush
FirebaseRemove::FirebaseRemove(const String& host, const String& auth,
                               const String& path,
                               HTTPClient* http)
  : FirebaseCall(host, auth, "DELETE", path, "", http) {
}

// FirebaseStream
FirebaseStream::FirebaseStream(const String& host, const String& auth,
                               const String& path,
                               HTTPClient* http)
  : FirebaseCall(host, auth, "STREAM", path, "", http) {
}

bool FirebaseStream::available() {
  return http_->getStreamPtr()->available();
}

FirebaseStream::Event FirebaseStream::read(String& event) {
  auto client = http_->getStreamPtr();
  Event type;
  String typeStr = client->readStringUntil('\n').substring(7);
  if (typeStr == "put") {
    type = Event::PUT;
  } else if (typeStr == "patch") {
    type = Event::PATCH;
  } else {
    type = Event::UNKNOWN;
  }
  event = client->readStringUntil('\n').substring(6);
  client->readStringUntil('\n'); // consume separator
  return type;
}
<commit_msg>forgot a parseResponse invocation<commit_after>//
// Copyright 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "Firebase.h"

// Detect whether stable version of HTTP library is installed instead of
// master branch and patch in missing status and methods.
#ifndef HTTP_CODE_TEMPORARY_REDIRECT
#define HTTP_CODE_TEMPORARY_REDIRECT 307
#define USE_ESP_ARDUINO_CORE_2_0_0
#endif

namespace {
const char* kFirebaseFingerprint = "7A 54 06 9B DC 7A 25 B3 86 8D 66 53 48 2C 0B 96 42 C7 B3 0A";
const uint16_t kFirebasePort = 443;

String makeFirebaseURL(const String& path, const String& auth) {
  String url;
  if (path[0] != '/') {
    url = "/";
  }
  url += path + ".json";
  if (auth.length() > 0) {
    url += "?auth=" + auth;
  }
  return url;
}

}  // namespace

Firebase::Firebase(const String& host) : host_(host) {
  http_.setReuse(true);
}

Firebase& Firebase::auth(const String& auth) {
  auth_ = auth;
  return *this;
}

FirebaseGet Firebase::get(const String& path) {
  return FirebaseGet(host_, auth_, path, &http_);
}

FirebaseSet Firebase::set(const String& path, const String& value) {
  return FirebaseSet(host_, auth_, path, value, &http_);
}

FirebasePush Firebase::push(const String& path, const String& value) {
  return FirebasePush(host_, auth_, path, value, &http_);
}

FirebaseRemove Firebase::remove(const String& path) {
  return FirebaseRemove(host_, auth_, path, &http_);
}

FirebaseStream Firebase::stream(const String& path) {
  // TODO: create new client dedicated to stream.
  return FirebaseStream(host_, auth_, path, &http_);
}

// FirebaseCall
FirebaseCall::FirebaseCall(const String& host, const String& auth,
                           const char* method, const String& path,
                           const String& data, HTTPClient* http) : http_(http) {
  String url = makeFirebaseURL(path, auth);
  http_->setReuse(true);
  http_->begin(host, kFirebasePort, url, true, kFirebaseFingerprint);

  bool followRedirect = false;
  if (method == "STREAM") {
    method = "GET";
    http_->addHeader("Accept", "text/event-stream");
    followRedirect = true;
  }

  if (followRedirect) {
    const char* headers[] = {"Location"};
    http_->collectHeaders(headers, 1);
  }

  int status = http_->sendRequest(method, (uint8_t*)data.c_str(), data.length());

  // TODO: Add a max redirect check
  if (followRedirect) {
    while (status == HTTP_CODE_TEMPORARY_REDIRECT) {
      String location = http_->header("Location");
      http_->setReuse(false);
      http_->end();
      http_->setReuse(true);
      http_->begin(location, kFirebaseFingerprint);
      status = http_->sendRequest("GET", (uint8_t*)NULL, 0);
    }
  }

  if (status != 200) {
#ifdef USE_ESP_ARDUINO_CORE_2_0_0
    error_ = FirebaseError(status, String(method) + " " + url + ": " + status);
#else
    error_ = FirebaseError(status, String(method) + " " + url + ": " + HTTPClient::errorToString(status));
#endif
  }

  // if not streaming.
  if (!followRedirect) {
    response_ = http_->getString();
  }
}

const JsonObject& FirebaseCall::json() {
  //TODO(edcoyne): This is not efficient, we should do something smarter with
  //the buffers.
  buffer_ = DynamicJsonBuffer();
  return buffer_.parseObject(response());
}

// FirebaseGet
FirebaseGet::FirebaseGet(const String& host, const String& auth,
                         const String& path,
                         HTTPClient* http)
  : FirebaseCall(host, auth, "GET", path, "", http) {
}

// FirebaseSet
FirebaseSet::FirebaseSet(const String& host, const String& auth,
       const String& path, const String& value,
       HTTPClient* http)
  : FirebaseCall(host, auth, "PUT", path, value, http) {
  if (!error()) {
    // TODO: parse json
    json_ = response();
  }
}
// FirebasePush
FirebasePush::FirebasePush(const String& host, const String& auth,
                           const String& path, const String& value,
                           HTTPClient* http)
  : FirebaseCall(host, auth, "POST", path, value, http) {
  if (!error()) {
    name_ = json()["name"].as<const char*>();
  }
}

// FirebasePush
FirebaseRemove::FirebaseRemove(const String& host, const String& auth,
                               const String& path,
                               HTTPClient* http)
  : FirebaseCall(host, auth, "DELETE", path, "", http) {
}

// FirebaseStream
FirebaseStream::FirebaseStream(const String& host, const String& auth,
                               const String& path,
                               HTTPClient* http)
  : FirebaseCall(host, auth, "STREAM", path, "", http) {
}

bool FirebaseStream::available() {
  return http_->getStreamPtr()->available();
}

FirebaseStream::Event FirebaseStream::read(String& event) {
  auto client = http_->getStreamPtr();
  Event type;
  String typeStr = client->readStringUntil('\n').substring(7);
  if (typeStr == "put") {
    type = Event::PUT;
  } else if (typeStr == "patch") {
    type = Event::PATCH;
  } else {
    type = Event::UNKNOWN;
  }
  event = client->readStringUntil('\n').substring(6);
  client->readStringUntil('\n'); // consume separator
  return type;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

namespace otb
{
namespace Wrapper
{

class TestApplication : public Application
{
public:
  /** Standard class typedefs. */
  typedef TestApplication               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(TestApplication, otb::Application);

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("TestApplication");
    SetDescription("This application helps developers to test parameters types");

    SetDocName("Test");
    SetDocLongDescription("The purpose of this application is to test parameters types.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag("Test");

    //std::cout << "TestApplication::DoInit" << std::endl;
    AddParameter(ParameterType_Empty, "boolean", "Boolean");
    AddParameter(ParameterType_Int, "int", "Integer");
    MandatoryOff("int");
    AddParameter(ParameterType_Float, "float", "Float");
    MandatoryOff("float");
    AddParameter(ParameterType_String, "string", "String");
    AddParameter(ParameterType_InputFilename, "filename", "File name");
    AddParameter(ParameterType_OutputFilename, "outfilename", "Output Filename");
    AddParameter(ParameterType_Directory, "directory", "Directory name");

    AddParameter(ParameterType_Choice, "choice", "Choice");
    AddChoice("choice.choice1", "Choice 1");
    AddChoice("choice.choice2", "Choice 2");
    AddChoice("choice.choice3", "Choice 3");
    AddParameter(ParameterType_Float,  "choice.choice1.floatchoice1", "Float of choice1");
    SetDefaultParameterFloat("choice.choice1.floatchoice1",   0.125);
    AddParameter(ParameterType_Float,  "choice.choice3.floatchoice3", "Float of choice3");
    SetDefaultParameterFloat("choice.choice3.floatchoice3",   5.0);

    AddParameter(ParameterType_Group, "ingroup", "Input Group");
    MandatoryOff("ingroup");
    AddParameter(ParameterType_Float,  "ingroup.integer", "Integer of Group");
    AddParameter(ParameterType_Group, "ingroup.images", "Input Images Group");
    AddParameter(ParameterType_InputImage, "ingroup.images.inputimage", "Input Image");

    AddParameter(ParameterType_Group, "outgroup", "Output Group");
    AddParameter(ParameterType_OutputImage, "outgroup.outputimage", "Output Image");

    AddParameter(ParameterType_InputImageList,  "il",   "Input image list");
    MandatoryOff("il");

    AddParameter(ParameterType_ListView,  "cl", "Output Image channels");
    AddChoice("cl.choice1", "Choice1");
    AddChoice("cl.choice2", "Choice2");
    MandatoryOff("cl");

    AddParameter(ParameterType_ComplexInputImage,  "cin", "Input Complex Image");
    AddParameter(ParameterType_ComplexOutputImage,  "cout", "Output Complex Image");

    // Doc example parameter settings
    SetDocExampleParameterValue("boolean", "true");
    SetDocExampleParameterValue("filename", "myFilename.foo");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    //std::cout << "TestApplication::DoUpdateParameters" << std::endl;
  }

  void DoExecute() ITK_OVERRIDE
  {
    FloatVectorImageListType* imgList = GetParameterImageList("il");
    SetParameterOutputImage("outgroup.outputimage", imgList->GetNthElement(0));
    SetParameterComplexOutputImage("cout", GetParameterComplexImage("cin"));
    //std::cout << "TestApplication::DoExecute" << std::endl;
  }
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::TestApplication)
<commit_msg>ENH: Added Input filename list parameter to Test-App.<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

namespace otb
{
namespace Wrapper
{

class TestApplication : public Application
{
public:
  /** Standard class typedefs. */
  typedef TestApplication               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(TestApplication, otb::Application);

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("TestApplication");
    SetDescription("This application helps developers to test parameters types");

    SetDocName("Test");
    SetDocLongDescription("The purpose of this application is to test parameters types.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag("Test");

    //std::cout << "TestApplication::DoInit" << std::endl;
    AddParameter(ParameterType_Empty, "boolean", "Boolean");
    AddParameter(ParameterType_Int, "int", "Integer");
    MandatoryOff("int");
    AddParameter(ParameterType_Float, "float", "Float");
    MandatoryOff("float");
    AddParameter(ParameterType_String, "string", "String");
    AddParameter(ParameterType_InputFilename, "filename", "File name");
    AddParameter(ParameterType_OutputFilename, "outfilename", "Output Filename");
    AddParameter(ParameterType_Directory, "directory", "Directory name");

    AddParameter(ParameterType_Choice, "choice", "Choice");
    AddChoice("choice.choice1", "Choice 1");
    AddChoice("choice.choice2", "Choice 2");
    AddChoice("choice.choice3", "Choice 3");
    AddParameter(ParameterType_Float,  "choice.choice1.floatchoice1", "Float of choice1");
    SetDefaultParameterFloat("choice.choice1.floatchoice1",   0.125);
    AddParameter(ParameterType_Float,  "choice.choice3.floatchoice3", "Float of choice3");
    SetDefaultParameterFloat("choice.choice3.floatchoice3",   5.0);

    AddParameter(ParameterType_Group, "ingroup", "Input Group");
    MandatoryOff("ingroup");
    AddParameter(ParameterType_Float,  "ingroup.integer", "Integer of Group");
    AddParameter(ParameterType_Group, "ingroup.images", "Input Images Group");
    AddParameter(ParameterType_InputImage, "ingroup.images.inputimage", "Input Image");

    AddParameter(ParameterType_Group, "outgroup", "Output Group");
    AddParameter(ParameterType_OutputImage, "outgroup.outputimage", "Output Image");

    AddParameter(ParameterType_InputImageList,  "il",   "Input image list");
    MandatoryOff("il");

    AddParameter( ParameterType_InputFilenameList, "fl", "Input filename list" );
    MandatoryOff( "fl" );

    AddParameter(ParameterType_ListView,  "cl", "Output Image channels");
    AddChoice("cl.choice1", "Choice1");
    AddChoice("cl.choice2", "Choice2");
    MandatoryOff("cl");

    AddParameter(ParameterType_ComplexInputImage,  "cin", "Input Complex Image");
    AddParameter(ParameterType_ComplexOutputImage,  "cout", "Output Complex Image");

    // Doc example parameter settings
    SetDocExampleParameterValue("boolean", "true");
    SetDocExampleParameterValue("filename", "myFilename.foo");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    //std::cout << "TestApplication::DoUpdateParameters" << std::endl;
  }

  void DoExecute() ITK_OVERRIDE
  {
    FloatVectorImageListType* imgList = GetParameterImageList("il");
    SetParameterOutputImage("outgroup.outputimage", imgList->GetNthElement(0));
    SetParameterComplexOutputImage("cout", GetParameterComplexImage("cin"));
    //std::cout << "TestApplication::DoExecute" << std::endl;
  }
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::TestApplication)
<|endoftext|>


<commit_before>/*
    This file is part of Akonadi.

    Copyright (c) 2006 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
    USA.
*/

#include "dataprovider.h"

#include "agendamodel.h"
#include "contactmodel.h"
#include "dummymodel.h"

#include <libakonadi/jobqueue.h>
#include <libakonadi/itemappendjob.h>
#include <libakonadi/messagefetchjob.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/icalformat.h>

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

#include <QDebug>

DataProvider::DataProvider()
  : mAgendaModel( 0 ), mContactModel( 0 )
{
}

void DataProvider::setupEventData()
{
  mAgendaModel = new AgendaModel();
  mModel = mAgendaModel;

  addEvent( 2006, 1, 10, 12, 13, "Eins" );
  addEvent( 2006, 1, 10, 15, 20, "Zwei" );
  addEvent( 2006, 1, 11, 12, 13, "Drei" );
  addEvent( 2006, 1, 12, 12, 13, "Vier" );
  addEvent( 2006, 1, 11, 8, 13, "Fuenf" );
  addEvent( 2006, 1, 20, 11, 13, "Sechs" );
  addEvent( 2006, 1, 21, 11, 13, "Sieben" );
  addEvent( 2006, 1, 24, 5, 23, "Acht" );
  addEvent( 2006, 1, 26, 0, 23, "Neun" );

  for( int i = 0; i < 23; ++i ) {
    addEvent( 2006, 2, i, i, i+1, "Event " + QString( i ) );
  }
}

void DataProvider::addEvent( int year, int month, int day,
  int startHour, int endHour, const QString &title )
{
  if ( !mAgendaModel ) return;

  Event e;

  e.start = QDateTime( QDate( year, month, day ), QTime( startHour, 0 ) );
  e.end = QDateTime( QDate( year, month, day ), QTime( endHour, 0 ) );
  e.title = title;

  mAgendaModel->addEvent( e );
}

void DataProvider::setupContactData()
{
  mContactModel = new ContactModel();
  mModel = mContactModel;

  addContact( "Dummy User", "dummy@example.com" );
  addContact( "Doris Dauerwurst" );
  addContact( "Hans Wurst", "hw@abc.de", "+493012345" );
  addContact( "Herr A" );
  addContact( "Herr B" );
  addContact( "Herr C" );
  addContact( "Herr D" );
  addContact( "Herr E" );
  addContact( "Herr F" );
  addContact( "Herr G" );
  addContact( "Herr H" );
  addContact( "Klara Klossbruehe", "kk@abc.de" );
  addContact( "Klaas Klever" );
  addContact( "Kater Karlo" );
  addContact( "Petrosilius Zwackelmann" );
  addContact( "Rumplestilzchen" );
  addContact( "Sabine Sonnenschein", "sonnenschein@sabine.org" );
  addContact( "Sebastian Sauertop", "sauertopf@sebastian.org" );
  addContact( "Xerxes", "xerxes@example.com" );
  addContact( "Zacharias Zimplerlich" );
}

void DataProvider::setupDummyData()
{
  mModel = new DummyModel();
}

void DataProvider::addContact( const QString &name, const QString &email,
  const QString &phone )
{
  if ( !mContactModel ) return;

  Contact c;

  c.name = name;
  c.email = email;
  c.phone = phone;

  mContactModel->addContact( c );
}

StripeView::Model *DataProvider::model() const
{
  return mModel;
}

void DataProvider::loadFile()
{
  if ( mAgendaModel ) {
    mAgendaModel->clear();

    KCal::CalendarLocal cal( "UTC" );
    cal.load( "kagenda.ics" );

    KCal::Event::List events = cal.events();
    foreach( KCal::Event *event, events ) {
      Event e;
      e.title = event->summary();
      e.start = event->dtStart();
      e.end = event->dtEnd();

      mAgendaModel->addEvent( e );
    }
  }
}

void DataProvider::saveFile()
{
  if ( mAgendaModel ) {
    KCal::CalendarLocal cal( "UTC" );
    foreach( Event e, mAgendaModel->events() ) {
      KCal::Event *event = new KCal::Event();
      event->setSummary( e.title );
      event->setDtStart( e.start );
      event->setDtEnd( e.end );
      event->setFloats( false );
      cal.addEvent( event );
    }
    cal.save( "kagenda.ics" );
  }

  if ( mContactModel ) {
  }
}

void DataProvider::loadAkonadi()
{
  if ( mAgendaModel ) {
    PIM::MessageFetchJob job( "res2/foo2" );
    if ( !job.exec() ) {
      KMessageBox::error( 0, "Error fetching messages" );
    } else {

    }
  }
}

void DataProvider::saveAkonadi()
{
  if ( mAgendaModel ) {
//    PIM::JobQueue jobQueue( this );
    KCal::ICalFormat format;
    foreach( Event e, mAgendaModel->events() ) {
      KCal::Event *event = new KCal::Event();
      event->setSummary( e.title );
      event->setDtStart( e.start );
      event->setDtEnd( e.end );
      event->setFloats( false );
      QString ical = format.toICalString( event );
      ical = "aaa";
      PIM::ItemAppendJob *job = new PIM::ItemAppendJob( "res2/foo2", ical.toUtf8(),
        "text/calendar", this );
      if ( !job->exec() ) {
        KMessageBox::error( 0, i18n("Error") );
      }
//      jobQueue.addJob( job );
    }
#if 0
    if ( !jobQueue.exec() ) {
      KMessageBox::error( 0, i18n("Error saving to Akonadi") );
    }
#endif
  }
}

void DataProvider::load()
{
  loadFile();
}

void DataProvider::save()
{
  saveFile();
  qDebug() << "tick";
  saveAkonadi();
  qDebug() << "tack";
}

#include "dataprovider.moc"
<commit_msg>Write actual iCalendar.<commit_after>/*
    This file is part of Akonadi.

    Copyright (c) 2006 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
    USA.
*/

#include "dataprovider.h"

#include "agendamodel.h"
#include "contactmodel.h"
#include "dummymodel.h"

#include <libakonadi/jobqueue.h>
#include <libakonadi/itemappendjob.h>
#include <libakonadi/messagefetchjob.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/icalformat.h>

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

#include <QDebug>

DataProvider::DataProvider()
  : mAgendaModel( 0 ), mContactModel( 0 )
{
}

void DataProvider::setupEventData()
{
  mAgendaModel = new AgendaModel();
  mModel = mAgendaModel;

  addEvent( 2006, 1, 10, 12, 13, "Eins" );
  addEvent( 2006, 1, 10, 15, 20, "Zwei" );
  addEvent( 2006, 1, 11, 12, 13, "Drei" );
  addEvent( 2006, 1, 12, 12, 13, "Vier" );
  addEvent( 2006, 1, 11, 8, 13, "Fuenf" );
  addEvent( 2006, 1, 20, 11, 13, "Sechs" );
  addEvent( 2006, 1, 21, 11, 13, "Sieben" );
  addEvent( 2006, 1, 24, 5, 23, "Acht" );
  addEvent( 2006, 1, 26, 0, 23, "Neun" );

  for( int i = 0; i < 23; ++i ) {
    addEvent( 2006, 2, i, i, i+1, "Event " + QString( i ) );
  }
}

void DataProvider::addEvent( int year, int month, int day,
  int startHour, int endHour, const QString &title )
{
  if ( !mAgendaModel ) return;

  Event e;

  e.start = QDateTime( QDate( year, month, day ), QTime( startHour, 0 ) );
  e.end = QDateTime( QDate( year, month, day ), QTime( endHour, 0 ) );
  e.title = title;

  mAgendaModel->addEvent( e );
}

void DataProvider::setupContactData()
{
  mContactModel = new ContactModel();
  mModel = mContactModel;

  addContact( "Dummy User", "dummy@example.com" );
  addContact( "Doris Dauerwurst" );
  addContact( "Hans Wurst", "hw@abc.de", "+493012345" );
  addContact( "Herr A" );
  addContact( "Herr B" );
  addContact( "Herr C" );
  addContact( "Herr D" );
  addContact( "Herr E" );
  addContact( "Herr F" );
  addContact( "Herr G" );
  addContact( "Herr H" );
  addContact( "Klara Klossbruehe", "kk@abc.de" );
  addContact( "Klaas Klever" );
  addContact( "Kater Karlo" );
  addContact( "Petrosilius Zwackelmann" );
  addContact( "Rumplestilzchen" );
  addContact( "Sabine Sonnenschein", "sonnenschein@sabine.org" );
  addContact( "Sebastian Sauertop", "sauertopf@sebastian.org" );
  addContact( "Xerxes", "xerxes@example.com" );
  addContact( "Zacharias Zimplerlich" );
}

void DataProvider::setupDummyData()
{
  mModel = new DummyModel();
}

void DataProvider::addContact( const QString &name, const QString &email,
  const QString &phone )
{
  if ( !mContactModel ) return;

  Contact c;

  c.name = name;
  c.email = email;
  c.phone = phone;

  mContactModel->addContact( c );
}

StripeView::Model *DataProvider::model() const
{
  return mModel;
}

void DataProvider::loadFile()
{
  if ( mAgendaModel ) {
    mAgendaModel->clear();

    KCal::CalendarLocal cal( "UTC" );
    cal.load( "kagenda.ics" );

    KCal::Event::List events = cal.events();
    foreach( KCal::Event *event, events ) {
      Event e;
      e.title = event->summary();
      e.start = event->dtStart();
      e.end = event->dtEnd();

      mAgendaModel->addEvent( e );
    }
  }
}

void DataProvider::saveFile()
{
  if ( mAgendaModel ) {
    KCal::CalendarLocal cal( "UTC" );
    foreach( Event e, mAgendaModel->events() ) {
      KCal::Event *event = new KCal::Event();
      event->setSummary( e.title );
      event->setDtStart( e.start );
      event->setDtEnd( e.end );
      event->setFloats( false );
      cal.addEvent( event );
    }
    cal.save( "kagenda.ics" );
  }

  if ( mContactModel ) {
  }
}

void DataProvider::loadAkonadi()
{
  if ( mAgendaModel ) {
    PIM::MessageFetchJob job( "res2/foo2" );
    if ( !job.exec() ) {
      KMessageBox::error( 0, "Error fetching messages" );
    } else {

    }
  }
}

void DataProvider::saveAkonadi()
{
  if ( mAgendaModel ) {
//    PIM::JobQueue jobQueue( this );
    KCal::ICalFormat format;
    foreach( Event e, mAgendaModel->events() ) {
      KCal::Event *event = new KCal::Event();
      event->setSummary( e.title );
      event->setDtStart( e.start );
      event->setDtEnd( e.end );
      event->setFloats( false );
      QString ical = format.toICalString( event );
      PIM::ItemAppendJob *job = new PIM::ItemAppendJob( "res2/foo2", ical.toUtf8(),
        "text/calendar", this );
      if ( !job->exec() ) {
        KMessageBox::error( 0, i18n("Error") );
      }
//      jobQueue.addJob( job );
    }
#if 0
    if ( !jobQueue.exec() ) {
      KMessageBox::error( 0, i18n("Error saving to Akonadi") );
    }
#endif
  }
}

void DataProvider::load()
{
  loadFile();
}

void DataProvider::save()
{
  saveFile();
  qDebug() << "tick";
  saveAkonadi();
  qDebug() << "tack";
}

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


<commit_before>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Copyright (c) 2020 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include "MockRpcConnection.h"

namespace opflexagent {

void ResponseDict::init() {
    uint64_t j = 1001;
    for (unsigned int i = 0 ; i < no_of_span_msgs; i++, j++) {
        d[i].GetAllocator().Clear();
        d[i].Parse(response[i].c_str());
        dict.emplace(j, i);
    }
    j = 2001;
    for (unsigned int i = no_of_span_msgs ; i < (no_of_span_msgs + no_of_netflow_msgs); i++, j++) {
        d[i].GetAllocator().Clear();
        d[i].Parse(response[i].c_str());
        dict.emplace(j, i);
    }
}

ResponseDict& ResponseDict::Instance() {
    static ResponseDict inst;
    if (!inst.isInitialized) {
        inst.init();
        inst.isInitialized = true;
    }
    return inst;
}

void MockRpcConnection::sendTransaction(const uint64_t& reqId, const list<JsonRpcTransactMessage>& requests, Transaction* trans) {
    ResponseDict& rDict = ResponseDict::Instance();
    auto itr = rDict.dict.find(reqId);
    if (itr != rDict.dict.end()) {
        trans->handleTransaction(reqId, rDict.d[itr->second]);
    } else {
        LOG(DEBUG) << "No response found for req " << reqId;
    }
}

}<commit_msg>Better mock JSONRPC requests in UT<commit_after>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Copyright (c) 2020 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include "MockRpcConnection.h"

namespace opflexagent {

void ResponseDict::init() {
    uint64_t j = 1001;
    for (unsigned int i = 0 ; i < no_of_span_msgs; i++, j++) {
        d[i].GetAllocator().Clear();
        d[i].Parse(response[i].c_str());
        dict.emplace(j, i);
    }
    j = 2001;
    for (unsigned int i = no_of_span_msgs ; i < (no_of_span_msgs + no_of_netflow_msgs); i++, j++) {
        d[i].GetAllocator().Clear();
        d[i].Parse(response[i].c_str());
        dict.emplace(j, i);
    }
}

ResponseDict& ResponseDict::Instance() {
    static ResponseDict inst;
    if (!inst.isInitialized) {
        inst.init();
        inst.isInitialized = true;
    }
    return inst;
}

void MockRpcConnection::sendTransaction(const uint64_t& reqId, const list<JsonRpcTransactMessage>& requests, Transaction* trans) {
    // prepare request
    std::shared_ptr<TransactReq> transactReq = std::make_shared<TransactReq>(TransactReq(requests, reqId));
    yajr::rpc::MethodName method(transactReq->getMethod().c_str());
    opflex::jsonrpc::PayloadWrapper wrapper(transactReq.get());
    ::yajr::internal::StringQueue sq;
    yajr::rpc::SendHandler sendHandler(sq);
    wrapper(sendHandler);

    // fake the response
    ResponseDict& rDict = ResponseDict::Instance();
    auto itr = rDict.dict.find(reqId);
    if (itr != rDict.dict.end()) {
        trans->handleTransaction(reqId, rDict.d[itr->second]);
    } else {
        LOG(DEBUG) << "No response found for req " << reqId;
    }
}

}<|endoftext|>


<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/fscapi.h"
#include "base/adapter/PlatformAdapter.h"
#include "base/util/StringBuffer.h"
#include "base/util/StringMap.h"
#include "base/Log.h"

BEGIN_NAMESPACE

StringBuffer PlatformAdapter::appContext(DEFAULT_APP_CONTEXT);
StringBuffer PlatformAdapter::homeFolder;
StringBuffer PlatformAdapter::configFolder;
bool PlatformAdapter::initialized = false;

// Initializes the platform-dependent parameters of the library.
void PlatformAdapter::init(const char *appcontext) {
    if(!initialized) {
        appContext = appcontext;
        homeFolder = "";
        configFolder = "";
    }
    else {
        LOG.error("PlatformAdapter::init(): already initialized.");
    }
}

// Initializes the platform-dependent parameters of the library.
void PlatformAdapter::init(const char *appcontext, StringMap& env) {
    if(!initialized) {
        appContext = appcontext;
        homeFolder = env["HOME_FOLDER"];
        configFolder = env["CONFIG_FOLDER"];
    }
    else {
        LOG.error("PlatformAdapter::init(): already initialized.");
    }
}

// Returns the application context
const StringBuffer& PlatformAdapter::getAppContext() {
    return appContext;
}

// Returns the home folder, or an empty string on failure.
const StringBuffer& PlatformAdapter::getHomeFolder() {
    if (homeFolder.empty()) {
        LOG.error("PlatformAdapter::getHomeFolder: to be implemented");
    }
    return homeFolder;
}

// Returns the home folder, or an empty string on failure.
const StringBuffer& PlatformAdapter::getConfigFolder() {
    if (configFolder.empty()){
        LOG.error("PlatformAdapter::getConfigFolder: to be implemented");
    }
    return configFolder;
}

END_NAMESPACE

<commit_msg>getHomeFolder()/getConfigFolder() implementation added<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/fscapi.h"
#include "base/adapter/PlatformAdapter.h"
#include "base/util/StringBuffer.h"
#include "base/util/StringMap.h"
#include "base/util/stringUtils.h"
#include "base/Log.h"

// include CEikonEnv framework for CEikonEnv::Static()
#include <eikapp.h>
#include <eikappui.h>
#include <eikenv.h>

BEGIN_NAMESPACE

StringBuffer PlatformAdapter::appContext(DEFAULT_APP_CONTEXT);
StringBuffer PlatformAdapter::homeFolder;
StringBuffer PlatformAdapter::configFolder;
bool PlatformAdapter::initialized = false;

// Initializes the platform-dependent parameters of the library.
void PlatformAdapter::init(const char *appcontext) {
    if(!initialized) {
        appContext = appcontext;
        homeFolder = "";
        configFolder = "";
        initialized = true;
    }
    else {
        LOG.error("PlatformAdapter::init(): already initialized.");
    }
}

// Initializes the platform-dependent parameters of the library.
void PlatformAdapter::init(const char *appcontext, StringMap& env) {
    if(!initialized) {
        appContext = appcontext;
        homeFolder = env["HOME_FOLDER"];
        configFolder = env["CONFIG_FOLDER"];
        initialized = true;
    }
    else {
        LOG.error("PlatformAdapter::init(): already initialized.");
    }
}

// Returns the application context
const StringBuffer& PlatformAdapter::getAppContext() {
    return appContext;
}

// Returns the home folder. On Symbian platform home folder is
// the application private folder
const StringBuffer& PlatformAdapter::getHomeFolder() {
    if (homeFolder.empty()) {
        TFileName appFullName = CEikonEnv::Static()->EikAppUi()->Application()->AppFullName();
        TParsePtr parse1(appFullName);
        TPtrC currentDrive = parse1.Drive();

        // Get ONLY the private path (e.g. "\private\2001BBA4")
        TBuf<KMaxPath> privatePath;
        CEikonEnv::Static()->FsSession().PrivatePath(privatePath);
        TParsePtr parse2(privatePath);
        TPtrC currentPath = parse2.Path();

        StringBuffer drive = bufToStringBuffer(currentDrive);
        homeFolder.append(drive);
        StringBuffer path = bufToStringBuffer(currentPath);
        homeFolder.append(path);
    }

    return homeFolder;
}

// Returns the config folder (on Symbian platform is the same as home folder)
const StringBuffer& PlatformAdapter::getConfigFolder() {
    return getHomeFolder();
}

END_NAMESPACE

<|endoftext|>


<commit_before>/*! \file MatTools.cpp
    \brief Implements the MatTools class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>

#include "CycException.h"
#include "Logger.h"
#include "Timer.h"
#include "MatTools.h"
#include "Material.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){
  IsoVector vec;
  CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));
  double kg = 0;

  if( !mats.empty() ){
    CompMapPtr comp_to_add;
    deque<mat_rsrc_ptr>::iterator mat;
    int iso;
    CompMap::const_iterator comp;

    for(mat = mats.begin(); mat != mats.end(); ++mat){
      kg += (*mat)->mass(MassUnit(KG));
      comp_to_add = (*mat)->isoVector().comp();
      comp_to_add->massify();
      for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {
        iso = comp->first;
        if(sum_comp->count(iso)!=0) {
          (*sum_comp)[iso] = (*sum_comp)[iso] + (comp->second)*kg;
        } else {
          (*sum_comp)[iso] = (comp->second)*kg;
        }
      }
    }
  } else {
    (*sum_comp)[92235] = 0;
  }
  vec = IsoVector(sum_comp);
  return make_pair(vec, kg);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){
  mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));
  left_over->setQuantity(0);
  while(!mat_list.empty()) {
    left_over->absorb(mat_list.back());
    mat_list.pop_back();
  }
  mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);
  if(left_over->mass(KG)>EPS_KG){
    mat_list.push_back(left_over);
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){
  MatTools::validate_finite_pos(vol);
  MatTools::validate_finite_pos(mass);

  IsoConcMap to_ret;
  int iso;
  double m_iso;
  CompMap::const_iterator it;
  it=(*comp).begin();
  while(it!= (*comp).end() ){
    iso = (*it).first;
    m_iso=((*it).second)*mass;
    to_ret.insert(make_pair(iso, m_iso/vol));
    ++it;
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){
  MatTools::validate_finite_pos(vol);

  CompMapPtr comp = CompMapPtr(new CompMap(MASS));
  double mass(0);
  int iso;
  double c_iso;
  double m_iso;
  CompMap::const_iterator it;
  it=conc.begin();
  while(it!= conc.end() ){
    iso = (*it).first;
    c_iso=((*it).second);
    m_iso = c_iso*vol;
    (*comp)[iso] = m_iso;
    mass+=m_iso;
    ++it;
  }
  (*comp).normalize();
  pair<CompMapPtr, double> to_ret = make_pair(comp, mass);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_f(double V_T, double theta){
  validate_percent(theta);
  validate_finite_pos(V_T);
  return theta*V_T;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ff(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_f(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_mf(double V_T, double theta, double d){
  return (V_f(V_T,theta) - V_ff(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_s(double V_T, double theta){
  return (V_T - V_f(V_T, theta));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ds(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_s(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ms(double V_T, double theta, double d){
  return (V_s(V_T, theta) - V_ds(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_percent(double per){
  if( per <= 1 && per >= 0 ){
    return;
  } else if ( per < 0) {
    throw CycRangeException("The value is not a valid percent. It is less than zero.");
  } else if ( per > 1) {
    throw CycRangeException("The value is not a valid percent. It is greater than one.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_finite_pos(double pos){
  if( pos >= 0 ){
    return;
  } else if ( pos < 0) {
    throw CycRangeException("The value is not positive and finite. It is less than zero.");
  } else if ( pos >= numeric_limits<double>::infinity() ) {
    throw CycRangeException("The value is not positive and finite. It is greater than infty.");
  }

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){
  double orig;
  IsoConcMap::iterator it;
  for(it = C_0.begin(); it != C_0.end(); ++it) {
    orig = C_0[(*it).first];
    C_0[(*it).first] = orig*scalar;
  }
  return C_0;
}
<commit_msg> used eps_rsrc from cyclus (thanks for the hint, @gidden)<commit_after>/*! \file MatTools.cpp
    \brief Implements the MatTools class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>

#include "CycException.h"
#include "CycLimits.h"
#include "MatTools.h"
#include "Material.h"
#include "Logger.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){
  IsoVector vec;
  CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));
  double kg = 0;

  if( !mats.empty() ){
    CompMapPtr comp_to_add;
    deque<mat_rsrc_ptr>::iterator mat;
    int iso;
    CompMap::const_iterator comp;

    for(mat = mats.begin(); mat != mats.end(); ++mat){
      kg += (*mat)->mass(MassUnit(KG));
      comp_to_add = (*mat)->isoVector().comp();
      comp_to_add->massify();
      for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {
        iso = comp->first;
        if(sum_comp->count(iso)!=0) {
          (*sum_comp)[iso] = (*sum_comp)[iso] + (comp->second)*kg;
        } else {
          (*sum_comp)[iso] = (comp->second)*kg;
        }
      }
    }
  } else {
    (*sum_comp)[92235] = 0;
  }
  vec = IsoVector(sum_comp);
  return make_pair(vec, kg);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){
  mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));
  left_over->setQuantity(0);
  while(!mat_list.empty()) {
    left_over->absorb(mat_list.back());
    mat_list.pop_back();
  }
  mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);
  if(left_over->mass(KG) > cyclus::eps_rsrc()){
    mat_list.push_back(left_over);
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){
  MatTools::validate_finite_pos(vol);
  MatTools::validate_finite_pos(mass);

  IsoConcMap to_ret;
  int iso;
  double m_iso;
  CompMap::const_iterator it;
  it=(*comp).begin();
  while(it!= (*comp).end() ){
    iso = (*it).first;
    m_iso=((*it).second)*mass;
    to_ret.insert(make_pair(iso, m_iso/vol));
    ++it;
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){
  MatTools::validate_finite_pos(vol);

  CompMapPtr comp = CompMapPtr(new CompMap(MASS));
  double mass(0);
  int iso;
  double c_iso;
  double m_iso;
  CompMap::const_iterator it;
  it=conc.begin();
  while(it!= conc.end() ){
    iso = (*it).first;
    c_iso=((*it).second);
    m_iso = c_iso*vol;
    (*comp)[iso] = m_iso;
    mass+=m_iso;
    ++it;
  }
  (*comp).normalize();
  pair<CompMapPtr, double> to_ret = make_pair(comp, mass);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_f(double V_T, double theta){
  validate_percent(theta);
  validate_finite_pos(V_T);
  return theta*V_T;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ff(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_f(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_mf(double V_T, double theta, double d){
  return (V_f(V_T,theta) - V_ff(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_s(double V_T, double theta){
  return (V_T - V_f(V_T, theta));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ds(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_s(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ms(double V_T, double theta, double d){
  return (V_s(V_T, theta) - V_ds(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_percent(double per){
  if( per <= 1 && per >= 0 ){
    return;
  } else if ( per < 0) {
    throw CycRangeException("The value is not a valid percent. It is less than zero.");
  } else if ( per > 1) {
    throw CycRangeException("The value is not a valid percent. It is greater than one.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_finite_pos(double pos){
  if( pos >= 0 ){
    return;
  } else if ( pos < 0) {
    throw CycRangeException("The value is not positive and finite. It is less than zero.");
  } else if ( pos >= numeric_limits<double>::infinity() ) {
    throw CycRangeException("The value is not positive and finite. It is greater than infty.");
  }

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){
  double orig;
  IsoConcMap::iterator it;
  for(it = C_0.begin(); it != C_0.end(); ++it) {
    orig = C_0[(*it).first];
    C_0[(*it).first] = orig*scalar;
  }
  return C_0;
}
<|endoftext|>


<commit_before>#include "Types.hpp"
#include "BufferFormat.hpp"

#include "GLContext.hpp"

PyObject * strsize(PyObject * self, PyObject * args) {
	const char * str;

	int args_ok = PyArg_ParseTuple(
		args,
		"s",
		&str
	);

	if (!args_ok) {
		return 0;
	}

	char first_chr = *str++;
	if (first_chr < '1' || first_chr > '9') {
		return 0;
	}

	long long value = first_chr - '0';

	while (char chr = *str++) {
		if (chr < '0' || chr > '9') {
			switch (chr) {
				case 'G':
					value *= 1024;

				case 'M':
					value *= 1024;

				case 'K':
					value *= 1024;

					if (*str++ != 'B') {
						return 0;
					}

				case 'B':
					if (*str++) {
						return 0;
					}

				case 0:
					break;

				default:
					return 0;
			}
			break;
		}

		value = value * 10 + chr - '0';
	}

	return PyLong_FromLongLong(value);
}

PyObject * fmtdebug(PyObject * self, PyObject * args) {
	const char * str;

	int args_ok = PyArg_ParseTuple(
		args,
		"s",
		&str
	);

	FormatIterator it = FormatIterator(str);
	FormatInfo format_info = it.info();

	PyObject * nodes = PyList_New(0);

	if (format_info.valid) {
		while (FormatNode * node = it.next()) {
			PyObject * obj = PyTuple_New(4);
			PyTuple_SET_ITEM(obj, 0, PyLong_FromLong(node->size));
			PyTuple_SET_ITEM(obj, 1, PyLong_FromLong(node->count));
			PyTuple_SET_ITEM(obj, 2, PyLong_FromLong(node->type));
			PyTuple_SET_ITEM(obj, 3, PyBool_FromLong(node->normalize));
			PyList_Append(nodes, obj);
		}
	}

	PyObject * res = PyTuple_New(5);
	PyTuple_SET_ITEM(res, 0, PyLong_FromLong(format_info.size));
	PyTuple_SET_ITEM(res, 1, PyLong_FromLong(format_info.nodes));
	PyTuple_SET_ITEM(res, 2, PyLong_FromLong(format_info.divisor));
	PyTuple_SET_ITEM(res, 3, PyBool_FromLong(format_info.valid));
	PyTuple_SET_ITEM(res, 4, PyList_AsTuple(nodes));
	Py_DECREF(nodes);
	return res;
}

PyObject * set_error_class(PyObject * self, PyObject * args) {
	PyObject * error_class;

	int args_ok = PyArg_ParseTuple(
		args,
		"O",
		&error_class
	);

	if (!args_ok) {
		return 0;
	}

	Py_INCREF(error_class);
	MGLError_TypePtr = error_class;
	Py_RETURN_NONE;
}

PyObject * create_standalone_context(PyObject * self, PyObject * args) {
	PyObject * settings;

	int args_ok = PyArg_ParseTuple(
		args,
		"O",
		&settings
	);

	if (!args_ok) {
		return 0;
	}

	MGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);

	ctx->gl_context = CreateGLContext(settings);
	ctx->wireframe = false;

	if (PyErr_Occurred()) {
		return 0;
	}

	MGLContext_Initialize(ctx);

	if (PyErr_Occurred()) {
		return 0;
	}

	Py_INCREF(ctx);

	PyObject * result = PyTuple_New(2);
	PyTuple_SET_ITEM(result, 0, (PyObject *)ctx);
	PyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));
	return result;
}

PyObject * create_context(PyObject * self) {
	MGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);

	ctx->gl_context = LoadCurrentGLContext();
	ctx->wireframe = false;

	if (PyErr_Occurred()) {
		return 0;
	}

	MGLContext_Initialize(ctx);

	if (PyErr_Occurred()) {
		return 0;
	}

	Py_INCREF(ctx);

	PyObject * result = PyTuple_New(2);
	PyTuple_SET_ITEM(result, 0, (PyObject *)ctx);
	PyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));
	return result;
}

PyMethodDef MGL_module_methods[] = {
	{"strsize", (PyCFunction)strsize, METH_VARARGS, 0},
	{"create_standalone_context", (PyCFunction)create_standalone_context, METH_VARARGS, 0},
	{"create_context", (PyCFunction)create_context, METH_NOARGS, 0},
	{"set_error_class", (PyCFunction)set_error_class, METH_VARARGS, 0},
	{"fmtdebug", (PyCFunction)fmtdebug, METH_VARARGS, 0},
	{0},
};

bool MGL_InitializeModule(PyObject * module) {
	{
		if (PyType_Ready(&MGLAttribute_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Attribute in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLAttribute_Type);

		PyModule_AddObject(module, "Attribute", (PyObject *)&MGLAttribute_Type);
	}

	{
		if (PyType_Ready(&MGLBuffer_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Buffer in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLBuffer_Type);

		PyModule_AddObject(module, "Buffer", (PyObject *)&MGLBuffer_Type);
	}

	{
		if (PyType_Ready(&MGLComputeShader_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register ComputeShader in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLComputeShader_Type);

		PyModule_AddObject(module, "ComputeShader", (PyObject *)&MGLComputeShader_Type);
	}

	{
		if (PyType_Ready(&MGLContext_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Context in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLContext_Type);

		PyModule_AddObject(module, "Context", (PyObject *)&MGLContext_Type);
	}

	{
		if (PyType_Ready(&MGLFramebuffer_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Framebuffer in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLFramebuffer_Type);

		PyModule_AddObject(module, "Framebuffer", (PyObject *)&MGLFramebuffer_Type);
	}

	{
		if (PyType_Ready(&MGLInvalidObject_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register InvalidObject in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLInvalidObject_Type);

		PyModule_AddObject(module, "InvalidObject", (PyObject *)&MGLInvalidObject_Type);
	}

	{
		if (PyType_Ready(&MGLProgram_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Program in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLProgram_Type);

		PyModule_AddObject(module, "Program", (PyObject *)&MGLProgram_Type);
	}

	{
		if (PyType_Ready(&MGLQuery_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Query in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLQuery_Type);

		PyModule_AddObject(module, "Query", (PyObject *)&MGLQuery_Type);
	}

	{
		if (PyType_Ready(&MGLRenderbuffer_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Renderbuffer in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLRenderbuffer_Type);

		PyModule_AddObject(module, "Renderbuffer", (PyObject *)&MGLRenderbuffer_Type);
	}

	{
		if (PyType_Ready(&MGLScope_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Scope in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLScope_Type);

		PyModule_AddObject(module, "Scope", (PyObject *)&MGLScope_Type);
	}

	{
		if (PyType_Ready(&MGLTexture_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Texture in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLTexture_Type);

		PyModule_AddObject(module, "Texture", (PyObject *)&MGLTexture_Type);
	}

	{
		if (PyType_Ready(&MGLTextureCube_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register TextureCube in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLTextureCube_Type);

		PyModule_AddObject(module, "TextureCube", (PyObject *)&MGLTextureCube_Type);
	}

	{
		if (PyType_Ready(&MGLTexture3D_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Texture3D in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLTexture3D_Type);

		PyModule_AddObject(module, "Texture3D", (PyObject *)&MGLTexture3D_Type);
	}

	{
		if (PyType_Ready(&MGLUniform_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Uniform in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLUniform_Type);

		PyModule_AddObject(module, "Uniform", (PyObject *)&MGLUniform_Type);
	}

	{
		if (PyType_Ready(&MGLUniformBlock_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register UniformBlock in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLUniformBlock_Type);

		PyModule_AddObject(module, "UniformBlock", (PyObject *)&MGLUniformBlock_Type);
	}

	{
		if (PyType_Ready(&MGLVertexArray_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register VertexArray in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLVertexArray_Type);

		PyModule_AddObject(module, "VertexArray", (PyObject *)&MGLVertexArray_Type);
	}

	return true;
}

PyModuleDef MGL_moduledef = {
	PyModuleDef_HEAD_INIT,
	"mgl",
	0,
	-1,
	MGL_module_methods,
	0,
	0,
	0,
	0,
};

extern "C" PyObject * PyInit_mgl() {
	PyObject * module = PyModule_Create(&MGL_moduledef);

	if (!MGL_InitializeModule(module)) {
		return 0;
	}

	return module;
}
<commit_msg>check args<commit_after>#include "Types.hpp"
#include "BufferFormat.hpp"

#include "GLContext.hpp"

PyObject * strsize(PyObject * self, PyObject * args) {
	const char * str;

	int args_ok = PyArg_ParseTuple(
		args,
		"s",
		&str
	);

	if (!args_ok) {
		return 0;
	}

	char first_chr = *str++;
	if (first_chr < '1' || first_chr > '9') {
		return 0;
	}

	long long value = first_chr - '0';

	while (char chr = *str++) {
		if (chr < '0' || chr > '9') {
			switch (chr) {
				case 'G':
					value *= 1024;

				case 'M':
					value *= 1024;

				case 'K':
					value *= 1024;

					if (*str++ != 'B') {
						return 0;
					}

				case 'B':
					if (*str++) {
						return 0;
					}

				case 0:
					break;

				default:
					return 0;
			}
			break;
		}

		value = value * 10 + chr - '0';
	}

	return PyLong_FromLongLong(value);
}

PyObject * fmtdebug(PyObject * self, PyObject * args) {
	const char * str;

	int args_ok = PyArg_ParseTuple(
		args,
		"s",
		&str
	);

	if (!args_ok) {
		return 0;
	}

	FormatIterator it = FormatIterator(str);
	FormatInfo format_info = it.info();

	PyObject * nodes = PyList_New(0);

	if (format_info.valid) {
		while (FormatNode * node = it.next()) {
			PyObject * obj = PyTuple_New(4);
			PyTuple_SET_ITEM(obj, 0, PyLong_FromLong(node->size));
			PyTuple_SET_ITEM(obj, 1, PyLong_FromLong(node->count));
			PyTuple_SET_ITEM(obj, 2, PyLong_FromLong(node->type));
			PyTuple_SET_ITEM(obj, 3, PyBool_FromLong(node->normalize));
			PyList_Append(nodes, obj);
		}
	}

	PyObject * res = PyTuple_New(5);
	PyTuple_SET_ITEM(res, 0, PyLong_FromLong(format_info.size));
	PyTuple_SET_ITEM(res, 1, PyLong_FromLong(format_info.nodes));
	PyTuple_SET_ITEM(res, 2, PyLong_FromLong(format_info.divisor));
	PyTuple_SET_ITEM(res, 3, PyBool_FromLong(format_info.valid));
	PyTuple_SET_ITEM(res, 4, PyList_AsTuple(nodes));
	Py_DECREF(nodes);
	return res;
}

PyObject * set_error_class(PyObject * self, PyObject * args) {
	PyObject * error_class;

	int args_ok = PyArg_ParseTuple(
		args,
		"O",
		&error_class
	);

	if (!args_ok) {
		return 0;
	}

	Py_INCREF(error_class);
	MGLError_TypePtr = error_class;
	Py_RETURN_NONE;
}

PyObject * create_standalone_context(PyObject * self, PyObject * args) {
	PyObject * settings;

	int args_ok = PyArg_ParseTuple(
		args,
		"O",
		&settings
	);

	if (!args_ok) {
		return 0;
	}

	MGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);

	ctx->gl_context = CreateGLContext(settings);
	ctx->wireframe = false;

	if (PyErr_Occurred()) {
		return 0;
	}

	MGLContext_Initialize(ctx);

	if (PyErr_Occurred()) {
		return 0;
	}

	Py_INCREF(ctx);

	PyObject * result = PyTuple_New(2);
	PyTuple_SET_ITEM(result, 0, (PyObject *)ctx);
	PyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));
	return result;
}

PyObject * create_context(PyObject * self) {
	MGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);

	ctx->gl_context = LoadCurrentGLContext();
	ctx->wireframe = false;

	if (PyErr_Occurred()) {
		return 0;
	}

	MGLContext_Initialize(ctx);

	if (PyErr_Occurred()) {
		return 0;
	}

	Py_INCREF(ctx);

	PyObject * result = PyTuple_New(2);
	PyTuple_SET_ITEM(result, 0, (PyObject *)ctx);
	PyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));
	return result;
}

PyMethodDef MGL_module_methods[] = {
	{"strsize", (PyCFunction)strsize, METH_VARARGS, 0},
	{"create_standalone_context", (PyCFunction)create_standalone_context, METH_VARARGS, 0},
	{"create_context", (PyCFunction)create_context, METH_NOARGS, 0},
	{"set_error_class", (PyCFunction)set_error_class, METH_VARARGS, 0},
	{"fmtdebug", (PyCFunction)fmtdebug, METH_VARARGS, 0},
	{0},
};

bool MGL_InitializeModule(PyObject * module) {
	{
		if (PyType_Ready(&MGLAttribute_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Attribute in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLAttribute_Type);

		PyModule_AddObject(module, "Attribute", (PyObject *)&MGLAttribute_Type);
	}

	{
		if (PyType_Ready(&MGLBuffer_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Buffer in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLBuffer_Type);

		PyModule_AddObject(module, "Buffer", (PyObject *)&MGLBuffer_Type);
	}

	{
		if (PyType_Ready(&MGLComputeShader_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register ComputeShader in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLComputeShader_Type);

		PyModule_AddObject(module, "ComputeShader", (PyObject *)&MGLComputeShader_Type);
	}

	{
		if (PyType_Ready(&MGLContext_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Context in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLContext_Type);

		PyModule_AddObject(module, "Context", (PyObject *)&MGLContext_Type);
	}

	{
		if (PyType_Ready(&MGLFramebuffer_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Framebuffer in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLFramebuffer_Type);

		PyModule_AddObject(module, "Framebuffer", (PyObject *)&MGLFramebuffer_Type);
	}

	{
		if (PyType_Ready(&MGLInvalidObject_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register InvalidObject in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLInvalidObject_Type);

		PyModule_AddObject(module, "InvalidObject", (PyObject *)&MGLInvalidObject_Type);
	}

	{
		if (PyType_Ready(&MGLProgram_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Program in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLProgram_Type);

		PyModule_AddObject(module, "Program", (PyObject *)&MGLProgram_Type);
	}

	{
		if (PyType_Ready(&MGLQuery_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Query in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLQuery_Type);

		PyModule_AddObject(module, "Query", (PyObject *)&MGLQuery_Type);
	}

	{
		if (PyType_Ready(&MGLRenderbuffer_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Renderbuffer in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLRenderbuffer_Type);

		PyModule_AddObject(module, "Renderbuffer", (PyObject *)&MGLRenderbuffer_Type);
	}

	{
		if (PyType_Ready(&MGLScope_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Scope in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLScope_Type);

		PyModule_AddObject(module, "Scope", (PyObject *)&MGLScope_Type);
	}

	{
		if (PyType_Ready(&MGLTexture_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Texture in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLTexture_Type);

		PyModule_AddObject(module, "Texture", (PyObject *)&MGLTexture_Type);
	}

	{
		if (PyType_Ready(&MGLTextureCube_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register TextureCube in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLTextureCube_Type);

		PyModule_AddObject(module, "TextureCube", (PyObject *)&MGLTextureCube_Type);
	}

	{
		if (PyType_Ready(&MGLTexture3D_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Texture3D in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLTexture3D_Type);

		PyModule_AddObject(module, "Texture3D", (PyObject *)&MGLTexture3D_Type);
	}

	{
		if (PyType_Ready(&MGLUniform_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register Uniform in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLUniform_Type);

		PyModule_AddObject(module, "Uniform", (PyObject *)&MGLUniform_Type);
	}

	{
		if (PyType_Ready(&MGLUniformBlock_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register UniformBlock in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLUniformBlock_Type);

		PyModule_AddObject(module, "UniformBlock", (PyObject *)&MGLUniformBlock_Type);
	}

	{
		if (PyType_Ready(&MGLVertexArray_Type) < 0) {
			PyErr_Format(PyExc_ImportError, "Cannot register VertexArray in %s (%s:%d)", __FUNCTION__, __FILE__, __LINE__);
			return false;
		}

		Py_INCREF(&MGLVertexArray_Type);

		PyModule_AddObject(module, "VertexArray", (PyObject *)&MGLVertexArray_Type);
	}

	return true;
}

PyModuleDef MGL_moduledef = {
	PyModuleDef_HEAD_INIT,
	"mgl",
	0,
	-1,
	MGL_module_methods,
	0,
	0,
	0,
	0,
};

extern "C" PyObject * PyInit_mgl() {
	PyObject * module = PyModule_Create(&MGL_moduledef);

	if (!MGL_InitializeModule(module)) {
		return 0;
	}

	return module;
}
<|endoftext|>