<commit_before>#include <Python.h>
#include "structmember.h"
#include <string>
#include <vector>

#include "cc/analysis/analyzer.h"
#include "cc/base/unicode/unicode.h"

using std::string;
using std::vector;

namespace {

/*-----------------------------------------------------------------------------
 *  PhraserExt object
 *-----------------------------------------------------------------------------*/
typedef struct {
        PyObject_HEAD
        Analyzer* ANALYZER;
} PhraserExt;

char PHRASER_DOC[] =
    "Python extension that detects phrases in text.\n"
    "\n"
    "phrase config texts -> error str or None.\n"
    "\n"
    "    >>> open('plaudit.txt', 'wb').write('\\n'.join([\n"
    "            'plaudit = verb object',\n"
    "            '----------',\n"
    "            'thanks',\n"
    "            '----------',\n"
    "            'obama',\n"
    "            'hitler',\n"
    "        ]))\n"
    "    >>> phrases_config_ff = ['plaudit.txt']\n"
    "    >>> phrase_configs = map(lambda f: open(f).read(), phrase_config_ff)\n"
    "    >>> phraser = PhraserExt(phrase_configs)\n"
    "    >>> assert phraser\n";

static PyObject *
PhraserExt_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PhraserExt *self;

    if ((self = (PhraserExt *)type->tp_alloc(type, 0)) == NULL) {
        PyErr_SetString(PyExc_MemoryError, "cannot allocate PhraserExt instance");
        return NULL;
    }

    self->ANALYZER = new Analyzer();
    //printf("Created analyzer instance %p\n", (void*)self->ANALYZER);
    if (self->ANALYZER == NULL) {
        Py_DECREF(self);
        PyErr_SetString(PyExc_MemoryError, "cannot allocate analyzer object");
        return NULL;
    }

    return (PyObject *)self;
}

static void
PhraserExt_dealloc(PhraserExt* self)
{
    //printf("Removing analyzer instance %p\n", (void*)self->ANALYZER);
    delete self->ANALYZER;
    Py_TYPE(self)->tp_free((PyObject*)self);
}

static int
PhraserExt_init(PhraserExt *self, PyObject *args, PyObject *kwds)
{
    // Get args.
    PyObject* list;
    if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list)) {
        return -1;
    }

    // Extract phrase configs from list.
    vector<string> phrase_configs;
    Py_ssize_t length = PyList_Size(list);
    for (Py_ssize_t i = 0; i < length; ++i) {
        PyObject* s = PyList_GetItem(list, i);
        if (!PyString_Check(s)) {
            PyErr_Format(PyExc_ValueError,
                    "[PhraserExt] List item at index %ld was not a string.", i);
            return -1;
        }
        phrase_configs.emplace_back(PyString_AsString(s));
    }

    if (!self->ANALYZER) {
        PyErr_SetString(PyExc_RuntimeError, "not initialized");
        return -1;
    }

    // Call Init().
    string error;
    if (!self->ANALYZER->Init(phrase_configs, &error)) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return -1;
    }

    return 0;
}

char ANALYZE_DOC[] =
    "Given an input Unicode string and a dict of options, analyze the string "
    "and return a result dict\n"
    "\n"
    "text, options -> phrase detection result dict.\n"
    "\n"
    "Analyze the text. Any errors are raised as exceptions\n"
    "\n"
    "    >>> text = u'This is a comment.'\n"
    "    >>> options = {\n"
    "            'destutter_max_consecutive': 3,\n"
    "            'replace_html_entities': True,\n"
    "        }\n"
    "    >>> result = phraserext.analyze(text, options)\n"
    "    >>> assert isinstance(result, dict)\n";

bool AnalysisOptionsFromDict(
        PyObject* obj, AnalysisOptions* options, string* error) {
    Py_ssize_t pos = 0;
    PyObject* key;
    PyObject* value;
    while (PyDict_Next(obj, &pos, &key, &value)) {
        if (!PyString_Check(key)) {
            *error = "[PhraserExt] Analysis options key is not a string.";
            return false;
        }
        const char* key_s = PyString_AsString(key);
        if (!strcmp(key_s, "destutter_max_consecutive")) {
            if (!PyInt_Check(value)) {
                *error = "[PhraserExt] Analysis option "
                         "'destutter_max_consecutive' is an integer.";
                return false;
            }
            Py_ssize_t size = PyInt_AsSsize_t(value);
            options->destutter_max_consecutive = static_cast<size_t>(size);
        } else if (!strcmp(key_s, "replace_html_entities")) {
            if (!PyBool_Check(value)) {
                *error = "[PhraserExt] Analysis option 'replace_html_entities' is "
                         "a bool.";
                return false;
            }
            options->replace_html_entities = PyObject_IsTrue(value);
        } else {
            *error = "[PhraserExt] Unknown analysis option.";
            return false;
        }
    }
    return true;
}

PyObject* UnicodeFromUstring(const ustring& s) {
#ifdef Py_UNICODE_WIDE
    // UCS 4 (eg, Linux).
    return PyUnicode_FromUnicode(s.data(), s.size());
#else
    // UCS 2 (eg, Mac OS X).
    vector<Py_UNICODE> v;
    for (auto& c : s) {
        v.emplace_back(static_cast<Py_UNICODE>(c));
    }
    return PyUnicode_FromUnicode(v.data(), v.size());
#endif
}

PyObject* MakeDict(const vector<PyObject*>& keys,
                   const vector<PyObject*>& values)
{
    auto num_keys = keys.size();
    auto num_vals = values.size();
    auto num_pairs = std::min(num_keys, num_vals);
    PyObject* d = PyDict_New();
    for (auto i = 0u; i < num_pairs; ++i) {
        PyObject* k = keys[i];
        PyObject* v = values[i];
        if (!k) {
            PyErr_Format(PyExc_KeyError, "Missing key at index %u", i);
            Py_DECREF(d);
            return NULL;
        }
        else if (!v) {
            PyErr_Format(PyExc_ValueError, "Missing value at index %u", i);
            Py_DECREF(d);
            return NULL;
        }
        auto code = PyDict_SetItem(d, k, v);
        Py_DECREF(k);
        Py_DECREF(v);
        if (code) {
            PyErr_Format(PyExc_RuntimeError, "Could not set item at index %u", i);
            Py_DECREF(d);
            return NULL;
        }
    }
    return d;
}

// Returned dicts look like
//
// {
//     'original_text':  'Some texxxxxxxt',
//     'clean_text':     'Some texxxt',
//     'tokens':         ['some', 'text'],
//     'phrase_results': [...],
// }
//
// where 'phrase_results' is a list like
//
// {
//     'phrase_name': 'threat_statement',
//     'subsequence_names': ['subject', 'aux', 'verb'],
//     'index_lists': [...]
// }
PyObject* DictFromAnalysisResult(const AnalysisResult& result, string* error) {
    PyObject* key;
    PyObject* value;
    vector<PyObject*> keys;
    vector<PyObject*> values;

    key = PyString_FromString("original_text");
    value = UnicodeFromUstring(result.original_text);
    keys.emplace_back(key);
    values.emplace_back(value);

    key = PyString_FromString("clean_text");
    value = UnicodeFromUstring(result.clean_text);
    keys.emplace_back(key);
    values.emplace_back(value);

    key = PyString_FromString("tokens");
    value = PyList_New(result.tokens.size());
    for (auto i = 0u; i < result.tokens.size(); ++i) {
        PyObject* token = PyString_FromString(result.tokens[i].data());
        PyList_SET_ITEM(value, i, token);
    }
    keys.emplace_back(key);
    values.emplace_back(value);

    key = PyString_FromString("phrase_matches");
    value = PyList_New(result.phrase_results.size());
    for (auto i = 0u; i < result.phrase_results.size(); ++i) {
        auto& phrase_result = result.phrase_results[i];

        vector<PyObject*> tmp_keys;
        vector<PyObject*> tmp_values;

        PyObject* tmp_key = PyString_FromString("phrase_name");
        PyObject* tmp_value = PyString_FromString(
            phrase_result.phrase_name.data());
        tmp_keys.emplace_back(tmp_key);
        tmp_values.emplace_back(tmp_value);

        tmp_key = PyString_FromString("subsequence_names");
        tmp_value = PyList_New(phrase_result.piece_names.size());
        for (auto j = 0u; j < phrase_result.piece_names.size(); ++j) {
            PyObject* subsequence_name =
                PyString_FromString(phrase_result.piece_names[j].data());
            PyList_SET_ITEM(tmp_value, j, subsequence_name);
        }
        tmp_keys.emplace_back(tmp_key);
        tmp_values.emplace_back(tmp_value);

        tmp_key = PyString_FromString("index_lists");
        tmp_value = PyList_New(phrase_result.matches.size());
        for (auto j = 0u; j < phrase_result.matches.size(); ++j) {
            auto& match = phrase_result.matches[j];
            PyObject* index_list = PyList_New(
                match.piece_begin_indexes.size() + 1);
            for (auto k = 0u; k < match.piece_begin_indexes.size(); ++k) {
                PyObject* item = PyInt_FromLong(match.piece_begin_indexes[k]);
                PyList_SET_ITEM(index_list, k, item);
            }
            PyObject* item = PyInt_FromLong(match.end_excl);
            PyList_SET_ITEM(index_list, match.piece_begin_indexes.size(), item);
            PyList_SET_ITEM(tmp_value, j, index_list);
        }
        tmp_keys.emplace_back(tmp_key);
        tmp_values.emplace_back(tmp_value);

        PyObject* tmp_d = MakeDict(tmp_keys, tmp_values);
        PyList_SET_ITEM(value, i, tmp_d);
    }
    keys.emplace_back(key);
    values.emplace_back(value);

    return MakeDict(keys, values);
}

static PyObject*
PhraserExt_analyze(PhraserExt* self, PyObject* args) {
    // Get args.
    //
    PyObject* py_text;
    PyObject* options_dict;
    if (!PyArg_ParseTuple(args, "UO!", &py_text, &PyDict_Type, &options_dict)) {
        // TODO: call PyErr_SetString here as well?
        return NULL;
    }

    // Check if initialized.
    if (!self->ANALYZER) {
        PyErr_SetString(PyExc_RuntimeError, "PhraserExt has not been initialized");
        return NULL;
    }

    // Get the input text to analyze.
    ustring text;
    Py_ssize_t size = PyUnicode_GetSize(py_text);
    for (Py_ssize_t i = 0; i < size; ++i) {
        text.emplace_back(PyUnicode_AsUnicode(py_text)[i]);
    }

    // Set the analysis options.
    AnalysisOptions options;
    string error;
    if (!AnalysisOptionsFromDict(options_dict, &options, &error)) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return NULL;
    }

    // Analyze the text.
    AnalysisResult result;
    if (!self->ANALYZER->Analyze(text, options, &result, &error)) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return NULL;
    }

    // Convert the results to a python dict.
    PyObject* result_dict;
    if (!(result_dict = DictFromAnalysisResult(result, &error))) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return NULL;
    }

    return result_dict;
}

