<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{

    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    bool runOn = true;
    string choice;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database." << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - View" << "\t" << "View the entire database." << endl;
        cout << " (4) - Save" << "\t" << "Save the database." << endl;
        cout << " (5) - Search" << "\t" << "Search the database." << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database." << endl;
        cout << " (7) - Exit" << "\t" << "Exit." << endl;

        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }

    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "6")
    {
        string sortcho;
        cout << "Enter a sort command (1 - 3):" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - Sort by chronological order" << endl;
        cout << " (3) - Return to main menu" << endl;
        cout << "Enter your command (1 - 2): ";
        cin >> sortcho;
        cout << endl;

        if(sortcho == "1")
        {
            list.sortNames();
             viewAll();
        }
        else if(sortcho == "2")
        {
            list.sortBirth();
             viewAll();
        }
        else if(sortcho == "3")
        {
            mainMenu();
        }

    }
    else if(ch == "5")
    {
        searching();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "8")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Name -- Searches for a name." << endl;
    cout << " (2) - Gender -- Searches for a Gender." << endl;
    cout << " (3) - Year -- Searches for a year born." << endl;
    cout << " (4) - Exit -- Exit to the main menu" << endl;
    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void ClassUI::search()
{
        string searchChoice;
        cout << "Enter your command (1 - 4): ";
        cin >> searchChoice;
        if (searchChoice == "1")
        {

            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin.ignore();
            std::getline(std::cin,namesearch);

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                std::size_t found = list.getName(i).find(namesearch);
                if (found!=std::string::npos)
                {
                    view(i);
                }

            }
            if(list.nameSearcher(namesearch) == false)
            {
                cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "2")
        {
            char gendersearch;

            cout << "Enter a gender you want to search for: (M/F)";
            cin >> gendersearch;
            if(gendersearch == 'm')
                {
                     gendersearch = 'M';
                }
            else if (gendersearch == 'f')
                {
                     gendersearch = 'F';
                }

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
            }
            if(list.genderSearcher(gendersearch) == false)
            {
                cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "3")
        {
                int yearsearch;
                cout << "Enter a year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                }
                if(list.yearSearcher(yearsearch) == false)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                    searching();
                }
        }
        else if (searchChoice == "4")
        {
            mainMenu();
        }
        else
        {
            cout << "Error reading input. Please enter a number between 1- 3." << endl;
            search();
        }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<commit_msg>repairing error<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{

    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    bool runOn = true;
    string choice;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database." << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - View" << "\t" << "View the entire database." << endl;
        cout << " (4) - Save" << "\t" << "Save the database." << endl;
        cout << " (5) - Search" << "\t" << "Search the database." << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database." << endl;
        cout << " (7) - Exit" << "\t" << "Exit." << endl;

        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }

    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "6")
    {
        string sortcho;
        cout << "Enter a sort command (1 - 3):" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - Sort by chronological order" << endl;
        cout << " (3) - Return to main menu" << endl;
        cout << "Enter your command (1 - 2): ";
        cin >> sortcho;
        cout << endl;

        if(sortcho == "1")
        {
            list.sortNames();
             viewAll();
        }
        else if(sortcho == "2")
        {
            list.sortBirth();
             viewAll();
        }
        else if(sortcho == "3")
        {
            mainMenu();
        }

    }
    else if(ch == "5")
    {
        searching();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "8")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void ClassUI::search()
{
        string searchChoice;
        cout << "Enter your command (1 - 4): ";
        cin >> searchChoice;
        if (searchChoice == "1")
        {

            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin.ignore();
            std::getline(std::cin,namesearch);

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                std::size_t found = list.getName(i).find(namesearch);
                if (found!=std::string::npos)
                {
                    view(i);
                }

            }
            if(list.nameSearcher(namesearch) == false)
            {
                cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "2")
        {
            char gendersearch;

            cout << "Enter a gender you want to search for: (M/F)";
            cin >> gendersearch;
            if(gendersearch == 'm')
                {
                     gendersearch = 'M';
                }
            else if (gendersearch == 'f')
                {
                     gendersearch = 'F';
                }

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
            }
            if(list.genderSearcher(gendersearch) == false)
            {
                cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "3")
        {
                int yearsearch;
                cout << "Enter a year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                }
                if(list.yearSearcher(yearsearch) == false)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                    searching();
                }
        }
        else if (searchChoice == "4")
        {
            mainMenu();
        }
        else
        {
            cout << "Error reading input. Please enter a number between 1- 3." << endl;
            search();
        }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<|endoftext|>


<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/framework/resource_handle.h"

#include "tensorflow/core/framework/resource_handle.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/strcat.h"

namespace tensorflow {

// Must be declared here for pre-C++17 compatibility.
/* static */ constexpr const char* ResourceHandle::ANONYMOUS_NAME;

ResourceHandle::ResourceHandle() {}

ResourceHandle::ResourceHandle(const ResourceHandleProto& proto) {
  FromProto(proto);
}

ResourceHandle::~ResourceHandle() {}

void ResourceHandle::AsProto(ResourceHandleProto* proto) const {
  // TODO(b/197757028): Register the resource with ResourceManager to enable
  // serialization of ref-counting handles.
  if (!IsRefCounting()) {
    LOG(ERROR) << "A ref-counted ResourceHandle cannot be serialized losslessly"
               << "Deserializing the result is a failure: " << name();
  }
  proto->set_device(device());
  proto->set_container(container());
  proto->set_name(name());
  proto->set_hash_code(hash_code());
  proto->set_maybe_type_name(maybe_type_name());
  for (const auto& dtype_and_shape_pair : dtypes_and_shapes_) {
    auto dtype_and_shape = proto->add_dtypes_and_shapes();
    dtype_and_shape->set_dtype(dtype_and_shape_pair.dtype);
    dtype_and_shape_pair.shape.AsProto(dtype_and_shape->mutable_shape());
  }
}

void ResourceHandle::FromProto(const ResourceHandleProto& proto) {
  set_device(proto.device());
  set_container(proto.container());
  set_name(proto.name());
  set_hash_code(proto.hash_code());
  set_maybe_type_name(proto.maybe_type_name());
  std::vector<DtypeAndPartialTensorShape> dtypes_and_shapes;
  for (const auto& dtype_and_shape : proto.dtypes_and_shapes()) {
    DataType dtype = dtype_and_shape.dtype();
    PartialTensorShape shape(dtype_and_shape.shape());
    dtypes_and_shapes.push_back(DtypeAndPartialTensorShape{dtype, shape});
  }
  dtypes_and_shapes_ = std::move(dtypes_and_shapes);
}

string ResourceHandle::SerializeAsString() const {
  ResourceHandleProto proto;
  AsProto(&proto);
  return proto.SerializeAsString();
}

bool ResourceHandle::ParseFromString(const string& s) {
  ResourceHandleProto proto;
  const bool status = proto.ParseFromString(s);
  if (status) FromProto(proto);
  return status;
}

string ResourceHandle::DebugString() const {
  return strings::StrCat("device: ", device(), " container: ", container(),
                         " name: ", name(), " hash_code: ", hash_code(),
                         " maybe_type_name: ", maybe_type_name());
}

ResourceHandle ResourceHandle::MakeRefCountingHandle(
    ResourceBase* resource, const string& device_name,
    const TypeIndex& type_index,
    const std::vector<DtypeAndPartialTensorShape>& dtypes_and_shapes,
    const absl::optional<ManagedStackTrace>& definition_stack_trace) {
  ResourceHandle result;
  result.resource_.reset(resource, /*add_ref=*/false);
  result.set_device(device_name);
  // "container" is only a ResourceMgr-only concept
  result.set_container("");
  result.set_definition_stack_trace(definition_stack_trace);
  result.set_name(strings::StrCat("_AnonymousResource", GenerateUniqueId()));
  result.set_hash_code(type_index.hash_code());
  result.set_maybe_type_name(type_index.name());
  result.set_dtypes_and_shapes(dtypes_and_shapes);
  return result;
}

Status ResourceHandle::ValidateType(const TypeIndex& type_index) const {
  if (type_index.hash_code() != hash_code()) {
    return errors::InvalidArgument(
        "Trying to access a handle's resource using the wrong type. ",
        "The handle points to a resource (name '", name(), "') of type '",
        maybe_type_name(), "' (hash code ", hash_code(),
        ") but you are trying to access the resource as type '",
        type_index.name(), "' (hash code ", type_index.hash_code(), ")");
  }
  return Status::OK();
}

std::atomic<int64_t> ResourceHandle::current_id_;

int64_t ResourceHandle::GenerateUniqueId() { return current_id_.fetch_add(1); }

string ProtoDebugString(const ResourceHandle& handle) {
  return handle.DebugString();
}

void EncodeResourceHandleList(const ResourceHandle* p, int64_t n,
                              std::unique_ptr<port::StringListEncoder> e) {
  ResourceHandleProto proto;
  for (int i = 0; i < n; ++i) {
    p[i].AsProto(&proto);
    e->Append(proto);
  }
  e->Finalize();
}

bool DecodeResourceHandleList(std::unique_ptr<port::StringListDecoder> d,
                              ResourceHandle* ps, int64_t n) {
  std::vector<uint32> sizes(n);
  if (!d->ReadSizes(&sizes)) return false;

  ResourceHandleProto proto;
  for (int i = 0; i < n; ++i) {
    if (!proto.ParseFromArray(d->Data(sizes[i]), sizes[i])) {
      return false;
    }
    ps[i].FromProto(proto);
  }
  return true;
}

}  // namespace tensorflow
<commit_msg>Fix error message condition in refcounting corruption detection.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/framework/resource_handle.h"

