<commit_before>/**
    @author Pedro Rodriguez
*/

#include <vector>
#include <iostream>
#include <Grappa.hpp>

#ifndef GRAPPARDD_RDD_H
#define GRAPPARDD_RDD_H

using std::cout;
using std::vector;
using std::endl;
using namespace Grappa;

namespace GrappaRDD {
    template<typename T>
    void print_vector(vector <T> v) {
        cout << "Length: " << v.size() << endl;
        for (auto i = v.begin(); i != v.end(); ++i) {
            cout << *i << ' ' << endl;
        }
    }

    template<typename A>
    A add(const A& left, const A& right) {
        return left + right;
    }

    template<typename A>
    A product(const A& left, const A& right) {
        return left * right;
    }
}

template<typename T, typename A>
class MappedRDD;

template<typename A>
class RangedRDD;

template<typename A>
class RDD {
public:
    template<typename T, typename U>
    friend class MappedRDD;

    static RangedRDD<A>* range(A start, A end);
    static RangedRDD<A>* range(A end);

    template<typename Func>
    auto map(Func f) -> RDD<decltype(f(A()))> * {
        return new MappedRDD<A, decltype(f(A()))>(this, f);
    }

    /**
        Folds the RDD to a single value using f.

        @param init Initial vale for fold
        @param f Function which folds elements by (A, A) -> A
        @return RDD<A> reduced using f
    */
    auto fold(A init, A (*f)(const A&, const A&)) -> A {
        auto rdd = this->compute();

        A global_value = init;

        auto rdd_address = this->rdd_address;
        auto size = this->size;
        auto global_value_addr = make_global(&global_value);

        finish([f, rdd_address, size, global_value_addr] {
            on_all_cores([rdd_address, size, global_value_addr, f]{
                A *local_start = rdd_address.localize();
                A *local_end = (rdd_address + size).localize();
                A local_value = *local_start;
                if (local_end > local_start) {
                    for(A *val = local_start + 1; val < local_end; ++val) {
                        local_value = f(local_value, *val);
                    }
                }
                delegate::call<async>(global_value_addr, [local_value, f] (A &global_value) {
                    global_value = f(global_value, local_value);
                });
            });
        });

        return global_value;
    }

    A sum() {
        return this->fold(A(), GrappaRDD::add);
    }

    A product() {
        return this->fold(A(), GrappaRDD::product);
    }

    auto collect() -> vector <A> {
        auto rdd = this->compute();
        vector <A> output;
        forall(rdd, size, [&output](A &e) {
            delegate::call<async>(0, [&output, e] {
                output.push_back(e);
            });
        });
        return output;
    }

    void print() {
        auto rdd = this->compute();
        forall(rdd, size, [](A &e) {
            cout << e << endl;
        });
    }

    virtual GlobalAddress <A> compute() = 0;
protected:
    int size;
    GlobalAddress <A> rdd_address;
};

template<typename T, typename A>
class MappedRDD : public RDD<A> {
public:
    static_assert(sizeof(A) == sizeof(T), "A and T must have the same size");
    RDD<T> *prev;
    std::function<A(T)> f;

    MappedRDD(RDD<T> *prev, std::function<A(T)> f) : prev(prev), f(f) {
        this->size = prev->size;
    }

    GlobalAddress <A> compute() {
        // Assumes sizeof(A)=sizeof(T)
        auto prev_address = prev->compute();
        this->rdd_address = static_cast<GlobalAddress <A>>(prev_address);
        auto func = this->f;

        forall(this->rdd_address, this->size, [func](int64_t i, A &e) {
            e = func((T &) e);
        });
        return this->rdd_address;
    }
};

//template<typename A>
//ParallelCollectionRDD<A> parallelize(vector<A> sequence) {
//return new ParallelCollectionRDD(sequence);
//}

template<typename A>
class ParallelCollectionRDD : public RDD<A> {
private:
    vector <A> sequence;
public:
    ParallelCollectionRDD(vector <A> sequence) : sequence(sequence) {
        this->size = sequence.size();
    }

    GlobalAddress <A> compute() {
        this->rdd_address = global_alloc<A>(this->size);
        auto size = this->size;
        auto rdd_address = this->rdd_address;
        auto sequence = this->sequence;
        finish([size, rdd_address, sequence]{
            for (int i = 0; i < size; i++) {
                delegate::write<async>(rdd_address + i, sequence[i]);
            }
        });
        return this->rdd_address;
    }
};

template<typename A>
class RangedRDD : public RDD<A> {
    A start;
    A end;
public:
    RangedRDD(A start, A end) : start(start), end(end) {
        this->size = static_cast<int>(end - start);
    }

    GlobalAddress <A> compute() {
        this->rdd_address = global_alloc<A>(this->size);
        forall(this->rdd_address, this->size, [](int64_t i, A &e) {
            e = i;
        });

        return this->rdd_address;
    }
};

template<typename A>
RangedRDD<A>* RDD<A>::range(A start, A end) {
    return new RangedRDD<A>(start, end);
}

template<typename A>
RangedRDD<A>* RDD<A>::range(A end) {
    return new RangedRDD<A>(0, end);
}

#endif //GRAPPARDD_RDD_H

<commit_msg>Added free methods and destructor to RDD<commit_after>/**
    @author Pedro Rodriguez
*/

#include <vector>
#include <iostream>
#include <Grappa.hpp>

#ifndef GRAPPARDD_RDD_H
#define GRAPPARDD_RDD_H

using std::cout;
using std::vector;
using std::endl;
using namespace Grappa;

namespace GrappaRDD {
    template<typename T>
    void print_vector(vector <T> v) {
        cout << "Length: " << v.size() << endl;
        for (auto i = v.begin(); i != v.end(); ++i) {
            cout << *i << ' ' << endl;
        }
    }

    template<typename A>
    A add(const A& left, const A& right) {
        return left + right;
    }

    template<typename A>
    A product(const A& left, const A& right) {
        return left * right;
    }
}

template<typename T, typename A>
class MappedRDD;

template<typename A>
class RangedRDD;

template<typename A>
class RDD {
public:
    template<typename T, typename U>
    friend class MappedRDD;

    static RangedRDD<A>* range(A start, A end);
    static RangedRDD<A>* range(A end);

    ~RDD() {
        this->free();
    }

    template<typename Func>
    auto map(Func f) -> RDD<decltype(f(A()))> * {
        return new MappedRDD<A, decltype(f(A()))>(this, f);
    }

    /**
        Folds the RDD to a single value using f.

        @param init Initial vale for fold
        @param f Function which folds elements by (A, A) -> A
        @return RDD<A> reduced using f
    */
    auto fold(A init, A (*f)(const A&, const A&)) -> A {
        auto rdd = this->compute();

        A global_value = init;

        auto rdd_address = this->rdd_address;
        auto size = this->size;
        auto global_value_addr = make_global(&global_value);

        finish([f, rdd_address, size, global_value_addr] {
            on_all_cores([rdd_address, size, global_value_addr, f]{
                A *local_start = rdd_address.localize();
                A *local_end = (rdd_address + size).localize();
                A local_value = *local_start;
                if (local_end > local_start) {
                    for(A *val = local_start + 1; val < local_end; ++val) {
                        local_value = f(local_value, *val);
                    }
                }
                delegate::call<async>(global_value_addr, [local_value, f] (A &global_value) {
                    global_value = f(global_value, local_value);
                });
            });
        });

        return global_value;
    }

    A sum() {
        return this->fold(A(), GrappaRDD::add);
    }

    A product() {
        return this->fold(A(), GrappaRDD::product);
    }

    auto collect() -> vector <A> {
        auto rdd = this->compute();
        vector <A> output;
        forall(rdd, size, [&output](A &e) {
            delegate::call<async>(0, [&output, e] {
                output.push_back(e);
            });
        });
        return output;
    }

    void print() {
        auto rdd = this->compute();
        forall(rdd, size, [](A &e) {
            cout << e << endl;
        });
    }

    virtual GlobalAddress <A> compute() = 0;
    virtual void free() = 0;
protected:
    int size;
    GlobalAddress <A> rdd_address;
};

template<typename T, typename A>
class MappedRDD : public RDD<A> {
public:
    static_assert(sizeof(A) == sizeof(T), "A and T must have the same size");
    RDD<T> *prev;
    std::function<A(T)> f;

    MappedRDD(RDD<T> *prev, std::function<A(T)> f) : prev(prev), f(f) {
        this->size = prev->size;
    }

    GlobalAddress <A> compute() {
        // Assumes sizeof(A)=sizeof(T)
        auto prev_address = prev->compute();
        this->rdd_address = static_cast<GlobalAddress <A>>(prev_address);
        auto func = this->f;

        forall(this->rdd_address, this->size, [func](int64_t i, A &e) {
            e = func((T &) e);
        });
        return this->rdd_address;
    }

    void free() {
        prev->free();
    }
};

//template<typename A>
//ParallelCollectionRDD<A> parallelize(vector<A> sequence) {
//return new ParallelCollectionRDD(sequence);
//}

template<typename A>
class ParallelCollectionRDD : public RDD<A> {
private:
    vector <A> sequence;
public:
    ParallelCollectionRDD(vector <A> sequence) : sequence(sequence) {
        this->size = sequence.size();
    }

    GlobalAddress <A> compute() {
        this->rdd_address = global_alloc<A>(this->size);
        auto size = this->size;
        auto rdd_address = this->rdd_address;
        auto sequence = this->sequence;
        finish([size, rdd_address, sequence]{
            for (int i = 0; i < size; i++) {
                delegate::write<async>(rdd_address + i, sequence[i]);
            }
        });
        return this->rdd_address;
    }

    void free() {
        global_free(this->rdd_address);
    }
};

template<typename A>
class RangedRDD : public RDD<A> {
    A start;
    A end;
public:
    RangedRDD(A start, A end) : start(start), end(end) {
        this->size = static_cast<int>(end - start);
    }

    GlobalAddress <A> compute() {
        this->rdd_address = global_alloc<A>(this->size);
        forall(this->rdd_address, this->size, [](int64_t i, A &e) {
            e = i;
        });

        return this->rdd_address;
    }

    void free() {
        global_free(this->rdd_address);
    }
};

template<typename A>
RangedRDD<A>* RDD<A>::range(A start, A end) {
    return new RangedRDD<A>(start, end);
}

template<typename A>
RangedRDD<A>* RDD<A>::range(A end) {
    return new RangedRDD<A>(0, end);
}

#endif //GRAPPARDD_RDD_H

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "core/sstring.hh"
#include <vector>
#include <sstream>
#include <unordered_set>
#include <set>
#include <experimental/optional>

#include "seastarx.hh"
#include "utils/chunked_vector.hh"

template<typename Iterator>
static inline
sstring join(sstring delimiter, Iterator begin, Iterator end) {
    std::ostringstream oss;
    while (begin != end) {
        oss << *begin;
        ++begin;
        if (begin != end) {
            oss << delimiter;
        }
    }
    return oss.str();
}