static PyMethodDef PhraserExt_methods[] = {
    {"analyze", (PyCFunction)PhraserExt_analyze, METH_VARARGS, ANALYZE_DOC},
    { NULL, NULL, 0, NULL }  /* sentinel */
};

static PyMemberDef PhraserExt_members[] = {
    { NULL, 0, 0, 0, NULL }  /* sentinel */
};

static PyTypeObject PhraserExtType = {
        PyVarObject_HEAD_INIT(NULL, 0)
                "phraserext.PhraserExt",     /* tp_name */
        sizeof(PhraserExt),             /* tp_basicsize */
        0,                              /* tp_itemsize */
        (destructor)PhraserExt_dealloc, /* tp_dealloc */
        0,                         /* tp_print */
        0,                         /* tp_getattr */
        0,                         /* tp_setattr */
        0,                         /* tp_reserved */
        0,                         /* tp_repr */
        0,                         /* tp_as_number */
        0,                         /* tp_as_sequence */
        0,                         /* tp_as_mapping */
        0,                         /* tp_hash  */
        0,                         /* tp_call */
        0,                         /* tp_str */
        0,                         /* tp_getattro */
        0,                         /* tp_setattro */
        0,                         /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
        PHRASER_DOC,           /* tp_doc */
        0,                         /* tp_traverse */
        0,                         /* tp_clear */
        0,                         /* tp_richcompare */
        0,                         /* tp_weaklistoffset */
        0,                         /* tp_iter */
        0,                         /* tp_iternext */
        PhraserExt_methods,        /* tp_methods */
        PhraserExt_members,        /* tp_members */
        0,                         /* tp_getset */
        0,                         /* tp_base */
        0,                         /* tp_dict */
        0,                         /* tp_descr_get */
        0,                         /* tp_descr_set */
        0,                         /* tp_dictoffset */
        (initproc)PhraserExt_init, /* tp_init */
        0,                         /* tp_alloc */
        PhraserExt_new,            /* tp_new */
        0,                      /*  tp_free */
        0,                      /* tp_is_gc */
        0,                      /* tp_bases */
        0,                      /* tp_mro */
        0,                      /* tp_cache */
        0,                      /* tp_subclasses */
        0,                      /* tp_weaklist */
        0,                      /*  tp_del */
        0,                      /*  tp_version_tag */
};

}  // namespace

extern "C" void initphraserext(void);

PyMODINIT_FUNC initphraserext(void) {

    PyObject* m;

    if (PyType_Ready(&PhraserExtType) < 0)
        return;

    m = Py_InitModule3("phraserext", PhraserExt_methods,
                       "Example module that creates an extension type.");

    Py_INCREF(&PhraserExtType);
    PyModule_AddObject(m, "PhraserExt", (PyObject *)&PhraserExtType);
}
<commit_msg>refactor makedict<commit_after>#include <Python.h>
#include "structmember.h"
#include <string>
#include <vector>

#include "cc/analysis/analyzer.h"
#include "cc/base/unicode/unicode.h"

using std::string;
using std::vector;

namespace {

/*-----------------------------------------------------------------------------
 *  PhraserExt object
 *-----------------------------------------------------------------------------*/
typedef struct {
        PyObject_HEAD
        Analyzer* ANALYZER;
} PhraserExt;

char PHRASER_DOC[] =
    "Python extension that detects phrases in text.\n"
    "\n"
    "phrase config texts -> error str or None.\n"
    "\n"
    "    >>> open('plaudit.txt', 'wb').write('\\n'.join([\n"
    "            'plaudit = verb object',\n"
    "            '----------',\n"
    "            'thanks',\n"
    "            '----------',\n"
    "            'obama',\n"
    "            'hitler',\n"
    "        ]))\n"
    "    >>> phrases_config_ff = ['plaudit.txt']\n"
    "    >>> phrase_configs = map(lambda f: open(f).read(), phrase_config_ff)\n"
    "    >>> phraser = PhraserExt(phrase_configs)\n"
    "    >>> assert phraser\n";

static PyObject *
PhraserExt_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PhraserExt *self;

    if ((self = (PhraserExt *)type->tp_alloc(type, 0)) == NULL) {
        PyErr_SetString(PyExc_MemoryError, "cannot allocate PhraserExt instance");
        return NULL;
    }

    self->ANALYZER = new Analyzer();
    //printf("Created analyzer instance %p\n", (void*)self->ANALYZER);
    if (self->ANALYZER == NULL) {
        Py_DECREF(self);
        PyErr_SetString(PyExc_MemoryError, "cannot allocate analyzer object");
        return NULL;
    }

    return (PyObject *)self;
}

static void
PhraserExt_dealloc(PhraserExt* self)
{
    //printf("Removing analyzer instance %p\n", (void*)self->ANALYZER);
    delete self->ANALYZER;
    Py_TYPE(self)->tp_free((PyObject*)self);
}

static int
PhraserExt_init(PhraserExt *self, PyObject *args, PyObject *kwds)
{
    // Get args.
    PyObject* list;
    if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list)) {
        return -1;
    }

    // Extract phrase configs from list.
    vector<string> phrase_configs;
    Py_ssize_t length = PyList_Size(list);
    for (Py_ssize_t i = 0; i < length; ++i) {
        PyObject* s = PyList_GetItem(list, i);
        if (!PyString_Check(s)) {
            PyErr_Format(PyExc_ValueError,
                    "[PhraserExt] List item at index %ld was not a string.", i);
            return -1;
        }
        phrase_configs.emplace_back(PyString_AsString(s));
    }

    if (!self->ANALYZER) {
        PyErr_SetString(PyExc_RuntimeError, "not initialized");
        return -1;
    }

    // Call Init().
    string error;
    if (!self->ANALYZER->Init(phrase_configs, &error)) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return -1;
    }

    return 0;
}

char ANALYZE_DOC[] =
    "Given an input Unicode string and a dict of options, analyze the string "
    "and return a result dict\n"
    "\n"
    "text, options -> phrase detection result dict.\n"
    "\n"
    "Analyze the text. Any errors are raised as exceptions\n"
    "\n"
    "    >>> text = u'This is a comment.'\n"
    "    >>> options = {\n"
    "            'destutter_max_consecutive': 3,\n"
    "            'replace_html_entities': True,\n"
    "        }\n"
    "    >>> result = phraserext.analyze(text, options)\n"
    "    >>> assert isinstance(result, dict)\n";

bool AnalysisOptionsFromDict(
        PyObject* obj, AnalysisOptions* options, string* error) {
    Py_ssize_t pos = 0;
    PyObject* key;
    PyObject* value;
    while (PyDict_Next(obj, &pos, &key, &value)) {
        if (!PyString_Check(key)) {
            *error = "[PhraserExt] Analysis options key is not a string.";
            return false;
        }
        const char* key_s = PyString_AsString(key);
        if (!strcmp(key_s, "destutter_max_consecutive")) {
            if (!PyInt_Check(value)) {
                *error = "[PhraserExt] Analysis option "
                         "'destutter_max_consecutive' is an integer.";
                return false;
            }
            Py_ssize_t size = PyInt_AsSsize_t(value);
            options->destutter_max_consecutive = static_cast<size_t>(size);
        } else if (!strcmp(key_s, "replace_html_entities")) {
            if (!PyBool_Check(value)) {
                *error = "[PhraserExt] Analysis option 'replace_html_entities' is "
                         "a bool.";
                return false;
            }
            options->replace_html_entities = PyObject_IsTrue(value);
        } else {
            *error = "[PhraserExt] Unknown analysis option.";
            return false;
        }
    }
    return true;
}

PyObject* UnicodeFromUstring(const ustring& s) {
#ifdef Py_UNICODE_WIDE
    // UCS 4 (eg, Linux).
    return PyUnicode_FromUnicode(s.data(), s.size());
#else
    // UCS 2 (eg, Mac OS X).
    vector<Py_UNICODE> v;
    for (auto& c : s) {
        v.emplace_back(static_cast<Py_UNICODE>(c));
    }
    return PyUnicode_FromUnicode(v.data(), v.size());
#endif
}

PyObject* MakeDict(const vector<PyObject*>& keys,
                   const vector<PyObject*>& values,
                   string* error)
{
    auto num_keys = keys.size();
    auto num_vals = values.size();
    auto num_pairs = std::min(num_keys, num_vals);
    PyObject* d = PyDict_New();
    for (auto i = 0u; i < num_pairs; ++i) {
        PyObject* k = keys[i];
        PyObject* v = values[i];
        if (!k) {
            *error = "Missing key";
            Py_DECREF(d);
            return NULL;
        }
        else if (!v) {
            *error = "Missing value";
            Py_DECREF(d);
            return NULL;
        }
        auto code = PyDict_SetItem(d, k, v);
        Py_DECREF(k);
        Py_DECREF(v);
        if (code) {
            *error = "Could not set item";
            Py_DECREF(d);
            return NULL;
        }
    }
    return d;
}