#include "tensorflow/core/framework/resource_handle.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/strcat.h"

namespace tensorflow {

// Must be declared here for pre-C++17 compatibility.
/* static */ constexpr const char* ResourceHandle::ANONYMOUS_NAME;

ResourceHandle::ResourceHandle() {}

ResourceHandle::ResourceHandle(const ResourceHandleProto& proto) {
  FromProto(proto);
}

ResourceHandle::~ResourceHandle() {}

void ResourceHandle::AsProto(ResourceHandleProto* proto) const {
  // TODO(b/197757028): Register the resource with ResourceManager to enable
  // serialization of ref-counting handles.
  if (IsRefCounting()) {
    LOG_FIRST_N(ERROR, 10)
        << "A ref-counting ResourceHandle cannot be serialized losslessly. "
        << "Deserializing the result produces a corrupted handle: " << name();
  }
  proto->set_device(device());
  proto->set_container(container());
  proto->set_name(name());
  proto->set_hash_code(hash_code());
  proto->set_maybe_type_name(maybe_type_name());
  for (const auto& dtype_and_shape_pair : dtypes_and_shapes_) {
    auto dtype_and_shape = proto->add_dtypes_and_shapes();
    dtype_and_shape->set_dtype(dtype_and_shape_pair.dtype);
    dtype_and_shape_pair.shape.AsProto(dtype_and_shape->mutable_shape());
  }
}

void ResourceHandle::FromProto(const ResourceHandleProto& proto) {
  set_device(proto.device());
  set_container(proto.container());
  set_name(proto.name());
  set_hash_code(proto.hash_code());
  set_maybe_type_name(proto.maybe_type_name());
  std::vector<DtypeAndPartialTensorShape> dtypes_and_shapes;
  for (const auto& dtype_and_shape : proto.dtypes_and_shapes()) {
    DataType dtype = dtype_and_shape.dtype();
    PartialTensorShape shape(dtype_and_shape.shape());
    dtypes_and_shapes.push_back(DtypeAndPartialTensorShape{dtype, shape});
  }
  dtypes_and_shapes_ = std::move(dtypes_and_shapes);
}

string ResourceHandle::SerializeAsString() const {
  ResourceHandleProto proto;
  AsProto(&proto);
  return proto.SerializeAsString();
}

bool ResourceHandle::ParseFromString(const string& s) {
  ResourceHandleProto proto;
  const bool status = proto.ParseFromString(s);
  if (status) FromProto(proto);
  return status;
}

string ResourceHandle::DebugString() const {
  return strings::StrCat("device: ", device(), " container: ", container(),
                         " name: ", name(), " hash_code: ", hash_code(),
                         " maybe_type_name: ", maybe_type_name());
}

ResourceHandle ResourceHandle::MakeRefCountingHandle(
    ResourceBase* resource, const string& device_name,
    const TypeIndex& type_index,
    const std::vector<DtypeAndPartialTensorShape>& dtypes_and_shapes,
    const absl::optional<ManagedStackTrace>& definition_stack_trace) {
  ResourceHandle result;
  result.resource_.reset(resource, /*add_ref=*/false);
  result.set_device(device_name);
  // "container" is only a ResourceMgr-only concept
  result.set_container("");
  result.set_definition_stack_trace(definition_stack_trace);
  result.set_name(strings::StrCat("_AnonymousResource", GenerateUniqueId()));
  result.set_hash_code(type_index.hash_code());
  result.set_maybe_type_name(type_index.name());
  result.set_dtypes_and_shapes(dtypes_and_shapes);
  return result;
}

Status ResourceHandle::ValidateType(const TypeIndex& type_index) const {
  if (type_index.hash_code() != hash_code()) {
    return errors::InvalidArgument(
        "Trying to access a handle's resource using the wrong type. ",
        "The handle points to a resource (name '", name(), "') of type '",
        maybe_type_name(), "' (hash code ", hash_code(),
        ") but you are trying to access the resource as type '",
        type_index.name(), "' (hash code ", type_index.hash_code(), ")");
  }
  return Status::OK();
}

std::atomic<int64_t> ResourceHandle::current_id_;

int64_t ResourceHandle::GenerateUniqueId() { return current_id_.fetch_add(1); }

string ProtoDebugString(const ResourceHandle& handle) {
  return handle.DebugString();
}

void EncodeResourceHandleList(const ResourceHandle* p, int64_t n,
                              std::unique_ptr<port::StringListEncoder> e) {
  ResourceHandleProto proto;
  for (int i = 0; i < n; ++i) {
    p[i].AsProto(&proto);
    e->Append(proto);
  }
  e->Finalize();
}

bool DecodeResourceHandleList(std::unique_ptr<port::StringListDecoder> d,
                              ResourceHandle* ps, int64_t n) {
  std::vector<uint32> sizes(n);
  if (!d->ReadSizes(&sizes)) return false;

  ResourceHandleProto proto;
  for (int i = 0; i < n; ++i) {
    if (!proto.ParseFromArray(d->Data(sizes[i]), sizes[i])) {
      return false;
    }
    ps[i].FromProto(proto);
  }
  return true;
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>#include "SlidingHyperService.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>
#include <syslog.h>

#include "config.h"
#include "set_manager.h"
#include "thrift_server.h"

using namespace apache::thrift::concurrency;
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

class SlidingHyperServiceHandler : virtual public SlidingHyperServiceIf {
 private:
  hlld_setmgr *mgr;
 public:
  SlidingHyperServiceHandler(hlld_setmgr *mgr) {
      assert(mgr != NULL);
      this->mgr = mgr;
  }

  void ping(std::string& _return) {
      _return = "PONG";
  }

  void add_many(const int32_t timestamp, const std::string& key, const std::vector<std::string> & values) {
      setmgr_client_checkpoint(mgr);

      char **char_v = (char**)malloc(sizeof(char*)*values.size());
      for(size_t i=0; i<values.size(); i++) {
          char_v[i] = (char*)&values[i][0];
      }

      int res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }
      free(char_v);
  }

  int32_t card(const int32_t timestamp, const int32_t window, const std::vector<std::string> & keys, const std::vector<std::string> & values) {
      //add(timestamp,
      //return get_union(timestamp, window, keys);
      setmgr_client_checkpoint(mgr);

      std::vector<hll_t*> sets;
      for(size_t i=0; i<values.size(); i++) {
          char *set_name = (char*)&values[i][0];
          hlld_set *set = setmgr_get_set(mgr, set_name);
          if (set != NULL)
              sets.push_back(&set->hll);
      }

      // if there aren't actually any sets for keys
      if (sets.size() == 0) {
          return values.size();
      }

      // calculate union of all keys
      hll_t result_set;
      hll_init(sets[0]->precision, sets[0]->window_period, sets[0]->window_precision, &result_set);
      for(std::string value: values) {
          hll_add_at_time(&result_set, (char*)&value[0], (time_t)timestamp);
      }
      sets.push_back(&result_set);

      double result = hll_union_size((hll_t**)&sets[0], sets.size(), window, timestamp);

      return (int32_t)result;
  }

  void flush() {
    // Your implementation goes here
  }

  void add(const int32_t timestamp, const std::string& key, const std::string& value) {
      char *values[] = {(char*)&value[0]};
      int res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }

  }