template<typename PrintableRange>
static inline
sstring join(sstring delimiter, const PrintableRange& items) {
    return join(delimiter, items.begin(), items.end());
}

namespace std {

template<typename Printable>
static inline
sstring
to_string(const std::vector<Printable>& items) {
    return "[" + join(", ", items) + "]";
}

template<typename Printable>
static inline
sstring
to_string(const std::set<Printable>& items) {
    return "{" + join(", ", items) + "}";
}

template<typename Printable>
static inline
sstring
to_string(const std::unordered_set<Printable>& items) {
    return "{" + join(", ", items) + "}";
}

template<typename Printable>
static inline
sstring
to_string(std::initializer_list<Printable> items) {
    return "[" + join(", ", std::begin(items), std::end(items)) + "]";
}

template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::pair<K, V>& p) {
    os << "{" << p.first << ", " << p.second << "}";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::unordered_set<T>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template<typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const std::array<T, N>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename K, typename V, typename... Args>
std::ostream& operator<<(std::ostream& os, const std::unordered_map<K, V, Args...>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename K, typename V, typename... Args>
std::ostream& operator<<(std::ostream& os, const std::map<K, V, Args...>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const utils::chunked_vector<T>& items) {
    os << "[" << join(", ", items) << "]";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::list<T>& items) {
    os << "[" << join(", ", items) << "]";
    return os;
}

namespace experimental {

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::experimental::optional<T>& opt) {
    if (opt) {
        os << "{" << *opt << "}";
    } else {
        os << "{}";
    }
    return os;
}

}

}
<commit_msg>to_string: Add operator<< overload for std::optional.<commit_after>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "core/sstring.hh"
#include <vector>
#include <sstream>
#include <unordered_set>
#include <set>
#include <experimental/optional>

#include "seastarx.hh"
#include "utils/chunked_vector.hh"

template<typename Iterator>
static inline
sstring join(sstring delimiter, Iterator begin, Iterator end) {
    std::ostringstream oss;
    while (begin != end) {
        oss << *begin;
        ++begin;
        if (begin != end) {
            oss << delimiter;
        }
    }
    return oss.str();
}

template<typename PrintableRange>
static inline
sstring join(sstring delimiter, const PrintableRange& items) {
    return join(delimiter, items.begin(), items.end());
}

namespace std {

template<typename Printable>
static inline
sstring
to_string(const std::vector<Printable>& items) {
    return "[" + join(", ", items) + "]";
}

template<typename Printable>
static inline
sstring
to_string(const std::set<Printable>& items) {
    return "{" + join(", ", items) + "}";
}

template<typename Printable>
static inline
sstring
to_string(const std::unordered_set<Printable>& items) {
    return "{" + join(", ", items) + "}";
}

template<typename Printable>
static inline
sstring
to_string(std::initializer_list<Printable> items) {
    return "[" + join(", ", std::begin(items), std::end(items)) + "]";
}

template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::pair<K, V>& p) {
    os << "{" << p.first << ", " << p.second << "}";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::unordered_set<T>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template<typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const std::array<T, N>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename K, typename V, typename... Args>
std::ostream& operator<<(std::ostream& os, const std::unordered_map<K, V, Args...>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename K, typename V, typename... Args>
std::ostream& operator<<(std::ostream& os, const std::map<K, V, Args...>& items) {
    os << "{" << join(", ", items) << "}";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const utils::chunked_vector<T>& items) {
    os << "[" << join(", ", items) << "]";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::list<T>& items) {
    os << "[" << join(", ", items) << "]";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::optional<T>& opt) {
    if (opt) {
        os << "{" << *opt << "}";
    } else {
        os << "{}";
    }
    return os;
}

namespace experimental {

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::experimental::optional<T>& opt) {
    if (opt) {
        os << "{" << *opt << "}";
    } else {
        os << "{}";
    }
    return os;
}

}

}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Cloudius Systems
 */

#pragma once

#include "core/sstring.hh"
#include <vector>
#include <sstream>

/**
 * Converts a vector of pointers to Printable elements.
 * Printable is an object which has to_string() method.
 */
template<typename PtrToPrintable>
static inline
sstring
to_string(std::vector<PtrToPrintable> items) {
    // TODO: optimize
    std::ostringstream oss;
    int left = items.size();
    oss << "[";
    for (auto&& item : items) {
        oss << item->to_string();
        if (left != 1) {
            oss << ", ";
        }
        --left;
    }
    oss << "]";
    return oss.str();
}
<commit_msg>to_string: Introduce join()<commit_after>/*
 * Copyright 2015 Cloudius Systems
 */

#pragma once

#include "core/sstring.hh"
#include <vector>
#include <sstream>

/**
 * Converts a vector of pointers to Printable elements.
 * Printable is an object which has to_string() method.
 */
template<typename PtrToPrintable>
static inline
sstring
to_string(std::vector<PtrToPrintable> items) {
    // TODO: optimize
    std::ostringstream oss;
    int left = items.size();
    oss << "[";
    for (auto&& item : items) {
        oss << item->to_string();
        if (left != 1) {
            oss << ", ";
        }
        --left;
    }
    oss << "]";
    return oss.str();
}

template<typename PtrToPrintable>
static inline
sstring join(sstring delimiter, std::vector<PtrToPrintable> items) {
    std::ostringstream oss;
    size_t left = items.size();
    for (auto&& item : items) {
        oss << item->to_string();
        if (left != 1) {
            oss << delimiter;
        }
        --left;
    }
    return oss.str();
}
<|endoftext|>


<commit_before>// Adobe Leaked Email Checker
// Date: December 2013
// Author: Jervis Muindi

// Standard Lib Header
#include <iostream>

#include "common/strings/strutil.h"
#include "common/log/log.h"

#include "third_party/leveldb/leveldb.h"

#include "alec.h"

using namespace std;

namespace alec {
  bool Credential::operator==(const Credential& other) const {
    return
      this->email == other.email &&
      this->hash == other.hash &&
      this->username == other.username &&
      this->rec_id == other.rec_id &&
      this->hint == other.hint;
  }

  string Credential::ToString() const {
    string result;
    result += "Email: '" + email + "'\n";
    result += "Username: '" + username + "'\n";
    result += "Record ID: " + rec_id + "\n";
    result += "Password Hint: '" + hint + "'\n";
    return result;
  }

  ostream& operator<<(ostream &out, const Credential& other) {
    string result = other.ToString();
    out << result;
    return out;
  }

  CredentialReader::CredentialReader(const string& filename) :
    filename_(filename),
    file_reader_(filename) {
    LOG(INFO) << "Cred reader initd";
  }
  bool CredentialReader::Done() {
    return file_reader_.Done();
  }
  bool CredentialReader::NextCredential(Credential *output) {
    if (output == NULL) {
      LOG(ERROR) << "Given a NULL output pointer";
      return false;
    }

    if (Done()) {
      return false;
    }

    Credential cred;
    // Find a non-empty credentials line
    bool line_empty;
    string line;
    do {
      line = file_reader_.line();
      line_empty = line.empty();
      if (line_empty) {
	file_reader_.Next();
      }
    } while (line_empty);

    if (!ParseLine(line, &cred)) {
      LOG(ERROR) << "Failed to Parse Line: '" << line << "'";
      return false;
    } else {
        *output = cred;
	file_reader_.Next();
	return true;
    }
  }

  // static class method
  bool CredentialReader::ParseLine(const string& line, Credential* result) {
    bool warnings_occurred = false;
    if (result == NULL) {
      LOG(ERROR) << "Given NULL result pointer";
      return false;
    }

    // line mostly looks like:
    // 000000010-|--|-person10@dls.net-|-IMj2ZmZchtNM=-|-internet|--
    // The format is :
    // <user_id> | <adobe_username> | <email address> | <password hash> | <password hint>
    // which was obtained from a SOPHOS analysis: http://goo.gl/xIEZSe

    vector<StringPiece> pieces = strings::Split(line, "|");
    int i = 0;
    for (auto& piece : pieces) {
      VLOG(2) << "piece " << i << ": " << piece;
      ++i;
    }

    // Check all the fields are present
    static const int kExpectedPieces = 6;
    if (pieces.size() != kExpectedPieces) {
      LOG(WARNING) << "Expected line to have " << kExpectedPieces
		 << " '|'-separates pieces but got " << pieces.size()
		 << "\nLine:" << line;
      warnings_occurred = true;
    }

    // Default expected indexes into the 'pieces' string vector
    int rec_id_idx = 0, username_idx = 1, email_idx = 2,
      hash_idx = 3, hint_idx = 4;

    // Sanity Check
    if ( pieces[5].as_string() != "--") {
      LOG(WARNING) << "Index 5 did not contain '--' as expected."
		   << "Credentials may be incorrectly parsed"
		   << "Line: " << line;
      warnings_occurred = true;
    }

    // There's a special case when 'line' is split into exactly
    // 7 pieces. In this scenario, the email is split into
    // separate username and domain parts. This looks like this:
    // 115985151-|--|-kadja_83|@yahoo.es-|-CWWWYFjjxa/ioxG6CatHBw==-|-dra|--
    bool email_special_case = pieces.size() == 7;
    if (email_special_case) {
      // The hash/hint fields are one away from their normal/expected location
      ++hash_idx;
      ++hint_idx;
    }

    string rec_id = pieces[rec_id_idx].as_string();
    // record id has form "<rec_id>-", so chop off the trailing '-' character
    rec_id = rec_id.substr(0, rec_id.size() - 1);

    // username has form "-<username>-", so chop off the leading/trailing '-' character.
    string username = pieces[username_idx].as_string();
    username = username.substr(1, username.size() - 2);

    string email = pieces[email_idx].as_string();
    // email has form "-<email>-", so chop of the leading and trailing '-' character.
    email = email.substr(1, email.size() - 2);
    if (email_special_case) {
      string domain = pieces[email_idx+1].as_string();
      // Domain looks like: '@yahoo.es-', so get rid of trailing '-'
      domain = domain.substr(0, domain.size() - 1);
      email += domain;
    }

    string hash = pieces[hash_idx].as_string();
    // hash has form "-<hash>-", so chop of the leading and trailing '-' character.
    hash = hash.substr(1, hash.size() - 2);

    string hint = pieces[hint_idx].as_string();
    // hint has form "-<hint>", so just chop of the leading '-' character
    hint = hint.substr(1);

    // Okay, save the parsed result
    result->email = email;
    result->username = username;
    result->rec_id = rec_id;
    result->hint = hint;
    result->hash = hash;

    // Print out the Parsed Credential object if warning occured
    if (warnings_occurred) {
      LOG(WARNING) << "Parsed Credential is\n" << *result << "\n---------";
    }
    return true;
  }

  CredentialReader::~CredentialReader() { ; }