// Returned dicts look like
//
// {
//     'original_text':  'Some texxxxxxxt',
//     'clean_text':     'Some texxxt',
//     'tokens':         ['some', 'text'],
//     'phrase_results': [...],
// }
//
// where 'phrase_results' is a list like
//
// {
//     'phrase_name': 'threat_statement',
//     'subsequence_names': ['subject', 'aux', 'verb'],
//     'index_lists': [...]
// }
PyObject* DictFromAnalysisResult(const AnalysisResult& result, string* error) {
    PyObject* key;
    PyObject* value;
    vector<PyObject*> keys;
    vector<PyObject*> values;

    key = PyString_FromString("original_text");
    value = UnicodeFromUstring(result.original_text);
    keys.emplace_back(key);
    values.emplace_back(value);

    key = PyString_FromString("clean_text");
    value = UnicodeFromUstring(result.clean_text);
    keys.emplace_back(key);
    values.emplace_back(value);

    key = PyString_FromString("tokens");
    value = PyList_New(result.tokens.size());
    for (auto i = 0u; i < result.tokens.size(); ++i) {
        PyObject* token = PyString_FromString(result.tokens[i].data());
        PyList_SET_ITEM(value, i, token);
    }
    keys.emplace_back(key);
    values.emplace_back(value);

    key = PyString_FromString("phrase_matches");
    value = PyList_New(result.phrase_results.size());
    for (auto i = 0u; i < result.phrase_results.size(); ++i) {
        auto& phrase_result = result.phrase_results[i];

        vector<PyObject*> tmp_keys;
        vector<PyObject*> tmp_values;

        PyObject* tmp_key = PyString_FromString("phrase_name");
        PyObject* tmp_value = PyString_FromString(
            phrase_result.phrase_name.data());
        tmp_keys.emplace_back(tmp_key);
        tmp_values.emplace_back(tmp_value);

        tmp_key = PyString_FromString("subsequence_names");
        tmp_value = PyList_New(phrase_result.piece_names.size());
        for (auto j = 0u; j < phrase_result.piece_names.size(); ++j) {
            PyObject* subsequence_name =
                PyString_FromString(phrase_result.piece_names[j].data());
            PyList_SET_ITEM(tmp_value, j, subsequence_name);
        }
        tmp_keys.emplace_back(tmp_key);
        tmp_values.emplace_back(tmp_value);

        tmp_key = PyString_FromString("index_lists");
        tmp_value = PyList_New(phrase_result.matches.size());
        for (auto j = 0u; j < phrase_result.matches.size(); ++j) {
            auto& match = phrase_result.matches[j];
            PyObject* index_list = PyList_New(
                match.piece_begin_indexes.size() + 1);
            for (auto k = 0u; k < match.piece_begin_indexes.size(); ++k) {
                PyObject* item = PyInt_FromLong(match.piece_begin_indexes[k]);
                PyList_SET_ITEM(index_list, k, item);
            }
            PyObject* item = PyInt_FromLong(match.end_excl);
            PyList_SET_ITEM(index_list, match.piece_begin_indexes.size(), item);
            PyList_SET_ITEM(tmp_value, j, index_list);
        }
        tmp_keys.emplace_back(tmp_key);
        tmp_values.emplace_back(tmp_value);

        PyObject* tmp_d = MakeDict(tmp_keys, tmp_values, error);
        if (!tmp_d) { return NULL; }
        PyList_SET_ITEM(value, i, tmp_d);
    }
    keys.emplace_back(key);
    values.emplace_back(value);

    return MakeDict(keys, values, error);
}

static PyObject*
PhraserExt_analyze(PhraserExt* self, PyObject* args) {
    // Get args.
    //
    PyObject* py_text;
    PyObject* options_dict;
    if (!PyArg_ParseTuple(args, "UO!", &py_text, &PyDict_Type, &options_dict)) {
        // TODO: call PyErr_SetString here as well?
        return NULL;
    }

    // Check if initialized.
    if (!self->ANALYZER) {
        PyErr_SetString(PyExc_RuntimeError, "PhraserExt has not been initialized");
        return NULL;
    }

    // Get the input text to analyze.
    ustring text;
    Py_ssize_t size = PyUnicode_GetSize(py_text);
    for (Py_ssize_t i = 0; i < size; ++i) {
        text.emplace_back(PyUnicode_AsUnicode(py_text)[i]);
    }

    // Set the analysis options.
    AnalysisOptions options;
    string error;
    if (!AnalysisOptionsFromDict(options_dict, &options, &error)) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return NULL;
    }

    // Analyze the text.
    AnalysisResult result;
    if (!self->ANALYZER->Analyze(text, options, &result, &error)) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return NULL;
    }

    // Convert the results to a python dict.
    PyObject* result_dict;
    if (!(result_dict = DictFromAnalysisResult(result, &error))) {
        PyErr_SetString(PyExc_RuntimeError, error.data());
        return NULL;
    }

    return result_dict;
}

static PyMethodDef PhraserExt_methods[] = {
    {"analyze", (PyCFunction)PhraserExt_analyze, METH_VARARGS, ANALYZE_DOC},
    { NULL, NULL, 0, NULL }  /* sentinel */
};

static PyMemberDef PhraserExt_members[] = {
    { NULL, 0, 0, 0, NULL }  /* sentinel */
};

static PyTypeObject PhraserExtType = {
        PyVarObject_HEAD_INIT(NULL, 0)
                "phraserext.PhraserExt",     /* tp_name */
        sizeof(PhraserExt),             /* tp_basicsize */
        0,                              /* tp_itemsize */
        (destructor)PhraserExt_dealloc, /* tp_dealloc */
        0,                         /* tp_print */
        0,                         /* tp_getattr */
        0,                         /* tp_setattr */
        0,                         /* tp_reserved */
        0,                         /* tp_repr */
        0,                         /* tp_as_number */
        0,                         /* tp_as_sequence */
        0,                         /* tp_as_mapping */
        0,                         /* tp_hash  */
        0,                         /* tp_call */
        0,                         /* tp_str */
        0,                         /* tp_getattro */
        0,                         /* tp_setattro */
        0,                         /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
        PHRASER_DOC,           /* tp_doc */
        0,                         /* tp_traverse */
        0,                         /* tp_clear */
        0,                         /* tp_richcompare */
        0,                         /* tp_weaklistoffset */
        0,                         /* tp_iter */
        0,                         /* tp_iternext */
        PhraserExt_methods,        /* tp_methods */
        PhraserExt_members,        /* tp_members */
        0,                         /* tp_getset */
        0,                         /* tp_base */
        0,                         /* tp_dict */
        0,                         /* tp_descr_get */
        0,                         /* tp_descr_set */
        0,                         /* tp_dictoffset */
        (initproc)PhraserExt_init, /* tp_init */
        0,                         /* tp_alloc */
        PhraserExt_new,            /* tp_new */
        0,                      /*  tp_free */
        0,                      /* tp_is_gc */
        0,                      /* tp_bases */
        0,                      /* tp_mro */
        0,                      /* tp_cache */
        0,                      /* tp_subclasses */
        0,                      /* tp_weaklist */
        0,                      /*  tp_del */
        0,                      /*  tp_version_tag */
};

}  // namespace

extern "C" void initphraserext(void);

PyMODINIT_FUNC initphraserext(void) {

    PyObject* m;

    if (PyType_Ready(&PhraserExtType) < 0)
        return;

    m = Py_InitModule3("phraserext", PhraserExt_methods,
                       "Example module that creates an extension type.");

    Py_INCREF(&PhraserExtType);
    PyModule_AddObject(m, "PhraserExt", (PyObject *)&PhraserExtType);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertysetcontainer.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:19:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_HELPER_PROPERTYSETCONTAINER_HXX_
#include <helper/propertysetcontainer.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#include <vcl/svapp.hxx>

#define WRONG_TYPE_EXCEPTION    "Only XPropertSet allowed!"

using namespace rtl;
using namespace vos;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;

namespace framework
{

PropertySetContainer::PropertySetContainer( const Reference< XMultiServiceFactory >& )
        :   ThreadHelpBase( &Application::GetSolarMutex() )
        ,   OWeakObject()

{
}

PropertySetContainer::~PropertySetContainer()
{
}

// XInterface
void SAL_CALL PropertySetContainer::acquire() throw ()
{
    OWeakObject::acquire();
}

void SAL_CALL PropertySetContainer::release() throw ()
{
    OWeakObject::release();
}

Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType )
throw ( RuntimeException )
{
    Any a = ::cppu::queryInterface(
                rType ,
                SAL_STATIC_CAST( XIndexContainer*, this ),
                SAL_STATIC_CAST( XIndexReplace*, this ),
                SAL_STATIC_CAST( XIndexAccess*, this ),
                SAL_STATIC_CAST( XElementAccess*, this ) );

    if( a.hasValue() )
    {
        return a;
    }

    return OWeakObject::queryInterface( rType );
}

// XIndexContainer
void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
    throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    sal_Int32 nSize = m_aPropertySetVector.size();

    if ( nSize >= Index )
    {
        Reference< XPropertySet > aPropertySetElement;

        if ( Element >>= aPropertySetElement )
        {
            if ( nSize == Index )
                m_aPropertySetVector.push_back( aPropertySetElement );
            else
            {
                PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
                aIter += Index;
                m_aPropertySetVector.insert( aIter, aPropertySetElement );
            }
        }
        else
        {
            throw IllegalArgumentException(
                OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
                (OWeakObject *)this, 2 );
        }
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index )
    throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    if ( (sal_Int32)m_aPropertySetVector.size() > Index )
    {
        PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
        aIter += Index;
        m_aPropertySetVector.erase( aIter );
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

// XIndexReplace
void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
    throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
{
    if ( (sal_Int32)m_aPropertySetVector.size() > Index )
    {
        Reference< XPropertySet > aPropertySetElement;

        if ( Element >>= aPropertySetElement )
        {
            m_aPropertySetVector[ Index ] = aPropertySetElement;
        }
        else
        {
            throw IllegalArgumentException(
                OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
                (OWeakObject *)this, 2 );
        }
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

// XIndexAccess
sal_Int32 SAL_CALL PropertySetContainer::getCount()
    throw ( RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    return m_aPropertySetVector.size();
}

Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index )
    throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    if ( (sal_Int32)m_aPropertySetVector.size() > Index )
    {
        Any a;

        a <<= m_aPropertySetVector[ Index ];
        return a;
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

// XElementAccess
sal_Bool SAL_CALL PropertySetContainer::hasElements()
    throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aGuard( m_aLock );

    return !( m_aPropertySetVector.empty() );
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.52); FILE MERGED 2006/09/01 17:29:11 kaib 1.3.52.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertysetcontainer.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:00:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

#ifndef __FRAMEWORK_HELPER_PROPERTYSETCONTAINER_HXX_
#include <helper/propertysetcontainer.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#include <vcl/svapp.hxx>

#define WRONG_TYPE_EXCEPTION    "Only XPropertSet allowed!"

using namespace rtl;
using namespace vos;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;

namespace framework
{

PropertySetContainer::PropertySetContainer( const Reference< XMultiServiceFactory >& )
        :   ThreadHelpBase( &Application::GetSolarMutex() )
        ,   OWeakObject()

{
}

PropertySetContainer::~PropertySetContainer()
{
}

// XInterface
void SAL_CALL PropertySetContainer::acquire() throw ()
{
    OWeakObject::acquire();
}

void SAL_CALL PropertySetContainer::release() throw ()
{
    OWeakObject::release();
}

Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType )
throw ( RuntimeException )
{
    Any a = ::cppu::queryInterface(
                rType ,
                SAL_STATIC_CAST( XIndexContainer*, this ),
                SAL_STATIC_CAST( XIndexReplace*, this ),
                SAL_STATIC_CAST( XIndexAccess*, this ),
                SAL_STATIC_CAST( XElementAccess*, this ) );

    if( a.hasValue() )
    {
        return a;
    }

    return OWeakObject::queryInterface( rType );
}

// XIndexContainer
void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
    throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    sal_Int32 nSize = m_aPropertySetVector.size();

    if ( nSize >= Index )
    {
        Reference< XPropertySet > aPropertySetElement;

        if ( Element >>= aPropertySetElement )
        {
            if ( nSize == Index )
                m_aPropertySetVector.push_back( aPropertySetElement );
            else
            {
                PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
                aIter += Index;
                m_aPropertySetVector.insert( aIter, aPropertySetElement );
            }
        }
        else
        {
            throw IllegalArgumentException(
                OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
                (OWeakObject *)this, 2 );
        }
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index )
    throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    if ( (sal_Int32)m_aPropertySetVector.size() > Index )
    {
        PropertySetVector::iterator aIter = m_aPropertySetVector.begin();
        aIter += Index;
        m_aPropertySetVector.erase( aIter );
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

// XIndexReplace
void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )
    throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
{
    if ( (sal_Int32)m_aPropertySetVector.size() > Index )
    {
        Reference< XPropertySet > aPropertySetElement;

        if ( Element >>= aPropertySetElement )
        {
            m_aPropertySetVector[ Index ] = aPropertySetElement;
        }
        else
        {
            throw IllegalArgumentException(
                OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )),
                (OWeakObject *)this, 2 );
        }
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

// XIndexAccess
sal_Int32 SAL_CALL PropertySetContainer::getCount()
    throw ( RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    return m_aPropertySetVector.size();
}

Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index )
    throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException )
{
    ResetableGuard aGuard( m_aLock );

    if ( (sal_Int32)m_aPropertySetVector.size() > Index )
    {
        Any a;

        a <<= m_aPropertySetVector[ Index ];
        return a;
    }
    else
        throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this );
}