  int32_t get(const int32_t timestamp, const int16_t window, const std::string& key) {
      uint64_t estimate = 0;
      int res = setmgr_set_size(mgr, (char*)&key[0], &estimate, window);
      if (res == -1) {
          res = setmgr_create_set(mgr, (char*)&key[0], NULL);
          return 0;
      } else if (res < -1) {
          syslog(LOG_ERR, "Failed to get set cardinality %s res %d", (char*)&key[0], res);
      }
      return estimate;
  }

  int32_t get_union(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys) {
      char **set_names = (char**)malloc(keys.size()*sizeof(char**));
      for(size_t i=0; i<keys.size(); i++) {
          set_names[i] = (char*)&keys[i];
      }
      uint64_t estimate;
      setmgr_set_union_size(mgr, keys.size(), set_names, &estimate, window);
      free(set_names);

      return (int32_t)estimate;

  }

  int32_t get_with_element(const int32_t timestamp, const int16_t window, const std::string& key, const std::string& value) {
    // Your implementation goes here
    printf("get_withelement\n");
  }

  int32_t get_union_with_element(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys, const std::string& value) {
    // Your implementation goes here
    printf("get_union_with_element\n");
  }

};

TThreadPoolServer *thrift_server;

void start_thrift_server(hlld_setmgr *mgr) {
  int port = 9090;
  shared_ptr<SlidingHyperServiceHandler> handler(new SlidingHyperServiceHandler(mgr));
  shared_ptr<TProcessor> processor(new SlidingHyperServiceProcessor(handler));
  shared_ptr<TServerSocket> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

 shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(4);

 shared_ptr<PosixThreadFactory> threadFactory
     = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());

 threadManager->threadFactory(threadFactory);

 threadManager->start();

  thrift_server = new TThreadPoolServer(processor, serverTransport, transportFactory, protocolFactory, threadManager);
  syslog(LOG_INFO, "Starting thrift server");
  thrift_server->serve();
  syslog(LOG_INFO, "Stopping thrift server");
}

void stop_thrift_server() {
    thrift_server->stop();
}
<commit_msg>card method fetches sets from keys not values<commit_after>#include "SlidingHyperService.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>
#include <syslog.h>

#include "config.h"
#include "set_manager.h"
#include "thrift_server.h"

using namespace apache::thrift::concurrency;
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

class SlidingHyperServiceHandler : virtual public SlidingHyperServiceIf {
 private:
  hlld_setmgr *mgr;
 public:
  SlidingHyperServiceHandler(hlld_setmgr *mgr) {
      assert(mgr != NULL);
      this->mgr = mgr;
  }

  void ping(std::string& _return) {
      _return = "PONG";
  }

  void add_many(const int32_t timestamp, const std::string& key, const std::vector<std::string> & values) {
      setmgr_client_checkpoint(mgr);

      char **char_v = (char**)malloc(sizeof(char*)*values.size());
      for(size_t i=0; i<values.size(); i++) {
          char_v[i] = (char*)&values[i][0];
      }

      int res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], char_v, values.size(), (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }
      free(char_v);
  }

  int32_t card(const int32_t timestamp, const int32_t window, const std::vector<std::string> & keys, const std::vector<std::string> & values) {
      //add(timestamp,
      //return get_union(timestamp, window, keys);
      setmgr_client_checkpoint(mgr);

      std::vector<hll_t*> sets;
      for(size_t i=0; i<keys.size(); i++) {
          char *set_name = (char*)&keys[i][0];
          hlld_set *set = setmgr_get_set(mgr, set_name);
          if (set != NULL)
              sets.push_back(&set->hll);
      }

      // if there aren't actually any sets for keys
      if (sets.size() == 0) {
          return values.size();
      }

      // calculate union of all keys
      hll_t result_set;
      hll_init(sets[0]->precision, sets[0]->window_period, sets[0]->window_precision, &result_set);
      for(std::string value: values) {
          hll_add_at_time(&result_set, (char*)&value[0], (time_t)timestamp);
      }
      sets.push_back(&result_set);

      double result = hll_union_size((hll_t**)&sets[0], sets.size(), window, timestamp);

      return (int32_t)result;
  }

  void flush() {
    // Your implementation goes here
  }

  void add(const int32_t timestamp, const std::string& key, const std::string& value) {
      char *values[] = {(char*)&value[0]};
      int res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      // set does not exist
      if (res == -1 ) {
          setmgr_create_set(mgr, (char*)&key[0], NULL);
          res = setmgr_set_keys(mgr, (char*)&key[0], values, 1, (time_t)timestamp);
      }
      else if (res < -1) {
          syslog(LOG_ERR, "Failure to add to key %s with value %s res: %d", (char*)&key[0], res);
      }

  }

  int32_t get(const int32_t timestamp, const int16_t window, const std::string& key) {
      uint64_t estimate = 0;
      int res = setmgr_set_size(mgr, (char*)&key[0], &estimate, window);
      if (res == -1) {
          return 0;
      } else if (res < -1) {
          syslog(LOG_ERR, "Failed to get set cardinality %s res %d", (char*)&key[0], res);
      }
      return estimate;
  }

  int32_t get_union(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys) {
      char **set_names = (char**)malloc(keys.size()*sizeof(char**));
      for(size_t i=0; i<keys.size(); i++) {
          set_names[i] = (char*)&keys[i];
      }
      uint64_t estimate;
      setmgr_set_union_size(mgr, keys.size(), set_names, &estimate, window);
      free(set_names);

      return (int32_t)estimate;

  }

  int32_t get_with_element(const int32_t timestamp, const int16_t window, const std::string& key, const std::string& value) {
    // Your implementation goes here
    printf("get_withelement\n");
  }

  int32_t get_union_with_element(const int32_t timestamp, const int16_t window, const std::vector<std::string> & keys, const std::string& value) {
    // Your implementation goes here
    printf("get_union_with_element\n");
  }

};

TThreadPoolServer *thrift_server;

void start_thrift_server(hlld_setmgr *mgr) {
  int port = 9090;
  shared_ptr<SlidingHyperServiceHandler> handler(new SlidingHyperServiceHandler(mgr));
  shared_ptr<TProcessor> processor(new SlidingHyperServiceProcessor(handler));
  shared_ptr<TServerSocket> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

 shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(4);

 shared_ptr<PosixThreadFactory> threadFactory
     = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());

 threadManager->threadFactory(threadFactory);

 threadManager->start();

  thrift_server = new TThreadPoolServer(processor, serverTransport, transportFactory, protocolFactory, threadManager);
  syslog(LOG_INFO, "Starting thrift server");
  thrift_server->serve();
  syslog(LOG_INFO, "Stopping thrift server");
}