  bool CredentialProcessor::GenerateDiskHashTable(StringPiece filename) {
    // Open a LevelDB Database
    leveldb::DB* db;
    leveldb::Options options;
    leveldb::Status status;
    options.create_if_missing = true;
    const string& filename_string = filename.ToString();
    status = leveldb::DB::Open(options, filename_string, &db);
    if (!status.ok()) {
      LOG(ERROR) << "Failed to Open LevelDB Database: " << filename_string ;
      return false;
    }

    // Read and save all credential records
    Credential cred;
    bool success_read;
    int count = 0, failed_reads = 0, failed_writes = 0;
    while (!cred_reader_->Done()) {
      LOG_EVERY_N(INFO, 100000) << "Processing Record #" << count << " ...";
      success_read = cred_reader_->NextCredential(&cred);
      if (!success_read) {
	++failed_reads;
	LOG(WARNING) << "Failed to obtain credential record # " << count
		     << ". Total Read Failures now at: " << failed_reads;
	++count;
	continue;
      }

      // Save the record to disk
      string key = strings::LowerString(cred.email);
      char *cred_data = reinterpret_cast<char*>(&cred);
      int cred_size = sizeof(cred);
      leveldb::Slice value(cred_data, cred_size);

      status = db->Put(leveldb::WriteOptions(), key, value);
      if (!status.ok()) {
	++failed_writes;
	LOG(WARNING) << "Failed to save credential record # " << count
		     << ". Total Write Failures now at: " << failed_writes;
      }
      ++count;
    }

    // Close the Database
    delete db;

    return true;
  }

} // alec namespace

<commit_msg>Resolve ArrayIndexOutofBound crash, when there are less fields than the expected amount<commit_after>// Adobe Leaked Email Checker
// Date: December 2013
// Author: Jervis Muindi

// Standard Lib Header
#include <iostream>

#include "common/strings/strutil.h"
#include "common/log/log.h"

#include "third_party/leveldb/leveldb.h"

#include "alec.h"

using namespace std;

namespace alec {
  bool Credential::operator==(const Credential& other) const {
    return
      this->email == other.email &&
      this->hash == other.hash &&
      this->username == other.username &&
      this->rec_id == other.rec_id &&
      this->hint == other.hint;
  }

  string Credential::ToString() const {
    string result;
    result += "Email: '" + email + "'\n";
    result += "Username: '" + username + "'\n";
    result += "Record ID: " + rec_id + "\n";
    result += "Password Hint: '" + hint + "'\n";
    return result;
  }

  ostream& operator<<(ostream &out, const Credential& other) {
    string result = other.ToString();
    out << result;
    return out;
  }

  CredentialReader::CredentialReader(const string& filename) :
    filename_(filename),
    file_reader_(filename) {
    LOG(INFO) << "Cred reader initd";
  }
  bool CredentialReader::Done() {
    return file_reader_.Done();
  }
  bool CredentialReader::NextCredential(Credential *output) {
    if (output == NULL) {
      LOG(ERROR) << "Given a NULL output pointer";
      return false;
    }

    if (Done()) {
      return false;
    }

    Credential cred;
    // Find a non-empty credentials line
    bool line_empty;
    string line;
    do {
      line = file_reader_.line();
      line_empty = line.empty();
      if (line_empty) {
	file_reader_.Next();
      }
    } while (line_empty);

    if (!ParseLine(line, &cred)) {
      LOG(ERROR) << "Failed to Parse Line: '" << line << "'";
      return false;
    } else {
        *output = cred;
	file_reader_.Next();
	return true;
    }
  }

  // static class method
  bool CredentialReader::ParseLine(const string& line, Credential* result) {
    bool warnings_occurred = false;
    if (result == NULL) {
      LOG(ERROR) << "Given NULL result pointer";
      return false;
    }

    // line mostly looks like:
    // 000000010-|--|-person10@dls.net-|-IMj2ZmZchtNM=-|-internet|--
    // The format is :
    // <user_id> | <adobe_username> | <email address> | <password hash> | <password hint>
    // which was obtained from a SOPHOS analysis: http://goo.gl/xIEZSe

    vector<StringPiece> pieces = strings::Split(line, "|");
    int i = 0;
    for (auto& piece : pieces) {
      VLOG(2) << "piece " << i << ": " << piece;
      ++i;
    }

    // Sanity check if expected fields are present
    static const int kExpectedPieces = 6;
    if (pieces.size() != kExpectedPieces) {
      LOG(WARNING) << "Expected line to have " << kExpectedPieces
		   << " '|'-separates pieces but got " << pieces.size()
		   << ". Credentials may be incorrectly parsed.\n"
		   << "\nLine:" << line;
      warnings_occurred = true;
    }

    // Default expected indexes into the 'pieces' string vector
    int rec_id_idx = 0, username_idx = 1, email_idx = 2,
      hash_idx = 3, hint_idx = 4;

    // Find the max valid index value
    const int kMaxIdx = pieces.size() - 1;

    // There's a special case when 'line' is split into exactly
    // 7 pieces. In this scenario, the email is split into
    // separate username and domain parts. This looks like this:
    // 115985151-|--|-kadja_83|@yahoo.es-|-CWWWYFjjxa/ioxG6CatHBw==-|-dra|--
    bool email_special_case = pieces.size() == 7;
    if (email_special_case) {
      // The hash/hint fields are one away from their normal/expected location
      ++hash_idx;
      ++hint_idx;
    }

    string rec_id = rec_id_idx <= kMaxIdx ? pieces[rec_id_idx].as_string() : "NA";
    // record id has form "<rec_id>-", so chop off the trailing '-' character
    rec_id = rec_id.substr(0, rec_id.size() - 1);

    // username has form "-<username>-", so chop off the leading/trailing '-' character.
    string username = username_idx <= kMaxIdx ?
      pieces[username_idx].as_string() : "NA";
    username = username.substr(1, username.size() - 2);

    string email = email_idx <= kMaxIdx ? pieces[email_idx].as_string() : "NA";
    // email has form "-<email>-", so chop of the leading and trailing '-' character.
    email = email.substr(1, email.size() - 2);
    if (email_special_case) {
      string domain = pieces[email_idx+1].as_string();
      // Domain looks like: '@yahoo.es-', so get rid of trailing '-'
      domain = domain.substr(0, domain.size() - 1);
      email += domain;
    }

    string hash = hash_idx <= kMaxIdx ? pieces[hash_idx].as_string() : "NA";
    // hash has form "-<hash>-", so chop of the leading and trailing '-' character.
    hash = hash.substr(1, hash.size() - 2);

    string hint = hint_idx <= kMaxIdx ? pieces[hint_idx].as_string() : "NA";
    // hint has form "-<hint>", so just chop of the leading '-' character
    hint = hint.substr(1);

    // Okay, save the parsed result
    result->email = email;
    result->username = username;
    result->rec_id = rec_id;
    result->hint = hint;
    result->hash = hash;

    // Print out the Parsed Credential object if warning occured
    if (warnings_occurred) {
      LOG(WARNING) << "Parsed Credential is\n" << *result << "\n---------";
    }
    return true;
  }

  CredentialReader::~CredentialReader() { ; }

  bool CredentialProcessor::GenerateDiskHashTable(StringPiece filename) {
    // Open a LevelDB Database
    leveldb::DB* db;
    leveldb::Options options;
    leveldb::Status status;
    options.create_if_missing = true;
    const string& filename_string = filename.ToString();
    status = leveldb::DB::Open(options, filename_string, &db);
    if (!status.ok()) {
      LOG(ERROR) << "Failed to Open LevelDB Database: " << filename_string ;
      return false;
    }

    // Read and save all credential records
    Credential cred;
    bool success_read;
    int count = 0, failed_reads = 0, failed_writes = 0;
    while (!cred_reader_->Done()) {
      LOG_EVERY_N(INFO, 100000) << "Processing Record #" << count << " ...";
      success_read = cred_reader_->NextCredential(&cred);
      if (!success_read) {
	++failed_reads;
	LOG(WARNING) << "Failed to obtain credential record # " << count
		     << ". Total Read Failures now at: " << failed_reads;
	++count;
	continue;
      }

      // Save the record to disk
      string key = strings::LowerString(cred.email);
      char *cred_data = reinterpret_cast<char*>(&cred);
      int cred_size = sizeof(cred);
      leveldb::Slice value(cred_data, cred_size);

      status = db->Put(leveldb::WriteOptions(), key, value);
      if (!status.ok()) {
	++failed_writes;
	LOG(WARNING) << "Failed to save credential record # " << count
		     << ". Total Write Failures now at: " << failed_writes;
      }
      ++count;
    }

    // Close the Database
    delete db;

    return true;
  }

} // alec namespace

<|endoftext|>


<commit_before>#pragma once

#include <array>
#include <memory>
#include <cstring>
#include <type_traits>

namespace detail
{

template <typename _DeleterT,
          typename _AnyT>
struct deleter
{
    ~deleter() { _DeleterT()(reinterpret_cast<_AnyT&>(*this)); }
};

template <typename _AnyT>
struct deleter<void, _AnyT> {};

}

template <std::size_t _N, typename _DeleterT = void>
struct any : public detail::deleter<_DeleterT, any<_N>>
{
    typedef std::size_t size_type;

    template <typename _T,
              typename _D = _DeleterT>
    typename std::enable_if<std::is_same<_D, void>::value, any&>::type
    operator=(_T&& t)
    {
        static_assert(std::is_trivially_destructible<_T>::value, "_T is not trivially destructible and does not use any deleter");
        copy_object(std::move(t));
        return *this;
    }

    template <typename _T,
              typename _D = _DeleterT>
    typename std::enable_if<!std::is_same<_D, void>::value, any&>::type
    operator=(_T&& t)
    {
        copy_object(std::move(t));
        return *this;
    }

    template <typename _T>
    void copy_object(_T&& t)
    {
        static_assert(std::is_trivially_copyable<_T>::value, "_T is not trivially copyable");
        static_assert(size() >= sizeof(_T), "_T is too big to be copied to any");

        std::memcpy(buff_.data(), (char*)&t, sizeof(_T));
    }

    template <typename _T>
    typename std::enable_if<!std::is_pointer<_T>::value, _T&>::type
    get() { return reinterpret_cast<_T&>(*buff_.data()); }

    template <typename _T>
    typename std::enable_if<!std::is_pointer<_T>::value, const _T&>::type
    get() const { return reinterpret_cast<const _T>(*buff_.data()); }

    template <typename _T>
    typename std::enable_if<std::is_pointer<_T>::value, _T>::type
    get() { return reinterpret_cast<_T>(buff_.data()); }

    template <typename _T>
    typename std::enable_if<std::is_pointer<_T>::value, const _T>::type
    get() const { return reinterpret_cast<const _T>(buff_.data()); }

    static constexpr size_type size() { return _N; }

private:
    std::array<char, _N> buff_;
};
<commit_msg>Adding any_p with type check<commit_after>#pragma once

#include <array>
#include <memory>
#include <cstring>
#include <type_traits>
#include <typeinfo>