// XElementAccess
sal_Bool SAL_CALL PropertySetContainer::hasElements()
    throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aGuard( m_aLock );

    return !( m_aPropertySetVector.empty() );
}

}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/touch/touch_hud_projection.h"

#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/wm/property_util.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/linear_animation.h"
#include "ui/base/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/size.h"
#include "ui/views/widget/widget.h"

namespace ash {
namespace internal {

const int kPointRadius = 20;
const SkColor kProjectionFillColor = SkColorSetRGB(0xF5, 0xF5, 0xDC);
const SkColor kProjectionStrokeColor = SK_ColorGRAY;
const int kProjectionAlpha = 0xB0;
const int kFadeoutDurationInMs = 250;
const int kFadeoutFrameRate = 60;

// TouchPointView draws a single touch point. This object manages its own
// lifetime and deletes itself upon fade-out completion or whenever |Remove()|
// is explicitly called.
class TouchPointView : public views::View,
                       public ui::AnimationDelegate,
                       public views::WidgetObserver {
 public:
  explicit TouchPointView(views::Widget* parent_widget)
      : circle_center_(kPointRadius + 1, kPointRadius + 1),
        gradient_center_(SkPoint::Make(kPointRadius + 1,
                                       kPointRadius + 1)) {
    SetPaintToLayer(true);
    SetFillsBoundsOpaquely(false);

    SetSize(gfx::Size(2 * kPointRadius + 2, 2 * kPointRadius + 2));

    stroke_paint_.setStyle(SkPaint::kStroke_Style);
    stroke_paint_.setColor(kProjectionStrokeColor);

    gradient_colors_[0] = kProjectionFillColor;
    gradient_colors_[1] = kProjectionStrokeColor;

    gradient_pos_[0] = SkFloatToScalar(0.9f);
    gradient_pos_[1] = SkFloatToScalar(1.0f);

    parent_widget->GetContentsView()->AddChildView(this);

    parent_widget->AddObserver(this);
  }

  void UpdateTouch(const ui::TouchEvent& touch) {
    if (touch.type() == ui::ET_TOUCH_RELEASED ||
        touch.type() == ui::ET_TOUCH_CANCELLED) {
      fadeout_.reset(new ui::LinearAnimation(kFadeoutDurationInMs,
                                             kFadeoutFrameRate,
                                             this));
      fadeout_->Start();
    } else {
      SetX(touch.root_location().x() - kPointRadius - 1);
      SetY(touch.root_location().y() - kPointRadius - 1);
    }
  }

  void Remove() {
    delete this;
  }

 private:
  virtual ~TouchPointView() {
    GetWidget()->RemoveObserver(this);
    parent()->RemoveChildView(this);
  }

  // Overridden from views::View.
  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    int alpha = kProjectionAlpha;
    if (fadeout_)
      alpha = static_cast<int>(fadeout_->CurrentValueBetween(alpha, 0));
    fill_paint_.setAlpha(alpha);
    stroke_paint_.setAlpha(alpha);
    SkShader* shader = SkGradientShader::CreateRadial(
        gradient_center_,
        SkIntToScalar(kPointRadius),
        gradient_colors_,
        gradient_pos_,
        arraysize(gradient_colors_),
        SkShader::kMirror_TileMode,
        NULL);
    fill_paint_.setShader(shader);
    shader->unref();
    canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
                       fill_paint_);
    canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
                       stroke_paint_);
  }

  // Overridden from ui::AnimationDelegate.
  virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE {
    DCHECK_EQ(fadeout_.get(), animation);
    delete this;
  }

  virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE {
    DCHECK_EQ(fadeout_.get(), animation);
    SchedulePaint();
  }

  virtual void AnimationCanceled(const ui::Animation* animation) OVERRIDE {
    AnimationEnded(animation);
  }

  // Overridden from views::WidgetObserver.
  virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
    fadeout_->Stop();
  }

  const gfx::Point circle_center_;
  const SkPoint gradient_center_;

  SkPaint fill_paint_;
  SkPaint stroke_paint_;
  SkColor gradient_colors_[2];
  SkScalar gradient_pos_[2];

  scoped_ptr<ui::Animation> fadeout_;

  DISALLOW_COPY_AND_ASSIGN(TouchPointView);
};

TouchHudProjection::TouchHudProjection(aura::RootWindow* initial_root)
    : TouchObserverHUD(initial_root) {
}

TouchHudProjection::~TouchHudProjection() {
}

void TouchHudProjection::Clear() {
  for (std::map<int, TouchPointView*>::iterator iter = points_.begin();
      iter != points_.end(); iter++)
    iter->second->Remove();
  points_.clear();
}

void TouchHudProjection::OnTouchEvent(ui::TouchEvent* event) {
  if (event->type() == ui::ET_TOUCH_PRESSED) {
    TouchPointView* point = new TouchPointView(widget());
    point->UpdateTouch(*event);
    std::pair<std::map<int, TouchPointView*>::iterator, bool> result =
        points_.insert(std::make_pair(event->touch_id(), point));
    // If a |TouchPointView| is already mapped to the touch id, remove it and
    // replace it with the new one.
    if (!result.second) {
      result.first->second->Remove();
      result.first->second = point;
    }
  } else {
    std::map<int, TouchPointView*>::iterator iter =
        points_.find(event->touch_id());
    if (iter != points_.end()) {
      iter->second->UpdateTouch(*event);
      if (event->type() == ui::ET_TOUCH_RELEASED ||
          event->type() == ui::ET_TOUCH_CANCELLED)
        points_.erase(iter);
    }
  }
}

void TouchHudProjection::SetHudForRootWindowController(
    RootWindowController* controller) {
  controller->set_touch_hud_projection(this);
}

void TouchHudProjection::UnsetHudForRootWindowController(
    RootWindowController* controller) {
  controller->set_touch_hud_projection(NULL);
}

}  // namespace internal
}  // namespace ash
<commit_msg>Fix projection touch HUD in RTL<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/touch/touch_hud_projection.h"

#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/wm/property_util.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/linear_animation.h"
#include "ui/base/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/size.h"
#include "ui/views/widget/widget.h"

namespace ash {
namespace internal {

const int kPointRadius = 20;
const SkColor kProjectionFillColor = SkColorSetRGB(0xF5, 0xF5, 0xDC);
const SkColor kProjectionStrokeColor = SK_ColorGRAY;
const int kProjectionAlpha = 0xB0;
const int kFadeoutDurationInMs = 250;
const int kFadeoutFrameRate = 60;

// TouchPointView draws a single touch point. This object manages its own
// lifetime and deletes itself upon fade-out completion or whenever |Remove()|
// is explicitly called.
class TouchPointView : public views::View,
                       public ui::AnimationDelegate,
                       public views::WidgetObserver {
 public:
  explicit TouchPointView(views::Widget* parent_widget)
      : circle_center_(kPointRadius + 1, kPointRadius + 1),
        gradient_center_(SkPoint::Make(kPointRadius + 1,
                                       kPointRadius + 1)) {
    SetPaintToLayer(true);
    SetFillsBoundsOpaquely(false);

    SetSize(gfx::Size(2 * kPointRadius + 2, 2 * kPointRadius + 2));

    stroke_paint_.setStyle(SkPaint::kStroke_Style);
    stroke_paint_.setColor(kProjectionStrokeColor);

    gradient_colors_[0] = kProjectionFillColor;
    gradient_colors_[1] = kProjectionStrokeColor;

    gradient_pos_[0] = SkFloatToScalar(0.9f);
    gradient_pos_[1] = SkFloatToScalar(1.0f);

    parent_widget->GetContentsView()->AddChildView(this);

    parent_widget->AddObserver(this);
  }

  void UpdateTouch(const ui::TouchEvent& touch) {
    if (touch.type() == ui::ET_TOUCH_RELEASED ||
        touch.type() == ui::ET_TOUCH_CANCELLED) {
      fadeout_.reset(new ui::LinearAnimation(kFadeoutDurationInMs,
                                             kFadeoutFrameRate,
                                             this));
      fadeout_->Start();
    } else {
      SetX(parent()->GetMirroredXInView(touch.root_location().x()) -
               kPointRadius - 1);
      SetY(touch.root_location().y() - kPointRadius - 1);
    }
  }

  void Remove() {
    delete this;
  }

 private:
  virtual ~TouchPointView() {
    GetWidget()->RemoveObserver(this);
    parent()->RemoveChildView(this);
  }

  // Overridden from views::View.
  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    int alpha = kProjectionAlpha;
    if (fadeout_)
      alpha = static_cast<int>(fadeout_->CurrentValueBetween(alpha, 0));
    fill_paint_.setAlpha(alpha);
    stroke_paint_.setAlpha(alpha);
    SkShader* shader = SkGradientShader::CreateRadial(
        gradient_center_,
        SkIntToScalar(kPointRadius),
        gradient_colors_,
        gradient_pos_,
        arraysize(gradient_colors_),
        SkShader::kMirror_TileMode,
        NULL);
    fill_paint_.setShader(shader);
    shader->unref();
    canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
                       fill_paint_);
    canvas->DrawCircle(circle_center_, SkIntToScalar(kPointRadius),
                       stroke_paint_);
  }

  // Overridden from ui::AnimationDelegate.
  virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE {
    DCHECK_EQ(fadeout_.get(), animation);
    delete this;
  }

  virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE {
    DCHECK_EQ(fadeout_.get(), animation);
    SchedulePaint();
  }