void stop_thrift_server() {
    thrift_server->stop();
}
<|endoftext|>


<commit_before>#include <vector>
#include <unordered_set>

namespace helpers
{
	namespace implementation
	{
		template <typename T>
		void fill_set(std::unordered_set<T>&)
		{
		}

		template <typename T, typename... Ts>
		void fill_set(
			std::unordered_set<T>& set,
			T current,
			Ts... next
		)
		{
			set.insert(current);
			fill_set(set, next...);
		}

		template <typename T>
		void fill_vector(std::vector<T>&)
		{
		}

		template <typename T, typename... Ts>
		void fill_vector(
			std::vector<T>& vec,
			T current,
			Ts... next
		)
		{
			vec.push_back(current);
			fill_vector(vec, next...);
		}
	}

	template <typename T, typename... Ts>
	std::unordered_set<T> unordered_set_of(
		T& first,
		Ts... next
	)
	{
		std::unordered_set<T> out;
		fill_set(out, first, next...);
		return out;
	}

	template <typename T, typename... Ts>
	std::vector<T> vector_of(
		T& first,
		Ts... next
	)
	{
		std::unordered_set<T> out;
		fill_vector(out, first, next...);
		return out;
	}
}
<commit_msg>References for variadic.hh<commit_after>#include <vector>
#include <unordered_set>

namespace helpers
{
	namespace implementation
	{
		template <typename T>
		void fill_set(std::unordered_set<T>&)
		{
		}

		template <typename T, typename... Ts>
		void fill_set(
			std::unordered_set<T>& set,
			T& current,
			Ts... next
		)
		{
			set.insert(current);
			fill_set(set, next...);
		}

		template <typename T>
		void fill_vector(std::vector<T>&)
		{
		}

		template <typename T, typename... Ts>
		void fill_vector(
			std::vector<T>& vec,
			T& current,
			Ts... next
		)
		{
			vec.push_back(current);
			fill_vector(vec, next...);
		}
	}

	template <typename T, typename... Ts>
	std::unordered_set<T> unordered_set_of(
		T& first,
		Ts... next
	)
	{
		std::unordered_set<T> out;
		fill_set(out, first, next...);
		return out;
	}

	template <typename T, typename... Ts>
	std::vector<T> vector_of(
		T& first,
		Ts... next
	)
	{
		std::unordered_set<T> out;
		fill_vector(out, first, next...);
		return out;
	}
}
<|endoftext|>


<commit_before>//
// File:   template.cc
// Author: ruehle
//
// Created on June 8, 2008, 10:41 PM
//

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <topologyreader.h>
#include <libversion.h>

using namespace std;

int main(int argc, char** argv)
{
    // initialize the readers/writers,
    // this will be combined in an initialize function later
//    TrajectoryReader::RegisterPlugins();
    TopologyReader::RegisterPlugins();

    // lets read in some program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    desc.add_options()
    ("help", "produce this help message")
    //("version", "show version info")
    ("top", boost::program_options::value<string>(), "atomistic topology file");

    // now read in the command line
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    // does the user want help?
    if (vm.count("help")) {
        cout << "csg_dump, lib version " << LIB_VERSION_STR << "\n\n";
        cout << desc << endl;
        return 0;
    }

    if(!vm.count("top")) {
        cout << "no topology specified\n";
        return 0;
    }

    // try to run the cg process, go through the frames, etc...
    try {
        Topology top;
        TopologyReader *reader;
        reader = TopReaderFactory().Create(vm["top"].as<string>());
        if(reader == NULL)
            throw string("input format not supported: ") + vm["top"].as<string>();

        reader->ReadTopology(vm["top"].as<string>(), top);
        cout << "I have " << top.BeadCount() << " beads in " << top.MoleculeCount() << " molecules" << endl;

        MoleculeContainer::iterator mol;
        for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
            cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName()
              << " beads: " << (*mol)->BeadCount() << endl;
            for(int i=0; i<(*mol)->BeadCount(); ++i) {
                cout << (*mol)->getBeadId(i) << " " <<
                    (*mol)->getBeadName(i) << (*mol)->getBead(i)->getType()->getName() << endl;
            }
        }
    }
    // did an error occour?
    catch(string error) {
        cerr << "An error occoured!" << endl << error << endl;
    }
    return 0;
}

<commit_msg>added missing space<commit_after>//
// File:   template.cc
// Author: ruehle
//
// Created on June 8, 2008, 10:41 PM
//

#include <math.h>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <topologyreader.h>
#include <libversion.h>

using namespace std;

int main(int argc, char** argv)
{
    // initialize the readers/writers,
    // this will be combined in an initialize function later
//    TrajectoryReader::RegisterPlugins();
    TopologyReader::RegisterPlugins();

    // lets read in some program options
    namespace po = boost::program_options;

    // Declare the supported options.
    po::options_description desc("Allowed options");

    // let cg_engine add some program options
    desc.add_options()
    ("help", "produce this help message")
    //("version", "show version info")
    ("top", boost::program_options::value<string>(), "atomistic topology file");

    // now read in the command line
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    // does the user want help?
    if (vm.count("help")) {
        cout << "csg_dump, lib version " << LIB_VERSION_STR << "\n\n";
        cout << desc << endl;
        return 0;
    }

    if(!vm.count("top")) {
        cout << "no topology specified\n";
        return 0;
    }

    // try to run the cg process, go through the frames, etc...
    try {
        Topology top;
        TopologyReader *reader;
        reader = TopReaderFactory().Create(vm["top"].as<string>());
        if(reader == NULL)
            throw string("input format not supported: ") + vm["top"].as<string>();

        reader->ReadTopology(vm["top"].as<string>(), top);
        cout << "I have " << top.BeadCount() << " beads in " << top.MoleculeCount() << " molecules" << endl;

        MoleculeContainer::iterator mol;
        for(mol=top.Molecules().begin(); mol!=top.Molecules().end();++mol) {
            cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName()
              << " beads: " << (*mol)->BeadCount() << endl;
            for(int i=0; i<(*mol)->BeadCount(); ++i) {
                cout << (*mol)->getBeadId(i) << " " <<
                    (*mol)->getBeadName(i) << " " << (*mol)->getBead(i)->getType()->getName() << endl;
            }
        }
    }
    // did an error occour?
    catch(string error) {
        cerr << "An error occoured!" << endl << error << endl;
    }
    return 0;
}

<|endoftext|>


<commit_before>void P010_TRootBrowser()
{
   gPluginMgr->AddHandler("TBrowserImp", "TRootBrowser", "TRootBrowser",
      "Gui", "NewBrowser(TBrowser *, const char *, Int_t, Int_t, UInt_t, UInt_t)");
   gPluginMgr->AddHandler("TBrowserImp", "TRootBrowser", "TRootBrowser",
      "Gui", "NewBrowser(TBrowser *, const char *, UInt_t, UInt_t)");
   gPluginMgr->AddHandler("TBrowserImp", "TRootBrowser", "TRootBrowser",
      "Gui", "NewBrowser(TBrowser *, const char *, Int_t, Int_t, UInt_t, UInt_t, Option_t *)");
}
<commit_msg>Revert browser changes (it has side effects)<commit_after>void P010_TRootBrowser()
{
   gPluginMgr->AddHandler("TBrowserImp", "TRootBrowser", "TRootBrowser",
      "Gui", "NewBrowser(TBrowser *, const char *, Int_t, Int_t, UInt_t, UInt_t)");
   gPluginMgr->AddHandler("TBrowserImp", "TRootBrowser", "TRootBrowser",
      "Gui", "NewBrowser(TBrowser *, const char *, UInt_t, UInt_t)");
}
<|endoftext|>


<commit_before><commit_msg>qt4: epg: Fix inputChanged signal prototype<commit_after><|endoftext|>