namespace detail
{

template <typename _DeleterT,
          typename _AnyT>
struct deleter
{
    ~deleter() { _DeleterT()(reinterpret_cast<_AnyT&>(*this)); }
};

template <typename _AnyT>
struct deleter<void, _AnyT> {};

}

template <std::size_t _N, typename _DeleterT = void>
struct any : public detail::deleter<_DeleterT, any<_N>>
{
    typedef std::size_t size_type;

    template <typename _T,
              typename _D = _DeleterT>
    typename std::enable_if<std::is_same<_D, void>::value, any&>::type
    operator=(_T&& t)
    {
        static_assert(std::is_trivially_destructible<_T>::value, "_T is not trivially destructible and does not use any deleter");
        copy_object(std::move(t));
        return *this;
    }

    template <typename _T,
              typename _D = _DeleterT>
    typename std::enable_if<!std::is_same<_D, void>::value, any&>::type
    operator=(_T&& t)
    {
        copy_object(std::move(t));
        return *this;
    }

    template <typename _T>
    void copy_object(_T&& t)
    {
        static_assert(std::is_trivially_copyable<_T>::value, "_T is not trivially copyable");
        static_assert(size() >= sizeof(_T), "_T is too big to be copied to any");

        std::memcpy(buff_.data(), (char*)&t, sizeof(_T));
    }

    template <typename _T>
    typename std::enable_if<!std::is_pointer<_T>::value, _T&>::type
    get() { return reinterpret_cast<_T&>(*buff_.data()); }

    template <typename _T>
    typename std::enable_if<!std::is_pointer<_T>::value, const _T&>::type
    get() const { return reinterpret_cast<const _T>(*buff_.data()); }

    template <typename _T>
    typename std::enable_if<std::is_pointer<_T>::value, _T>::type
    get() { return reinterpret_cast<_T>(buff_.data()); }

    template <typename _T>
    typename std::enable_if<std::is_pointer<_T>::value, const _T>::type
    get() const { return reinterpret_cast<const _T>(buff_.data()); }

    static constexpr size_type size() { return _N; }

private:
    std::array<char, _N> buff_;
};

template <std::size_t _N, typename _DeleterT = void>
struct any_p : public detail::deleter<_DeleterT, any_p<_N>>
{
    typedef std::size_t size_type;

    template <typename _T,
              typename _D = _DeleterT>
    typename std::enable_if<std::is_same<_D, void>::value, any_p&>::type
    operator=(_T&& t)
    {
        static_assert(std::is_trivially_destructible<_T>::value, "_T is not trivially destructible and does not use any_p deleter");
        copy_object(std::move(t));
        return *this;
    }

    template <typename _T,
              typename _D = _DeleterT>
    typename std::enable_if<!std::is_same<_D, void>::value, any_p&>::type
    operator=(_T&& t)
    {
        copy_object(std::move(t));
        return *this;
    }

    template <typename _T>
    void copy_object(_T&& t)
    {
        static_assert(std::is_trivially_copyable<_T>::value, "_T is not trivially copyable");
        static_assert(size() >= sizeof(_T), "_T is too big to be copied to any_p");

        std::memcpy(buff_.data(), (char*)&t, sizeof(_T));
        type_ = typeid(_T).hash_code();
    }

    template <typename _T>
    typename std::enable_if<!std::is_pointer<_T>::value, _T&>::type
    get()
    {
        is_stored_type<_T>();
        return reinterpret_cast<_T&>(*buff_.data());
    }

    template <typename _T>
    typename std::enable_if<!std::is_pointer<_T>::value, const _T&>::type
    get() const
    {
        is_stored_type<_T>();
        return reinterpret_cast<const _T&>(*buff_.data());
    }

    template <typename _T>
    typename std::enable_if<std::is_pointer<_T>::value, _T>::type
    get()
    {
        is_stored_type<_T>();
        return reinterpret_cast<_T>(buff_.data());
    }

    template <typename _T>
    typename std::enable_if<std::is_pointer<_T>::value, const _T>::type
    get() const
    {
        is_stored_type<_T>();
        return reinterpret_cast<const _T>(buff_.data());
    }

    static constexpr size_type size() { return _N; }

private:
    template <typename _T>
    void is_stored_type()
    {
        if (type_ != typeid(_T).hash_code())
            throw std::bad_cast();
    }

    std::array<char, _N> buff_;
    std::size_t          type_;
};
<|endoftext|>


<commit_before>/*=========================================================================

Program:   BlueBerry Platform
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "berryWorkbenchWindowAdvisor.h"

#include <Poco/Bugcheck.h>

#include <berryWorkbenchPreferenceConstants.h>
#include <berryObjects.h>
#include <berryIPreferences.h>

#include "../internal/berryWorkbenchWindowConfigurer.h"
#include "../internal/berryWorkbenchPlugin.h"

namespace berry
{

IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer()
{
  return windowConfigurer;
}

WorkbenchWindowAdvisor::WorkbenchWindowAdvisor(
    IWorkbenchWindowConfigurer::Pointer configurer)
{
  poco_assert(configurer.IsNotNull());
  this->windowConfigurer = configurer;
}

WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor()
{
}

void WorkbenchWindowAdvisor::PreWindowOpen()
{
  // do nothing
}

ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor(
    IActionBarConfigurer::Pointer configurer)
{
  ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer));
  return actionBarAdvisor;
}

void WorkbenchWindowAdvisor::PostWindowRestore()
{
  // do nothing
}

void WorkbenchWindowAdvisor::OpenIntro()
{
  // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call

  // introOpened flag needs to be global
  IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer();
  std::string key = "introOpened"; //$NON-NLS-1$
  ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast<ObjectBool>();
  if (introOpened && introOpened->GetValue())
  {
    return;
  }

  wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true)));

  IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences();

  bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true);

  IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager();

  bool hasIntro = introManager->HasIntro();
  bool isNewIntroContentAvailable = introManager->IsNewContentAvailable();

  if (hasIntro && (showIntro || isNewIntroContentAvailable))
  {
    introManager
    ->ShowIntro(GetWindowConfigurer()->GetWindow(), false);

   /* workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false);
    workbenchPrefs->Flush();*/
  }
}

void WorkbenchWindowAdvisor::PostWindowCreate()
{
  // do nothing
}

void WorkbenchWindowAdvisor::PostWindowOpen()
{
  // do nothing
}

bool WorkbenchWindowAdvisor::PreWindowShellClose()
{
  // do nothing, but allow the close() to proceed
  return true;
}

void WorkbenchWindowAdvisor::PostWindowClose()
{
  // do nothing
}

void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell)
{
  this->GetWindowConfigurer().Cast<WorkbenchWindowConfigurer>()->CreateDefaultContents(shell);
}

void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void*  /*parent*/)
{
  return 0;
}

bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

}
<commit_msg>FIX (#5732): Reverted changes to blueberry framework.<commit_after>/*=========================================================================

Program:   BlueBerry Platform
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "berryWorkbenchWindowAdvisor.h"

#include <Poco/Bugcheck.h>

#include <berryWorkbenchPreferenceConstants.h>
#include <berryObjects.h>
#include <berryIPreferences.h>

#include "../internal/berryWorkbenchWindowConfigurer.h"
#include "../internal/berryWorkbenchPlugin.h"

namespace berry
{

IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer()
{
  return windowConfigurer;
}

WorkbenchWindowAdvisor::WorkbenchWindowAdvisor(
    IWorkbenchWindowConfigurer::Pointer configurer)
{
  poco_assert(configurer.IsNotNull());
  this->windowConfigurer = configurer;
}

WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor()
{
}

void WorkbenchWindowAdvisor::PreWindowOpen()
{
  // do nothing
}

ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor(
    IActionBarConfigurer::Pointer configurer)
{
  ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer));
  return actionBarAdvisor;
}

void WorkbenchWindowAdvisor::PostWindowRestore()
{
  // do nothing
}

void WorkbenchWindowAdvisor::OpenIntro()
{
  // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call

  // introOpened flag needs to be global
  IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer();
  std::string key = "introOpened"; //$NON-NLS-1$
  ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast<ObjectBool>();
  if (introOpened && introOpened->GetValue())
  {
    return;
  }

  wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true)));

  IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences();

  bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true);

  IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager();

  bool hasIntro = introManager->HasIntro();
  bool isNewIntroContentAvailable = introManager->IsNewContentAvailable();

  if (hasIntro && (showIntro || isNewIntroContentAvailable))
  {
    introManager
    ->ShowIntro(GetWindowConfigurer()->GetWindow(), false);

    workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false);
    workbenchPrefs->Flush();
  }
}

void WorkbenchWindowAdvisor::PostWindowCreate()
{
  // do nothing
}

void WorkbenchWindowAdvisor::PostWindowOpen()
{
  // do nothing
}

bool WorkbenchWindowAdvisor::PreWindowShellClose()
{
  // do nothing, but allow the close() to proceed
  return true;
}

void WorkbenchWindowAdvisor::PostWindowClose()
{
  // do nothing
}

void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell)
{
  this->GetWindowConfigurer().Cast<WorkbenchWindowConfigurer>()->CreateDefaultContents(shell);
}

void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void*  /*parent*/)
{
  return 0;
}

bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

}
<|endoftext|>


<commit_before>/***************************************************************************
             filter_lnotes.cxx  -  Lotus Notes Structured Text mail import
                             -------------------
    begin                : Wed Feb 16, 2005
    copyright            : (C) 2005 by Robert Rockers
    email                : kconfigure@rockerssoft.com
 ***************************************************************************/

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

#include <config.h>

#include <klocale.h>
#include <kfiledialog.h>
#include <ktempfile.h>
#include <kdebug.h>
#include <qfileinfo.h>

#include "filter_lnotes.hxx"