  virtual void AnimationCanceled(const ui::Animation* animation) OVERRIDE {
    AnimationEnded(animation);
  }

  // Overridden from views::WidgetObserver.
  virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
    fadeout_->Stop();
  }

  const gfx::Point circle_center_;
  const SkPoint gradient_center_;

  SkPaint fill_paint_;
  SkPaint stroke_paint_;
  SkColor gradient_colors_[2];
  SkScalar gradient_pos_[2];

  scoped_ptr<ui::Animation> fadeout_;

  DISALLOW_COPY_AND_ASSIGN(TouchPointView);
};

TouchHudProjection::TouchHudProjection(aura::RootWindow* initial_root)
    : TouchObserverHUD(initial_root) {
}

TouchHudProjection::~TouchHudProjection() {
}

void TouchHudProjection::Clear() {
  for (std::map<int, TouchPointView*>::iterator iter = points_.begin();
      iter != points_.end(); iter++)
    iter->second->Remove();
  points_.clear();
}

void TouchHudProjection::OnTouchEvent(ui::TouchEvent* event) {
  if (event->type() == ui::ET_TOUCH_PRESSED) {
    TouchPointView* point = new TouchPointView(widget());
    point->UpdateTouch(*event);
    std::pair<std::map<int, TouchPointView*>::iterator, bool> result =
        points_.insert(std::make_pair(event->touch_id(), point));
    // If a |TouchPointView| is already mapped to the touch id, remove it and
    // replace it with the new one.
    if (!result.second) {
      result.first->second->Remove();
      result.first->second = point;
    }
  } else {
    std::map<int, TouchPointView*>::iterator iter =
        points_.find(event->touch_id());
    if (iter != points_.end()) {
      iter->second->UpdateTouch(*event);
      if (event->type() == ui::ET_TOUCH_RELEASED ||
          event->type() == ui::ET_TOUCH_CANCELLED)
        points_.erase(iter);
    }
  }
}

void TouchHudProjection::SetHudForRootWindowController(
    RootWindowController* controller) {
  controller->set_touch_hud_projection(this);
}

void TouchHudProjection::UnsetHudForRootWindowController(
    RootWindowController* controller) {
  controller->set_touch_hud_projection(NULL);
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


<commit_before>#ifndef RBX_EXCEPTION_POINT_HPP
#define RBX_EXCEPTION_POINT_HPP

#include <setjmp.h>

#include "windows_compat.h"

namespace rubinius {
  class NativeMethodEnvironment;

  class ExceptionPoint {
    bool jumped_to_;
    ExceptionPoint* previous_;

  public:
    jmp_buf __jump_buffer;

  public:
    ExceptionPoint(NativeMethodEnvironment* env);

    bool jumped_to() {
      return jumped_to_;
    }

    void reset() {
      jumped_to_ = false;
    }

    void return_to(NativeMethodEnvironment* env);

    void unwind_to_previous(NativeMethodEnvironment* env) {
      previous_->return_to(env);
    }

    void pop(NativeMethodEnvironment* env);
  };
}

#define PLACE_EXCEPTION_POINT(ep) set_jump(ep.__jump_buffer)

#endif
<commit_msg>Store file and line number where exception point is placed<commit_after>#ifndef RBX_EXCEPTION_POINT_HPP
#define RBX_EXCEPTION_POINT_HPP

#include <setjmp.h>

#include "windows_compat.h"

namespace rubinius {
  class NativeMethodEnvironment;

  class ExceptionPoint {
    bool jumped_to_;
    ExceptionPoint* previous_;

  public:
    jmp_buf __jump_buffer;
    const char* file;
    int line;

  public:
    ExceptionPoint(NativeMethodEnvironment* env);

    bool jumped_to() {
      return jumped_to_;
    }

    void reset() {
      jumped_to_ = false;
    }

    void return_to(NativeMethodEnvironment* env);

    void unwind_to_previous(NativeMethodEnvironment* env) {
      previous_->return_to(env);
    }

    void pop(NativeMethodEnvironment* env);
  };
}

#define PLACE_EXCEPTION_POINT(ep) ep.file = __FILE__; ep.line = __LINE__; set_jump(ep.__jump_buffer)

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include "rglob.h"

using namespace std;
using namespace rglob;

static void validate(string p, string t, bool x = true, bool pp = false);

/*
	Both the main and validate functions below illustrate some sample patterns
	and targets, as well as providing a useful framework for simple testing.

	N.B. - it should be emphasized that "globs" are NOT "regexps", and in
	particular, a single character class, no matter how complex, will match AT
	MOST a SINGLE [UTF-8] character / "code point" from the target string.
*/
int main(int argc, char* argv[])
{
	// validate the simplest patterns...
	validate("abc", "abc");
	validate("abc", "abC", false);
	validate("ab?", "abC");
	validate("*bar", "foobar");
	validate("*ba?", "foobaR");

	// ... now for some character classes
	validate("[A-Z][0-9][^0-9]", "B2B");
	validate("[A-Z][0-9][^0-9]", "B2Bx", false);
	validate("[A-Z][0-9][^0-9]*", "B2Bx-ray");
	validate("[A-Z][0-9][^0-9]", "B23", false);

	// can you spot why this will throw an exception?
	validate("[A-Z][0-9][^0-9*", "B2Bx-ray");

	// how about some fun?
	validate("a?c*def*[^]ABx-z]*", "abcYdefABBA Van Halen");
	validate("a?c*def[^]ABx-z]*", "abcYdefABBA Van Halen", false);
	validate("a?c*def[]ABx-z]*", "abcYdefABBA Van Halen");

	// the next two validations are really about showing the equivalence between
	// two different ways of inserting Unicode chars into strings (hard vs easy)
	// (they really ARE the same pattern, see the pretty_print output yourself!)
	validate(u8"*[\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F]BAR", u8"fu\u041f \u0444BAR", true, true);
	validate(u8"*[А-Я а-я][А-Я а-я][А-Я а-я]BAR", u8"fuП фBAR", true, true);
	return 0;
}

/*
	validate "wraps" pattern compiling, optional pretty-printing, and matching,
	displaying a [generally] single-line/test formatted report, while catching
	and reporting any of the exceptions thrown by rglob.

	Usage
	=====
	p	pattern to compile and match against
	t	target text for matching
	x	expected result of match (true -> MATCH, false -> FAIL!)
	pp	pretty_print the compiled version of this pattern

	N.B. - whether or not the handy "u8" from of string literals is used, both
	the pattern and target will be interpreted as containing Unicode in UTF-8!
*/
static void validate(string p, string t, bool x, bool pp)
{
	auto mf = [](bool tf) { return tf ? "MATCH" : "FAIL!"; };
	glob g;
	try {
		g.compile(p);
	} catch (invalid_argument& e) {
		cerr << "*** Compiling " << p << " => std::invalid_argument: " << e.what() << endl;
		return; // we're outta here - after a compile fail, "match" is undefined
	} catch (length_error& e) {
		cerr << "*** Compiling " << p << " => std::length_error: " << e.what() << endl;
		return; // we're outta here - after a compile fail, "match" is undefined
	}
	if (pp)
		cout << "Pretty_print of " << p << ':' << endl, g.pretty_print(cout);
	try {
		const auto r = g.match(t);
		cout << "Wanted "
			<< mf(x) << ", got "
			<< mf(r) << " ("
			<< ((r != x) ? "BZZZT!" : "OK") << ") with "
			<< t << " -> "
			<< p << endl;
	} catch (invalid_argument& e) {
		cerr << "*** Matching " << t << " => std::invalid_argument: " << e.what() << endl;
	}
}
<commit_msg>Natural languages have so many sources of ambiguities...<commit_after>#include <iostream>
#include "rglob.h"

using namespace std;
using namespace rglob;

static void validate(string p, string t, bool x = true, bool pp = false);

/*
	Both the main and validate functions below illustrate some sample patterns
	and targets, as well as providing a useful framework for simple testing.

	N.B. - it should be emphasized that "globs" are NOT "regexps", and in
	particular, a single character class, no matter how complex, will match AT
	MOST a SINGLE [UTF-8] character / "code point" from the target string - no
	number of '+' or '*' chars after the closing ']' will change this, because
	well, "glob" patterns really AREN'T regular expressions (like we said).
*/
int main(int argc, char* argv[])
{
	// validate the simplest patterns...
	validate("abc", "abc");
	validate("abc", "abC", false);
	validate("ab?", "abC");
	validate("*bar", "foobar");
	validate("*ba?", "foobaR");

	// ... now for some character classes
	validate("[A-Z][0-9][^0-9]", "B2B");
	validate("[A-Z][0-9][^0-9]", "B2Bx", false);
	validate("[A-Z][0-9][^0-9]*", "B2Bx-ray");
	validate("[A-Z][0-9][^0-9]", "B23", false);

	// can you spot why this will throw an exception?
	validate("[A-Z][0-9][^0-9*", "B2Bx-ray");

	// how about some fun?
	validate("a?c*def*[^]ABx-z]*", "abcYdefABBA Van Halen");
	validate("a?c*def[^]ABx-z]*", "abcYdefABBA Van Halen", false);
	validate("a?c*def[]ABx-z]*", "abcYdefABBA Van Halen");

	// the next two validations are really about showing the equivalence between
	// two different ways of inserting Unicode chars into strings (hard vs easy)
	// (they really ARE the same pattern, see the pretty_print output yourself!)
	validate(u8"*[\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F][\u0410-\u042F \u0430-\u044F]BAR", u8"fu\u041f \u0444BAR", true, true);
	validate(u8"*[А-Я а-я][А-Я а-я][А-Я а-я]BAR", u8"fuП фBAR", true, true);
	return 0;
}

/*
	validate "wraps" pattern compiling, optional pretty-printing, and matching,
	displaying a [generally] single-line/test formatted report, while catching
	and reporting any of the exceptions thrown by rglob.

	Usage
	=====
	p	pattern to compile and match against
	t	target text for matching
	x	expected result of match (true -> MATCH, false -> FAIL!)
	pp	pretty_print the compiled version of this pattern

	N.B. - whether or not the handy "u8" from of string literals is used, both
	the pattern and target will be interpreted as containing Unicode in UTF-8!
*/
static void validate(string p, string t, bool x, bool pp)
{
	auto mf = [](bool tf) { return tf ? "MATCH" : "FAIL!"; };
	glob g;
	try {
		g.compile(p);
	} catch (invalid_argument& e) {
		cerr << "*** Compiling " << p << " => std::invalid_argument: " << e.what() << endl;
		return; // we're outta here - after a compile fail, "match" is undefined
	} catch (length_error& e) {
		cerr << "*** Compiling " << p << " => std::length_error: " << e.what() << endl;
		return; // we're outta here - after a compile fail, "match" is undefined
	}
	if (pp)
		cout << "Pretty_print of " << p << ':' << endl, g.pretty_print(cout);
	try {
		const auto r = g.match(t);
		cout << "Wanted "
			<< mf(x) << ", got "
			<< mf(r) << " ("
			<< ((r != x) ? "BZZZT!" : "OK") << ") with "
			<< t << " -> "
			<< p << endl;
	} catch (invalid_argument& e) {
		cerr << "*** Matching " << t << " => std::invalid_argument: " << e.what() << endl;
	}
}
<|endoftext|>


<commit_before>#include "vvLoadDataReaction.h"

#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCoreUtilities.h"
#include "pqObjectBuilder.h"
#include "pqPipelineRepresentation.h"
#include "pqPipelineSource.h"
#include "pqServer.h"
#include "pqView.h"
#include "vtkDataObject.h"
#include "vtkPVArrayInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyManager.h"
#include "vtkSMReaderFactory.h"

#include <QFileDialog>
//-----------------------------------------------------------------------------
vvLoadDataReaction::vvLoadDataReaction(QAction* parentAction)
  : Superclass(parentAction)
{
  QObject::connect(this, SIGNAL(loadedData(pqPipelineSource*)),
    this, SLOT(onDataLoaded(pqPipelineSource*)));
}

//-----------------------------------------------------------------------------
vvLoadDataReaction::~vvLoadDataReaction()
{
}

//-----------------------------------------------------------------------------
void vvLoadDataReaction::onDataLoaded(pqPipelineSource* source)
{
  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();

  if (this->PreviousSource)
    {
    builder->destroy(this->PreviousSource);
    }
  Q_ASSERT(this->PreviousSource == NULL);

  this->PreviousSource = source;
  pqActiveObjects::instance().setActiveSource(source);
  pqPipelineRepresentation* repr = qobject_cast<pqPipelineRepresentation*>(
    builder->createDataRepresentation(
    source->getOutputPort(0), pqActiveObjects::instance().activeView()));
  if (!repr)
    {
    qWarning("Failed to create representation");
    return;
    }
  vtkSMPropertyHelper(repr->getProxy(), "Representation").Set("Points");

  // color by "intensity" if array is present.
  vtkPVDataInformation* info = repr->getInputDataInformation();
  vtkPVArrayInformation* arrayInfo =
    info->GetPointDataInformation()->GetArrayInformation("intensity");
  if (arrayInfo !=NULL)
    {
    repr->colorByArray("intensity", vtkDataObject::FIELD_ASSOCIATION_POINTS);
    }
  repr->getProxy()->UpdateVTKObjects();
  repr->renderViewEventually();
  pqActiveObjects::instance().activeView()->resetDisplay();
}

//-----------------------------------------------------------------------------
pqPipelineSource* vvLoadDataReaction::loadData()
{
  pqServer* server = pqActiveObjects::instance().activeServer();
  vtkSMReaderFactory* readerFactory =
    vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
  QString filters = readerFactory->GetSupportedFileTypes(server->session());
  if (!filters.isEmpty())
    {
    filters += ";;";
    }
  filters += "All files (*)";

 QString fileName = QFileDialog::getOpenFileName(
    pqCoreUtilities::mainWidget(), tr("Open File"), QString(), filters);
 if (!fileName.isEmpty())
   {
   QStringList files;
   files << fileName;
   return pqLoadDataReaction::loadData(files);
   }
 return NULL;
}
<commit_msg>Disable InterpolateScalarsBeforeMapping after loading the point cloud data<commit_after>#include "vvLoadDataReaction.h"

#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCoreUtilities.h"
#include "pqObjectBuilder.h"
#include "pqPipelineRepresentation.h"
#include "pqPipelineSource.h"
#include "pqServer.h"
#include "pqView.h"
#include "vtkDataObject.h"
#include "vtkPVArrayInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMProxy.h"
#include "vtkSMProxyManager.h"
#include "vtkSMReaderFactory.h"

#include <QFileDialog>
//-----------------------------------------------------------------------------
vvLoadDataReaction::vvLoadDataReaction(QAction* parentAction)
  : Superclass(parentAction)
{
  QObject::connect(this, SIGNAL(loadedData(pqPipelineSource*)),
    this, SLOT(onDataLoaded(pqPipelineSource*)));
}

//-----------------------------------------------------------------------------
vvLoadDataReaction::~vvLoadDataReaction()
{
}

//-----------------------------------------------------------------------------
void vvLoadDataReaction::onDataLoaded(pqPipelineSource* source)
{
  pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();

  if (this->PreviousSource)
    {
    builder->destroy(this->PreviousSource);
    }
  Q_ASSERT(this->PreviousSource == NULL);

  this->PreviousSource = source;
  pqActiveObjects::instance().setActiveSource(source);
  pqPipelineRepresentation* repr = qobject_cast<pqPipelineRepresentation*>(
    builder->createDataRepresentation(
    source->getOutputPort(0), pqActiveObjects::instance().activeView()));
  if (!repr)
    {
    qWarning("Failed to create representation");
    return;
    }

  vtkSMPropertyHelper(repr->getProxy(), "Representation").Set("Points");
  vtkSMPropertyHelper(repr->getProxy(), "InterpolateScalarsBeforeMapping").Set(0);

  // color by "intensity" if array is present.
  vtkPVDataInformation* info = repr->getInputDataInformation();
  vtkPVArrayInformation* arrayInfo =
    info->GetPointDataInformation()->GetArrayInformation("intensity");
  if (arrayInfo !=NULL)
    {
    repr->colorByArray("intensity", vtkDataObject::FIELD_ASSOCIATION_POINTS);
    }

  repr->getProxy()->UpdateVTKObjects();
  repr->renderViewEventually();
  pqActiveObjects::instance().activeView()->resetDisplay();
}

//-----------------------------------------------------------------------------
pqPipelineSource* vvLoadDataReaction::loadData()
{
  pqServer* server = pqActiveObjects::instance().activeServer();
  vtkSMReaderFactory* readerFactory =
    vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
  QString filters = readerFactory->GetSupportedFileTypes(server->session());
  if (!filters.isEmpty())
    {
    filters += ";;";
    }
  filters += "All files (*)";

 QString fileName = QFileDialog::getOpenFileName(
    pqCoreUtilities::mainWidget(), tr("Open File"), QString(), filters);
 if (!fileName.isEmpty())
   {
   QStringList files;
   files << fileName;
   return pqLoadDataReaction::loadData(files);
   }
 return NULL;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "CPUSPHFluidForceFieldWithOpenCL.h"

void CPUSPHFluidForceFieldWithOpenCL::addForce(unsigned int _gsize, const _device_pointer _cells, const _device_pointer _cellGhost, GPUSPHFluid* params,_device_pointer _f, const _device_pointer _pos4, const _device_pointer _v)
{
    float3 *f = new float3[NUM_ELEMENTS];
    float4 *pos4 = new float4[NUM_ELEMENTS];
    int *cells = new int[32800+8*NUM_ELEMENTS];
    int *cellGhost = new int[32768];
    float3 *v = new float3[NUM_ELEMENTS];

    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,f,_f.m,_f.offset,sizeof(float3)*NUM_ELEMENTS);
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,pos4,_pos4.m,_pos4.offset,sizeof(float4)*NUM_ELEMENTS);
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cells,_cells.m,_cells.offset,sizeof(int)*(32800+8*NUM_ELEMENTS));
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cellGhost,_cellGhost.m,_cellGhost.offset,sizeof(int)*32768);
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,v,_v.m,_v.offset,sizeof(float3)*NUM_ELEMENTS);

    vectorAddForce(_gsize,cells,cellGhost,*params,f,pos4,v);

    sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_v.m,_v.offset,v,sizeof(float3)*NUM_ELEMENTS);
    sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_f.m,_f.offset,f,sizeof(float3)*NUM_ELEMENTS);

    delete(pos4);
    delete(cells);
    delete(cellGhost);
    delete(v);
    delete(f);
}
<commit_msg>SofaOpenCL: fixing deletings<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "CPUSPHFluidForceFieldWithOpenCL.h"