<commit_before>#include "VUMeterModule.h"
#include "../Renderer.h"
#include <cstdio>
#include <algorithm>
#include <cmath>

VUMeterModule::VUMeterModule(ModularSynth& synth)
	:SynthModule(synth, moduleId, 1, 1, 1), mInputValue(0), mType(0)
{
}

void VUMeterModule::cycle()
{
	mInputValue = getInput(0);

	// Passthru
	setOutput(0, getInput(0));
}

const char * VUMeterModule::getInputName(int input) const
{
	static const char *names[] = {"Input"};
	return names[input];
}

const char * VUMeterModule::getOutputName(int output) const
{
	static const char *names[] = {"Passthru"};
	return names[output];
}

const char * VUMeterModule::getName() const
{
	return "VUMeter";
}

SynthModule * VUMeterModule::createModule(ModularSynth& synth)
{
	return new VUMeterModule(synth);
}

void VUMeterModule::render(Renderer& renderer, const SDL_Rect& moduleArea, bool isSelected) const
{
	renderer.renderRect(moduleArea, getModuleColor(isSelected));

	switch (mType)
	{
		// 0.0 .. 1.0
		default:
		case 0: {
			float input = std::min(1.0f, std::max(0.0f, mInputValue));
			SDL_Rect meterArea = { moduleArea.x, moduleArea.y,
				static_cast<int>(static_cast<float>(moduleArea.w) * input), moduleArea.h };

			renderer.renderRect(meterArea, Color(192, 192, 192));
		} break;

		// -1.0 .. 1.0
		case 1: {
			float input = std::min(1.0f, std::max(-1.0f, mInputValue));
			int x1 = static_cast<int>(static_cast<float>(moduleArea.w) * (input * 0.5f + 0.5f));
			int x2 = moduleArea.w / 2;
			SDL_Rect meterArea = { moduleArea.x + std::min(x1, x2), moduleArea.y,
				abs(x1 - x2), moduleArea.h };
			renderer.renderRect(meterArea, Color(192, 192, 192));
			renderer.renderLine(moduleArea.x + moduleArea.w / 2, moduleArea.y,
				moduleArea.x + moduleArea.w / 2, moduleArea.y + moduleArea.h - 1, Color());
		} break;
	}
}

void VUMeterModule::onDial(int delta)
{
	mType = (static_cast<int>(static_cast<float>(delta) + mParams[0]) + 2) % 2;
	setParam(0, mType);
}

void VUMeterModule::onLoaded()
{
	// Trigger update
	onDial(0);
}
<commit_msg>Cleanup<commit_after>#include "VUMeterModule.h"
#include "../Renderer.h"
#include <cstdio>
#include <algorithm>

VUMeterModule::VUMeterModule(ModularSynth& synth)
	:SynthModule(synth, moduleId, 1, 1, 1), mInputValue(0), mType(0)
{
}

void VUMeterModule::cycle()
{
	mInputValue = getInput(0);

	// Passthru
	setOutput(0, getInput(0));
}

const char * VUMeterModule::getInputName(int input) const
{
	static const char *names[] = {"Input"};
	return names[input];
}

const char * VUMeterModule::getOutputName(int output) const
{
	static const char *names[] = {"Passthru"};
	return names[output];
}

const char * VUMeterModule::getName() const
{
	return "VUMeter";
}

SynthModule * VUMeterModule::createModule(ModularSynth& synth)
{
	return new VUMeterModule(synth);
}

void VUMeterModule::render(Renderer& renderer, const SDL_Rect& moduleArea, bool isSelected) const
{
	renderer.renderRect(moduleArea, getModuleColor(isSelected));

	switch (mType)
	{
		// 0.0 .. 1.0
		default:
		case 0: {
			float input = std::min(1.0f, std::max(0.0f, mInputValue));
			SDL_Rect meterArea = { moduleArea.x, moduleArea.y,
				static_cast<int>(static_cast<float>(moduleArea.w) * input), moduleArea.h };

			renderer.renderRect(meterArea, Color(192, 192, 192));
		} break;

		// -1.0 .. 1.0
		case 1: {
			float input = std::min(1.0f, std::max(-1.0f, mInputValue));
			int x1 = static_cast<int>(static_cast<float>(moduleArea.w) * (input * 0.5f + 0.5f));
			int x2 = moduleArea.w / 2;
			SDL_Rect meterArea = { moduleArea.x + std::min(x1, x2), moduleArea.y,
				abs(x1 - x2), moduleArea.h };
			renderer.renderRect(meterArea, Color(192, 192, 192));
			renderer.renderLine(moduleArea.x + moduleArea.w / 2, moduleArea.y,
				moduleArea.x + moduleArea.w / 2, moduleArea.y + moduleArea.h - 1, Color());
		} break;
	}
}

void VUMeterModule::onDial(int delta)
{
	mType = (static_cast<int>(static_cast<float>(delta) + mParams[0]) + 2) % 2;
	setParam(0, mType);
}