/** Default constructor. */
FilterLNotes::FilterLNotes() :
        Filter( i18n("Import Lotus Notes Emails"),
                "Robert Rockers",
                i18n("
Lotus Notes Structured Text mail import filter
"
                     "
This filter will import Structure Text files from an exported Lotus Notes email "
                     "client into KMail. Use this filter if you want to import mails from Lotus or other "
                     "mailers that use Lotus Notes' Structured Text format.
"
                     "
Note: Since it is possible to recreate the folder structure, the imported "
                     "messages will be stored in subfolders named by the files they ame from under: "
                     "\"Sylpheed-Import\" in your local folder.
"))
{}

/** Destructor. */
FilterLNotes::~FilterLNotes() {
    endImport();
}

/**
 * Recursive import of The Bat! maildir.
 * @param info Information storage for the operation.
 */
void FilterLNotes::import(FilterInfo *info) {

    inf = info;
    currentFile = 1;
    totalFiles = 0;

    QStringList filenames = KFileDialog::getOpenFileNames( QDir::homeDirPath(), "*|" + i18n("All Files (*)"),
                                                           inf->parent() );
    totalFiles = filenames.count();
    inf->setOverall(0);

    // See filter_mbox.cxx for better reference.
    for ( QStringList::Iterator filename = filenames.begin(); filename != filenames.end(); ++filename ) {

        ++currentFile;
        info->addLog( i18n("Importing emails from %1").arg(*filename) );
        ImportLNotes( *filename );
        inf->setOverall( 100 * currentFile / totalFiles );
        if ( info->shouldTerminate() )
            break;
    }
}

/**
 * Import the files within a Folder.
 * @param file The name of the file to import.
 */
void FilterLNotes::ImportLNotes(const QString& file) {

    // See Filter_pmail.cxx for better reference

    // Format of a Lotus Notes 5 Structured Text Document w form feed
    // Each email begins with a custom Header Principal:
    // The Message ends with a 0c character

    // open the message
    QFile f(file);

    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( file ) );
    } else {

        int ch = 0;
        int state = 0;
        int n = 0;
        KTempFile *tempfile = 0;

        // Get folder name
        QFileInfo filenameInfo( file );
        QString folder("LNotes-Import/" + filenameInfo.baseName(TRUE));
        inf->setTo(folder);

        // State machine to read the data in. The fgetc usage is probably terribly slow ...
        while ((ch = f.getch()) >= 0) {
            switch (state) {
                    // new message state
                case 0:
                    // open temp output file
                    tempfile = new KTempFile;
                    state = 1;
                    inf->setCurrent(i18n("Message %1").arg(n++));
                    if ( inf->shouldTerminate() )
                        return;
                    // fall through

                    // inside a message state
                case 1:
                    if (ch == 0x0c) {
                        // close file, send it
                        tempfile->close();

                        if(inf->removeDupMsg)
                            addMessage( inf, folder, tempfile->name() );
                        else
                            addMessage_fastImport( inf, folder, tempfile->name() );

                        tempfile->unlink();
                        delete tempfile;
                        state = 0;

                        int currentPercentage = (int) ( ( (float) f.at() / filenameInfo.size() ) * 100 );
                        inf->setCurrent( currentPercentage );
                        if ( inf->shouldTerminate() )
                            return;

                        break;
                    }
                    if (ch == 0x0d) {
                        break;
                    }
                    tempfile->file()->putch(ch);
                    break;
            }
        }

        // did Folder end without 0x1a at the end?
        if (state != 0) {
            tempfile->close();

            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile->name() );
            else
                addMessage_fastImport( inf, folder, tempfile->name() );

            tempfile->unlink();
            delete tempfile;
        }
        f.close();
    }
}
<commit_msg>Copy paste error in i18n.<commit_after>/***************************************************************************
             filter_lnotes.cxx  -  Lotus Notes Structured Text mail import
                             -------------------
    begin                : Wed Feb 16, 2005
    copyright            : (C) 2005 by Robert Rockers
    email                : kconfigure@rockerssoft.com
 ***************************************************************************/

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

#include <config.h>

#include <klocale.h>
#include <kfiledialog.h>
#include <ktempfile.h>
#include <kdebug.h>
#include <qfileinfo.h>

#include "filter_lnotes.hxx"

/** Default constructor. */
FilterLNotes::FilterLNotes() :
        Filter( i18n("Import Lotus Notes Emails"),
                "Robert Rockers",
                i18n("
Lotus Notes Structured Text mail import filter
"
                     "
This filter will import Structure Text files from an exported Lotus Notes email "
                     "client into KMail. Use this filter if you want to import mails from Lotus or other "
                     "mailers that use Lotus Notes' Structured Text format.
"
                     "
Note: Since it is possible to recreate the folder structure, the imported "
                     "messages will be stored in subfolders named by the files they ame from under: "
                     "\"LNotes-Import\" in your local folder.
"))
{}

/** Destructor. */
FilterLNotes::~FilterLNotes() {
    endImport();
}

/**
 * Recursive import of The Bat! maildir.
 * @param info Information storage for the operation.
 */
void FilterLNotes::import(FilterInfo *info) {

    inf = info;
    currentFile = 1;
    totalFiles = 0;

    QStringList filenames = KFileDialog::getOpenFileNames( QDir::homeDirPath(), "*|" + i18n("All Files (*)"),
                                                           inf->parent() );
    totalFiles = filenames.count();
    inf->setOverall(0);

    // See filter_mbox.cxx for better reference.
    for ( QStringList::Iterator filename = filenames.begin(); filename != filenames.end(); ++filename ) {

        ++currentFile;
        info->addLog( i18n("Importing emails from %1").arg(*filename) );
        ImportLNotes( *filename );
        inf->setOverall( 100 * currentFile / totalFiles );
        if ( info->shouldTerminate() )
            break;
    }
}

/**
 * Import the files within a Folder.
 * @param file The name of the file to import.
 */
void FilterLNotes::ImportLNotes(const QString& file) {

    // See Filter_pmail.cxx for better reference

    // Format of a Lotus Notes 5 Structured Text Document w form feed
    // Each email begins with a custom Header Principal:
    // The Message ends with a 0c character

    // open the message
    QFile f(file);

    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( file ) );
    } else {

        int ch = 0;
        int state = 0;
        int n = 0;
        KTempFile *tempfile = 0;

        // Get folder name
        QFileInfo filenameInfo( file );
        QString folder("LNotes-Import/" + filenameInfo.baseName(TRUE));
        inf->setTo(folder);

        // State machine to read the data in. The fgetc usage is probably terribly slow ...
        while ((ch = f.getch()) >= 0) {
            switch (state) {
                    // new message state
                case 0:
                    // open temp output file
                    tempfile = new KTempFile;
                    state = 1;
                    inf->setCurrent(i18n("Message %1").arg(n++));
                    if ( inf->shouldTerminate() )
                        return;
                    // fall through

                    // inside a message state
                case 1:
                    if (ch == 0x0c) {
                        // close file, send it
                        tempfile->close();

                        if(inf->removeDupMsg)
                            addMessage( inf, folder, tempfile->name() );
                        else
                            addMessage_fastImport( inf, folder, tempfile->name() );

                        tempfile->unlink();
                        delete tempfile;
                        state = 0;

                        int currentPercentage = (int) ( ( (float) f.at() / filenameInfo.size() ) * 100 );
                        inf->setCurrent( currentPercentage );
                        if ( inf->shouldTerminate() )
                            return;

                        break;
                    }
                    if (ch == 0x0d) {
                        break;
                    }
                    tempfile->file()->putch(ch);
                    break;
            }
        }

        // did Folder end without 0x1a at the end?
        if (state != 0) {
            tempfile->close();

            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile->name() );
            else
                addMessage_fastImport( inf, folder, tempfile->name() );

            tempfile->unlink();
            delete tempfile;
        }
        f.close();
    }
}
<|endoftext|>


<commit_before>
#pragma once

#include "ksp_plugin/vessel.hpp"

#include <algorithm>
#include <limits>
#include <vector>

#include "integrators/embedded_explicit_runge_kutta_nyström_integrator.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/make_not_null.hpp"