void CPUSPHFluidForceFieldWithOpenCL::addForce(unsigned int _gsize, const _device_pointer _cells, const _device_pointer _cellGhost, GPUSPHFluid* params,_device_pointer _f, const _device_pointer _pos4, const _device_pointer _v)
{
    float3 *f = new float3[NUM_ELEMENTS];
    float4 *pos4 = new float4[NUM_ELEMENTS];
    int *cells = new int[32800+8*NUM_ELEMENTS];
    int *cellGhost = new int[32768];
    float3 *v = new float3[NUM_ELEMENTS];

    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,f,_f.m,_f.offset,sizeof(float3)*NUM_ELEMENTS);
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,pos4,_pos4.m,_pos4.offset,sizeof(float4)*NUM_ELEMENTS);
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cells,_cells.m,_cells.offset,sizeof(int)*(32800+8*NUM_ELEMENTS));
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,cellGhost,_cellGhost.m,_cellGhost.offset,sizeof(int)*32768);
    sofa::gpu::opencl::myopenclEnqueueReadBuffer(0,v,_v.m,_v.offset,sizeof(float3)*NUM_ELEMENTS);

    vectorAddForce(_gsize,cells,cellGhost,*params,f,pos4,v);

    sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_v.m,_v.offset,v,sizeof(float3)*NUM_ELEMENTS);
    sofa::gpu::opencl::myopenclEnqueueWriteBuffer(0,_f.m,_f.offset,f,sizeof(float3)*NUM_ELEMENTS);

    delete [] pos4;
    delete [] cells;
    delete [] cellGhost;
    delete [] v;
    delete [] f;
}
<|endoftext|>


<commit_before>/*
 * SSLConfig.cpp
 *
 *  Created on: May 1, 2016
 *      Author: James Hong
 */

#include "tcp/SSLConfig.h"

#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cassert>
#include <iostream>
#include <sstream>

#include "Debug.h"
#include "util/file.h"

bool SSLConfig::initialized = false;
std::mutex SSLConfig::initMutex;