void VUMeterModule::onLoaded()
{
	// Trigger update
	onDial(0);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/ffdc/p9_collect_lpc_regs.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>p9_sbe_lpc_init: Add final check for errors<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/ffdc/p9_collect_lpc_regs.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _COLLECT_LPC_REGS_H_
#define _COLLECT_LPC_REGS_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <return_code.H>
#include <error_info_defs.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_collect_lpc_regs_FP_t)(fapi2::ffdc_t&, fapi2::ReturnCode&);

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

///
/// @brief Procedure for gathering LPC register data into FFDC, to complement p9_sbe_lpc_init
/// @param[in] i_target_chip - P9 chip to collect LPC registers from
/// @param[out] o_rc - return code to add FFDC data to.
///
/// @return FAPI2_RC_SUCCESS
extern "C" fapi2::ReturnCode p9_collect_lpc_regs(fapi2::ffdc_t& i_target_chip, fapi2::ReturnCode& o_rc);

#endif
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <tsdb/SQLEngine.h>
#include <tsdb/TSDBNode.h>
#include <tsdb/TimeWindowPartitioner.h>
#include <chartsql/defaults.h>

namespace tsdb {

SQLEngine::SQLEngine(TSDBNode* tsdb_node) : tsdb_node_(tsdb_node) {
  installDefaultSymbols(&sql_runtime_);
}

void SQLEngine::executeQuery(
    const String& tsdb_namespace,
    const String& query,
    RefPtr<csql::ResultFormat> result_format) {
  auto qplan = parseAndBuildQueryPlan(tsdb_namespace, query);
  csql::ExecutionContext context;
  result_format->formatResults(qplan, &context);
}

RefPtr<csql::QueryPlan> SQLEngine::parseAndBuildQueryPlan(
    const String& tsdb_namespace,
    const String& query) {
  return sql_runtime_.parseAndBuildQueryPlan(
      query,
      tableProviderForNamespace(tsdb_namespace),
      std::bind(
          &SQLEngine::rewriteQuery,
          this,
          tsdb_namespace,
          std::placeholders::_1));
}

RefPtr<csql::QueryTreeNode> SQLEngine::rewriteQuery(
    const String& tsdb_namespace,
    RefPtr<csql::QueryTreeNode> query) {
  if (dynamic_cast<csql::TableExpressionNode*>(query.get())) {
    auto tbl_expr = query.asInstanceOf<csql::TableExpressionNode>();
    replaceAllSequentialScansWithUnions(tsdb_namespace, &tbl_expr);
    return tbl_expr.get();
  }

  return query;
}

RefPtr<csql::TableProvider> SQLEngine::tableProviderForNamespace(
    const String& tsdb_namespace) {
  return new TSDBTableProvider(tsdb_namespace, tsdb_node_);
}

void SQLEngine::replaceAllSequentialScansWithUnions(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  if (dynamic_cast<csql::SequentialScanNode*>(node->get())) {
    replaceSequentialScanWithUnion(tsdb_namespace, node);
    return;
  }

  auto ntables = node->get()->numInputTables();
  for (int i = 0; i < ntables; ++i) {
    replaceAllSequentialScansWithUnions(
        tsdb_namespace,
        node->get()->mutableInputTable(i));
  }
}

void SQLEngine::replaceSequentialScanWithUnion(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  auto seqscan = node->asInstanceOf<csql::SequentialScanNode>();

  auto stream_key = seqscan->tableName();
  if (StringUtil::beginsWith(stream_key, "tsdb://")) {
    return;
  }

  auto partitions = TimeWindowPartitioner::partitionKeysFor(
      stream_key,
      WallClock::unixMicros() - 30 * kMicrosPerDay,
      WallClock::unixMicros(),
      4 * kMicrosPerHour);

  Vector<RefPtr<csql::TableExpressionNode>> union_tables;
  for (const auto& partition : partitions) {
    auto table_name = StringUtil::format(
        "tsdb://$0/$1",
        URI::urlEncode(stream_key),
        partition.toString());

    auto copy = seqscan->deepCopyAs<csql::SequentialScanNode>();
    copy->setTableName(table_name);
    union_tables.emplace_back(copy.get());
  }

  *node = RefPtr<csql::TableExpressionNode>(new csql::UnionNode(union_tables));
}

}
<commit_msg>push query execution down into runtime<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <tsdb/SQLEngine.h>
#include <tsdb/TSDBNode.h>
#include <tsdb/TimeWindowPartitioner.h>
#include <chartsql/defaults.h>

namespace tsdb {

SQLEngine::SQLEngine(TSDBNode* tsdb_node) : tsdb_node_(tsdb_node) {
  installDefaultSymbols(&sql_runtime_);
}

void SQLEngine::executeQuery(
    const String& tsdb_namespace,
    const String& query,
    RefPtr<csql::ResultFormat> result_format) {
  auto qplan = parseAndBuildQueryPlan(tsdb_namespace, query);
  sql_runtime_.executeQuery(qplan, result_format);
}

RefPtr<csql::QueryPlan> SQLEngine::parseAndBuildQueryPlan(
    const String& tsdb_namespace,
    const String& query) {
  return sql_runtime_.parseAndBuildQueryPlan(
      query,
      tableProviderForNamespace(tsdb_namespace),
      std::bind(
          &SQLEngine::rewriteQuery,
          this,
          tsdb_namespace,
          std::placeholders::_1));
}

RefPtr<csql::QueryTreeNode> SQLEngine::rewriteQuery(
    const String& tsdb_namespace,
    RefPtr<csql::QueryTreeNode> query) {
  if (dynamic_cast<csql::TableExpressionNode*>(query.get())) {
    auto tbl_expr = query.asInstanceOf<csql::TableExpressionNode>();
    replaceAllSequentialScansWithUnions(tsdb_namespace, &tbl_expr);
    return tbl_expr.get();
  }

  return query;
}

RefPtr<csql::TableProvider> SQLEngine::tableProviderForNamespace(
    const String& tsdb_namespace) {
  return new TSDBTableProvider(tsdb_namespace, tsdb_node_);
}

void SQLEngine::replaceAllSequentialScansWithUnions(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  if (dynamic_cast<csql::SequentialScanNode*>(node->get())) {
    replaceSequentialScanWithUnion(tsdb_namespace, node);
    return;
  }

  auto ntables = node->get()->numInputTables();
  for (int i = 0; i < ntables; ++i) {
    replaceAllSequentialScansWithUnions(
        tsdb_namespace,
        node->get()->mutableInputTable(i));
  }
}

void SQLEngine::replaceSequentialScanWithUnion(
    const String& tsdb_namespace,
    RefPtr<csql::TableExpressionNode>* node) {
  auto seqscan = node->asInstanceOf<csql::SequentialScanNode>();

  auto stream_key = seqscan->tableName();
  if (StringUtil::beginsWith(stream_key, "tsdb://")) {
    return;
  }

  auto partitions = TimeWindowPartitioner::partitionKeysFor(
      stream_key,
      WallClock::unixMicros() - 30 * kMicrosPerDay,
      WallClock::unixMicros(),
      4 * kMicrosPerHour);

  Vector<RefPtr<csql::TableExpressionNode>> union_tables;
  for (const auto& partition : partitions) {
    auto table_name = StringUtil::format(
        "tsdb://$0/$1",
        URI::urlEncode(stream_key),
        partition.toString());

    auto copy = seqscan->deepCopyAs<csql::SequentialScanNode>();
    copy->setTableName(table_name);
    union_tables.emplace_back(copy.get());
  }

  *node = RefPtr<csql::TableExpressionNode>(new csql::UnionNode(union_tables));
}

}
<|endoftext|>


<commit_before><commit_msg>Update ZivkovicAGMM.cpp<commit_after><|endoftext|>


<commit_before>/*
 *  This file is part of WinSparkle (http://winsparkle.org)
 *
 *  Copyright (C) 2009-2010 Vaclav Slavik
 *  Copyright (C) 2007 Andy Matuschak
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "updatechecker.h"
#include "appcast.h"
#include "ui.h"
#include "error.h"
#include "settings.h"
#include "download.h"
#include "utils.h"

#include <vector>
#include <cstdlib>
#include <algorithm>

using namespace std;

namespace winsparkle
{

/*--------------------------------------------------------------------------*
                              version comparison
 *--------------------------------------------------------------------------*/

// Note: This code is based on Sparkle's SUStandardVersionComparator by
//       Andy Matuschak.

namespace
{

// String characters classification. Valid components of version numbers
// are numbers, period or string fragments ("beta" etc.).
enum CharType
{
    Type_Number,
    Type_Period,
    Type_String
};

CharType ClassifyChar(char c)
{
    if ( c == '.' )
        return Type_Period;
    else if ( c >= '0' && c <= '9' )
        return Type_Number;
    else
        return Type_String;
}

// Split version string into individual components. A component is continuous
// run of characters with the same classification. For example, "1.20rc3" would
// be split into ["1",".","20","rc","3"].
vector<string> SplitVersionString(const string& version)
{
    vector<string> list;

    if ( version.empty() )
        return list; // nothing to do here

    string s;
    const size_t len = version.length();

    s = version[0];
    CharType prevType = ClassifyChar(version[0]);

    for ( size_t i = 1; i < len; i++ )
    {
        const char c = version[i];
        const CharType newType = ClassifyChar(c);

        if ( prevType != newType || prevType == Type_Period )
        {
            // We reached a new segment. Period gets special treatment,
            // because "." always delimiters components in version strings
            // (and so ".." means there's empty component value).
            list.push_back(s);
            s = c;
        }
        else
        {
            // Add character to current segment and continue.
            s += c;
        }

        prevType = newType;
    }

    // Don't forget to add the last part:
    list.push_back(s);

    return list;
}

} // anonymous namespace

int UpdateChecker::CompareVersions(const string& verA, const string& verB)
{
    const vector<string> partsA = SplitVersionString(verA);
    const vector<string> partsB = SplitVersionString(verB);

    // Compare common length of both version strings.
    const size_t n = min(partsA.size(), partsB.size());
    for ( size_t i = 0; i < n; i++ )
    {
        const string& a = partsA[i];
        const string& b = partsB[i];

        const CharType typeA = ClassifyChar(a[0]);
        const CharType typeB = ClassifyChar(b[0]);

        if ( typeA == typeB )
        {
            if ( typeA == Type_String )
            {
                int result = a.compare(b);
                if ( result != 0 )
                    return result;
            }
            else if ( typeA == Type_Number )
            {
                const int intA = atoi(a.c_str());
                const int intB = atoi(b.c_str());
                if ( intA > intB )
                    return 1;
                else if ( intA < intB )
                    return -1;
            }
        }
        else // components of different types
        {
            if ( typeA != Type_String && typeB == Type_String )
            {
                // 1.2.0 > 1.2rc1
                return 1;
            }
            else if ( typeA == Type_String && typeB != Type_String )
            {
                // 1.2rc1 < 1.2.0
                return -1;
            }
            else
            {
                // One is a number and the other is a period. The period
                // is invalid.
                return (typeA == Type_Number) ? 1 : -1;
            }
        }
    }

    // The versions are equal up to the point where they both still have
    // parts. Lets check to see if one is larger than the other.
    if ( partsA.size() == partsB.size() )
        return 0; // the two strings are identical

    // Lets get the next part of the larger version string
    // Note that 'n' already holds the index of the part we want.

    int shorterResult, longerResult;
    CharType missingPartType; // ('missing' as in "missing in shorter version")

    if ( partsA.size() > partsB.size() )
    {
        missingPartType = ClassifyChar(partsA[n][0]);
        shorterResult = -1;
        longerResult = 1;
    }
    else
    {
        missingPartType = ClassifyChar(partsB[n][0]);
        shorterResult = 1;
        longerResult = -1;
    }

    if ( missingPartType == Type_String )
    {
        // 1.5 > 1.5b3
        return shorterResult;
    }
    else
    {
        // 1.5.1 > 1.5
        return longerResult;
    }
}

/*--------------------------------------------------------------------------*
                             UpdateChecker::Run()
 *--------------------------------------------------------------------------*/

UpdateChecker::UpdateChecker(): Thread("WinSparkle updates check")
{
}

void UpdateChecker::Run()
{
    // no initialization to do, so signal readiness immediately
    SignalReady();

    try
    {
        const std::string url = Settings::GetAppcastURL();
        if ( url.empty() )
            throw std::runtime_error("Appcast URL not specified.");

        StringDownloadSink appcast_xml;
        DownloadFile(url, &appcast_xml);

        Appcast appcast;
        appcast.Load(appcast_xml.data);

        // FIXME: really check appcast data...
        OutputDebugStringA("WinSparkle appcast data:\n");
        OutputDebugStringA(("    Version:       " + appcast.Version + "\n").c_str());
        OutputDebugStringA(("    Download:      " + appcast.DownloadURL + "\n").c_str());
        OutputDebugStringA(("    Release notes: " + appcast.ReleaseNotesURL + "\n").c_str());

        const std::string currentVersion =
                WideToAnsi(Settings::GetAppVersion());

        if ( CompareVersions(currentVersion, appcast.Version) < 0 )
        {
            UI::NotifyUpdateAvailable(appcast);
        }
        else
        {
            UI::NotifyNoUpdates();
        }
    }
    catch ( ... )
    {
        UI::NotifyNoUpdates();
        throw;
    }
}

} // namespace winsparkle
<commit_msg>Removed forgotten debugging output.<commit_after>/*
 *  This file is part of WinSparkle (http://winsparkle.org)
 *
 *  Copyright (C) 2009-2010 Vaclav Slavik
 *  Copyright (C) 2007 Andy Matuschak
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "updatechecker.h"
#include "appcast.h"
#include "ui.h"
#include "error.h"
#include "settings.h"
#include "download.h"
#include "utils.h"

#include <vector>
#include <cstdlib>
#include <algorithm>

using namespace std;

namespace winsparkle
{

/*--------------------------------------------------------------------------*
                              version comparison
 *--------------------------------------------------------------------------*/