namespace principia {

using integrators::DormandElMikkawyPrince1986RKN434FM;
using integrators::McLachlanAtela1992Order5Optimal;
using quantites::IsFinite;
using quantities::si::Kilogram;
using quantities::si::Milli;

namespace ksp_plugin {

inline Vessel::Vessel(not_null<Celestial const*> const parent,
                      not_null<Ephemeris<Barycentric>*> const ephemeris,
                      Ephemeris<Barycentric>::FixedStepParameters const&
                          history_fixed_step_parameters,
                      Ephemeris<Barycentric>::AdaptiveStepParameters const&
                          prolongation_adaptive_step_parameters,
                      Ephemeris<Barycentric>::AdaptiveStepParameters const&
                          prediction_adaptive_step_parameters)
    : body_(),
      history_fixed_step_parameters_(history_fixed_step_parameters),
      prolongation_adaptive_step_parameters_(
          prolongation_adaptive_step_parameters),
      prediction_adaptive_step_parameters_(
          prediction_adaptive_step_parameters),
      parent_(parent),
      ephemeris_(ephemeris) {}

inline not_null<MasslessBody const*> Vessel::body() const {
  return &body_;
}

inline bool Vessel::is_initialized() const {
  CHECK_EQ(history_ == nullptr, prolongation_ == nullptr);
  CHECK_EQ(history_ == nullptr, prediction_ == nullptr);
  return history_ != nullptr;
}

inline not_null<Celestial const*> Vessel::parent() const {
  return parent_;
}

inline void Vessel::set_parent(not_null<Celestial const*> const parent) {
  parent_ = parent;
}

inline DiscreteTrajectory<Barycentric> const& Vessel::history() const {
  CHECK(is_initialized());
  return *history_;
}

inline DiscreteTrajectory<Barycentric> const& Vessel::prolongation() const {
  CHECK(is_initialized());
  return *prolongation_;
}

inline DiscreteTrajectory<Barycentric> const& Vessel::prediction() const {
  CHECK(is_initialized());
  return *prediction_;
}

inline FlightPlan& Vessel::flight_plan() const {
  CHECK(has_flight_plan());
  return *flight_plan_;
}

inline bool Vessel::has_flight_plan() const {
  return flight_plan_ != nullptr;
}

inline void Vessel::set_dirty() {
  is_dirty_ = true;
}

inline bool Vessel::is_dirty() const {
  return is_dirty_;
}

inline void Vessel::set_prediction_adaptive_step_parameters(
    Ephemeris<Barycentric>::AdaptiveStepParameters const&
        prediction_adaptive_step_parameters) {
  prediction_adaptive_step_parameters_ = prediction_adaptive_step_parameters;
}

inline Ephemeris<Barycentric>::AdaptiveStepParameters const&
Vessel::prediction_adaptive_step_parameters() const {
  return prediction_adaptive_step_parameters_;
}

inline void Vessel::CreateHistoryAndForkProlongation(
    Instant const& time,
    DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {
  CHECK(!is_initialized());
  history_ = std::make_unique<DiscreteTrajectory<Barycentric>>();
  history_->Append(time, degrees_of_freedom);
  prolongation_ = history_->NewForkAtLast();
  prediction_ = history_->NewForkAtLast();
}

inline void Vessel::AdvanceTimeNotInBubble(Instant const& time) {
  CHECK(is_initialized());
  AdvanceHistoryIfNeeded(time);
  FlowProlongation(time);
}

inline void Vessel::AdvanceTimeInBubble(
    Instant const& time,
    DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {
  CHECK(is_initialized());
  AdvanceHistoryIfNeeded(time);
  prolongation_->Append(time, degrees_of_freedom);
  is_dirty_ = true;
}

inline void Vessel::ForgetBefore(Instant const& time) {
  CHECK(is_initialized());
  if (prediction_->Fork().time() < time) {
    history_->DeleteFork(&prediction_);
    prediction_ = history_->NewForkAtLast();
  }
  if (flight_plan_ != nullptr) {
    flight_plan_->ForgetBefore(time, [this]() { flight_plan_.reset(); });
  }
  history_->ForgetBefore(time);
}

inline void Vessel::CreateFlightPlan(
    Instant const& final_time,
    Mass const& initial_mass,
    Ephemeris<Barycentric>::AdaptiveStepParameters const&
        flight_plan_adaptive_step_parameters) {
  auto const history_last = history().last();
  flight_plan_ = std::make_unique<FlightPlan>(
      initial_mass,
      /*initial_time=*/history_last.time(),
      /*initial_degrees_of_freedom=*/history_last.degrees_of_freedom(),
      final_time,
      ephemeris_,
      flight_plan_adaptive_step_parameters);
}

inline void Vessel::DeleteFlightPlan() {
  flight_plan_.reset();
}

inline void Vessel::UpdatePrediction(Instant const& last_time) {
  CHECK(is_initialized());
  history_->DeleteFork(&prediction_);
  prediction_ = history_->NewForkAtLast();
  auto const prolongation_last = prolongation_->last();
  if (history_->last().time() != prolongation_last.time()) {
    prediction_->Append(prolongation_last.time(),
                        prolongation_last.degrees_of_freedom());
  }
  FlowPrediction(last_time);
}

inline void Vessel::WriteToMessage(
    not_null<serialization::Vessel*> const message) const {
  CHECK(is_initialized());
  body_.WriteToMessage(message->mutable_body());
  prolongation_adaptive_step_parameters_.WriteToMessage(
      message->mutable_prolongation_adaptive_step_parameters());
  history_fixed_step_parameters_.WriteToMessage(
      message->mutable_history_fixed_step_parameters());
  history_->WriteToMessage(message->mutable_history(), {prolongation_});
  prediction_->Fork().time().WriteToMessage(
      message->mutable_prediction_fork_time());
  prediction_->last().time().WriteToMessage(
      message->mutable_prediction_last_time());
  prediction_adaptive_step_parameters_.WriteToMessage(
      message->mutable_prediction_adaptive_step_parameters());
  if (flight_plan_ != nullptr) {
    flight_plan_->WriteToMessage(message->mutable_flight_plan());
  }
  message->set_is_dirty(is_dirty_);
}

inline not_null<std::unique_ptr<Vessel>> Vessel::ReadFromMessage(
    serialization::Vessel const& message,
    not_null<Ephemeris<Barycentric>*> const ephemeris,
    not_null<Celestial const*> const parent) {
  // NOTE(egg): for now we do not read the |MasslessBody| as it can contain no
  // information.
  std::unique_ptr<Vessel> vessel;
  bool const is_pre_буняковский = message.has_history_and_prolongation() ||
                                  message.has_owned_prolongation();

  if (is_pre_буняковский) {
    vessel = make_not_null_unique<Vessel>(parent,
                                          ephemeris,
                                          DefaultHistoryParameters(),
                                          DefaultProlongationParameters(),
                                          DefaultPredictionParameters());

    if (message.has_history_and_prolongation()) {
      vessel->history_ =
          DiscreteTrajectory<Barycentric>::ReadFromMessage(
              message.history_and_prolongation().history(), /*forks=*/{});
      vessel->prolongation_ =
          DiscreteTrajectory<Barycentric>::ReadPointerFromMessage(
              message.history_and_prolongation().prolongation(),
              vessel->history_.get());
      if (message.has_prediction()) {
        vessel->prediction_ =
            DiscreteTrajectory<Barycentric>::ReadPointerFromMessage(
                message.prediction(),
                vessel->history_.get());
      }
      if (message.has_flight_plan()) {
        vessel->flight_plan_ = FlightPlan::ReadFromMessage(
            message.flight_plan(), vessel->history_.get(), ephemeris);
      }
    } else {
      vessel->history_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(
                             message.owned_prolongation(), /*forks=*/{});
      vessel->prolongation_ = vessel->history_->NewForkAtLast();
      CHECK(!message.has_prediction());
      CHECK(!message.has_flight_plan());
    }
    if (vessel->prediction_ == nullptr) {
      vessel->prediction_ = vessel->history_->NewForkAtLast();
    }
  } else {
    CHECK(message.has_history() &&
          message.has_history_fixed_step_parameters() &&
          message.has_prolongation_adaptive_step_parameters() &&
          message.has_prediction_fork_time() &&
          message.has_prediction_last_time() &&
          message.has_prediction_adaptive_step_parameters())
        << message.DebugString();
    vessel = make_not_null_unique<Vessel>(
        parent,
        ephemeris,
        Ephemeris<Barycentric>::FixedStepParameters::ReadFromMessage(
            message.history_fixed_step_parameters()),
        Ephemeris<Barycentric>::AdaptiveStepParameters::ReadFromMessage(
            message.prolongation_adaptive_step_parameters()),
        Ephemeris<Barycentric>::AdaptiveStepParameters::ReadFromMessage(
            message.prediction_adaptive_step_parameters()));
    vessel->history_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(
        message.history(), {&vessel->prolongation_});
    vessel->prediction_ = vessel->history_->NewForkWithoutCopy(
        Instant::ReadFromMessage(message.prediction_fork_time()));
    vessel->FlowPrediction(
        Instant::ReadFromMessage(message.prediction_last_time()));
    if (message.has_flight_plan()) {
      vessel->flight_plan_ = FlightPlan::ReadFromMessage(
          message.flight_plan(), vessel->history_.get(), ephemeris);
    }
    vessel->is_dirty_ = message.is_dirty();
  }
  return std::move(vessel);
}

inline Vessel::Vessel()
    : body_(),
      history_fixed_step_parameters_(DefaultHistoryParameters()),
      prolongation_adaptive_step_parameters_(DefaultProlongationParameters()),
      prediction_adaptive_step_parameters_(DefaultPredictionParameters()),
      parent_(testing_utilities::make_not_null<Celestial const*>()),
      ephemeris_(testing_utilities::make_not_null<Ephemeris<Barycentric>*>()) {}

inline void Vessel::AdvanceHistoryIfNeeded(Instant const& time) {
  Instant const& history_last_time = history_->last().time();
  Time const& Δt = history_fixed_step_parameters_.step();

  if (history_last_time + Δt < time) {
    if (is_dirty_) {
      FlowProlongation(history_last_time + Δt);
      history_->Append(history_last_time + Δt,
                       prolongation_->last().degrees_of_freedom());
      is_dirty_ = false;
    }
    FlowHistory(time);
    history_->DeleteFork(&prolongation_);
    prolongation_ = history_->NewForkAtLast();
  }
}

inline void Vessel::FlowHistory(Instant const& time) {
  ephemeris_->FlowWithFixedStep(
      {history_.get()},
      Ephemeris<Barycentric>::kNoIntrinsicAccelerations,
      time,
      history_fixed_step_parameters_);
}

inline void Vessel::FlowProlongation(Instant const& time) {
  Instant const& prolongation_last_time = prolongation_->last().time();
  CHECK_LE(prolongation_last_time, time);
  if (prolongation_last_time == time) {
    return;
  }
  ephemeris_->FlowWithAdaptiveStep(
      prolongation_,
      Ephemeris<Barycentric>::kNoIntrinsicAcceleration,
      time,
      prolongation_adaptive_step_parameters_,
      Ephemeris<Barycentric>::unlimited_max_ephemeris_steps);
}

inline void Vessel::FlowPrediction(Instant const& time) {
  if (time > prediction_->last().time()) {
    bool finite_time = IsFinite(time - prediction_->last().time()));
    Instant const t = finite_time ? time : ephemeris_->t_max();
    // This will not prolong the ephemeris if |time| is infinite (but it may do
    // no if it is finite).
    bool reached_t = ephemeris_->FlowWithAdaptiveStep(
        prediction_,
        Ephemeris<Barycentric>::kNoIntrinsicAcceleration,
        t,
        prediction_adaptive_step_parameters_,
        FlightPlan::max_ephemeris_steps_per_frame);
    if (!finite_time && reached_t) {
      // This will prolong the ephemeris by |max_ephemeris_steps_per_frame|.
      ephemeris_->FlowWithAdaptiveStep(
        prediction_,
        Ephemeris<Barycentric>::kNoIntrinsicAcceleration,
        time,
        prediction_adaptive_step_parameters_,
        FlightPlan::max_ephemeris_steps_per_frame);
    }
  }
}

inline Ephemeris<Barycentric>::FixedStepParameters DefaultHistoryParameters() {
  return Ephemeris<Barycentric>::FixedStepParameters(
             McLachlanAtela1992Order5Optimal<Position<Barycentric>>(),
             /*step=*/10 * Second);
}

inline Ephemeris<Barycentric>::AdaptiveStepParameters
DefaultProlongationParameters() {
  return Ephemeris<Barycentric>::AdaptiveStepParameters(
             DormandElMikkawyPrince1986RKN434FM<Position<Barycentric>>(),
             /*max_steps=*/std::numeric_limits<std::int64_t>::max(),
             /*length_integration_tolerance=*/1 * Milli(Metre),
             /*speed_integration_tolerance=*/1 * Milli(Metre) / Second);
}

inline Ephemeris<Barycentric>::AdaptiveStepParameters
DefaultPredictionParameters() {
  return Ephemeris<Barycentric>::AdaptiveStepParameters(
             DormandElMikkawyPrince1986RKN434FM<Position<Barycentric>>(),
             /*max_steps=*/1000,
             /*length_integration_tolerance=*/1 * Metre,
             /*speed_integration_tolerance=*/1 * Metre / Second);
}

}  // namespace ksp_plugin
}  // namespace principia
<commit_msg>typos<commit_after>
#pragma once

#include "ksp_plugin/vessel.hpp"

#include <algorithm>
#include <limits>
#include <vector>

#include "integrators/embedded_explicit_runge_kutta_nyström_integrator.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/make_not_null.hpp"

namespace principia {

using integrators::DormandElMikkawyPrince1986RKN434FM;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::IsFinite;
using quantities::si::Kilogram;
using quantities::si::Milli;

namespace ksp_plugin {

inline Vessel::Vessel(not_null<Celestial const*> const parent,
                      not_null<Ephemeris<Barycentric>*> const ephemeris,
                      Ephemeris<Barycentric>::FixedStepParameters const&
                          history_fixed_step_parameters,
                      Ephemeris<Barycentric>::AdaptiveStepParameters const&
                          prolongation_adaptive_step_parameters,
                      Ephemeris<Barycentric>::AdaptiveStepParameters const&
                          prediction_adaptive_step_parameters)
    : body_(),
      history_fixed_step_parameters_(history_fixed_step_parameters),
      prolongation_adaptive_step_parameters_(
          prolongation_adaptive_step_parameters),
      prediction_adaptive_step_parameters_(
          prediction_adaptive_step_parameters),
      parent_(parent),
      ephemeris_(ephemeris) {}

inline not_null<MasslessBody const*> Vessel::body() const {
  return &body_;
}

inline bool Vessel::is_initialized() const {
  CHECK_EQ(history_ == nullptr, prolongation_ == nullptr);
  CHECK_EQ(history_ == nullptr, prediction_ == nullptr);
  return history_ != nullptr;
}

inline not_null<Celestial const*> Vessel::parent() const {
  return parent_;
}

inline void Vessel::set_parent(not_null<Celestial const*> const parent) {
  parent_ = parent;
}

inline DiscreteTrajectory<Barycentric> const& Vessel::history() const {
  CHECK(is_initialized());
  return *history_;
}

inline DiscreteTrajectory<Barycentric> const& Vessel::prolongation() const {
  CHECK(is_initialized());
  return *prolongation_;
}

inline DiscreteTrajectory<Barycentric> const& Vessel::prediction() const {
  CHECK(is_initialized());
  return *prediction_;
}

inline FlightPlan& Vessel::flight_plan() const {
  CHECK(has_flight_plan());
  return *flight_plan_;
}

inline bool Vessel::has_flight_plan() const {
  return flight_plan_ != nullptr;
}

inline void Vessel::set_dirty() {
  is_dirty_ = true;
}

inline bool Vessel::is_dirty() const {
  return is_dirty_;
}

inline void Vessel::set_prediction_adaptive_step_parameters(
    Ephemeris<Barycentric>::AdaptiveStepParameters const&
        prediction_adaptive_step_parameters) {
  prediction_adaptive_step_parameters_ = prediction_adaptive_step_parameters;
}

inline Ephemeris<Barycentric>::AdaptiveStepParameters const&
Vessel::prediction_adaptive_step_parameters() const {
  return prediction_adaptive_step_parameters_;
}

inline void Vessel::CreateHistoryAndForkProlongation(
    Instant const& time,
    DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {
  CHECK(!is_initialized());
  history_ = std::make_unique<DiscreteTrajectory<Barycentric>>();
  history_->Append(time, degrees_of_freedom);
  prolongation_ = history_->NewForkAtLast();
  prediction_ = history_->NewForkAtLast();
}

inline void Vessel::AdvanceTimeNotInBubble(Instant const& time) {
  CHECK(is_initialized());
  AdvanceHistoryIfNeeded(time);
  FlowProlongation(time);
}

inline void Vessel::AdvanceTimeInBubble(
    Instant const& time,
    DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {
  CHECK(is_initialized());
  AdvanceHistoryIfNeeded(time);
  prolongation_->Append(time, degrees_of_freedom);
  is_dirty_ = true;
}

inline void Vessel::ForgetBefore(Instant const& time) {
  CHECK(is_initialized());
  if (prediction_->Fork().time() < time) {
    history_->DeleteFork(&prediction_);
    prediction_ = history_->NewForkAtLast();
  }
  if (flight_plan_ != nullptr) {
    flight_plan_->ForgetBefore(time, [this]() { flight_plan_.reset(); });
  }
  history_->ForgetBefore(time);
}

inline void Vessel::CreateFlightPlan(
    Instant const& final_time,
    Mass const& initial_mass,
    Ephemeris<Barycentric>::AdaptiveStepParameters const&
        flight_plan_adaptive_step_parameters) {
  auto const history_last = history().last();
  flight_plan_ = std::make_unique<FlightPlan>(
      initial_mass,
      /*initial_time=*/history_last.time(),
      /*initial_degrees_of_freedom=*/history_last.degrees_of_freedom(),
      final_time,
      ephemeris_,
      flight_plan_adaptive_step_parameters);
}

inline void Vessel::DeleteFlightPlan() {
  flight_plan_.reset();
}

inline void Vessel::UpdatePrediction(Instant const& last_time) {
  CHECK(is_initialized());
  history_->DeleteFork(&prediction_);
  prediction_ = history_->NewForkAtLast();
  auto const prolongation_last = prolongation_->last();
  if (history_->last().time() != prolongation_last.time()) {
    prediction_->Append(prolongation_last.time(),
                        prolongation_last.degrees_of_freedom());
  }
  FlowPrediction(last_time);
}

inline void Vessel::WriteToMessage(
    not_null<serialization::Vessel*> const message) const {
  CHECK(is_initialized());
  body_.WriteToMessage(message->mutable_body());
  prolongation_adaptive_step_parameters_.WriteToMessage(
      message->mutable_prolongation_adaptive_step_parameters());
  history_fixed_step_parameters_.WriteToMessage(
      message->mutable_history_fixed_step_parameters());
  history_->WriteToMessage(message->mutable_history(), {prolongation_});
  prediction_->Fork().time().WriteToMessage(
      message->mutable_prediction_fork_time());
  prediction_->last().time().WriteToMessage(
      message->mutable_prediction_last_time());
  prediction_adaptive_step_parameters_.WriteToMessage(
      message->mutable_prediction_adaptive_step_parameters());
  if (flight_plan_ != nullptr) {
    flight_plan_->WriteToMessage(message->mutable_flight_plan());
  }
  message->set_is_dirty(is_dirty_);
}

inline not_null<std::unique_ptr<Vessel>> Vessel::ReadFromMessage(
    serialization::Vessel const& message,
    not_null<Ephemeris<Barycentric>*> const ephemeris,
    not_null<Celestial const*> const parent) {
  // NOTE(egg): for now we do not read the |MasslessBody| as it can contain no
  // information.
  std::unique_ptr<Vessel> vessel;
  bool const is_pre_буняковский = message.has_history_and_prolongation() ||
                                  message.has_owned_prolongation();

  if (is_pre_буняковский) {
    vessel = make_not_null_unique<Vessel>(parent,
                                          ephemeris,
                                          DefaultHistoryParameters(),
                                          DefaultProlongationParameters(),
                                          DefaultPredictionParameters());

    if (message.has_history_and_prolongation()) {
      vessel->history_ =
          DiscreteTrajectory<Barycentric>::ReadFromMessage(
              message.history_and_prolongation().history(), /*forks=*/{});
      vessel->prolongation_ =
          DiscreteTrajectory<Barycentric>::ReadPointerFromMessage(
              message.history_and_prolongation().prolongation(),
              vessel->history_.get());
      if (message.has_prediction()) {
        vessel->prediction_ =
            DiscreteTrajectory<Barycentric>::ReadPointerFromMessage(
                message.prediction(),
                vessel->history_.get());
      }
      if (message.has_flight_plan()) {
        vessel->flight_plan_ = FlightPlan::ReadFromMessage(
            message.flight_plan(), vessel->history_.get(), ephemeris);
      }
    } else {
      vessel->history_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(
                             message.owned_prolongation(), /*forks=*/{});
      vessel->prolongation_ = vessel->history_->NewForkAtLast();
      CHECK(!message.has_prediction());
      CHECK(!message.has_flight_plan());
    }
    if (vessel->prediction_ == nullptr) {
      vessel->prediction_ = vessel->history_->NewForkAtLast();
    }
  } else {
    CHECK(message.has_history() &&
          message.has_history_fixed_step_parameters() &&
          message.has_prolongation_adaptive_step_parameters() &&
          message.has_prediction_fork_time() &&
          message.has_prediction_last_time() &&
          message.has_prediction_adaptive_step_parameters())
        << message.DebugString();
    vessel = make_not_null_unique<Vessel>(
        parent,
        ephemeris,
        Ephemeris<Barycentric>::FixedStepParameters::ReadFromMessage(
            message.history_fixed_step_parameters()),
        Ephemeris<Barycentric>::AdaptiveStepParameters::ReadFromMessage(
            message.prolongation_adaptive_step_parameters()),
        Ephemeris<Barycentric>::AdaptiveStepParameters::ReadFromMessage(
            message.prediction_adaptive_step_parameters()));
    vessel->history_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(
        message.history(), {&vessel->prolongation_});
    vessel->prediction_ = vessel->history_->NewForkWithoutCopy(
        Instant::ReadFromMessage(message.prediction_fork_time()));
    vessel->FlowPrediction(
        Instant::ReadFromMessage(message.prediction_last_time()));
    if (message.has_flight_plan()) {
      vessel->flight_plan_ = FlightPlan::ReadFromMessage(
          message.flight_plan(), vessel->history_.get(), ephemeris);
    }
    vessel->is_dirty_ = message.is_dirty();
  }
  return std::move(vessel);
}

inline Vessel::Vessel()
    : body_(),
      history_fixed_step_parameters_(DefaultHistoryParameters()),
      prolongation_adaptive_step_parameters_(DefaultProlongationParameters()),
      prediction_adaptive_step_parameters_(DefaultPredictionParameters()),
      parent_(testing_utilities::make_not_null<Celestial const*>()),
      ephemeris_(testing_utilities::make_not_null<Ephemeris<Barycentric>*>()) {}

inline void Vessel::AdvanceHistoryIfNeeded(Instant const& time) {
  Instant const& history_last_time = history_->last().time();
  Time const& Δt = history_fixed_step_parameters_.step();

  if (history_last_time + Δt < time) {
    if (is_dirty_) {
      FlowProlongation(history_last_time + Δt);
      history_->Append(history_last_time + Δt,
                       prolongation_->last().degrees_of_freedom());
      is_dirty_ = false;
    }
    FlowHistory(time);
    history_->DeleteFork(&prolongation_);
    prolongation_ = history_->NewForkAtLast();
  }
}

inline void Vessel::FlowHistory(Instant const& time) {
  ephemeris_->FlowWithFixedStep(
      {history_.get()},
      Ephemeris<Barycentric>::kNoIntrinsicAccelerations,
      time,
      history_fixed_step_parameters_);
}

inline void Vessel::FlowProlongation(Instant const& time) {
  Instant const& prolongation_last_time = prolongation_->last().time();
  CHECK_LE(prolongation_last_time, time);
  if (prolongation_last_time == time) {
    return;
  }
  ephemeris_->FlowWithAdaptiveStep(
      prolongation_,
      Ephemeris<Barycentric>::kNoIntrinsicAcceleration,
      time,
      prolongation_adaptive_step_parameters_,
      Ephemeris<Barycentric>::unlimited_max_ephemeris_steps);
}

inline void Vessel::FlowPrediction(Instant const& time) {
  if (time > prediction_->last().time()) {
    bool finite_time = IsFinite(time - prediction_->last().time());
    Instant const t = finite_time ? time : ephemeris_->t_max();
    // This will not prolong the ephemeris if |time| is infinite (but it may do
    // no if it is finite).
    bool reached_t = ephemeris_->FlowWithAdaptiveStep(
        prediction_,
        Ephemeris<Barycentric>::kNoIntrinsicAcceleration,
        t,
        prediction_adaptive_step_parameters_,
        FlightPlan::max_ephemeris_steps_per_frame);
    if (!finite_time && reached_t) {
      // This will prolong the ephemeris by |max_ephemeris_steps_per_frame|.
      ephemeris_->FlowWithAdaptiveStep(
        prediction_,
        Ephemeris<Barycentric>::kNoIntrinsicAcceleration,
        time,
        prediction_adaptive_step_parameters_,
        FlightPlan::max_ephemeris_steps_per_frame);
    }
  }
}

inline Ephemeris<Barycentric>::FixedStepParameters DefaultHistoryParameters() {
  return Ephemeris<Barycentric>::FixedStepParameters(
             McLachlanAtela1992Order5Optimal<Position<Barycentric>>(),
             /*step=*/10 * Second);
}

inline Ephemeris<Barycentric>::AdaptiveStepParameters
DefaultProlongationParameters() {
  return Ephemeris<Barycentric>::AdaptiveStepParameters(
             DormandElMikkawyPrince1986RKN434FM<Position<Barycentric>>(),
             /*max_steps=*/std::numeric_limits<std::int64_t>::max(),
             /*length_integration_tolerance=*/1 * Milli(Metre),
             /*speed_integration_tolerance=*/1 * Milli(Metre) / Second);
}

inline Ephemeris<Barycentric>::AdaptiveStepParameters
DefaultPredictionParameters() {
  return Ephemeris<Barycentric>::AdaptiveStepParameters(
             DormandElMikkawyPrince1986RKN434FM<Position<Barycentric>>(),
             /*max_steps=*/1000,
             /*length_integration_tolerance=*/1 * Metre,
             /*speed_integration_tolerance=*/1 * Metre / Second);
}

}  // namespace ksp_plugin
}  // namespace principia
<|endoftext|>


<commit_before>// gui.cpp
// GUI for mancala game, using gtkmm
// Copyright Matthew Chandler 2012

#include <sstream>

#include <gtkmm/messagedialog.h>

#include "gui.h"

Mancala_win::Mancala_win():
    main_box(Gtk::ORIENTATION_VERTICAL),
    board_box(Gtk::ORIENTATION_HORIZONTAL),
    sub_board_box(Gtk::ORIENTATION_VERTICAL),
    top_row_box(Gtk::ORIENTATION_HORIZONTAL),
    bottom_row_box(Gtk::ORIENTATION_HORIZONTAL),
    hint_box(Gtk::ORIENTATION_HORIZONTAL),
    hint_b("Hint"),
    player(1),
    playable(true)
{

    // set window properties
    set_border_width(10);
    set_default_size(200,100);
    set_title("Mancala");

    // add widgets to contatiners
    add(main_box);
    main_box.pack_start(player_label, Gtk::PACK_SHRINK);
    main_box.pack_start(board_box);

    board_box.pack_start(l_store);
    board_box.pack_end(r_store);

    board_box.pack_start(sub_board_box);
    sub_board_box.pack_start(top_row_box);
    sub_board_box.pack_end(bottom_row_box);

    main_box.pack_end(hint_box, Gtk::PACK_SHRINK);
    hint_box.pack_start(hint_b, Gtk::PACK_EXPAND_PADDING);

    // create and store widgets for the bowls
    // bind events to each button
    for(int i = 0; i < b.num_bowls; ++i)
    {
        top_row_bowls.push_back(std::unique_ptr<Gtk::Label> (new Gtk::Label));
        top_row_box.pack_start(*top_row_bowls[i]);

        bottom_row_bowls.push_back(std::unique_ptr<Gtk::Button> (new Gtk::Button));
        bottom_row_box.pack_start(*bottom_row_bowls[i]);
        bottom_row_bowls.back()->signal_clicked().connect(sigc::bind<int>(sigc::mem_fun(*this, &Mancala_win::move), i));
    }

    hint_b.signal_clicked().connect(sigc::mem_fun(*this, &Mancala_win::hint));

    // set all labels for number of seeds
    update_board();

    show_all_children();
}

// make a move (called by button signals)
void Mancala_win::move(const int i)
{
    if(!playable)
        return;

    if(b.bowls[b.p1_start + i].count <= 0)
        return;

    if(!b.move(i))
    {
        //player = (player == 1)? 2 : 1;
        b.swapsides();

        int ai_move = 0;
        do
        {
            if(b.finished())
                break;
            ai_move = choosemove(b);
        }
        while(b.move(ai_move));

        b.swapsides();
    }

    update_board();

    // check to see if the game is over
    if(b.finished())
    {
        Glib::ustring msg;
        // check for a tie
        if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count)
            msg = "Tie";

        // determine the current player, and then see if they won or lost
        else if(player == 1)
            if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
                msg = "Player 1 wins";
            else
                msg = "Player 2 wins";
        else
            if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
                msg = "Player 2 wins";
            else
                msg = "Player 1 wins";

        // was the win full of win?
        if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10)
            msg += "\nFATALITY";