SSLConfig::SSLConfig(bool verifyPeers, bool isServer, std::string cert, std::string key,
		std::string caCert) {
	initMutex.lock();
	if (!initialized) {
		SSL_load_error_strings();
		SSL_library_init();
		initialized = true;
	}
	initMutex.unlock();

	const SSL_METHOD *method;
	if (isServer) {
		method = TLSv1_2_server_method();
	} else {
		method = TLSv1_2_client_method();
	}
	ctx = SSL_CTX_new(method);
	SSL_CTX_load_verify_locations(ctx, caCert.c_str(), NULL);
	if (verifyPeers) {
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
				[](int preverify_ok, X509_STORE_CTX *ctx) -> int {
			char buf[512];
			X509 *err_cert;
			int err, depth;

			err_cert = X509_STORE_CTX_get_current_cert(ctx);
			err = X509_STORE_CTX_get_error(ctx);
			depth = X509_STORE_CTX_get_error_depth(ctx);

			/*
			 * Retrieve the pointer to the SSL of the connection currently treated
			 * and the application specific data stored into the SSL object.
			 */
			X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
			if (debug) {
				std::stringstream ss;
				ss << buf;
				pdebug(ss.str());
			}

			/*
			 * At this point, err contains the last verification error. We can use
			 * it for something special
			 */
			if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT))
			{
				X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf));
				printf("issuer= %s\n", buf);
			}

			return preverify_ok;
		});
	} else {
		SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
	}
	SSL_CTX_set_timeout(ctx, 6);
	SSL_CTX_set_verify_depth(ctx, 2);
	SSL_CTX_set_cipher_list(ctx, "HIGH");
	SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);

	if (!file_exists(cert)) {
		throw std::invalid_argument("cert not found: " + cert);
	}
	if (!file_exists(key)) {
		throw std::invalid_argument("key not found: " + key);
	}

	/* Set the key and cert */
	if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) < 0) {
		ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
	}

	if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) < 0) {
		ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
	}
}

SSLConfig::~SSLConfig() {
	SSL_CTX_free(ctx);
	ERR_free_strings();
	EVP_cleanup();
}

SSL_CTX *SSLConfig::getCtx() {
	return ctx;
}

<commit_msg>Add comment.<commit_after>/*
 * SSLConfig.cpp
 *
 *  Created on: May 1, 2016
 *      Author: James Hong
 */

#include "tcp/SSLConfig.h"

#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cassert>
#include <iostream>
#include <sstream>

#include "Debug.h"
#include "util/file.h"

bool SSLConfig::initialized = false;
std::mutex SSLConfig::initMutex;

SSLConfig::SSLConfig(bool verifyPeers, bool isServer, std::string cert, std::string key,
		std::string caCert) {
	initMutex.lock();
	if (!initialized) {
		SSL_load_error_strings();
		SSL_library_init();
		initialized = true;
	}
	initMutex.unlock();

	const SSL_METHOD *method;
	if (isServer) {
		method = TLSv1_2_server_method();
	} else {
		method = TLSv1_2_client_method();
	}
	ctx = SSL_CTX_new(method);
	SSL_CTX_load_verify_locations(ctx, caCert.c_str(), NULL);
	if (verifyPeers) {
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
				[](int preverify_ok, X509_STORE_CTX *ctx) -> int {
			char buf[512];
			X509 *err_cert;
			int err, depth;

			err_cert = X509_STORE_CTX_get_current_cert(ctx);
			err = X509_STORE_CTX_get_error(ctx);
			depth = X509_STORE_CTX_get_error_depth(ctx);

			/*
			 * TODO: use fields to identify gateway, controller, applications
			 */

			/*
			 * Retrieve the pointer to the SSL of the connection currently treated
			 * and the application specific data stored into the SSL object.
			 */
			X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
			if (debug) {
				std::stringstream ss;
				ss << buf;
				pdebug(ss.str());
			}

			/*
			 * At this point, err contains the last verification error. We can use
			 * it for something special
			 */
			if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT))
			{
				X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf));
				printf("issuer= %s\n", buf);
			}

			return preverify_ok;
		});
	} else {
		SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
	}
	SSL_CTX_set_timeout(ctx, 6);
	SSL_CTX_set_verify_depth(ctx, 2);
	SSL_CTX_set_cipher_list(ctx, "HIGH");
	SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);

	if (!file_exists(cert)) {
		throw std::invalid_argument("cert not found: " + cert);
	}
	if (!file_exists(key)) {
		throw std::invalid_argument("key not found: " + key);
	}

	/* Set the key and cert */
	if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) < 0) {
		ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
	}

	if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) < 0) {
		ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
	}
}

SSLConfig::~SSLConfig() {
	SSL_CTX_free(ctx);
	ERR_free_strings();
	EVP_cleanup();
}

SSL_CTX *SSLConfig::getCtx() {
	return ctx;
}

<|endoftext|>


<commit_before>
/*

 passiveLocationPush

 Example app using samsonClient lib
 It generates random xml documents simulating information from OSS Passive Location pilot

 AUTHOR: Andreu Urruela

 */

#include <stdio.h>      // printf
#include <stdlib.h>     // exit
#include <string.h>     // memcpy
#include <iostream>     // std::cout
#include <time.h>       // strptime, struct tm

#include "au/time.h"            // au::todatString()
#include "au/string.h"          // au::str()
#include "au/Cronometer.h"      // au::Cronometer
#include "au/CommandLine.h"     // au::CommandLine

#include "samson/client/SamsonClient.h"         // samson::SamsonClient

bool random_user = false;
size_t last_user = 0;