// Note: This code is based on Sparkle's SUStandardVersionComparator by
//       Andy Matuschak.

namespace
{

// String characters classification. Valid components of version numbers
// are numbers, period or string fragments ("beta" etc.).
enum CharType
{
    Type_Number,
    Type_Period,
    Type_String
};

CharType ClassifyChar(char c)
{
    if ( c == '.' )
        return Type_Period;
    else if ( c >= '0' && c <= '9' )
        return Type_Number;
    else
        return Type_String;
}

// Split version string into individual components. A component is continuous
// run of characters with the same classification. For example, "1.20rc3" would
// be split into ["1",".","20","rc","3"].
vector<string> SplitVersionString(const string& version)
{
    vector<string> list;

    if ( version.empty() )
        return list; // nothing to do here

    string s;
    const size_t len = version.length();

    s = version[0];
    CharType prevType = ClassifyChar(version[0]);

    for ( size_t i = 1; i < len; i++ )
    {
        const char c = version[i];
        const CharType newType = ClassifyChar(c);

        if ( prevType != newType || prevType == Type_Period )
        {
            // We reached a new segment. Period gets special treatment,
            // because "." always delimiters components in version strings
            // (and so ".." means there's empty component value).
            list.push_back(s);
            s = c;
        }
        else
        {
            // Add character to current segment and continue.
            s += c;
        }

        prevType = newType;
    }

    // Don't forget to add the last part:
    list.push_back(s);

    return list;
}

} // anonymous namespace

int UpdateChecker::CompareVersions(const string& verA, const string& verB)
{
    const vector<string> partsA = SplitVersionString(verA);
    const vector<string> partsB = SplitVersionString(verB);

    // Compare common length of both version strings.
    const size_t n = min(partsA.size(), partsB.size());
    for ( size_t i = 0; i < n; i++ )
    {
        const string& a = partsA[i];
        const string& b = partsB[i];

        const CharType typeA = ClassifyChar(a[0]);
        const CharType typeB = ClassifyChar(b[0]);

        if ( typeA == typeB )
        {
            if ( typeA == Type_String )
            {
                int result = a.compare(b);
                if ( result != 0 )
                    return result;
            }
            else if ( typeA == Type_Number )
            {
                const int intA = atoi(a.c_str());
                const int intB = atoi(b.c_str());
                if ( intA > intB )
                    return 1;
                else if ( intA < intB )
                    return -1;
            }
        }
        else // components of different types
        {
            if ( typeA != Type_String && typeB == Type_String )
            {
                // 1.2.0 > 1.2rc1
                return 1;
            }
            else if ( typeA == Type_String && typeB != Type_String )
            {
                // 1.2rc1 < 1.2.0
                return -1;
            }
            else
            {
                // One is a number and the other is a period. The period
                // is invalid.
                return (typeA == Type_Number) ? 1 : -1;
            }
        }
    }

    // The versions are equal up to the point where they both still have
    // parts. Lets check to see if one is larger than the other.
    if ( partsA.size() == partsB.size() )
        return 0; // the two strings are identical

    // Lets get the next part of the larger version string
    // Note that 'n' already holds the index of the part we want.

    int shorterResult, longerResult;
    CharType missingPartType; // ('missing' as in "missing in shorter version")

    if ( partsA.size() > partsB.size() )
    {
        missingPartType = ClassifyChar(partsA[n][0]);
        shorterResult = -1;
        longerResult = 1;
    }
    else
    {
        missingPartType = ClassifyChar(partsB[n][0]);
        shorterResult = 1;
        longerResult = -1;
    }

    if ( missingPartType == Type_String )
    {
        // 1.5 > 1.5b3
        return shorterResult;
    }
    else
    {
        // 1.5.1 > 1.5
        return longerResult;
    }
}

/*--------------------------------------------------------------------------*
                             UpdateChecker::Run()
 *--------------------------------------------------------------------------*/

UpdateChecker::UpdateChecker(): Thread("WinSparkle updates check")
{
}

void UpdateChecker::Run()
{
    // no initialization to do, so signal readiness immediately
    SignalReady();

    try
    {
        const std::string url = Settings::GetAppcastURL();
        if ( url.empty() )
            throw std::runtime_error("Appcast URL not specified.");

        StringDownloadSink appcast_xml;
        DownloadFile(url, &appcast_xml);

        Appcast appcast;
        appcast.Load(appcast_xml.data);

        const std::string currentVersion =
                WideToAnsi(Settings::GetAppVersion());

        if ( CompareVersions(currentVersion, appcast.Version) < 0 )
        {
            UI::NotifyUpdateAvailable(appcast);
        }
        else
        {
            UI::NotifyNoUpdates();
        }
    }
    catch ( ... )
    {
        UI::NotifyNoUpdates();
        throw;
    }
}

} // namespace winsparkle
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Hewlett Packard Enterprise Development LP
 *
 * 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 "application/Application.h"