        //create and show a dialog announcing the winner
        Gtk::MessageDialog dlg(*this, "Game Over");
        dlg.set_secondary_text(msg);
        dlg.run();

        //mark the game as unplayable
        playable = false;
    }
}

// get a hint, will highlight a bowl
void Mancala_win::hint()
{
    // clear any existing highlights
    for(auto &i: bottom_row_bowls)
        i->drag_unhighlight();

    // use AI function to find best move
    int bestmove = choosemove(b);

    //highlight chosen one
    bottom_row_bowls[bestmove]->drag_highlight();
}

// update the numbers for each bowl / store
void Mancala_win::update_board()
{
    // Show who's turn it is TODO: ugly
    if(player == 1)
        player_label.set_text("Player 1");
    else
        player_label.set_text("Player 2");

    // get and update the counts for the stores
    std::ostringstream l_store_count_str;
    l_store_count_str<<b.bowls[b.p2_store].count;
    l_store.set_text(l_store_count_str.str());

    std::ostringstream r_store_count_str;
    r_store_count_str<<b.bowls[b.p1_store].count;
    r_store.set_text(r_store_count_str.str());

    for(int i = 0; i < b.num_bowls; ++i)
    {
        std::ostringstream top_count_str;
        top_count_str.clear();
        top_count_str<<b.bowls[b.bowls[b.p1_start + i].across].count;
        top_row_bowls[i]->set_text(top_count_str.str());

        std::ostringstream bottom_count_str;
        bottom_count_str.clear();
        bottom_count_str<<b.bowls[b.p1_start + i].count;
        bottom_row_bowls[i]->set_label(bottom_count_str.str());

        // clear any hint highlighting
        bottom_row_bowls[i]->drag_unhighlight();
    }
}
<commit_msg>disabled hint button when game is over<commit_after>// gui.cpp
// GUI for mancala game, using gtkmm
// Copyright Matthew Chandler 2012

#include <sstream>

#include <gtkmm/messagedialog.h>

#include "gui.h"

Mancala_win::Mancala_win():
    main_box(Gtk::ORIENTATION_VERTICAL),
    board_box(Gtk::ORIENTATION_HORIZONTAL),
    sub_board_box(Gtk::ORIENTATION_VERTICAL),
    top_row_box(Gtk::ORIENTATION_HORIZONTAL),
    bottom_row_box(Gtk::ORIENTATION_HORIZONTAL),
    hint_box(Gtk::ORIENTATION_HORIZONTAL),
    hint_b("Hint"),
    player(1),
    playable(true)
{

    // set window properties
    set_border_width(10);
    set_default_size(200,100);
    set_title("Mancala");

    // add widgets to contatiners
    add(main_box);
    main_box.pack_start(player_label, Gtk::PACK_SHRINK);
    main_box.pack_start(board_box);

    board_box.pack_start(l_store);
    board_box.pack_end(r_store);

    board_box.pack_start(sub_board_box);
    sub_board_box.pack_start(top_row_box);
    sub_board_box.pack_end(bottom_row_box);

    main_box.pack_end(hint_box, Gtk::PACK_SHRINK);
    hint_box.pack_start(hint_b, Gtk::PACK_EXPAND_PADDING);

    // create and store widgets for the bowls
    // bind events to each button
    for(int i = 0; i < b.num_bowls; ++i)
    {
        top_row_bowls.push_back(std::unique_ptr<Gtk::Label> (new Gtk::Label));
        top_row_box.pack_start(*top_row_bowls[i]);

        bottom_row_bowls.push_back(std::unique_ptr<Gtk::Button> (new Gtk::Button));
        bottom_row_box.pack_start(*bottom_row_bowls[i]);
        bottom_row_bowls.back()->signal_clicked().connect(sigc::bind<int>(sigc::mem_fun(*this, &Mancala_win::move), i));
    }

    hint_b.signal_clicked().connect(sigc::mem_fun(*this, &Mancala_win::hint));

    // set all labels for number of seeds
    update_board();

    show_all_children();
}

// make a move (called by button signals)
void Mancala_win::move(const int i)
{
    if(!playable)
        return;

    if(b.bowls[b.p1_start + i].count <= 0)
        return;

    if(!b.move(i))
    {
        //player = (player == 1)? 2 : 1;
        b.swapsides();

        int ai_move = 0;
        do
        {
            if(b.finished())
                break;
            ai_move = choosemove(b);
        }
        while(b.move(ai_move));

        b.swapsides();
    }

    update_board();

    // check to see if the game is over
    if(b.finished())
    {
        Glib::ustring msg;
        // check for a tie
        if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count)
            msg = "Tie";

        // determine the current player, and then see if they won or lost
        else if(player == 1)
            if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
                msg = "Player 1 wins";
            else
                msg = "Player 2 wins";
        else
            if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count)
                msg = "Player 2 wins";
            else
                msg = "Player 1 wins";