int main( int argc , const char *argv[] )
{
   au::CommandLine cmd;
   cmd.set_flag_int( "users" , 100000 );
   cmd.parse( argc , argv );

   int num_users = cmd.get_flag_int("users");

   if( cmd.get_num_arguments() < 2 )
   {
	   fprintf(stderr,"Usage %s rate_in_messages_per_second -users <num_users>\n", argv[0] );
		exit(0);
   }

	size_t rate = atoll( argv[1] );
	size_t max_kvs = 0;
	if( argc > 2 )
	  max_kvs = atoll( argv[2] );

	// Small mini-buffer to generate
	char *line = (char*) malloc( 20000 );

	// Control of time and size
	au::Cronometer cronometer;

	size_t total_size = 0;
	size_t num_messages = 0;

	size_t theoretical_seconds = 0;

	while( true )
	{
	   // Generat 5 seconds data
	   fprintf(stderr,"Generating %d messages\n",  (int)(5 * rate) );
	   for( int i = 0 ; i < (int)(5 * rate); i++)
	   {

		  size_t user_id;
		  if( random_user )
			 user_id = rand()%num_users;
		  else
		  {
			 last_user = (last_user+1)%num_users;
			 user_id = last_user;
		  }

		  int cell = 65528;

		  if( (time(NULL)%200)> 100 )
			 cell = 65534;

			snprintf( line, 20000 ,  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns0:AMRReport xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'  xmlns:ns0='http://O2.arcanum.vitria.com'  xsi:schemaLocation='http://O2.arcanum.vitria.com AMR.xsd'>  <SubscriberReport>    <User>      <IMSI>%lu</IMSI>      <PTMSI>FB869371</PTMSI>  <CellID>%d</CellID>   <Paging>      <Location>        <LocationArea>12124</LocationArea>        <RoutingArea>134</RoutingArea>      </Location>    </Paging>  </SubscriberReport>  <Timestamp>2011-07-21T16:07:47</Timestamp></ns0:AMRReport>" , user_id , cell );

		total_size += strlen(line);
		num_messages++;

		// Emit line to the output
		std::cout << line << "\n";

	   }

	   if( max_kvs > 0 )
	     if( num_messages > max_kvs )
	       {
		 fprintf(stderr,"Finish since a limit of %lu kvs was specified. Generated %lu key-vaue\n", max_kvs ,num_messages);

		 return 0;
	       }

		// Detect if we need to sleep....
		theoretical_seconds += 5;

		size_t ellapsed_seconds = cronometer.diffTimeInSeconds();

		// Sleep some time to simulate a particular rate
		if( ellapsed_seconds < theoretical_seconds )
		{
			int sleep_seconds = theoretical_seconds - ellapsed_seconds;
			std::cerr << "Sleeping " << sleep_seconds << " seconds... num messages " << au::str(num_messages) << " size " << au::str( total_size , "bytes") << " time " << au::time_string(ellapsed_seconds) << " theoretical time " << au::time_string(theoretical_seconds)<<"\n";
			sleep( sleep_seconds );
		}

	}

}

<commit_msg>Update in the passive location generator<commit_after>
/*

 passiveLocationPush

 Example app using samsonClient lib
 It generates random xml documents simulating information from OSS Passive Location pilot

 AUTHOR: Andreu Urruela

 */

#include <stdio.h>      // printf
#include <stdlib.h>     // exit
#include <string.h>     // memcpy
#include <iostream>     // std::cout
#include <time.h>       // strptime, struct tm

#include "au/time.h"            // au::todatString()
#include "au/string.h"          // au::str()
#include "au/Cronometer.h"      // au::Cronometer
#include "au/CommandLine.h"     // au::CommandLine

#include "samson/client/SamsonClient.h"         // samson::SamsonClient

size_t get_user_id( size_t pos )
{
   return 666666666 + pos;
}

int main( int argc , const char *argv[] )
{
   au::CommandLine cmd;
   cmd.set_flag_uint64( "users" , 100000 );
   cmd.set_flag_uint64( "num" , 0 );  // Number of messages
   cmd.set_flag_boolean( "random" );     // Generate a message for all users
   cmd.parse( argc , argv );

   size_t num_users = cmd.get_flag_uint64("users");
   size_t num       = cmd.get_flag_uint64("num");
   bool random_user = cmd.get_flag_bool("random");

   srand( time(NULL) );

   if( cmd.get_num_arguments() < 2 )
   {
	   fprintf(stderr,"Usage %s rate_in_messages_per_second -users <num_users> -num <max_num_messages> -random \n", argv[0] );
		exit(0);
   }

   size_t rate = atoll( cmd.get_argument(1).c_str() );

   fprintf(stderr, "Running generator with rate=%lu num=%lu users=%lu\n" , rate , num , num_users );

   // Small mini-buffer to generate
	char *line = (char*) malloc( 20000 );

	// Control of time and size
	au::Cronometer cronometer;

   size_t last_user = 0;

   size_t total_size = 0;
   size_t num_messages = 0;

   size_t theoretical_seconds = 0;

	while( true )
	{
	   // Generat 5 seconds data
	   fprintf(stderr,"Generating %d messages ( mesages in 5 seconds at %lu events/s ) \n",  (int)(5 * rate) , rate );

	   for( int i = 0 ; i < (int)(5 * rate); i++)
	   {

		  size_t user_id;
		  if( random_user )
			 user_id = get_user_id( rand()%num_users );
		  else
		  {
			 last_user = get_user_id( (last_user+1)%num_users );
			 user_id = last_user;
		  }

		  int cell = 65528;

		  if( (time(NULL)%200)> 100 )
			 cell = 65534;

			snprintf( line, 20000 ,  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns0:AMRReport xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'  xmlns:ns0='http://O2.arcanum.vitria.com'  xsi:schemaLocation='http://O2.arcanum.vitria.com AMR.xsd'>  <SubscriberReport>    <User>      <IMSI>%lu</IMSI>      <PTMSI>FB869371</PTMSI>  <CellID>%d</CellID>   <Paging>      <Location>        <LocationArea>12124</LocationArea>        <RoutingArea>134</RoutingArea>      </Location>    </Paging>  </SubscriberReport>  <Timestamp>2011-07-21T16:07:47</Timestamp></ns0:AMRReport>" , user_id , cell );

		total_size += strlen(line);
		num_messages++;

		// Emit line to the output
		std::cout << line << "\n";

		if( num > 0 )
		{
		   if( num_messages >= num )
		   {
			  fprintf(stderr,"Generated %s messages" , au::str( num_messages).c_str() );
			  exit(0);
		   }
		}

	   }

	   // Detect if we need to sleep....
	   theoretical_seconds += 5;

	   size_t ellapsed_seconds = cronometer.diffTimeInSeconds();

	   // Sleep some time to simulate a particular rate
	   if( ellapsed_seconds < theoretical_seconds )
	   {
		  int sleep_seconds = theoretical_seconds - ellapsed_seconds;
		  std::cerr << "Sleeping " << sleep_seconds << " seconds... We have generate " << au::str(num_messages) << " messages with size " << au::str( total_size , "bytes") << " time " << au::time_string(ellapsed_seconds) << " theoretical time " << au::time_string(theoretical_seconds)<<"\n";
		  sleep( sleep_seconds );
	   }

	}

}

<|endoftext|>


<commit_before>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include "configure.h"
#include "conv_layer_wrapper.h"
#include <tiramisu/utils.h>

// MKL-DNN default format is NCHW according to
// https://www.tensorflow.org/performance/performance_guide

int main(int, char**)
{
    Halide::Buffer<float> input(N+K, N+K, FIn, BATCH_SIZE);
    Halide::Buffer<float> filter(K, K, FIn, FOut);
    Halide::Buffer<float> bias(FIn);
    Halide::Buffer<float> conv(N, N, FOut, BATCH_SIZE);
    Halide::Buffer<float> conv_tiramisu_buffer(N, N, FOut, BATCH_SIZE);
    Halide::Buffer<int> parameters(5);

    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    for (int y = 0; y < N+K; ++y)
        for (int x = 0; x < N+K; ++x)
            for (int z = 0; z < FIn; ++z)
	        for (int n = 0; n < BATCH_SIZE; ++n)
		    input(x, y, z, n) = 1;

    for (int z = 0; z < FIn; ++z)
        bias(z) = 1;

     for (int y = 0; y < K; ++y)
        for (int x = 0; x < K; ++x)
            for (int z = 0; z < FIn; ++z)
		for (int q = 0; q < FOut; ++q)
		    filter(x, y, z, q) = 1;

    std::cout << "\t\tBuffers initialized" << std::endl;

    unsigned int count = 0;

    // Initialize parameters[]
    parameters(0) = N;
    parameters(1) = K;
    parameters(2) = FIn;
    parameters(3) = FOut;
    parameters(4) = BATCH_SIZE;

    for (int i=0; i<NB_TESTS; i++)
    {
        auto start1 = std::chrono::high_resolution_clock::now();
	conv_tiramisu(parameters.raw_buffer(), input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(), conv_tiramisu_buffer.raw_buffer());
	auto end1 = std::chrono::high_resolution_clock::now();
	std::chrono::duration<double,std::milli> duration = end1 - start1;
	duration_vector_2.push_back(duration);
    }

    std::cout << "\t\tTiramisu conv" << ": " << median(duration_vector_2) << "; " << std::endl;
    std::cout << "\t\tResult" << ": ";
    count = 0;
    for (int y = 0; y < N+K; ++y)
        for (int x = 0; x < N+K; ++x)
            for (int z = 0; z < FIn; ++z)
	        for (int n = 0; n < BATCH_SIZE; ++n)
		    if (count < 10)
		    {
			std::cerr << conv_tiramisu_buffer(x, y, z, n) << ", ";
			count++;
		    }
    std::cout << std::endl;

    return 0;
}
<commit_msg>Update conv_layer_wrapper.cpp<commit_after>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include "configure.h"
#include "conv_layer_wrapper.h"
#include <tiramisu/utils.h>

// MKL-DNN default format is NCHW according to
// https://www.tensorflow.org/performance/performance_guide

int main(int, char **)
{

    int sizes[26][4];

    sizes[0][0] = 32;
    sizes[0][1] = 8;
    sizes[0][2] = 16;
    sizes[0][3] = 16;

    sizes[1][0] = 64;
    sizes[1][1] = 32;
    sizes[1][2] = 16;
    sizes[1][3] = 16;

    sizes[2][0] = 512;
    sizes[2][1] = 100;
    sizes[2][2] = 16;
    sizes[2][3] = 16;

    sizes[3][0] = 224;
    sizes[3][1] = 8;
    sizes[3][2] = 3;
    sizes[3][3] = 64;

    sizes[4][0] = 224;
    sizes[4][1] = 32;
    sizes[4][2] = 3;
    sizes[4][3] = 64;

    sizes[5][0] = 224;
    sizes[5][1] = 100;
    sizes[5][2] = 3;
    sizes[5][3] = 64;

    sizes[6][0] = 56;
    sizes[6][1] = 8;
    sizes[6][2] = 64;
    sizes[6][3] = 64;

    sizes[7][0] = 56;
    sizes[7][1] = 32;
    sizes[7][2] = 64;
    sizes[7][3] = 64;

    sizes[8][0] = 56;
    sizes[8][1] = 100;
    sizes[8][2] = 64;
    sizes[8][3] = 64;

    sizes[9][0] = 56;
    sizes[9][1] = 8;
    sizes[9][2] = 64;
    sizes[9][3] = 128;

    sizes[10][0] = 56;
    sizes[10][1] = 32;
    sizes[10][2] = 64;
    sizes[10][3] = 128;

    sizes[11][0] = 56;
    sizes[11][1] = 100;
    sizes[11][2] = 64;
    sizes[11][3] = 128;

    sizes[12][0] = 28;
    sizes[12][1] = 8;
    sizes[12][2] = 128;
    sizes[12][3] = 128;

    sizes[13][0] = 28;
    sizes[13][1] = 32;
    sizes[13][2] = 128;
    sizes[13][3] = 128;

    sizes[14][0] = 28;
    sizes[14][1] = 100;
    sizes[14][2] = 128;
    sizes[14][3] = 128;

    sizes[15][0] = 28;
    sizes[15][1] = 8;
    sizes[15][2] = 100;
    sizes[15][3] = 256;

    sizes[16][0] = 28;
    sizes[16][1] = 32;
    sizes[16][2] = 100;
    sizes[16][3] = 256;

    sizes[17][0] = 28;
    sizes[17][1] = 100;
    sizes[17][2] = 100;
    sizes[17][3] = 256;

    sizes[18][0] = 14;
    sizes[18][1] = 8;
    sizes[18][2] = 256;
    sizes[18][3] = 256;

    sizes[19][0] = 14;
    sizes[19][1] = 32;
    sizes[19][2] = 256;
    sizes[19][3] = 256;

    sizes[20][0] = 14;
    sizes[20][1] = 100;
    sizes[20][2] = 256;
    sizes[20][3] = 256;

    sizes[21][0] = 14;
    sizes[21][1] = 8;
    sizes[21][2] = 310;
    sizes[21][3] = 512;

    sizes[22][0] = 14;
    sizes[22][1] = 32;
    sizes[22][2] = 310;
    sizes[22][3] = 512;

    sizes[23][0] = 14;
    sizes[23][1] = 100;
    sizes[23][2] = 310;
    sizes[23][3] = 512;

    sizes[24][0] = 7;
    sizes[24][1] = 8;
    sizes[24][2] = 512;
    sizes[24][3] = 512;

    sizes[25][0] = 7;
    sizes[25][1] = 32;
    sizes[25][2] = 512;
    sizes[25][3] = 512;

    sizes[26][0] = 7;
    sizes[26][1] = 100;
    sizes[26][2] = 512;
    sizes[26][3] = 512;

    std::ofstream resultfile;
    resultfile.open("tiramisu_result.txt");

    for (int j = 0; j < 20; ++j)
    {

        int N = sizes[j][0];
        int BATCH_SIZE = sizes[j][1];
        int FIn = sizes[j][2];
        int FOut = sizes[j][3];

        Halide::Buffer<double> input(N + K, N + K, FIn, BATCH_SIZE);
        Halide::Buffer<double> filter(K, K, FIn, FOut);
        Halide::Buffer<double> bias(FIn);
        Halide::Buffer<double> conv(N, N, FOut, BATCH_SIZE);
        Halide::Buffer<double> conv_tiramisu_buffer(N, N, FOut, BATCH_SIZE);
        Halide::Buffer<int> parameters(5);

        std::vector<std::chrono::duration<double, std::milli>> duration_vector_1;
        std::vector<std::chrono::duration<double, std::milli>> duration_vector_2;

        for (int y = 0; y < N + K; ++y)
            for (int x = 0; x < N + K; ++x)
                for (int z = 0; z < FIn; ++z)
                    for (int n = 0; n < BATCH_SIZE; ++n)
                        input(x, y, z, n) = 1;

        for (int z = 0; z < FIn; ++z)
            bias(z) = 1;

        for (int y = 0; y < K; ++y)
            for (int x = 0; x < K; ++x)
                for (int z = 0; z < FIn; ++z)
                    for (int q = 0; q < FOut; ++q)
                        filter(x, y, z, q) = 1;

        std::cout << "\t\tBuffers initialized" << std::endl;

        unsigned int count = 0;

        // Initialize parameters[]
        parameters(0) = N;
        parameters(1) = K;
        parameters(2) = FIn;
        parameters(3) = FOut;
        parameters(4) = BATCH_SIZE;

        for (int i = 0; i < NB_TESTS; i++)
        {
            auto start1 = std::chrono::high_resolution_clock::now();
            conv_tiramisu(parameters.raw_buffer(), input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(), conv_tiramisu_buffer.raw_buffer());
            auto end1 = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double, std::milli> duration = end1 - start1;
            duration_vector_2.push_back(duration);
        }

        std::cout << "\t\tTiramisu conv"
                  << ": " << median(duration_vector_2) << "; " << std::endl;

        resultfile << median(duration_vector_2) << "\n";

        std::cout << "\t\tResult"
                  << ": ";
        count = 0;
        for (int y = 0; y < N + K; ++y)
            for (int x = 0; x < N + K; ++x)
                for (int z = 0; z < FIn; ++z)
                    for (int n = 0; n < BATCH_SIZE; ++n)
                        if (count < 10)
                        {
                            std::cerr << conv_tiramisu_buffer(x, y, z, n) << ", ";
                            count++;
                        }
        std::cout << std::endl;
    }
    resultfile.close();
    return 0;
}
<|endoftext|>