#include <cassert>
#include <cmath>

#include "application/Messenger.h"
#include "application/Terminal.h"
#include "network/Network.h"

Application::Application(const std::string& _name, const Component* _parent,
                         MetadataHandler* _metadataHandler,
                         Json::Value _settings)
    : Component(_name, _parent), metadataHandler_(_metadataHandler) {
  Network* network = gSim->getNetwork();

  u32 radix = network->numInterfaces();
  terminals_.resize(radix, nullptr);
  messengers_.resize(radix, nullptr);

  // extract maximum injection rate
  maxInjectionRate_ = _settings["max_injection_rate"].asDouble();
  if (maxInjectionRate_ <= 0.0) {
    maxInjectionRate_ = INFINITY;
  }

  // instantiate the messengers
  for (u32 id = 0; id < radix; id++) {
    // create the messenger
    std::string cname = "Messenger_" + std::to_string(id);
    messengers_.at(id) = new Messenger(cname, this, this, id);

    // link the messenger to the network
    messengers_.at(id)->linkInterface(network->getInterface(id));
  }

  // create a MessageLog
  messageLog_ = new MessageLog(_settings["message_log"]);

  // create the rate log
  rateLog_ = new RateLog(_settings["rate_log"]);
}

Application::~Application() {
  for (u32 idx = 0; idx < terminals_.size(); idx++) {
    delete terminals_.at(idx);
    delete messengers_.at(idx);
  }
  delete messageLog_;
  delete rateLog_;
}

u32 Application::numTerminals() const {
  return terminals_.size();
}

Terminal* Application::getTerminal(u32 _id) const {
  return terminals_.at(_id);
}

MessageLog* Application::getMessageLog() const {
  return messageLog_;
}

MetadataHandler* Application::getMetadataHandler() const {
  return metadataHandler_;
}

u64 Application::createTransaction(u32 _tid, u32 _lid) {
  u64 trans = ((u64)_tid << 32) | (u64)_lid;
  u64 now = gSim->time();
  bool res = transactions_.insert(std::make_pair(trans, now)).second;
  (void)res;  // unused
  assert(res);
  return trans;
}

u64 Application::transactionCreationTime(u64 _trans) const {
  return transactions_.at(_trans);
}

void Application::endTransaction(u64 _trans) {
  u64 res = transactions_.erase(_trans);
  (void)res;  // unused
  assert(res == 1);
}

u64 Application::cyclesToSend(u32 _numFlits) const {
  if (isinf(maxInjectionRate_)) {
    return 0;  // infinite injection rate
  }
  f64 cycles = _numFlits / maxInjectionRate_;

  // if the number of cycles is not even, probablistic cycles must be computed
  f64 fraction = modf(cycles, &cycles);
  if (fraction != 0.0) {
    assert(fraction > 0.0);
    assert(fraction < 1.0);
    f64 rnd = gSim->rnd.nextF64();
    if (fraction > rnd) {
      cycles += 1.0;
    }
  }
  return (u64)cycles;
}

void Application::startMonitoring() {
  for (u32 i = 0; i < messengers_.size(); i++) {
    messengers_.at(i)->startRateMonitors();
  }
}

void Application::endMonitoring() {
  for (u32 i = 0; i < messengers_.size(); i++) {
    messengers_.at(i)->endRateMonitors();
  }
  for (u32 i = 0; i < messengers_.size(); i++) {
    messengers_.at(i)->logRates(rateLog_);
  }
}

void Application::setTerminal(u32 _id, Terminal* _terminal) {
  terminals_.at(_id) = _terminal;
  messengers_.at(_id)->linkTerminal(terminals_.at(_id));
}
<commit_msg>isinf needs std:: for GCC 5.3<commit_after>/*
 * Copyright 2016 Hewlett Packard Enterprise Development LP
 *
 * 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 "application/Application.h"

#include <cassert>
#include <cmath>

#include "application/Messenger.h"
#include "application/Terminal.h"
#include "network/Network.h"

Application::Application(const std::string& _name, const Component* _parent,
                         MetadataHandler* _metadataHandler,
                         Json::Value _settings)
    : Component(_name, _parent), metadataHandler_(_metadataHandler) {
  Network* network = gSim->getNetwork();

  u32 radix = network->numInterfaces();
  terminals_.resize(radix, nullptr);
  messengers_.resize(radix, nullptr);

  // extract maximum injection rate
  maxInjectionRate_ = _settings["max_injection_rate"].asDouble();
  if (maxInjectionRate_ <= 0.0) {
    maxInjectionRate_ = INFINITY;
  }

  // instantiate the messengers
  for (u32 id = 0; id < radix; id++) {
    // create the messenger
    std::string cname = "Messenger_" + std::to_string(id);
    messengers_.at(id) = new Messenger(cname, this, this, id);

    // link the messenger to the network
    messengers_.at(id)->linkInterface(network->getInterface(id));
  }

  // create a MessageLog
  messageLog_ = new MessageLog(_settings["message_log"]);

  // create the rate log
  rateLog_ = new RateLog(_settings["rate_log"]);
}

Application::~Application() {
  for (u32 idx = 0; idx < terminals_.size(); idx++) {
    delete terminals_.at(idx);
    delete messengers_.at(idx);
  }
  delete messageLog_;
  delete rateLog_;
}

u32 Application::numTerminals() const {
  return terminals_.size();
}

Terminal* Application::getTerminal(u32 _id) const {
  return terminals_.at(_id);
}

MessageLog* Application::getMessageLog() const {
  return messageLog_;
}

MetadataHandler* Application::getMetadataHandler() const {
  return metadataHandler_;
}

u64 Application::createTransaction(u32 _tid, u32 _lid) {
  u64 trans = ((u64)_tid << 32) | (u64)_lid;
  u64 now = gSim->time();
  bool res = transactions_.insert(std::make_pair(trans, now)).second;
  (void)res;  // unused
  assert(res);
  return trans;
}

u64 Application::transactionCreationTime(u64 _trans) const {
  return transactions_.at(_trans);
}

void Application::endTransaction(u64 _trans) {
  u64 res = transactions_.erase(_trans);
  (void)res;  // unused
  assert(res == 1);
}

u64 Application::cyclesToSend(u32 _numFlits) const {
  if (std::isinf(maxInjectionRate_)) {
    return 0;  // infinite injection rate
  }
  f64 cycles = _numFlits / maxInjectionRate_;

  // if the number of cycles is not even, probablistic cycles must be computed
  f64 fraction = modf(cycles, &cycles);
  if (fraction != 0.0) {
    assert(fraction > 0.0);
    assert(fraction < 1.0);
    f64 rnd = gSim->rnd.nextF64();
    if (fraction > rnd) {
      cycles += 1.0;
    }
  }
  return (u64)cycles;
}

void Application::startMonitoring() {
  for (u32 i = 0; i < messengers_.size(); i++) {
    messengers_.at(i)->startRateMonitors();
  }
}

void Application::endMonitoring() {
  for (u32 i = 0; i < messengers_.size(); i++) {
    messengers_.at(i)->endRateMonitors();
  }
  for (u32 i = 0; i < messengers_.size(); i++) {
    messengers_.at(i)->logRates(rateLog_);
  }
}

void Application::setTerminal(u32 _id, Terminal* _terminal) {
  terminals_.at(_id) = _terminal;
  messengers_.at(_id)->linkTerminal(terminals_.at(_id));
}
<|endoftext|>