        // was the win full of win?
        if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10)
            msg += "\nFATALITY";

        //create and show a dialog announcing the winner
        Gtk::MessageDialog dlg(*this, "Game Over");
        dlg.set_secondary_text(msg);
        dlg.run();

        //mark the game as unplayable
        playable = false;
    }
}

// get a hint, will highlight a bowl
void Mancala_win::hint()
{
    // clear any existing highlights
    for(auto &i: bottom_row_bowls)
        i->drag_unhighlight();

    if(!playable)
        return;

    // use AI function to find best move
    int bestmove = choosemove(b);

    //highlight chosen one
    bottom_row_bowls[bestmove]->drag_highlight();
}

// update the numbers for each bowl / store
void Mancala_win::update_board()
{
    // Show who's turn it is TODO: ugly
    if(player == 1)
        player_label.set_text("Player 1");
    else
        player_label.set_text("Player 2");

    // get and update the counts for the stores
    std::ostringstream l_store_count_str;
    l_store_count_str<<b.bowls[b.p2_store].count;
    l_store.set_text(l_store_count_str.str());

    std::ostringstream r_store_count_str;
    r_store_count_str<<b.bowls[b.p1_store].count;
    r_store.set_text(r_store_count_str.str());

    for(int i = 0; i < b.num_bowls; ++i)
    {
        std::ostringstream top_count_str;
        top_count_str.clear();
        top_count_str<<b.bowls[b.bowls[b.p1_start + i].across].count;
        top_row_bowls[i]->set_text(top_count_str.str());

        std::ostringstream bottom_count_str;
        bottom_count_str.clear();
        bottom_count_str<<b.bowls[b.p1_start + i].count;
        bottom_row_bowls[i]->set_label(bottom_count_str.str());

        // clear any hint highlighting
        bottom_row_bowls[i]->drag_unhighlight();
    }
}
<|endoftext|>