blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
2ef541e7a24b1932ac25a0a5e481691afc45c04f
259b8edfeb02c1a38953213a93723f4939300078
/extensions/tree_collection/cython/py_wrapper.cpp
d7520c4566c125801458a76a1a13ac32d02c3257
[]
no_license
verajohne/treeCl
6892398acae8ac37b67168d54ca2f3e433066e6f
b1a3935807bd478cfeda1213e702d2661bb2a49a
refs/heads/master
2021-01-18T05:35:11.282714
2014-07-11T15:27:43
2014-07-11T15:27:43
null
0
0
null
null
null
null
UTF-8
C++
false
true
105,291
cpp
py_wrapper.cpp
/* Generated by Cython 0.20.1 on Thu May 8 00:40:11 2014 */ #define PY_SSIZE_T_CLEAN #ifndef CYTHON_USE_PYLONG_INTERNALS #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 0 #else #include "pyconfig.h" #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 1 #else #define CYTHON_USE_PYLONG_INTERNALS 0 #endif #endif #endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02040000 #error Cython requires Python 2.4+. #else #define CYTHON_ABI "0_20_1" #include <stddef.h> /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if CYTHON_COMPILING_IN_PYPY #define Py_OptimizeFlag 0 #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ (PyErr_Format(PyExc_TypeError, \ "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ (PyObject*)0)) #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ !PyComplex_Check(o)) #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #define __Pyx_PyIndex_Check PyIndex_Check #endif #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #if PY_VERSION_HEX < 0x02060000 #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_VERSION_HEX < 0x02060000 #define Py_TPFLAGS_HAVE_VERSION_TAG 0 #endif #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) #define Py_TPFLAGS_IS_ABSTRACT 0 #endif #if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytes_CheckExact PyString_CheckExact #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_DecodeEscape PyString_DecodeEscape #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_Size PyString_Size #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_Repr PyString_Repr #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) #else #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) #else #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) #else #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is a quiet NaN. */ float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #define __PYX_HAVE__tree_collection #define __PYX_HAVE_API__tree_collection #include "string.h" #include <string> #include "ios" #include "new" #include "stdexcept" #include "typeinfo" #include <utility> #include <set> #include <vector> #include <map> #include "wrapper.cpp" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "ascii # for cython>=0.19" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ (sizeof(type) < sizeof(Py_ssize_t)) || \ (sizeof(type) > sizeof(Py_ssize_t) && \ likely(v < (type)PY_SSIZE_T_MAX || \ v == (type)PY_SSIZE_T_MAX) && \ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ v == (type)PY_SSIZE_T_MIN))) || \ (sizeof(type) == sizeof(Py_ssize_t) && \ (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) #define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) #define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) #define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return u_end - u - 1; } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys = NULL; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; sys = PyImport_ImportModule("sys"); if (sys == NULL) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); if (default_encoding == NULL) goto bad; if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (ascii_chars_u == NULL) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } } Py_XDECREF(sys); Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return 0; bad: Py_XDECREF(sys); Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys = NULL; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (sys == NULL) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); if (default_encoding == NULL) goto bad; default_encoding_c = PyBytes_AS_STRING(default_encoding); __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(sys); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(sys); Py_XDECREF(default_encoding); return -1; } #endif #endif #ifdef __GNUC__ /* Test for GCC > 2.95 */ #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* __GNUC__ > 2 ... */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ > 2 ... */ #else /* __GNUC__ */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char *__pyx_f[] = { "py_wrapper.pyx", "stringsource", "stringsource", }; /*--- Type declarations ---*/ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil) \ if (acquire_gil) { \ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ PyGILState_Release(__pyx_gilstate_save); \ } else { \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil) \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext() \ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ #define __Pyx_XDECREF_SET(r, v) do { \ PyObject *tmp = (PyObject *) r; \ r = v; __Pyx_XDECREF(tmp); \ } while (0) #define __Pyx_DECREF_SET(r, v) do { \ PyObject *tmp = (PyObject *) r; \ r = v; __Pyx_DECREF(tmp); \ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ const char* function_name); /*proto*/ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); #ifndef __Pyx_CppExn2PyErr #include <new> #include <typeinfo> #include <stdexcept> #include <ios> static void __Pyx_CppExn2PyErr() { try { if (PyErr_Occurred()) ; // let the latest Python exn pass through and ignore the current one else throw; } catch (const std::bad_alloc& exn) { PyErr_SetString(PyExc_MemoryError, exn.what()); } catch (const std::bad_cast& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::domain_error& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::invalid_argument& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::ios_base::failure& exn) { PyErr_SetString(PyExc_IOError, exn.what()); } catch (const std::out_of_range& exn) { PyErr_SetString(PyExc_IndexError, exn.what()); } catch (const std::overflow_error& exn) { PyErr_SetString(PyExc_OverflowError, exn.what()); } catch (const std::range_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::underflow_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::exception& exn) { PyErr_SetString(PyExc_RuntimeError, exn.what()); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); } } #endif static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); typedef struct { int code_line; PyCodeObject* code_object; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'libc.string' */ /* Module declarations from 'libcpp.string' */ /* Module declarations from 'libcpp.utility' */ /* Module declarations from 'libcpp.pair' */ /* Module declarations from 'libcpp.set' */ /* Module declarations from 'libcpp.vector' */ /* Module declarations from 'libcpp.map' */ /* Module declarations from 'libcpp' */ /* Module declarations from 'wrapper' */ /* Module declarations from 'tree_collection' */ static std::string __pyx_convert_string_from_py_(PyObject *); /*proto*/ static PyObject *__pyx_convert_string_to_py_(const std::string &); /*proto*/ #define __Pyx_MODULE_NAME "tree_collection" int __pyx_module_is_main_tree_collection = 0; /* Implementation of 'tree_collection' */ static PyObject *__pyx_pf_15tree_collection_compute(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_matrices, PyObject *__pyx_v_mapping, PyObject *__pyx_v_labels, PyObject *__pyx_v_tree, PyObject *__pyx_v_iter, PyObject *__pyx_v_keep_topology, PyObject *__pyx_v_quiet); /* proto */ static PyObject *__pyx_pf_15tree_collection_2fit(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_matrices, PyObject *__pyx_v_mapping, PyObject *__pyx_v_labels, PyObject *__pyx_v_tree); /* proto */ static char __pyx_k_r[] = "_r"; static char __pyx_k_fit[] = "fit"; static char __pyx_k_iter[] = "iter"; static char __pyx_k_main[] = "__main__"; static char __pyx_k_test[] = "__test__"; static char __pyx_k_tree[] = "tree"; static char __pyx_k_quiet[] = "quiet"; static char __pyx_k_labels[] = "labels"; static char __pyx_k_compute[] = "compute"; static char __pyx_k_mapping[] = "mapping"; static char __pyx_k_matrices[] = "matrices"; static char __pyx_k_py_result[] = "py_result"; static char __pyx_k_keep_topology[] = "keep_topology"; static char __pyx_k_tree_collection[] = "tree_collection"; static char __pyx_k_arg_iter_wrong_type[] = "arg iter wrong type"; static char __pyx_k_arg_tree_wrong_type[] = "arg tree wrong type"; static char __pyx_k_arg_quiet_wrong_type[] = "arg quiet wrong type"; static char __pyx_k_arg_labels_wrong_type[] = "arg labels wrong type"; static char __pyx_k_arg_mapping_wrong_type[] = "arg mapping wrong type"; static char __pyx_k_arg_matrices_wrong_type[] = "arg matrices wrong type"; static char __pyx_k_arg_keep_topology_wrong_type[] = "arg keep_topology wrong type"; static char __pyx_k_Users_kgori_git_repos_github_tr[] = "/Users/kgori/git_repos/github/treeCl/extensions/tree_collection/cython/py_wrapper.pyx"; static PyObject *__pyx_kp_s_Users_kgori_git_repos_github_tr; static PyObject *__pyx_kp_s_arg_iter_wrong_type; static PyObject *__pyx_kp_s_arg_keep_topology_wrong_type; static PyObject *__pyx_kp_s_arg_labels_wrong_type; static PyObject *__pyx_kp_s_arg_mapping_wrong_type; static PyObject *__pyx_kp_s_arg_matrices_wrong_type; static PyObject *__pyx_kp_s_arg_quiet_wrong_type; static PyObject *__pyx_kp_s_arg_tree_wrong_type; static PyObject *__pyx_n_s_compute; static PyObject *__pyx_n_s_fit; static PyObject *__pyx_n_s_iter; static PyObject *__pyx_n_s_keep_topology; static PyObject *__pyx_n_s_labels; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mapping; static PyObject *__pyx_n_s_matrices; static PyObject *__pyx_n_s_py_result; static PyObject *__pyx_n_s_quiet; static PyObject *__pyx_n_s_r; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_tree; static PyObject *__pyx_n_s_tree_collection; static PyObject *__pyx_int_5; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__3; static PyObject *__pyx_codeobj__2; static PyObject *__pyx_codeobj__4; /* "py_wrapper.pyx":17 * # char * _cast_const_away(char *) * * def compute(bytes matrices , bytes mapping , bytes labels , bytes tree , iter=5 , keep_topology=False , quiet=True ): # <<<<<<<<<<<<<< * """ This is a wrapper to the MinSquareTreeCollection::compute function * */ /* Python wrapper */ static PyObject *__pyx_pw_15tree_collection_1compute(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_15tree_collection_compute[] = " This is a wrapper to the MinSquareTreeCollection::compute function\n\n :param matrices: Matrix of distances (upper triangle) and variances (lower triangle)\n :type matrices: str.\n :param mapping: Genome map\n :type mapping: str.\n :param labels: A list of species labels\n :type labels: str.\n :param tree: The guide tree in newick format\n :type tree: str.\n :param iter: Number of iterations to do in the compute (resets on each tree swap)\n :type iter: int.\n :param keep_topology: If True, will assess the guidetree with no optimisation\n :type keep_topology: bool.\n :param quiet: If True, this will suppress printing progress to the screen\n :type quiet: bool.\n\n :returns: str -- the output tree, float -- the sum of squared residuals\n\n "; static PyMethodDef __pyx_mdef_15tree_collection_1compute = {__Pyx_NAMESTR("compute"), (PyCFunction)__pyx_pw_15tree_collection_1compute, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_15tree_collection_compute)}; static PyObject *__pyx_pw_15tree_collection_1compute(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_matrices = 0; PyObject *__pyx_v_mapping = 0; PyObject *__pyx_v_labels = 0; PyObject *__pyx_v_tree = 0; PyObject *__pyx_v_iter = 0; PyObject *__pyx_v_keep_topology = 0; PyObject *__pyx_v_quiet = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("compute (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_matrices,&__pyx_n_s_mapping,&__pyx_n_s_labels,&__pyx_n_s_tree,&__pyx_n_s_iter,&__pyx_n_s_keep_topology,&__pyx_n_s_quiet,0}; PyObject* values[7] = {0,0,0,0,0,0,0}; values[4] = ((PyObject *)__pyx_int_5); values[5] = ((PyObject *)Py_False); values[6] = ((PyObject *)Py_True); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_matrices)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mapping)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute", 0, 4, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_labels)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute", 0, 4, 7, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tree)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute", 0, 4, 7, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_iter); if (value) { values[4] = value; kw_args--; } } case 5: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_keep_topology); if (value) { values[5] = value; kw_args--; } } case 6: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_quiet); if (value) { values[6] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_matrices = ((PyObject*)values[0]); __pyx_v_mapping = ((PyObject*)values[1]); __pyx_v_labels = ((PyObject*)values[2]); __pyx_v_tree = ((PyObject*)values[3]); __pyx_v_iter = values[4]; __pyx_v_keep_topology = values[5]; __pyx_v_quiet = values[6]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("compute", 0, 4, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("tree_collection.compute", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_matrices), (&PyBytes_Type), 1, "matrices", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mapping), (&PyBytes_Type), 1, "mapping", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), (&PyBytes_Type), 1, "labels", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tree), (&PyBytes_Type), 1, "tree", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_15tree_collection_compute(__pyx_self, __pyx_v_matrices, __pyx_v_mapping, __pyx_v_labels, __pyx_v_tree, __pyx_v_iter, __pyx_v_keep_topology, __pyx_v_quiet); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15tree_collection_compute(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_matrices, PyObject *__pyx_v_mapping, PyObject *__pyx_v_labels, PyObject *__pyx_v_tree, PyObject *__pyx_v_iter, PyObject *__pyx_v_keep_topology, PyObject *__pyx_v_quiet) { std::pair<std::string,double> __pyx_v__r; PyObject *__pyx_v_py_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; std::string __pyx_t_4; std::string __pyx_t_5; std::string __pyx_t_6; std::string __pyx_t_7; int __pyx_t_8; bool __pyx_t_9; bool __pyx_t_10; std::pair<std::string,double> __pyx_t_11; PyObject *__pyx_t_12 = NULL; PyObject *__pyx_t_13 = NULL; PyObject *__pyx_t_14 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("compute", 0); /* "py_wrapper.pyx":38 * * """ * assert isinstance(matrices, bytes), 'arg matrices wrong type' # <<<<<<<<<<<<<< * assert isinstance(mapping, bytes), 'arg mapping wrong type' * assert isinstance(labels, bytes), 'arg labels wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_matrices); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_matrices_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":39 * """ * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' # <<<<<<<<<<<<<< * assert isinstance(labels, bytes), 'arg labels wrong type' * assert isinstance(tree, bytes), 'arg tree wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_mapping); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_mapping_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":40 * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' * assert isinstance(labels, bytes), 'arg labels wrong type' # <<<<<<<<<<<<<< * assert isinstance(tree, bytes), 'arg tree wrong type' * assert isinstance(iter, (int, long)), 'arg iter wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_labels); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_labels_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":41 * assert isinstance(mapping, bytes), 'arg mapping wrong type' * assert isinstance(labels, bytes), 'arg labels wrong type' * assert isinstance(tree, bytes), 'arg tree wrong type' # <<<<<<<<<<<<<< * assert isinstance(iter, (int, long)), 'arg iter wrong type' * assert isinstance(keep_topology, (int, long)), 'arg keep_topology wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_tree); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_tree_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":42 * assert isinstance(labels, bytes), 'arg labels wrong type' * assert isinstance(tree, bytes), 'arg tree wrong type' * assert isinstance(iter, (int, long)), 'arg iter wrong type' # <<<<<<<<<<<<<< * assert isinstance(keep_topology, (int, long)), 'arg keep_topology wrong type' * assert isinstance(quiet, (int, long)), 'arg quiet wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyInt_Check(__pyx_v_iter); if (!__pyx_t_1) { __pyx_t_2 = PyLong_Check(__pyx_v_iter); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (unlikely(!(__pyx_t_3 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_iter_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":43 * assert isinstance(tree, bytes), 'arg tree wrong type' * assert isinstance(iter, (int, long)), 'arg iter wrong type' * assert isinstance(keep_topology, (int, long)), 'arg keep_topology wrong type' # <<<<<<<<<<<<<< * assert isinstance(quiet, (int, long)), 'arg quiet wrong type' * */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_3 = PyInt_Check(__pyx_v_keep_topology); if (!__pyx_t_3) { __pyx_t_1 = PyLong_Check(__pyx_v_keep_topology); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (unlikely(!(__pyx_t_2 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_keep_topology_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":44 * assert isinstance(iter, (int, long)), 'arg iter wrong type' * assert isinstance(keep_topology, (int, long)), 'arg keep_topology wrong type' * assert isinstance(quiet, (int, long)), 'arg quiet wrong type' # <<<<<<<<<<<<<< * * */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_2 = PyInt_Check(__pyx_v_quiet); if (!__pyx_t_2) { __pyx_t_3 = PyLong_Check(__pyx_v_quiet); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_quiet_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":52 * * * _r = _compute_wrapper((<libcpp_string>matrices), (<libcpp_string>mapping), (<libcpp_string>labels), (<libcpp_string>tree), (<int>iter), (<bool>keep_topology), (<bool>quiet)) # <<<<<<<<<<<<<< * cdef list py_result = [_r.first, _r.second] * return py_result */ __pyx_t_4 = __pyx_convert_string_from_py_(__pyx_v_matrices); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_5 = __pyx_convert_string_from_py_(__pyx_v_mapping); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = __pyx_convert_string_from_py_(__pyx_v_labels); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = __pyx_convert_string_from_py_(__pyx_v_tree); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_8 = __Pyx_PyInt_As_int(__pyx_v_iter); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_v_keep_topology); if (unlikely((__pyx_t_9 == (bool)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_v_quiet); if (unlikely((__pyx_t_10 == (bool)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} try { __pyx_t_11 = compute(((std::string)__pyx_t_4), ((std::string)__pyx_t_5), ((std::string)__pyx_t_6), ((std::string)__pyx_t_7), ((int)__pyx_t_8), ((bool)__pyx_t_9), ((bool)__pyx_t_10)); } catch(...) { __Pyx_CppExn2PyErr(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v__r = __pyx_t_11; /* "py_wrapper.pyx":53 * * _r = _compute_wrapper((<libcpp_string>matrices), (<libcpp_string>mapping), (<libcpp_string>labels), (<libcpp_string>tree), (<int>iter), (<bool>keep_topology), (<bool>quiet)) * cdef list py_result = [_r.first, _r.second] # <<<<<<<<<<<<<< * return py_result * */ __pyx_t_12 = __pyx_convert_string_to_py_(__pyx_v__r.first); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_12); __pyx_t_13 = PyFloat_FromDouble(__pyx_v__r.second); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_13); __pyx_t_14 = PyList_New(2); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_14); PyList_SET_ITEM(__pyx_t_14, 0, __pyx_t_12); __Pyx_GIVEREF(__pyx_t_12); PyList_SET_ITEM(__pyx_t_14, 1, __pyx_t_13); __Pyx_GIVEREF(__pyx_t_13); __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_v_py_result = ((PyObject*)__pyx_t_14); __pyx_t_14 = 0; /* "py_wrapper.pyx":54 * _r = _compute_wrapper((<libcpp_string>matrices), (<libcpp_string>mapping), (<libcpp_string>labels), (<libcpp_string>tree), (<int>iter), (<bool>keep_topology), (<bool>quiet)) * cdef list py_result = [_r.first, _r.second] * return py_result # <<<<<<<<<<<<<< * * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_py_result); __pyx_r = __pyx_v_py_result; goto __pyx_L0; /* "py_wrapper.pyx":17 * # char * _cast_const_away(char *) * * def compute(bytes matrices , bytes mapping , bytes labels , bytes tree , iter=5 , keep_topology=False , quiet=True ): # <<<<<<<<<<<<<< * """ This is a wrapper to the MinSquareTreeCollection::compute function * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_12); __Pyx_XDECREF(__pyx_t_13); __Pyx_XDECREF(__pyx_t_14); __Pyx_AddTraceback("tree_collection.compute", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_py_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "py_wrapper.pyx":56 * return py_result * * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): # <<<<<<<<<<<<<< * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' */ /* Python wrapper */ static PyObject *__pyx_pw_15tree_collection_3fit(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_15tree_collection_3fit = {__Pyx_NAMESTR("fit"), (PyCFunction)__pyx_pw_15tree_collection_3fit, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; static PyObject *__pyx_pw_15tree_collection_3fit(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_matrices = 0; PyObject *__pyx_v_mapping = 0; PyObject *__pyx_v_labels = 0; PyObject *__pyx_v_tree = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("fit (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_matrices,&__pyx_n_s_mapping,&__pyx_n_s_labels,&__pyx_n_s_tree,0}; PyObject* values[4] = {0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_matrices)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mapping)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("fit", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_labels)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("fit", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tree)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("fit", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "fit") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); } __pyx_v_matrices = ((PyObject*)values[0]); __pyx_v_mapping = ((PyObject*)values[1]); __pyx_v_labels = ((PyObject*)values[2]); __pyx_v_tree = ((PyObject*)values[3]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("fit", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("tree_collection.fit", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_matrices), (&PyBytes_Type), 1, "matrices", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mapping), (&PyBytes_Type), 1, "mapping", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), (&PyBytes_Type), 1, "labels", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tree), (&PyBytes_Type), 1, "tree", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_15tree_collection_2fit(__pyx_self, __pyx_v_matrices, __pyx_v_mapping, __pyx_v_labels, __pyx_v_tree); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15tree_collection_2fit(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_matrices, PyObject *__pyx_v_mapping, PyObject *__pyx_v_labels, PyObject *__pyx_v_tree) { double __pyx_v__r; double __pyx_v_py_result; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; std::string __pyx_t_2; std::string __pyx_t_3; std::string __pyx_t_4; std::string __pyx_t_5; double __pyx_t_6; PyObject *__pyx_t_7 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("fit", 0); /* "py_wrapper.pyx":57 * * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): * assert isinstance(matrices, bytes), 'arg matrices wrong type' # <<<<<<<<<<<<<< * assert isinstance(mapping, bytes), 'arg mapping wrong type' * assert isinstance(labels, bytes), 'arg labels wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_matrices); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_matrices_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":58 * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' # <<<<<<<<<<<<<< * assert isinstance(labels, bytes), 'arg labels wrong type' * assert isinstance(tree, bytes), 'arg tree wrong type' */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_mapping); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_mapping_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":59 * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' * assert isinstance(labels, bytes), 'arg labels wrong type' # <<<<<<<<<<<<<< * assert isinstance(tree, bytes), 'arg tree wrong type' * */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_labels); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_labels_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":60 * assert isinstance(mapping, bytes), 'arg mapping wrong type' * assert isinstance(labels, bytes), 'arg labels wrong type' * assert isinstance(tree, bytes), 'arg tree wrong type' # <<<<<<<<<<<<<< * * */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyBytes_Check(__pyx_v_tree); if (unlikely(!(__pyx_t_1 != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_arg_tree_wrong_type); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "py_wrapper.pyx":65 * * * cdef double _r = _fit_wrapper((<libcpp_string>matrices), (<libcpp_string>mapping), (<libcpp_string>labels), (<libcpp_string>tree)) # <<<<<<<<<<<<<< * py_result = <double>_r * return py_result */ __pyx_t_2 = __pyx_convert_string_from_py_(__pyx_v_matrices); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = __pyx_convert_string_from_py_(__pyx_v_mapping); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = __pyx_convert_string_from_py_(__pyx_v_labels); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_5 = __pyx_convert_string_from_py_(__pyx_v_tree); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} try { __pyx_t_6 = fit(((std::string)__pyx_t_2), ((std::string)__pyx_t_3), ((std::string)__pyx_t_4), ((std::string)__pyx_t_5)); } catch(...) { __Pyx_CppExn2PyErr(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v__r = __pyx_t_6; /* "py_wrapper.pyx":66 * * cdef double _r = _fit_wrapper((<libcpp_string>matrices), (<libcpp_string>mapping), (<libcpp_string>labels), (<libcpp_string>tree)) * py_result = <double>_r # <<<<<<<<<<<<<< * return py_result */ __pyx_v_py_result = ((double)__pyx_v__r); /* "py_wrapper.pyx":67 * cdef double _r = _fit_wrapper((<libcpp_string>matrices), (<libcpp_string>mapping), (<libcpp_string>labels), (<libcpp_string>tree)) * py_result = <double>_r * return py_result # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __pyx_t_7 = PyFloat_FromDouble(__pyx_v_py_result); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __pyx_r = __pyx_t_7; __pyx_t_7 = 0; goto __pyx_L0; /* "py_wrapper.pyx":56 * return py_result * * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): # <<<<<<<<<<<<<< * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_7); __Pyx_AddTraceback("tree_collection.fit", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.from_py":13 * * @cname("__pyx_convert_string_from_py_") * cdef string __pyx_convert_string_from_py_(object o) except *: # <<<<<<<<<<<<<< * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) */ static std::string __pyx_convert_string_from_py_(PyObject *__pyx_v_o) { Py_ssize_t __pyx_v_length; char *__pyx_v_data; std::string __pyx_r; __Pyx_RefNannyDeclarations char *__pyx_t_1; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_convert_string_from_py_", 0); /* "string.from_py":15 * cdef string __pyx_convert_string_from_py_(object o) except *: * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) # <<<<<<<<<<<<<< * return string(data, length) * */ __pyx_t_1 = __Pyx_PyObject_AsStringAndSize(__pyx_v_o, (&__pyx_v_length)); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_data = __pyx_t_1; /* "string.from_py":16 * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) * return string(data, length) # <<<<<<<<<<<<<< * * */ __pyx_r = std::string(__pyx_v_data, __pyx_v_length); goto __pyx_L0; /* "string.from_py":13 * * @cname("__pyx_convert_string_from_py_") * cdef string __pyx_convert_string_from_py_(object o) except *: # <<<<<<<<<<<<<< * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("string.from_py.__pyx_convert_string_from_py_", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.to_py":30 * * @cname("__pyx_convert_string_to_py_") * cdef object __pyx_convert_string_to_py_(string& s): # <<<<<<<<<<<<<< * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) * */ static PyObject *__pyx_convert_string_to_py_(const std::string &__pyx_v_s) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_convert_string_to_py_", 0); /* "string.to_py":31 * @cname("__pyx_convert_string_to_py_") * cdef object __pyx_convert_string_to_py_(string& s): * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "string.to_py":30 * * @cname("__pyx_convert_string_to_py_") * cdef object __pyx_convert_string_to_py_(string& s): # <<<<<<<<<<<<<< * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("string.to_py.__pyx_convert_string_to_py_", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif __Pyx_NAMESTR("tree_collection"), 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_Users_kgori_git_repos_github_tr, __pyx_k_Users_kgori_git_repos_github_tr, sizeof(__pyx_k_Users_kgori_git_repos_github_tr), 0, 0, 1, 0}, {&__pyx_kp_s_arg_iter_wrong_type, __pyx_k_arg_iter_wrong_type, sizeof(__pyx_k_arg_iter_wrong_type), 0, 0, 1, 0}, {&__pyx_kp_s_arg_keep_topology_wrong_type, __pyx_k_arg_keep_topology_wrong_type, sizeof(__pyx_k_arg_keep_topology_wrong_type), 0, 0, 1, 0}, {&__pyx_kp_s_arg_labels_wrong_type, __pyx_k_arg_labels_wrong_type, sizeof(__pyx_k_arg_labels_wrong_type), 0, 0, 1, 0}, {&__pyx_kp_s_arg_mapping_wrong_type, __pyx_k_arg_mapping_wrong_type, sizeof(__pyx_k_arg_mapping_wrong_type), 0, 0, 1, 0}, {&__pyx_kp_s_arg_matrices_wrong_type, __pyx_k_arg_matrices_wrong_type, sizeof(__pyx_k_arg_matrices_wrong_type), 0, 0, 1, 0}, {&__pyx_kp_s_arg_quiet_wrong_type, __pyx_k_arg_quiet_wrong_type, sizeof(__pyx_k_arg_quiet_wrong_type), 0, 0, 1, 0}, {&__pyx_kp_s_arg_tree_wrong_type, __pyx_k_arg_tree_wrong_type, sizeof(__pyx_k_arg_tree_wrong_type), 0, 0, 1, 0}, {&__pyx_n_s_compute, __pyx_k_compute, sizeof(__pyx_k_compute), 0, 0, 1, 1}, {&__pyx_n_s_fit, __pyx_k_fit, sizeof(__pyx_k_fit), 0, 0, 1, 1}, {&__pyx_n_s_iter, __pyx_k_iter, sizeof(__pyx_k_iter), 0, 0, 1, 1}, {&__pyx_n_s_keep_topology, __pyx_k_keep_topology, sizeof(__pyx_k_keep_topology), 0, 0, 1, 1}, {&__pyx_n_s_labels, __pyx_k_labels, sizeof(__pyx_k_labels), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mapping, __pyx_k_mapping, sizeof(__pyx_k_mapping), 0, 0, 1, 1}, {&__pyx_n_s_matrices, __pyx_k_matrices, sizeof(__pyx_k_matrices), 0, 0, 1, 1}, {&__pyx_n_s_py_result, __pyx_k_py_result, sizeof(__pyx_k_py_result), 0, 0, 1, 1}, {&__pyx_n_s_quiet, __pyx_k_quiet, sizeof(__pyx_k_quiet), 0, 0, 1, 1}, {&__pyx_n_s_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_tree, __pyx_k_tree, sizeof(__pyx_k_tree), 0, 0, 1, 1}, {&__pyx_n_s_tree_collection, __pyx_k_tree_collection, sizeof(__pyx_k_tree_collection), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { return 0; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "py_wrapper.pyx":17 * # char * _cast_const_away(char *) * * def compute(bytes matrices , bytes mapping , bytes labels , bytes tree , iter=5 , keep_topology=False , quiet=True ): # <<<<<<<<<<<<<< * """ This is a wrapper to the MinSquareTreeCollection::compute function * */ __pyx_tuple_ = PyTuple_Pack(9, __pyx_n_s_matrices, __pyx_n_s_mapping, __pyx_n_s_labels, __pyx_n_s_tree, __pyx_n_s_iter, __pyx_n_s_keep_topology, __pyx_n_s_quiet, __pyx_n_s_r, __pyx_n_s_py_result); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(7, 0, 9, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_kgori_git_repos_github_tr, __pyx_n_s_compute, 17, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "py_wrapper.pyx":56 * return py_result * * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): # <<<<<<<<<<<<<< * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' */ __pyx_tuple__3 = PyTuple_Pack(6, __pyx_n_s_matrices, __pyx_n_s_mapping, __pyx_n_s_labels, __pyx_n_s_tree, __pyx_n_s_r, __pyx_n_s_py_result); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); __pyx_codeobj__4 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__3, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_kgori_git_repos_github_tr, __pyx_n_s_fit, 56, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_5 = PyInt_FromLong(5); if (unlikely(!__pyx_int_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC inittree_collection(void); /*proto*/ PyMODINIT_FUNC inittree_collection(void) #else PyMODINIT_FUNC PyInit_tree_collection(void); /*proto*/ PyMODINIT_FUNC PyInit_tree_collection(void) #endif { PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_tree_collection(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __Pyx_CyFunction_USED if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4(__Pyx_NAMESTR("tree_collection"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif if (__pyx_module_is_main_tree_collection) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!PyDict_GetItemString(modules, "tree_collection")) { if (unlikely(PyDict_SetItemString(modules, "tree_collection", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ /* "py_wrapper.pyx":17 * # char * _cast_const_away(char *) * * def compute(bytes matrices , bytes mapping , bytes labels , bytes tree , iter=5 , keep_topology=False , quiet=True ): # <<<<<<<<<<<<<< * """ This is a wrapper to the MinSquareTreeCollection::compute function * */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15tree_collection_1compute, NULL, __pyx_n_s_tree_collection); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_compute, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "py_wrapper.pyx":56 * return py_result * * def fit(bytes matrices , bytes mapping , bytes labels , bytes tree ): # <<<<<<<<<<<<<< * assert isinstance(matrices, bytes), 'arg matrices wrong type' * assert isinstance(mapping, bytes), 'arg mapping wrong type' */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15tree_collection_3fit, NULL, __pyx_n_s_tree_collection); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_fit, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "py_wrapper.pyx":1 * #cython: c_string_encoding=ascii # for cython>=0.19 # <<<<<<<<<<<<<< * from libcpp.string cimport string as libcpp_string * from libcpp.set cimport set as libcpp_set */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "string.to_py":30 * * @cname("__pyx_convert_string_to_py_") * cdef object __pyx_convert_string_to_py_(string& s): # <<<<<<<<<<<<<< * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) * */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { __Pyx_AddTraceback("init tree_collection", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init tree_collection"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* Runtime support code */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* CYTHON_REFNANNY */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ { \ func_type value = func(x); \ if (sizeof(target_type) < sizeof(func_type)) { \ if (unlikely(value != (func_type) (target_type) value)) { \ func_type zero = 0; \ PyErr_SetString(PyExc_OverflowError, \ (is_unsigned && unlikely(value < zero)) ? \ "can't convert negative value to " #target_type : \ "value too large to convert to " #target_type); \ return (target_type) -1; \ } \ } \ return (target_type) value; \ } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(int)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) } else if (sizeof(int) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(int)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) } else if (sizeof(int) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(long) <= sizeof(unsigned long long)) { return PyLong_FromUnsignedLongLong((unsigned long long) value); } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(long long)) { return PyLong_FromLongLong((long long) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) } else if (sizeof(long) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) } else if (sizeof(long) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } } static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); #if PY_VERSION_HEX < 0x02050000 return PyErr_Warn(NULL, message); #else return PyErr_WarnEx(NULL, message, 1); #endif } return 0; } static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = (start + end) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ 0, /*int kwonlyargcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_globals = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else /* Python 3+ has unicode identifiers */ if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else /* PY_VERSION_HEX < 0x03030000 */ if (PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_DATA_SIZE(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ return PyUnicode_AsUTF8AndSize(o, length); #endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ #endif /* PY_VERSION_HEX < 0x03030000 */ } else #endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ #if !CYTHON_COMPILING_IN_PYPY #if PY_VERSION_HEX >= 0x02060000 if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) return PyInt_AS_LONG(b); #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(b)) { case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; case 0: return 0; case 1: return ((PyLongObject*)b)->ob_digit[0]; } #endif #endif #if PY_VERSION_HEX < 0x02060000 return PyInt_AsSsize_t(b); #else return PyLong_AsSsize_t(b); #endif } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) return PyInt_FromLong((long)ival); else { unsigned char *bytes = (unsigned char *) &ival; int one = 1; int little = (int)*(unsigned char*)&one; return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); } #else return PyInt_FromSize_t(ival); #endif } #endif /* Py_PYTHON_H */
0235d6fc15310acd3476d12311d03f71fe4a2783
4661911e173f2ba160c7c4e5b9c08bb72981e9f1
/Calculator/Calculator.cpp
4a9b39bfcdc95d85fe2a229130aad44b8a7c5a12
[]
no_license
NerdSmith/Calculator
0a2c00b31c28ba81345a51094fbe151b3e255c41
72985c67bb9b00790884c7d4b91ca57469f67dd2
refs/heads/main
2023-03-13T23:35:40.275459
2021-03-03T18:31:58
2021-03-03T18:31:58
344,225,880
0
0
null
null
null
null
UTF-8
C++
false
false
1,120
cpp
Calculator.cpp
#include <iostream> int main() { double x, y; char sign; bool flag = 1; while (flag) { std::cout << "Enter X: "; std::cin >> x; std::cout << "Enter sign: "; std::cin >> sign; std::cout << "Enter Y: "; std::cin >> y; switch (sign) { case '+': { std::cout << "Result: " << (x + y) << std::endl; break; } case '-': { std::cout << "Result: " << (x - y) << std::endl; break; } case '*': { std::cout << "Result: " << (x * y) << std::endl; break; } case '/': { if (y == 0) { std::cout << "Error: division by zero" << std::endl; } else { std::cout << "Result: " << (x / y) << std::endl; } break; } default: std::cout << "Error: sign is incorrect" << std::endl; break; } std::cout << "Enter any number to continue or zero to close: "; std::cin >> flag; } }
68e81d08d75060022872d11c1b0e29a9d8ee6a8a
545c47484b4c40cccbe1f01d0878ccc66b421a82
/2020/2020_08_02/BOJ_circle.cpp
7806b38d6f9933722a11296ae3c569d64403aa68
[]
no_license
zzid/Coding-Test-Practice
93858b04647ac3cc85f5b255c0e7933841833f25
33993ac74cc4d252c6ce5cb7ea872e3a49de08c2
refs/heads/master
2023-03-03T01:03:29.711685
2021-02-14T13:47:27
2021-02-14T13:47:27
265,266,902
1
0
null
null
null
null
UTF-8
C++
false
false
2,857
cpp
BOJ_circle.cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> p; int maps[51][51]; int n,m,t; // n circles, m numbers per circle void rotate(int i, int d, int k){ if(d == 0){ // clock wise >>> for(int x=0; x<k; x++){ int temp = maps[i][m]; for(int j=m; j>1; j--){ maps[i][j] = maps[i][j-1]; } maps[i][1] = temp; } } else{// counter clock wise <<<< for(int x=0; x<k; x++){ int temp = maps[i][1]; for(int j=1; j<m; j++){ maps[i][j] = maps[i][j+1]; } maps[i][m] = temp; } } } void calc(){ vector<p> suc; for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ if(maps[i][j] == 0 ) continue; if(maps[i][j] == maps[i][j-1] && j>1){ suc.push_back({i,j}); suc.push_back({i,j-1}); } if(maps[i][j] == maps[i][j+1] && j<n){ suc.push_back({i,j}); suc.push_back({i,j+1}); } if(maps[i][j] == maps[i-1][j] && i>1){ suc.push_back({i,j}); suc.push_back({i-1,j}); } if(maps[i][j] == maps[i+1][j] && i<n){ suc.push_back({i,j}); suc.push_back({i+1,j}); } } if(maps[i][1] == maps[i][m] && maps[i][1] != 0){ suc.push_back({i,1}); suc.push_back({i,m}); } } // cout << "**** : " << suc.size() <<endl; if(suc.empty()){// average and calc int total=0, num =0; vector<p> non; for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ if(maps[i][j] !=0){ non.push_back({i,j}); total += maps[i][j]; num++; } } } float avg = (float)total / (float)num; //cout << "********* : " << avg <<endl; for(auto a : non){ if(maps[a.first][a.second] < avg) maps[a.first][a.second]++; else if(maps[a.first][a.second] > avg) maps[a.first][a.second]--; } }else{ for(auto a : suc){ maps[a.first][a.second] = 0; } } } int sum(){ int ret=0; for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ ret += maps[i][j]; } } return ret; } int main(){ scanf("%d %d %d", &n, &m, &t); for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ scanf("%d", &maps[i][j]); } } for(int i=0; i<t; i++){ int x, d, k; scanf("%d %d %d", &x, &d, &k); for(int a=1; a<=n; a++) if(a%x ==0) rotate(a,d,k); calc(); } printf("%d\n", sum()); return 0; }
cc203910d0def96cb5b2ad5b9ea26b12831e2f33
14aa16cd9080af696fbcc28e5dbc8ce0c4d2e7b2
/src/physics/material/ElementSelector.i.hh
7175054004a098acabe876c493da304dff58f455
[ "MIT", "Apache-2.0" ]
permissive
vrpascuzzi/celeritas
f8220a7d741186ade67c23dad5de872ed9e5b100
6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f
refs/heads/master
2023-08-24T21:39:50.924005
2021-04-21T08:24:57
2021-04-21T08:24:57
284,079,349
0
0
null
null
null
null
UTF-8
C++
false
false
2,539
hh
ElementSelector.i.hh
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file ElementSelector.i.hh //---------------------------------------------------------------------------// #include "base/Assert.hh" #include "base/Range.hh" #include "random/distributions/GenerateCanonical.hh" namespace celeritas { //---------------------------------------------------------------------------// /*! * Construct with material, xs calculator, and storage. */ template<class MicroXsCalc> CELER_FUNCTION ElementSelector::ElementSelector(const MaterialView& material, MicroXsCalc&& calc_micro_xs, SpanReal storage) : elements_(material.elements()) , material_xs_(0) , elemental_xs_(storage.data()) { CELER_EXPECT(!elements_.empty()); CELER_EXPECT(storage.size() >= material.num_elements()); for (auto i : range<size_type>(elements_.size())) { const real_type micro_xs = calc_micro_xs(elements_[i].element); CELER_ASSERT(micro_xs >= 0); const real_type frac = elements_[i].fraction; elemental_xs_[i] = micro_xs; material_xs_ += micro_xs * frac; } CELER_ENSURE(material_xs_ >= 0); } //---------------------------------------------------------------------------// /*! * Sample the element with the given RNG. * * To reduce register usage, this function starts with the cumulative sums and * counts backward. */ template<class Engine> CELER_FUNCTION ElementComponentId ElementSelector::operator()(Engine& rng) const { real_type accum_xs = -material_xs_ * generate_canonical(rng); size_type i = 0; size_type imax = elements_.size() - 1; for (; i != imax; ++i) { accum_xs += elements_[i].fraction * elemental_xs_[i]; if (accum_xs > 0) break; } return ElementComponentId{i}; } //---------------------------------------------------------------------------// /*! * Get individual microscopic cross sections. */ CELER_FUNCTION auto ElementSelector::elemental_micro_xs() const -> SpanConstReal { return {elemental_xs_, elements_.size()}; } //---------------------------------------------------------------------------// } // namespace celeritas
74419c90df5772875f639d49ddbd6f6bce591453
4fec1e270c892228d3b5faefc2871d7ec819f10c
/FlightData_Archive/editwindow.h
e393fd226b31c28e5a3723271804298c081da3b8
[]
no_license
bareev/FlightData_archive
b95bd1a314cefe3a42210876aaa29693811ed2f9
d11fe5b14b6b317248b1fc2067465376f5b0bbe2
refs/heads/master
2020-04-21T11:56:54.687844
2019-04-29T05:48:56
2019-04-29T05:49:04
169,545,452
0
0
null
null
null
null
UTF-8
C++
false
false
1,098
h
editwindow.h
#ifndef EDITWINDOW_H #define EDITWINDOW_H #include <wcore.h> #define ADDITIONAL_COMBO_BOX 4 namespace Ui { class EditWindow; } class EditWindow : public Wcore { Q_OBJECT public: EditWindow(); void setEdit(WhoEdit e){m_edit = e; emit newState((int) e); return;} WhoEdit getEdit(){return m_edit;} Q_INVOKABLE int newDBWrite(bool newR, QString currentR, QString currentN, QString currentP, QString currLat, QString currLon, QString currDesc); void setCB(WhoEdit e, QStringList i){if (e != noneEdit) {comboboxes.replace(int(e), i);} return;} QStringList getCB(WhoEdit e){if (e != noneEdit) {return comboboxes.at(int(e));} else {return (QStringList(""));}} void text(); Q_INVOKABLE void loadNewCB(QString txt); public slots: void newRecs(QStringList s, int t, int w); private: WhoEdit m_edit; QList<QStringList> comboboxes; signals: void newState(int e); void newRec(QVariantMap _map); void sigNewRecs(QStringList s, int t); void updateFromMain(QString txt, int w); }; #endif // EDITWINDOW_H
bd9fad851c1715495da6fefeacd91a1545190aca
41dcd61d833fcaad3ea4f48f2e9d75212fb44d78
/KeyValueStore/KeyValueStore/KeyValueStore.h
44f6d5c3972cb4e33be763b9dd8b5b656dda27c6
[]
no_license
MarinaIvIvanova/Data-structures-FMI
fff6ddf9dc2f794a91e83a05eca260cba7036fb3
e9aff0990798aba0db183b68a17d37364124ac77
refs/heads/master
2021-01-11T18:16:23.464913
2017-05-28T13:49:58
2017-05-28T13:49:58
69,332,613
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
KeyValueStore.h
#ifndef KeyValueStore_H #define KeyValueStore_H #include "Node.h" class KeyValueStore { public: KeyValueStore(); KeyValueStore(int initialCapacity); ~KeyValueStore(); KeyValueStore(const KeyValueStore &); KeyValueStore& operator=(const KeyValueStore &); void destroyArray(); int hashFunction(const char*, int); int indexOf(int, int); char* store(char*, size_t); bool load(char* key, char*& pBlock, size_t& size); void erase(char*); private: char* getKeyString(int hash, int id); void writeInFile(char* key, char* value); void eraseFromFile(char* key); Node** buckets; int capacity; int size; static int id; }; #endif
7447f24049c796c3931788b3e27cfccbc81b41a3
429fc472077e1cd3ca705eb4e45141dfb12907a0
/SPOJ/FANCY - FANCY NUMBERS.cpp
7bf9e81f5ff603efdd0a16f5d6e90b0614575bb7
[]
no_license
ahbarif/Online-Judge-Solutions
7274ba8f58198f3fd793c42aa29cf00f2aef2584
e1e5f79330a254d825ebbfe3ca99f6b12a42f052
refs/heads/master
2020-03-26T02:19:36.370567
2019-10-29T14:12:58
2019-10-29T14:12:58
144,406,117
1
0
null
null
null
null
UTF-8
C++
false
false
561
cpp
FANCY - FANCY NUMBERS.cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll dp[35]; char str[40]; int main(){ dp[0] = 1LL; for(int i = 1; i<=30; i++){ dp[i] = dp[i-1] * 2; } int t; cin>>t; while(t--){ ll ret = 1LL, cnt = 1; scanf("%s", str); for(int i = 0; str[i]; i++){ if(str[i] == str[i+1]) cnt++; else{ // cout<<"cnt = "<<cnt<<endl; ret *= dp[cnt-1]; cnt = 1; } } printf("%lld\n", ret); } }
bf683fd19a0ec548d50815726c5a81d4acd33f18
4dcf657ba90de40c5ef349af3e9ef9d6a2c5f8cb
/code-forces/1003/problemA.cpp
3d91b0e9c773ffccf902897f452a63bc6481a974
[]
no_license
andrekorol/competition
36c5f851bd70ad213e18ef49089c7e2ed3ba197c
d34f7d1af4e5b355d908fe428dae661b3c6ba50c
refs/heads/master
2021-01-01T04:58:35.786600
2019-04-26T17:18:56
2019-04-26T17:18:56
97,281,314
1
0
null
null
null
null
UTF-8
C++
false
false
467
cpp
problemA.cpp
#include <bits/stdc++.h> using namespace std; using vi = vector<int>; int main(int argc, char const *argv[]) { int n, i; cin >> n; vi V; while (cin >> i) V.push_back(i); int pockets = 0; for (i = 0; i < n; ++i) { int count = 1; for (int j = i + 1; j < n; ++j) if (V[i] == V[j]) ++count; if (count > pockets) pockets = count; } cout << pockets << '\n'; return 0; }
4d40290b50a6df2a9ce84dadcda3de2f309410e4
5b5908b0e7390933037f57960d8fa0f7137c7074
/RemComMessage.h
c662406de8969f397743193ccdfa8f367d75a797
[]
no_license
ebrenthobbs/remcom
19397eb99f69ff032756d52dfc12d0654902a52d
ea7101309f935ec9aeb8dd917e9e57659ca76940
refs/heads/master
2018-11-15T06:09:33.290877
2018-03-30T00:16:55
2018-03-30T00:16:55
105,713,027
0
0
null
null
null
null
UTF-8
C++
false
false
1,809
h
RemComMessage.h
#pragma once #include "RemCom.h" #include "Logger.h" namespace RemCom { struct RemComMessagePayload { DWORD dwCommandLength; TCHAR szWorkingDir[_MAX_PATH]; DWORD dwPriority; DWORD dwProcessId; TCHAR szMachine[_MAX_PATH]; BOOL bNoWait; DWORD dwLogonFlags; TCHAR szUser[_MAX_PATH]; TCHAR szPassword[_MAX_PATH]; }; class RemComMessage { public: RemComMessage(DWORD dwReadBufferSize, Logger* pLogger); ~RemComMessage(); RemComMessage& operator<<(const char* szString); const std::string& getCommand(std::string& command); LPCTSTR getMachine(); void setMachine(LPCTSTR machine); void setNoWait(bool noWait); bool shouldWait(); DWORD getLogonFlags(); void setLogonFlags(DWORD logonFlags); LPCTSTR getPassword(); void setPassword(LPCTSTR password); DWORD getPriority(); void setPriority(DWORD priority); DWORD getProcessId(); void setProcessId(DWORD processId); LPCTSTR getUser(); void setUser(LPCTSTR user); LPCTSTR getWorkingDirectory(); void setWorkingDirectory(LPCTSTR workingDirectory); bool receive(const HANDLE &handle); bool send(const HANDLE &handle); void createPipeName(const char* baseName, std::string& pipeName); private: Logger* m_pLogger; RemComMessagePayload m_payload; std::stringstream m_command; DWORD m_dwReadBufferSize; LPBYTE m_readBuffer; bool readAck(const HANDLE &pipe); bool receiveCommandText(const HANDLE &pipe); bool receiveHeader(const HANDLE &pipe); bool sendCommandText(const HANDLE &pipe, const std::string &command); bool sendHeader(const HANDLE &pipe); bool writeAck(const HANDLE &pipe); bool readBytes(const HANDLE &pipe, LPVOID bytes, DWORD numBytes, const char* suffix); bool writeBytes(const HANDLE &pipe, LPVOID bytes, DWORD numBytes, const char* suffix); }; }
f8995c54bcf1da18a62c021f38005d07d756ff00
8bf3a88138ce1fb6ebb7888d342e9e2852bbbd64
/RADS_common/Reading_data.cpp
d67486e14ba58cbc432a4a443b37bffdc0797c82
[ "BSD-2-Clause" ]
permissive
tm-kn/rads
df69479d2327dafa0bd4a7c8674f734e75df0fa6
4cbbeb3023333dd4c399c991768c611fe4f24415
refs/heads/master
2020-05-30T19:40:03.302577
2017-03-24T20:34:17
2017-03-24T20:34:17
83,682,140
0
0
null
null
null
null
UTF-8
C++
false
false
3,311
cpp
Reading_data.cpp
#include <algorithm> #include <ctime> #include <iostream> #include <string> #include <vector> #include "Reading_data.h" #include "Sensor.h" #include "Fuel_level.h" #include "Speed.h" #include "Temperature.h" #include "GPS_position.h" using std::cout; using std::endl; using std::sort; using std::string; using std::time_t; using std::vector; namespace Readings { /// /// <summary>Sort readings by their reading time.</summary> /// bool way_to_sort(Sensor* sensor_one, Sensor* sensor_two) { return sensor_one->get_datetime() < sensor_two->get_datetime(); } Reading_data::Reading_data(time_t start_datetime, time_t end_datetime, vector<Sensor*> sensor_data) { this->reading_start_datetime = start_datetime; this->reading_end_datetime = end_datetime; this->sensor_data = sensor_data; sort(this->sensor_data.begin(), this->sensor_data.end(), way_to_sort); } Reading_data::~Reading_data() {} vector<Sensor*> Reading_data::get_data() { return this->sensor_data; } time_t Reading_data::get_reading_start_datetime() { return this->reading_start_datetime; } time_t Reading_data::get_reading_end_datetime() { return this->reading_end_datetime; } Sensor * Reading_data::convert_packet_to_sensor(Packet packet) { string data_string(packet.data); if (packet.data_type == GPS_POSITION_SENSOR) { vector<string> tokens; size_t pos = 0; std::string token; // Split string from LAT;LNG;ALT while ((pos = data_string.find(';')) != std::string::npos) { tokens.push_back(data_string.substr(0, pos)); data_string.erase(0, pos + 1); } tokens.push_back(data_string); GPS_position::GPS_position * gps_pos = new GPS_position::GPS_position(stof(tokens[0]), stof(tokens[1]), stof(tokens[2])); gps_pos->set_datetime(packet.datetime); return gps_pos; } else if (packet.data_type == FUEL_LEVEL_SENSOR) { Fuel_level::Fuel_level * fuel = new Fuel_level::Fuel_level(stof(data_string)); fuel->set_datetime(packet.datetime); return fuel; ; } else if (packet.data_type == TEMPERATURE_SENSOR) { vector<string> tokens; size_t pos = 0; std::string token; // Split string from SENSOR_NAME;TMP while ((pos = data_string.find(';')) != std::string::npos) { tokens.push_back(data_string.substr(0, pos)); data_string.erase(0, pos + 1); } tokens.push_back(data_string); Temperature::Temperature * temperature = new Temperature::Temperature(tokens[0], stof(tokens[1])); temperature->set_datetime(packet.datetime); return temperature; } else if (packet.data_type == SPEED_SENSOR) { Speed::Speed * speed = new Speed::Speed(stof(data_string)); speed->set_datetime(packet.datetime); return speed; } else { cout << "Reading Data: Unknown packet data type " << packet.data_type << endl; return NULL; } } }
773d2b549fcb396334242ee84f7ecb94f7a0d038
de0524250a32e3734b3d972618b663738dbdaa45
/Podstawy_programowania/Merge_sort.cpp
82532117dcbe9262582939940205223ed98ab020
[]
no_license
Kitee666/UMK
9702b8e83520194aae586aa48e27f5cb8e502d25
62ce69ba0e4ac323b6b702e80ef5f6c83f009c74
refs/heads/main
2023-05-28T09:40:27.913257
2021-06-07T10:32:45
2021-06-07T10:32:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,606
cpp
Merge_sort.cpp
#include <iostream> using namespace std; /* Dawid Sikorski Sortowanie szybkie */ void MergeSort(int dane[],int poczatek, int koniec) { // Jezeli jestesmy w zbiorze 1 elementowym nie mamy co sortowac if(poczatek==koniec) return; // Deklarujemy element srodkowy zbioru int srodek; srodek=(poczatek+koniec)/2; // Sortujemy lewa czesc tablicy MergeSort(dane,poczatek,srodek); // Sortujemt prawa czesc tablicy MergeSort(dane,srodek+1,koniec); // A nastepnie bedziemy laczyc dwie czesci // Deklarujemy tablice pomocnicza i przepisujemy do niej wartosci tablicy glownej int pomocnicza[koniec+1]; for(int i=poczatek;i<=koniec;i++) pomocnicza[i]=dane[i]; // Deklarujemy zmienne pomocnicze int i,j,r; // Nadajemy wartosc poczatka dla "i" i "r" i=poczatek; r=poczatek; // Nadajemy wartosc nastepna po elemencie srodkowym dla "j" poniewaz bedziemy laczyc dwie polowki j=srodek+1; // Rozpoczynamy scalanie dwoch posortowanych polowek: // Lewej od poczatku do srodka oraz prawej od nastepnika srodka do konca while(i<=srodek && j<=koniec){ // Jezeli element i-ty w lewej polowce jest mniejszy od elementu j-tego w prawej polowce (za pomoca tablicy pomocniczej) if(pomocnicza[i]<pomocnicza[j]){ // To na r'tej pozycji w glownej tablicy nalezy nadpisac element i-ty dane[r]=pomocnicza[i]; // Przesuwamy sie o jeden element dalej w lewej polowce i++; }// w przeciwnym razie i-ty w lewej polowce jest wiekszy lub rowny od elementu j-tego w prawej polowce (za pomoca tablicy pomocniczej) else{ // To na r'tej pozycji w glownej tablicy nalezy nadpisac element j-ty dane[r]=pomocnicza[j]; // Przesuwamy sie o jeden element dalej w prawej polowce j++; } // Przesuwamy sie o jeden element w glownej tablicy r++; } // Jezeli prawa czesc zostala wyczerpana a lewa nie // trzeba przepisac reszte elementow lewej polowki while(i<=srodek){ // Na r'tej pozycji w glownej tablicy nalezy nadpisac element i-ty dane[r]=pomocnicza[i]; // Przesuwamy sie o jeden element dalej w lewej polowce i++; // Przesuwamy sie o jeden element w glownej tablicy r++; } } int main() { // Wprowadzamy dane do posortowania int dane[4]={6,1,4,1}; // Wypisujemy dane przed posortowaniem for(int i=0;i<4;i++){ cout.width(2);cout<<dane[i]; } cout<<"\n"; // Sortujemy dane od indeksu pierwszego ( 0 ) do ostatniego ( ilosc - 1 ) MergeSort(dane,0,3); // Wypisujemy dane posortowane niemalejaco for(int i=0;i<4;i++){ cout.width(2);cout<<dane[i]; } return 0; }
838e46f30742de83686b46dcbca3161d8a89fc12
d5a8771efcb11b671f51dacf0f9b9dc7a03e4069
/inc/fonctions.hpp
455afda52bb5f580091b07357a5dedb0fb56471c
[]
no_license
YannCat/calculatrice_hp
ca51c67de16046a259835e9c897a35343c801151
1e3d11055776b2fe690bf6ed3653f52458d912b8
refs/heads/master
2020-04-27T00:21:32.604120
2019-03-28T15:53:14
2019-03-28T15:53:14
173,931,456
2
0
null
null
null
null
UTF-8
C++
false
false
1,131
hpp
fonctions.hpp
#ifndef FONCTIONS_HPP #define FONCTIONS_HPP #include <iostream> // cout, endl #include <string> // string ; string::find ; stoi ; stod ; to_string #include <stack> // stack - LIFO #include <queue> // queue - FIFO #include <utility> // pair #include <algorithm> // min_element #include <locale> // isdigit #include <exception> // try {instructions} ; throw (type) ; catch{type const& name} /* author : Maxime BELAVAL * ON NE MODIFIE PAS MON CODE SANS ME PREVENIR ET SANS MON AUTORISATION. * ON N'UTILISE PAS DE NAMESPACE STD. */ // prototypes à mettre dans une classe, en privé std::pair<std::stack<std::string>, std::queue<std::string> > resultByStack(std::string const userInput); std::string evaluate_A_B_op(std::string operandA, std::string operandB, std::string operatorUsed); std::string calculation(std::pair<std::stack<std::string>, std::queue<std::string> > myPair); int checkInput(std::string const& userInput); // à affiner et adapter à la GUI -- c'est donc normal que cette fonction ne compile pas ! void userInputManagement(std::string const& userInput); #endif // FONCTIONS_HPP
324f80a08ff473994464a3fb552d8f17766b9be8
3d64350bd59f0f9d6a95a6f738790f0256fdeba8
/src/core/testing/test.h
09e618605b1d6c934ddf3364c9416f88bd8d28fc
[ "MIT" ]
permissive
imnetcat/cout
633f07b1904b686fa16dcd106f4bf4f77396494e
f188c1b345b9c95f4bfcd5b928845465f048ff6e
refs/heads/master
2023-02-12T20:36:44.448811
2021-01-17T08:26:32
2021-01-17T08:26:32
250,235,488
3
0
null
null
null
null
UTF-8
C++
false
false
1,457
h
test.h
#pragma once #include "../config.h" #ifdef INDEBUG #include "../logging/ilogger.h" #include "assert.h" #include "profiler.h" #include "../exception/logic_error.h" #include <functional> #include <utility> namespace Cout { namespace Core { namespace Testing { struct ITest { virtual void run(Logging::ILogger& logger, size_t& count, size_t& success) const = 0; }; struct UnitTest : ITest { UnitTest(std::function<void()> f) : _func(f) {} void run(Logging::ILogger& logger, size_t& count, size_t& success) const override { count++; try { _func(); success++; } catch (const Cout::Exceptions::base& except) { logger.Error(except); return; } catch (const std::exception & stdex) { logger.Error(stdex); return; } } const std::function<void()> _func; }; struct TimeTest : ITest { TimeTest(std::function<void(Logging::ILogger& logger)> f) : _func(f) {} void run(Logging::ILogger& logger, size_t& count, size_t& success) const override { count++; try { _func(logger); success++; } catch (const Cout::Exceptions::base& except) { logger.Error(except); return; } /*catch (std::exception & stdex) { logger.Error(stdex); return; } */ } const std::function<void(Logging::ILogger& logger)> _func; }; } } } #endif
54c9f8f851b50eb86bfe1005706649a472780783
529b9af0c2de92c46f75a440cd0be4f0922fc6e1
/Light oj/Light-oj 1080.cpp
00e3a99fb6cbeb74b98be9ba8a18af4d725df433
[]
no_license
pranto84/Online-judge
168639e9f50dd92492428a7cae2612d86bbca3f3
4542f278a3777b65e14609d51867c92071ecfaf9
refs/heads/master
2021-01-20T17:15:30.305051
2019-08-27T17:52:20
2019-08-27T17:52:20
65,147,183
0
0
null
null
null
null
UTF-8
C++
false
false
2,612
cpp
Light-oj 1080.cpp
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <vector> using namespace std; #define MAX 1000001 #define N 100000001 #define sci(a) scanf("%d", &a) #define sci2(a,b) scanf("%d%d", &a, &b) int ara[MAX], tree[MAX], lazy[MAX]; void propagate(int node, int l, int r) { if(l != r) { lazy[node*2] = (lazy[node*2]+1) %2; lazy[node*2+1] = (lazy[node*2+1]+1) %2; } else{ if(lazy[node] %2 == 1){ if(tree[node] == 1) tree[node]=0; else tree[node] = 1; } } lazy[node] = 0; return; } void build_tree(int node,int Start, int End) { if(Start > End) return; if(Start == End){ tree[node] = ara[Start]; return; } build_tree(node*2, Start, (Start+End)/2); build_tree(node*2 +1, 1+(Start+End)/2, End); tree[node] = tree[node*2+1] + tree[node*2]; } void update(int node, int Start, int End, int l, int r) { if(lazy[node] != 0) propagate(node, Start, End); if(l > End || r < Start) return; if(l <= Start && End <= r){ if(Start != End){ lazy[node*2] = (lazy[node*2]+1) %2; lazy[node*2+1] = (lazy[node*2+1]+1) %2; } else{ lazy[node] = (lazy[node] +1)%2; propagate(node, Start, End); } return; } int mid = (Start + End) /2; update(node*2,Start, mid, l, r); update(1+node*2, mid+1, End, l, r); return; } void query(int node, int Start, int End , int x) { if(lazy[node] != 0) propagate(node, Start, End); if(Start == x && End == x){ printf("%d\n",tree[node]); return; } int mid = (Start + End) /2; if(x >= Start && x <= End){ query(node*2, Start, mid, x); query(node*2+1, mid+1, End, x); } else return; } int main() { freopen("in.txt", "r", stdin); int ts, x, y, q; char st[MAX], ch; sci(ts); for(int t=1; t<= ts; t++){ scanf(" %s", st); getchar(); int n = strlen(st); for(int i=0; i<n; i++) ara[i+1] = st[i]-'0'; build_tree(1, 1, n); for(int i = 0; i<4*n;i++) lazy[i]=0; sci(q); printf("Case %d:\n", t); for(int i=0; i<q; i++){ scanf(" %c", &ch); if(ch == 'I'){ sci2(x,y); update(1,1,n,x,y); } else{ sci(x); query(1,1,n,x); } } } return 0; }
e6d1431e56d592f29a3fd87bb72a66f21cc79ffe
e6018f2af3b1a401db03431647783c82c590865e
/kth divisor/main.cpp
bd38f32d962e9844a9d21e3936c5c7c3ef928ff6
[]
no_license
Archonsh/ACM-code
260f78e2605467aaf55653efbe655d57585e84ef
6e00d1bf7adce9ee11fe94f587e16b0768375b99
refs/heads/master
2021-01-13T10:56:11.305069
2018-01-18T09:18:27
2018-01-18T09:18:27
72,264,598
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
main.cpp
/* * divisor of a number is always PAIRED * only concern is whether sqrt(N) is a divisor, as it pairs itself * O(logN) */ #include <cstdio> #include <cmath> #include <iostream> #include <vector> using namespace std; vector<long long>q; int main() { long long n,k,i,j,div=0,flag=0; cin>>n>>k; if(k==1) {printf("1");return 0;} double sq=sqrt(n); if(abs(floor(sq)*floor(sq)-n)<1e-6) //judge whether sqrt(N) is a divisor. IF YES, flag = 1 flag=1; for(i=1;i<=sq;i++) { if(n%i==0) { div++; //number of divisors q.push_back(i); //record this divisor in q if(div == k) { cout<<i; return 0; } } } if(q.size()*2 < k && !flag) //number N has less than 2*q.size() divisors { printf("-1"); return 0; } if(q.size()*2 <= k && flag) { printf("-1"); return 0; } if(flag) //divisors are symmetric about sqrt(N) @ q.end() { div=q.size()-(k-q.size())-1; cout<<n/q[div]; return 0; } else { div=q.size()-(k-(q.size()+1))-1; cout<<n/q[div]; } return 0; }
61777aae583e0c1fb91c70595c38501c8da31501
b8c9c5a7fd1942c88da5035eb8aca8d85c9c6d6a
/common/tools/ats/smoketest/messaging/Src/TestMessSetDefaultSC.cpp
63530be1541a4c4c293b6fe3163b4bc298be3ad3
[]
no_license
fedor4ever/default
28f193846bea546f2d09516f5689e050d63d8958
b94dd7c4880b5b598816bebaf9c8eb2eb38f101d
refs/heads/master
2021-01-01T19:19:34.867792
2015-04-12T11:23:16
2015-04-12T11:23:16
33,690,214
0
0
null
null
null
null
UTF-8
C++
false
false
2,927
cpp
TestMessSetDefaultSC.cpp
// Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of the License "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // This contains TestMessSetDefaultSc which sets an SMS // SC as default SC. // // #include "TestMessSetDefaultSC.h" // EPOC includes #include <msvids.h> #include <miutset.h> #include <smutset.h> #include <etelmm.h> #include <msvstore.h> #include <csmsaccount.h> _LIT(KSCName, "scname"); CTestMessSetDefaultSc::CTestMessSetDefaultSc() : CTestMessBase(EFalse) { SetTestStepName(_L("SetSmsSc")); } TVerdict CTestMessSetDefaultSc::doTestStepL() { // Printing to the console and log file INFO_PRINTF1(_L("Set Default Service Center")); CSmsSettings* smsSettings = CSmsSettings::NewL(); CleanupStack::PushL(smsSettings); SetEntryL(KMsvRootIndexEntryId); EntryL().SetSortTypeL(SelectionOrdering()); CMsvEntrySelection* selection=EntryL().ChildrenWithTypeL(KUidMsvServiceEntry); CleanupStack::PushL(selection); TInt count=selection->Count(); TBool found=EFalse; for (TInt i=count; i>0 && !found; ) { SetEntryL(selection->At(--i)); // Log child if ( EntryL().Entry().iMtm == KUidMsgTypeSMS && EntryL().Entry().iType == KUidMsvServiceEntry ) { found=ETrue; } } if ( !found ) { ERR_PRINTF1(_L("No SMS Account found")); SetTestStepResult(EFail); } TName network; //IMK TBool returnValue=(GetPhoneSmsNetworkL(network)==KErrNone); TBool returnValue=false; //IMK TPtrC ptrSCName(network); if ( !returnValue ) { returnValue=GetStringFromConfig(ConfigSection(), KSCName, ptrSCName); } if ( !returnValue ) { ERR_PRINTF1(_L("No SC specified in script/ini file")); SetTestStepResult(EFail); } INFO_PRINTF2(_L("SC Name = %S"), &ptrSCName); if ( TestStepResult()==EPass ) { CSmsAccount* smsAccount = CSmsAccount::NewLC(); smsAccount->LoadSettingsL(*smsSettings); const TInt numSCAddr = smsSettings->ServiceCenterCount(); if( !numSCAddr ) { ERR_PRINTF1(_L("No SC found")); SetTestStepResult(EFail); } TBool scFound = EFalse; for( TInt index=0; (index<numSCAddr) && (!scFound);index++ ) { CSmsServiceCenter& scAddr = smsSettings->GetServiceCenter(index); if( (scAddr.Name()).CompareF(ptrSCName) == 0) { smsSettings->SetDefaultServiceCenter(index); smsAccount->SaveSettingsL(*smsSettings); scFound = ETrue; } } if ( !scFound ) { ERR_PRINTF2(_L("%S NOT Found"), &ptrSCName); SetTestStepResult(EFail); } CleanupStack::PopAndDestroy(smsAccount); } CleanupStack::PopAndDestroy(2, smsSettings); return TestStepResult(); }
558930beba18a401e5fbd5a54e9fb813546d504f
814573e0d9d7e5758bfd1be435a89bba903a0bd0
/Other/7-42.cpp
2cb10f4557935810f781d6ab7c625a28f68bade7
[]
no_license
FairyHao/DataStructue
0d4c544bbb7af4e0f08e71cf3bf05ba5024d9d43
13f3bb7c6909c9b1b4f725a6d7de616faf031bb9
refs/heads/master
2021-01-01T05:57:09.095816
2017-07-19T09:36:04
2017-07-19T09:36:04
97,316,720
0
0
null
null
null
null
GB18030
C++
false
false
423
cpp
7-42.cpp
// 7-42.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "DGraph.h" #include "iostream" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { DGraph G; char ch; int k; G.CreateGraph(); cout<<"输入源顶点:"; cin>>ch; cout<<"求从顶点 "<<ch<<" 到其余顶点的最短路径:"<<endl; k=G.LocateVex(ch); G.ShortestPath_DIJ(k); G.OutPutPath(k); system("pause"); }
9a7bbdcdecb5a8e1cbb9470ba995c4a915f89239
40b8d3f3b84d23affcb5781d011910fb18128ce7
/string Class v2/string Class Final/strings.cpp
b1a865d12d55e33eb35963343b68b3bd19129c40
[]
no_license
qaz34/text-adventure
02e750609b1569f6b90c65b37af645df594dc0fa
ce3273e0910ac67c7bf8af62e5a0ce3e3a27f719
refs/heads/master
2021-01-10T04:44:30.119749
2016-03-29T04:48:52
2016-03-29T04:48:52
53,899,619
0
0
null
null
null
null
UTF-8
C++
false
false
4,099
cpp
strings.cpp
#include "strings.h" #include <cstring> #include <ctype.h> String::String() { m_string = nullptr; m_string = new char[1]; m_size = 0; m_capacity = 1; m_string[0] = '\0'; } String::String(char input[]) { int length = strlen(input); m_string = nullptr; m_string = new char[length + 1]; strcpy(m_string, input); m_capacity = length + 1; m_size = length; } String::String(int size) { m_string = new char[size + 1]; m_capacity = size + 1; m_size = size; m_string[0] = '\0'; } String::String(String & other) { m_string = nullptr; *this = other; } String::~String() { delete[]m_string; } int String::Length() { return std::strlen(m_string); } bool String::operator==(String & other) { if (strcmp(m_string, other.m_string) == 0) return true; else return false; } bool String::operator==(const char * other) { if (strcmp(m_string, other) == 0) return true; else return false; } char* String::operator[](const int location) { if (this->Length() >= location && location >= 0) return &m_string[location]; else return nullptr; } String String::toLower() { String temp = m_string; for (int i = 0; i < m_size; i++) { temp.m_string[i] = tolower(*temp[i]); } return temp; } String String::toUpper() { String temp = m_string; for (int i = 0; i < m_size; i++) { temp.m_string[i] = toupper(*temp[i]); } return temp; } void String::resize(int newSize) { String temp(newSize); strcpy(temp.m_string, m_string); temp.m_size = strlen(m_string); *this = temp; } void String::operator=(char string[]) { int length = strlen(string); if (m_capacity <= length) { resize(length); } m_size = length; strcpy(m_string, string); } void String::operator=(String & other) { if (m_string != nullptr) { delete[]m_string; } m_string = new char[other.m_capacity]; m_size = other.m_size; m_capacity = other.m_capacity; strcpy(m_string, other.m_string); } void String::operator+=(const String & other) { if (!(m_capacity > (int)(strlen(m_string) + strlen(other.m_string)))) { resize(m_size + other.m_size); } strcat(m_string, other.m_string); m_size = strlen(m_string); } void String::operator+=(const char* other) { if (!(m_capacity > (int)(strlen(m_string) + strlen(other)))) { resize(m_size + strlen(other)); } strcat(m_string, other); m_size = strlen(m_string); } String String::operator+(const String & other) { String temp(*this); temp += other; return temp; } String String::operator+(const char * other) { String temp(m_string); temp += other; return temp; } char* String::subStringFind(const char * subString) { return strstr(m_string, subString); } char* String::subStringFind(const char * subString, int location) { return strstr(m_string + location, subString); } void String::subStringReplace(const char * subString, char* replacement) { char * temp = this->subStringFind(subString); if (temp != nullptr) { int subLen, repLen; subLen = strlen(subString); repLen = strlen(replacement); if (subLen == repLen) strncpy(temp, replacement, repLen); else { String temp3p[3]; int tempNum; int counter = 0; for (int i = 0; i < m_size; i++) { if (m_string[i] == subString[0]) { for (int k = 0; k < subLen; k++) { if (m_string[i + k] == subString[k]) { counter++; } } if (counter = subLen) { tempNum = i; break; } } } temp3p[0].resize(m_size + repLen - subLen); temp3p[0] = m_string; *temp3p[0][tempNum] = '\0'; temp3p[0].m_size = tempNum; temp3p[1] = replacement; temp3p[2].resize(m_size + 1); temp3p[2].m_size = 0; char* quickTemp = temp + subLen; temp3p[2] = quickTemp; temp3p[2].m_size = temp3p[2].Length(); temp3p[0] += replacement; temp3p[0].m_string[tempNum + repLen] = '\0'; temp3p[0].m_size = tempNum + repLen; temp3p[0] += temp3p[2]; temp3p[0].m_size = temp3p[0].Length(); *this = temp3p[0]; } } } const char * String::get() { return m_string; } String operator + (char lhs[], String rhs) { String temp(lhs); temp += rhs; return temp; }
0d44ecab7f16fd604758defccf6d02736617a6ce
f2217d0ee6dfefe24c9fe1b616e81bf106f48a1f
/src/rtsp/rtsp_splitter.h
3ef4f8e3682a99d0023daf8f160a28eea5c4c627
[ "MIT" ]
permissive
lam2003/MediaServer
0dffaf3bd8c979f26b8deab3efd7cad3a7b052df
3189acd9789702740f4bd33bbc9a1b3342966cae
refs/heads/master
2023-03-08T07:45:18.765641
2021-02-22T03:40:43
2021-02-22T03:40:43
315,336,435
2
2
null
null
null
null
UTF-8
C++
false
false
763
h
rtsp_splitter.h
#ifndef SMS_RTSP_SPLITTER_H #define SMS_RTSP_SPLITTER_H #include <http/http_request_splitter.h> #include <common/media_source.h> namespace sms { class RtspSplitter : public HttpRequestSplitter { public: RtspSplitter() = default; virtual ~RtspSplitter() = default; protected: // override HttpRequestSplitter virtual const char *on_search_packet_tail(const char *data, size_t len) override; virtual size_t on_recv_header(const char *data, size_t len) override; virtual void on_recv_content(const char *data, size_t len) override; protected: virtual void on_whole_rtsp_packet(HttpParser &parser) = 0; protected: bool is_rtp_packet_{false}; }; } // namespace sms #endif
10b76457ee59d0412f06e4441a5447c5e53d71aa
d6dedc98c0bbdb6e7c7c1a861e00548cdd4ac4cf
/3D_Framework/3D_Framework/cPlayer.h
463559a592a0a5465c39524a9cd09c3ca84706eb
[]
no_license
hongsunKim/DirectX3DPortfolio-Borderland
4f45a68d28adc1d80b9e1bce707677b5f6ca9dae
140c2c5137786e2a102a05146d4a0dc68c8ee4f2
refs/heads/master
2021-01-11T20:17:38.536108
2017-01-16T04:32:10
2017-01-16T04:32:10
79,082,793
0
0
null
null
null
null
UHC
C++
false
false
5,628
h
cPlayer.h
#pragma once #include "Player_Stat.h" class cXMesh_Skinned; class cSkinnedAnimation; class cBoundBox; class cCamera; class cTerrain; class cTransform; class cLight_Direction; class cItem0; class cSetBoundObject; class cBaseObject; class enemyClass2; class enemyClass1; class bossClass; class Effect; class cPlayer { private: typedef vector<cSetBoundObject*> VEC_OBJECT; private: vector<BULLET> m_vecBullet; private: cTerrain* m_pTerrain; int Total_Damage = 0; float moveEye; //std::vector<cBaseObject*> WeaponObjects; // 추가 웨폰 벡터 private: cXMesh_Skinned* m_pWeapon1; cSkinnedAnimation* m_pWeaponAni1; cTransform* m_pWeaponTrans1; BONE* m_pWeaponBone1; cXMesh_Skinned* m_pWeapon2; cSkinnedAnimation* m_pWeaponAni2; BONE* m_pWeaponBone2; cXMesh_Skinned* m_pWeapon3; cSkinnedAnimation* m_pWeaponAni3; BONE* m_pWeaponBone3; cXMesh_Skinned* m_pWeapon4; cSkinnedAnimation* m_pWeaponAni4; BONE* m_pWeaponBone4; cXMesh_Skinned* m_pWeapon5; cSkinnedAnimation* m_pWeaponAni5; BONE* m_pWeaponBone5; cXMesh_Skinned* m_pWeapon6; cSkinnedAnimation* m_pWeaponAni6; BONE* m_pWeaponBone6; cXMesh_Skinned* m_pWeapon7; cSkinnedAnimation* m_pWeaponAni7; BONE* m_pWeaponBone7; private: cSkinnedAnimation* m_pMeshAni; cTransform* m_pPlayerUpperTrans; BONE* m_pDummy21; cCamera* m_pPlayerEye; PLAYER_STATE m_ekPlayerState; //이동속도 관련 멤버 float m_fRunSpeed; float m_fWalkSpeed; float m_fCurSpeed; //점프 관련 멤버 float m_fPosTerrainHeight; //현 위치 고도 정보 float m_fGravity; //중력값 float m_fJumpCurPower; //점프 현재 파워 float m_fJumpStartPower; //점프 시작 파워 bool m_bAir; //현재 공중? bool m_bJump = false; bool m_bOnBox; cBaseObject* m_pkOnBox = NULL; bool m_bReact = false; //적 관련 멤버 //에너미 매니져가 들어갈 것... cTransform* m_pEnemy; DWORD m_checkColor; //아이템 창 관련 cItem0* m_weaponSlot[4]; cItem0* m_equipWeapon; //충돌용 박스 cBoundBox m_kCollisionBox; VEC_OBJECT* m_pVecObjects; bool Air_Check; bool Warp_Check; //==== float m_fCurShield; float m_fFullShield; float m_fCurHp; float m_fFullHp; float m_fShieldRegenCount; float m_fShieldRegenStartCount; LPDIRECT3DTEXTURE9 RenderTexture; private: vector<enemyClass1*>* m_vecEnemy1; vector<enemyClass2*>* m_vecEnemy2; vector<bossClass*>* m_vecBoss; private: Ray* m_pkRay; public: int m_iGrenadeMax; int m_iGrenade; int m_iBulletMax; float m_fExpCur; float m_fExpMax; UIINFO m_stUiInfo; bool _cri; private: Effect* m_pEffect; bool m_bBlood = false; float m_fBloodCount; private: float m_fGrenadeCount = 0.f; bool m_bExpStart = true; int m_iBulletMaxCell = 5; int m_iBulletCurCell = 5; private: vector<GRENADE> m_vecGrenade; bool m_bThrow; bool m_bIsThrown; float m_fThrowTimeCount; public: cBoundSphere* playerSphere; cBoundSphere* playerCoreSphere; cTransform* m_pPlayerTrans; cXMesh_Skinned* m_pMesh; static int m_iBulletCount; static int Bullet_Total_Max; bool getWarp_Check() { return Warp_Check; } int getTotal_Damage() { return Total_Damage; } cPlayer(); ~cPlayer(); HRESULT Init(cTerrain* terrain); void Release(); void Update(float timDelta); void Render(cCamera* camera, cLight_Direction* Light_D); cCamera* GetPlayerEye() { return m_pPlayerEye; } void InitObjectSet(VEC_OBJECT* pVecObjects) { m_pVecObjects = pVecObjects; } void CollisionBox(); vector<BULLET>* GetVecBullet() { return &m_vecBullet; } //데미지 입력 void AttackedByEnemy(float damage); bool IsPlayerAlive(); void SetEnemyVector(vector<enemyClass1*>*, vector<enemyClass2*>*, vector<bossClass*>*); Ray* GetRay() { return m_pkRay; } float GetCurHp() { return m_fCurHp; } bool IsPlayerAim() { if (PLAYER_STATE::AIM == m_ekPlayerState) { return true; } else { return false; } } UIINFO* GetUiInfo() { return &m_stUiInfo; } void SetRenderTexture(LPDIRECT3DTEXTURE9 Texture) { this->RenderTexture = Texture; }; private: void ShiledUpdate(float timeDelta, float startSec, float regenSec); private: void W_IsStayDownUpdate(float timeDelta); void S_IsStayDownUpdate(float timeDelta); void A_IsStayDownUpdate(float timeDelta); void D_IsStayDownUpdate(float timeDelta); void G_IsOnceDownUpdate(float timeDelta); void R_IsOnceDownUpdate(float timeDelta); void SPACE_IsOnceDownUpdate(float timeDelta); void LBUTTON_IsOnceDownUpdate(float timeDelta); void LSHIFT_IsStayDownUpdate(float timeDelta); void LSHIFT_IsNotStayDownUpdate(float timeDelta); void RBUTTON_IsStayDownUpdate(float timeDelta); void RBUTTON_IsNotStayDownUpdate(float timeDelta); void ShowPlayerMotionState(); void ShowBulletState(); float GetHeightGap(); void UpdateBullet(float timedelta); void fire(); bool LineSphereCollision(D3DXVECTOR3 lineStart, D3DXVECTOR3 lineEnd, D3DXVECTOR3 center, float radius); public: bool getAir() { return m_bAir; } void Set_Hp_Healing(int Set_Hp) { m_fCurHp += Set_Hp; if (m_fCurHp > Player_Full_Hp) m_fCurHp = Player_Full_Hp; } void Set_Bullet_Reload(int Set_Bullet) { Bullet_Total_Max += Set_Bullet; if (Bullet_Total_Max > Player_Total_Bullet_Max) Bullet_Total_Max = Player_Total_Bullet_Max; } private: void GrenadeUpdate(float timeDelta); };
d9bf3976b03db2cd85814e1c99730cbbd4b426fc
c976078bf8dde5baf96416d60dd3bb06c72111ad
/include/fastrtps/types/DynamicDataFactory.h
db87510f51abf15f2eb104d3a53aba8f1c313806
[ "Apache-2.0" ]
permissive
eProsima/Fast-DDS
21f3fecacca5a285ad9950b7683456c6f9930a4d
107ea8d64942102696840cd7d3e4cf93fa7a143e
refs/heads/master
2023-08-31T14:56:45.942016
2023-08-11T11:40:25
2023-08-11T11:40:25
20,296,703
1,225
463
Apache-2.0
2023-09-14T11:33:09
2014-05-29T14:36:15
C++
UTF-8
C++
false
false
1,907
h
DynamicDataFactory.h
// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TYPES_DYNAMIC_DATA_FACTORY_H #define TYPES_DYNAMIC_DATA_FACTORY_H #include <fastrtps/types/TypesBase.h> #include <fastrtps/types/DynamicTypePtr.h> #include <fastrtps/types/DynamicTypeBuilder.h> #include <fastrtps/types/DynamicType.h> #include <fastrtps/types/DynamicData.h> #include <mutex> //#define DISABLE_DYNAMIC_MEMORY_CHECK namespace eprosima { namespace fastrtps { namespace types { class DynamicDataFactory { protected: DynamicDataFactory(); ReturnCode_t create_members( DynamicData* pData, DynamicType_ptr pType); #ifndef DISABLE_DYNAMIC_MEMORY_CHECK std::vector<DynamicData*> dynamic_datas_; mutable std::recursive_mutex mutex_; #endif public: ~DynamicDataFactory(); RTPS_DllAPI static DynamicDataFactory* get_instance(); RTPS_DllAPI static ReturnCode_t delete_instance(); RTPS_DllAPI DynamicData* create_data(DynamicTypeBuilder* pBuilder); RTPS_DllAPI DynamicData* create_data(DynamicType_ptr pType); RTPS_DllAPI DynamicData* create_copy(const DynamicData* pData); RTPS_DllAPI ReturnCode_t delete_data(DynamicData* pData); RTPS_DllAPI bool is_empty() const; }; } // namespace types } // namespace fastrtps } // namespace eprosima #endif // TYPES_DYNAMIC_DATA_FACTORY_H
28b1efef94c3abfa1fc678d39d9a3433bcdb1f07
50c100118e3296d608f52ebeb8a96011da064f44
/src/model/Player.h
31fb1b708f63bf1f9a28213b96a7458d57d236ed
[]
no_license
ottojo/Hexxagon
b6e80aef7e8a03677f3d533e51e7c1f189d5539f
28180b2547fb6ca38d6da065d812d89db532ba9a
refs/heads/master
2020-11-28T12:46:39.596234
2020-02-02T01:00:06
2020-02-02T01:00:06
229,818,175
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
Player.h
// // Created by jonas on 30.12.19. // #ifndef HEXXAGON_PLAYER_H #define HEXXAGON_PLAYER_H #include <util/UUID.h> class Player { public: Player(); Player(std::string name, UUID id); std::string name; UUID id; }; #endif //HEXXAGON_PLAYER_H
9eaf59ffaca70be0856c25f690fc3ea7eb47b5e3
b4dbdb2dc1a33ff9c5b259af3b4180a734c28476
/include/catch_runner.hpp
3b859443219b94e4f1ea9fb4f4cf040e7f161b43
[ "BSL-1.0" ]
permissive
hajimehoshi/Catch
2aefad9c716b4259d6db8c88f047febbc725f9ed
f7e27776655726f4d8470fcfb70e6edbebf3da0a
refs/heads/master
2021-01-17T22:53:11.033051
2011-09-30T07:04:54
2011-09-30T07:04:54
3,013,998
1
0
null
null
null
null
UTF-8
C++
false
false
4,658
hpp
catch_runner.hpp
/* * catch_runner.hpp * Catch * * Created by Phil on 31/10/2010. * Copyright 2010 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ #ifndef TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED #include "internal/catch_hub_impl.hpp" #include "internal/catch_commandline.hpp" #include "internal/catch_list.hpp" #include "reporters/catch_reporter_basic.hpp" #include "reporters/catch_reporter_xml.hpp" #include "reporters/catch_reporter_junit.hpp" #include <fstream> #include <stdlib.h> #include <limits> namespace Catch { ////////////////////////////////////////////////////////////////////////// inline int Main ( Config& config ) { // Handle list request if( config.listWhat() != Config::List::None ) return List( config ); // Open output file, if specified std::ofstream ofs; if( !config.getFilename().empty() ) { ofs.open( config.getFilename().c_str() ); if( ofs.fail() ) { std::cerr << "Unable to open file: '" << config.getFilename() << "'" << std::endl; return (std::numeric_limits<int>::max)(); } config.setStreamBuf( ofs.rdbuf() ); } Runner runner( config ); // Run test specs specified on the command line - or default to all if( !config.testsSpecified() ) { config.getReporter()->StartGroup( "" ); runner.runAll(); config.getReporter()->EndGroup( "", runner.getSuccessCount(), runner.getFailureCount() ); } else { // !TBD We should get all the testcases upfront, report any missing, // then just run them std::vector<std::string>::const_iterator it = config.getTestSpecs().begin(); std::vector<std::string>::const_iterator itEnd = config.getTestSpecs().end(); for(; it != itEnd; ++it ) { size_t prevSuccess = runner.getSuccessCount(); size_t prevFail = runner.getFailureCount(); config.getReporter()->StartGroup( *it ); if( runner.runMatching( *it ) == 0 ) { // Use reporter? // std::cerr << "\n[Unable to match any test cases with: " << *it << "]" << std::endl; } config.getReporter()->EndGroup( *it, runner.getSuccessCount()-prevSuccess, runner.getFailureCount()-prevFail ); } } return static_cast<int>( runner.getFailureCount() ); } ////////////////////////////////////////////////////////////////////////// void showHelp ( std::string exeName ) { std::string::size_type pos = exeName.find_last_of( "/\\" ); if( pos != std::string::npos ) { exeName = exeName.substr( pos+1 ); } std::cout << exeName << " is a CATCH host application. Options are as follows:\n\n" << "\t-l, --list <tests | reporters> [xml]\n" << "\t-t, --test <testspec> [<testspec>...]\n" << "\t-r, --reporter <reporter name>\n" << "\t-o, --out <file name>|<%stream name>\n" << "\t-s, --success\n" << "\t-b, --break\n" << "\t-n, --name <name>\n\n" << "For more detail usage please see: https://github.com/philsquared/Catch/wiki/Command-line" << std::endl; } ////////////////////////////////////////////////////////////////////////// inline int Main ( int argc, char* const argv[], Config& config ) { ArgParser( argc, argv, config ); if( !config.getMessage().empty() ) { std::cerr << config.getMessage() << std::endl; return (std::numeric_limits<int>::max)(); } // Handle help if( config.showHelp() ) { showHelp( argv[0] ); return 0; } return Main( config ); } ////////////////////////////////////////////////////////////////////////// inline int Main ( int argc, char* const argv[] ) { Config config; // if( isDebuggerActive() ) // config.useStream( "debug" ); return Main( argc, argv, config ); } } // end namespace Catch #endif // TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED
b90eb7af5106671669751c751e6198806f4b20f2
1a8a5a3c24ad69bf6feaed37c6a0164f417ba33d
/sources/commands/TCmdPrint.h
e5f570c0328082d017a87f42b1d574a6240e43c1
[]
no_license
artemis-dev/artemis
689396d9763b076673eb3ad02ac83e5f2321f545
d4689a3a14f3120cdf6c89fb30e2c56d3901e858
refs/heads/master
2023-08-18T13:24:49.318197
2023-01-28T10:42:47
2023-01-28T10:42:47
18,690,622
2
6
null
2023-08-16T08:06:04
2014-04-11T22:27:49
C++
UTF-8
C++
false
false
1,120
h
TCmdPrint.h
/** * @file TCmdPrint.h * @brief print the last-saved figure * * @date Created : 2017-06-13 16:38:24 JST * Last Modified : 2019-11-15 20:42:02 JST (ota) * @author KAWASE Shoichiro <kawase@aees.kyushu-u.ac.jp> * * (C) 2017 KAWASE Shoichiro */ #ifndef INCLUDE_GUARD_UUID_9784A220_859C_4809_9B48_A9561F2CD114 #define INCLUDE_GUARD_UUID_9784A220_859C_4809_9B48_A9561F2CD114 #include "TCatCmd.h" namespace art { class TCmdPrint; } class art::TCmdPrint : public TCatCmd { public: TCmdPrint(); virtual ~TCmdPrint(); Long_t Run(); Long_t Cmd(vector<TString>); void SetPrinter(const char* printer); void SetOption(const char* option); void SetCommand(const char* command) { fPrintCmd = command; } protected: TString fPrinter; // printer name TString fOption; // option TString fPrintCmd; // directly set the command private: TCmdPrint(const TCmdPrint&); // undefined TCmdPrint& operator=(const TCmdPrint&); // undefined ClassDef(TCmdPrint,0) // print the last-saved figure }; #endif // INCLUDE_GUARD_UUID_9784A220_859C_4809_9B48_A9561F2CD114
08990706bd12f9d489d7c015caec48507dc97b24
161eb9f445a4221cfafbf51f045d50903c95118b
/程式腦/2.cpp
b0bc098bba4e132d94bd5367052b848c39e4930b
[]
no_license
tsian077/c
d199f5ec4badb168d5ccf21d737aae7754178c5b
b802861effce61d0592a121b8f71ed25cf6497b6
refs/heads/master
2020-03-14T12:00:17.285707
2018-04-30T13:47:37
2018-04-30T13:47:37
97,822,966
0
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
2.cpp
#include<iostream> using namespace std; int increment(int ); int main() { int x=10; cout<<increment(x)<<endl; cout<<x<<endl; return 0; } int increment(int n) { n=n+1; return n; }
fc22f9a57dcb32a6ed577555794508c31cfcdc99
de85c2528ab8653986218be4fa8303da826383e0
/BlogPost.cpp
61361e031915fe8bdcaf7785816a2a6151bb30d0
[]
no_license
JacobIsrael18/BlogParserLibrary
68b0391d1ee9b61bded4588685debad68d43cd96
2ac0e908ee34d42562ce978bde57a298ff1b54d5
refs/heads/master
2021-01-13T11:50:32.850862
2016-12-29T05:44:40
2016-12-29T05:44:40
77,564,044
0
0
null
null
null
null
UTF-8
C++
false
false
4,497
cpp
BlogPost.cpp
/**************************** BlogPost.cpp A class that models a single post Created by Jacob Israel on 12/21/16. *******************************/ #include "BlogPost.h" #include <regex.h> // Prototypes string findStringForQuotedKeyInString(string key, string sourceString); int findIntegerForQuotedKeyInString(string key, string sourceString); /*! =========================== @function Constructor ============================= */ BlogPost::BlogPost(string dictionaryContents){ userID = findIntegerForQuotedKeyInString("userId", dictionaryContents); blogID = findIntegerForQuotedKeyInString("id", dictionaryContents); title = findStringForQuotedKeyInString("title", dictionaryContents); body = findStringForQuotedKeyInString("body", dictionaryContents); } /*! =========================== @function findStringForQuotedKeyInString ============================= */ string findStringForQuotedKeyInString(string key, string sourceString){ key = "\"" + key + "\""; size_t index = sourceString.find(key); if(index >= sourceString.length() || index == string::npos){ printf("Warning key not found: %s\n", key.c_str() ); return ""; } index += key.length() ; sourceString = sourceString.substr(index, sourceString.length() - index); // There must be a double-quote char* lastCharacter = ((char*) sourceString.c_str() + sourceString.length() - 1); char* characterPtr = strstr(sourceString.c_str() , "\"" ); if(characterPtr == NULL || characterPtr >= lastCharacter){ return ""; } characterPtr++ ; char* characterPtr2 = characterPtr + 1; while (characterPtr2 < lastCharacter && *characterPtr2 != '"') { characterPtr2++ ; } string resultString = characterPtr; resultString = resultString.substr(0, characterPtr2 - characterPtr); return resultString; } /*! =========================== @function findIntegerForQuotedKeyInString ============================= */ int findIntegerForQuotedKeyInString(string key, string sourceString){ key = "\"" + key + "\""; char* characterPtr = strstr(sourceString.c_str() , key.c_str() ); if(characterPtr == NULL){ return -1; } characterPtr += key.length(); if (sourceString.length() == 0) { return -1; } // Find the first digit char* lastCharacter = ((char*) sourceString.c_str() + sourceString.length() - 1); while (characterPtr < lastCharacter && (*characterPtr < '0' || *characterPtr > '9' ) ) { characterPtr++ ; } if (characterPtr > lastCharacter) { return -1; } // Assignnment operator sourceString = characterPtr; int resultInteger = std::stoi (sourceString); return resultInteger; } #pragma mark - Setters /*! =========================== @function setUserID ============================= */ void BlogPost::setUserID(int newValue){ userID = newValue; } /*! =========================== @function setID ============================= */ void BlogPost::setID(int newValue){ blogID = newValue; } /*! =========================== @function setTitle ============================= */ void BlogPost::setTitle(string newValue){ title = newValue; } /*! =========================== @function setBody ============================= */ void BlogPost::setBody(string newValue){ body = newValue; } #pragma mark - Getters /*! =========================== @function getUserID ============================= */ int BlogPost::getUserID(){ return userID; } /*! =========================== @function getID ============================= */ int BlogPost::getID(){ return blogID; } /*! =========================== @function getTitle ============================= */ string BlogPost::getTitle(){ return title; } /*! =========================== @function getBody ============================= */ string BlogPost::getBody(){ return body; } /*! =========================== @function toString() @discussion print the posts's title & body on seperate lines ============================= */ string BlogPost::toString(){ string output = title + "\n" + body + "\n"; return output; } /*! =========================== @function print @discussion print the posts's title & body on seperate lines ============================= */ void BlogPost::print(){ cout << toString(); }
410233d634dd1fcf459d365237ddbb4383b5e819
306964c8f964c06c54c25f5cb4b5c9e9b0ad60f0
/OrionUO/Party.h
c2ffd5ed1d52bb031707f7b9403b99c28a8425be
[ "MIT" ]
permissive
Sghirate/Siebenwind-Beta-Client
d6b6116c2c15e9a5454021d7c658ea27c375f127
3ebda8bfebae36ea66691189fc641da374235dcf
refs/heads/master
2022-08-26T21:10:31.853391
2022-07-28T18:32:56
2022-07-28T18:32:56
477,818,125
0
0
MIT
2022-07-23T16:11:45
2022-04-04T18:07:40
C++
UTF-8
C++
false
false
379
h
Party.h
#pragma once #include "Core/Minimal.h" #include "Core/DataStream.h" #include "PartyObject.h" class CParty { public: u32 Leader = 0; u32 Inviter = 0; bool CanLoot = false; CPartyObject Member[10]; CParty(); ~CParty(); void ParsePacketData(Core::StreamReader& a_reader); bool Contains(int a_serial); void Clear(); }; extern CParty g_Party;
c6ddf879e9d88d9c9ea63264c1fce73d927ecfd1
e0b06e5734ab1b090cd074fa2c2355ee781e744c
/Program3_HashFunction/main.cpp
c93e48fe0296ef2b2aa50fcdd4b9446542990c2b
[ "Unlicense" ]
permissive
averymortenson/CSS-343
7869f2bce896f42ed0424b9c9acaf89056500dc9
5f093ff6714cdebac54c1e47cc1c6b6e9891770f
refs/heads/master
2020-06-01T16:02:10.864908
2018-03-04T05:20:03
2018-03-04T05:20:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,012
cpp
main.cpp
/* * Program 3: Implement Hash Functions for a phone book * Purpose main.cpp : Driver and process the input * @author Thuan Tran, CSSE Junior at the University of Washington Bothell * February 12th, 2017 * @version 1.1 */ #include <iostream> #include <fstream> #include "HashPhone.h" using namespace std; void processString(string line , HashPhone &thePhone) { string result = ""; string firstname = ""; string lastname = ""; for ( char x: line ) { if ( x == ',' ) { lastname = result; // ok we finished the last name result = ""; continue; } if ( x == '(' || x == ')' || x == '-' ) { if ( firstname == "" ) // if we reach this part of number, we finished the first name { firstname = result; result = ""; } continue; } if ( !isblank(x)) { // append everything else result = result + string(1 , x); } } // By this point, result should be the phone number thePhone.insert(firstname + " " + lastname , result); return; } int main() { cout << "There are 3 hash functions in this program" << endl; cout << "The one I used is the final one, but you can change it to the other two" << endl; cout << "I also included a method that will create text files that show the distribution and variance of the hash"; HashPhone * thePhone = new HashPhone(); ifstream phonebook("phonebook.txt"); string line = ""; if ( phonebook.is_open()) { while ( getline(phonebook , line)) // Process until the end of file { processString(line , *thePhone); } // Uncomment the part below to calculate the variance and receive a text file to show the distribution // You can also change the insert function in HashPhone.cpp and run again to see different result // Only need to change the name of the method finalHash to firstHash or secondHash in insert //thePhone->calculateVariance(); phonebook.close(); // Close the file when done } else { cout << "Unable to open file"; } delete thePhone; cout << "Finished"; return 0; }
201cd90943c9cac4e7784c96b996e53d28c6b47c
4e90bb515cd90d119eadd502c8f598c2c0ce5486
/kvDB/compator.h
a4606ed9526bf4f5b07cb9db4455609cc6476bd4
[]
no_license
wangbiaoyu/simpleDB
24b4546f41b78d237c74b4f3fa47d9180538814e
6b0ece678a83c717a671a428d833d23f1ef768a4
refs/heads/master
2020-05-30T21:07:47.638269
2020-02-16T04:48:30
2020-02-16T04:48:30
189,964,620
2
0
null
null
null
null
UTF-8
C++
false
false
163
h
compator.h
/*** * *2019-10-17 wby * ***/ #pragma once namespace kvDB{ class Compator{ public: virtual ~Compator(); virtual bool Compare() = 0; private: }; }
3f3d135b6addabb7daf36f44b875e3ba55c63cf7
993141583fcbbfc4862211518609d624d99ffe3e
/PourTX.hpp
6dc87f6a69a76a0444c33ca2c67574f8677046fb
[ "MIT" ]
permissive
jancarlsson/kapital
09de72d303e061e318613a42e8e19cd23e1f83dd
90f232e85b0f7b259eb56adf16f47c519be47ed8
refs/heads/master
2021-03-13T00:05:37.438949
2015-07-02T00:25:49
2015-07-02T00:25:49
38,401,784
4
4
null
null
null
null
UTF-8
C++
false
false
2,889
hpp
PourTX.hpp
#ifndef _KAPITAL_POUR_TX_HPP_ #define _KAPITAL_POUR_TX_HPP_ #include <sstream> #include <string> #include <vector> #include /*cryptopp*/ <oids.h> #include <snarkfront.hpp> #include <kapital/AddressKey.hpp> #include <kapital/Coin.hpp> #include <kapital/EncryptedCoin.hpp> #include <kapital/HashFunctions.hpp> #include <kapital/SignatureKey.hpp> namespace kapital { //////////////////////////////////////////////////////////////////////////////// // base class of pouring coins transaction // (cryptographic aspect) // template <typename FIELD> // CryptoPP::ECP or CryptoPP::EC2N class PourTX { typedef snarkfront::eval::MerkleAuthPath_SHA256 AUTHPATH; public: virtual ~PourTX() = default; // validity of public signature key only, not the transaction or proof bool valid() const { return m_valid; } // public input variables const HashDigest& merkleRoot() const { return m_merkleRoot; } const HashDigest& hSig() const { return m_hSig; } const std::vector<HashDigest>& serial_number() const { return m_oldSN; } const std::vector<HashDigest>& h() const { return m_oldH; } const std::vector<HashDigest>& commitment_cm() const { return m_newCM; } // count of input and output coins std::size_t oldCount() const { return m_oldCount; } std::size_t newCount() const { return m_newCount; } protected: PourTX() : m_valid(false), m_oldCount(0), m_newCount(0) {} PourTX(const CryptoPP::OID& curve, const HashDigest& merkleRoot) : m_signSKey(curve), m_signPKey(m_signSKey), m_valid(m_signSKey.valid() && m_signPKey.valid()), m_hSig(hashSig(m_signPKey)), m_merkleRoot(merkleRoot), m_oldCount(0), m_newCount(0) {} template <template <typename> class POUR, typename PAIRING> void setProofInput(const POUR<PAIRING>& dummy) { // zero knowledge proof inputs are part of signed message std::stringstream ss; ss << (*snarkfront::input<PAIRING>()); m_zkInput = ss.str(); } std::string sigMessage() const { std::stringstream ss; snarkfront::writeStream(ss, m_zkInput); snarkfront::writeStream(ss, m_zkProof); snarkfront::writeStream(ss, m_txInfo); for (const auto& a : m_newEncryptedCoin) ss << a; return ss.str(); } // root and signature SecretSig<FIELD> m_signSKey; PublicSig<FIELD> m_signPKey; bool m_valid; HashDigest m_hSig, m_merkleRoot; // message to sign std::string m_zkInput, m_zkProof, m_txInfo, m_msgSignature; // old coins std::size_t m_oldCount; std::vector<HashDigest> m_oldSN, m_oldH; // new coins std::size_t m_newCount; std::vector<EncryptedCoin<FIELD>> m_newEncryptedCoin; std::vector<HashDigest> m_newCM; }; } // namespace kapital #endif
9066cb0b371feabedac759bf0f980bbf2d0dbe49
5dd36c9dc3e6169b7a22529a75f620e42da80ee1
/00085. Maximal Rectangle.cpp
54768640e125d1a36c36a9a6acca10d5a5050107
[]
no_license
SanyaAttri/LeetCode
cdd6d3831f7a0f707285fd5bb9a5b11556efaa32
d0cf03fcd6525ceeee231ba7efe40955eec4314d
refs/heads/master
2022-12-24T20:58:20.040302
2020-10-10T11:12:27
2020-10-10T11:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
00085. Maximal Rectangle.cpp
//Accepted 28 ms cpp class Solution { public: int largestRectangleArea(vector<int>& height) { int ans = 0; height.push_back(0); int n = (int)height.size(); stack<int> s; int ranger = 0; while(ranger < n){ if(s.empty() || height[ranger] >= height[s.top()]) s.push(ranger++); else{ int index = s.top(); s.pop(); ans = max(ans, height[index] * (s.empty() ? ranger : ranger - s.top() - 1)); } } return ans; } int maximalRectangle(vector<vector<char>>& matrix) { if(!matrix.size()) return 0; size_t n = matrix.size(),m = matrix[0].size(); vector<int> heights(m,0); // init for(int i=0;i<m;i++){ if(matrix[0][i] == '1') heights[i] = 1; } int ans = largestRectangleArea(heights); for(int i=1;i<n;i++){ for(int j=0;j<m;j++){ if(matrix[i][j] == '1') heights[j]+=1; else heights[j] = 0; } ans = max(ans, largestRectangleArea(heights)); } return ans; } private: int max(const int a,const int b){ return a > b ? a : b; } };
5a54ef8b4837ffec46060310a150f7fb0aa5b775
b10702b48696b9457fe89e62d9a9cf320ea9f1b5
/first_last_pos_bs.cpp
0aab23a6caba9200a7b59665437b6ab99def4f84
[]
no_license
nikhiljha261/CP
93683e54c6e3fbced95d097dde1c1f13e7117402
7cdf93e63682e153407573e27947f889060c2309
refs/heads/main
2023-07-10T13:26:37.042363
2021-08-14T08:52:08
2021-08-14T08:52:08
339,957,988
1
0
null
null
null
null
UTF-8
C++
false
false
1,249
cpp
first_last_pos_bs.cpp
class Solution { public: vector<int> searchRange(vector<int>& a, int t) { vector<int> ans; vector<int> finall; int l=0; int h=a.size()-1; while(l<=h) { int mid=(l+h)/2; if(a[mid]==t) { ans.push_back(mid); h=mid-1; } else if(a[mid]>t) { h=mid-1; } else { l=mid+1; } } if(ans.size()!=0) finall.push_back(ans.back()); l=0; h=a.size()-1; while(l<=h) { int mid=(l+h)/2; if(a[mid]==t) { ans.push_back(mid); l=mid+1; } else if(a[mid]>t) { h=mid-1; } else { l=mid+1; } } if(ans.size()!=0) finall.push_back(ans.back()); if(finall.size()==0) { finall.push_back(-1); finall.push_back(-1); return finall; } return finall; } };
67b46ba37d25af4ad7ae38cb5ea87d5e261a29d2
b7da5c7433696943a474eca79b40633f3d9aa166
/src/undo/classitem/nsClassItem_changefontcommand.h
b457c5b4480fc95a255895337da1dc3febec0d79
[]
no_license
alakese/fUml
2cfb2f4103588ce2d1ac660bff5bd93c26690c4e
f405775cfd85e8fa6c198325c5bc4c86f99bf931
refs/heads/master
2020-02-26T17:25:23.626129
2016-10-03T14:57:36
2016-10-03T14:57:36
69,876,530
0
0
null
null
null
null
UTF-8
C++
false
false
744
h
nsClassItem_changefontcommand.h
#ifndef NSCLASSITEM_CHANGEFONTCOMMAND_H #define NSCLASSITEM_CHANGEFONTCOMMAND_H #include <QUndoCommand> #include <QFont> class ClassItem; /*! * \namespace nClassItem */ namespace nsClassItem { /*! * \brief The ChangeFontCommand class */ class ChangeFontCommand : public QUndoCommand { enum { ID = 3 }; ClassItem *m_pClassItem; QFont m_oldFont; QFont m_newFont; public: ChangeFontCommand(ClassItem *, QUndoCommand *parent = 0); ~ChangeFontCommand(); int id() const; void undo(); void redo(); bool mergeWith(const QUndoCommand *); QFont font() const; ClassItem *classItem() const; }; } // Namespace #endif // NSCLASSITEM_CHANGEFONTCOMMAND_H
967bece8a180d5e72701f1a274c3b4e7b1ba24f7
1f63dde39fcc5f8be29f2acb947c41f1b6f1683e
/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/video_coding/codecs/vp9/svc_rate_allocator.h
61297838974b526b39af202d33ff0e714a440d56
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webm", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-unknown-license-reference" ]
permissive
koobonil/Boss2D
09ca948823e0df5a5a53b64a10033c4f3665483a
e5eb355b57228a701495f2660f137bd05628c202
refs/heads/master
2022-10-20T09:02:51.341143
2019-07-18T02:13:44
2019-07-18T02:13:44
105,999,368
7
2
MIT
2022-10-04T23:31:12
2017-10-06T11:57:07
C++
UTF-8
C++
false
false
1,806
h
svc_rate_allocator.h
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_VIDEO_CODING_CODECS_VP9_SVC_RATE_ALLOCATOR_H_ #define MODULES_VIDEO_CODING_CODECS_VP9_SVC_RATE_ALLOCATOR_H_ #include BOSS_FAKEWIN_V_stdint_h //original-code:<stdint.h> #include <vector> #include BOSS_WEBRTC_U_api__video__video_bitrate_allocator_h //original-code:"api/video/video_bitrate_allocator.h" #include BOSS_WEBRTC_U_api__video_codecs__video_codec_h //original-code:"api/video_codecs/video_codec.h" namespace webrtc { extern const float kSpatialLayeringRateScalingFactor; extern const float kTemporalLayeringRateScalingFactor; class SvcRateAllocator : public VideoBitrateAllocator { public: explicit SvcRateAllocator(const VideoCodec& codec); VideoBitrateAllocation GetAllocation(uint32_t total_bitrate_bps, uint32_t framerate_fps) override; private: VideoBitrateAllocation GetAllocationNormalVideo( uint32_t total_bitrate_bps) const; VideoBitrateAllocation GetAllocationScreenSharing( uint32_t total_bitrate_bps) const; std::vector<size_t> SplitBitrate(size_t num_layers, size_t total_bitrate, float rate_scaling_factor) const; bool AdjustAndVerify(std::vector<size_t>* spatial_layer_bitrate_bps) const; const VideoCodec codec_; }; } // namespace webrtc #endif // MODULES_VIDEO_CODING_CODECS_VP9_SVC_RATE_ALLOCATOR_H_
e7e9bd5f7c7d2821bb09209db631aa7e3391e154
e91828f8e87a17b942cc26da4bf061f65e3a04c8
/searchlib/src/vespa/searchlib/transactionlog/trans_log_server_explorer.h
65d3a687bc959645fb4d38e95f07e7dfd200ca1e
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
NolanJos/vespa
69dbe95b1a9e8cba2879d7b39d882501dc92bebc
fdc4350398029fbffbed3c0498380589a73571d7
refs/heads/master
2022-08-02T10:29:40.065863
2020-06-02T12:47:31
2020-06-02T12:47:31
268,804,702
1
0
Apache-2.0
2020-06-02T13:12:47
2020-06-02T13:12:46
null
UTF-8
C++
false
false
795
h
trans_log_server_explorer.h
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "translogserver.h" #include <vespa/vespalib/net/state_explorer.h> namespace search::transactionlog { /** * Class used to explore the state of a transaction log server. */ class TransLogServerExplorer : public vespalib::StateExplorer { private: TransLogServer::SP _server; public: TransLogServerExplorer(TransLogServer::SP server) : _server(std::move(server)) {} virtual void get_state(const vespalib::slime::Inserter &inserter, bool full) const override; virtual std::vector<vespalib::string> get_children_names() const override; virtual std::unique_ptr<StateExplorer> get_child(vespalib::stringref name) const override; }; }
dee6d8a87dedd648999d013019e23aeb5583e4a6
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/www/iridium/files/patch-chrome_common_media_cdm__host__file__path.cc
5e89b583ca027ebf32d17986fd0169d3bcc4b4f2
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
519
cc
patch-chrome_common_media_cdm__host__file__path.cc
--- chrome/common/media/cdm_host_file_path.cc.orig 2023-03-13 07:33:08 UTC +++ chrome/common/media/cdm_host_file_path.cc @@ -90,7 +90,7 @@ void AddCdmHostFilePaths( cdm_host_file_paths->emplace_back(chrome_framework_path, chrome_framework_sig_path); -#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) +#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_BSD) base::FilePath chrome_exe_dir; if (!base::PathService::Get(base::DIR_EXE, &chrome_exe_dir))
c7173eb2890376d20b1ddcdf1ae7052b48016e69
ca00c1ec7d540afac296302bead0b4e6432bb0ec
/common/inflate.cpp
682a0c2902cb871aa331191de6a363e24545d805
[]
no_license
jterweeme/wincore
18f7f4c2a5c3ecc83cd35d12f018cb50bc0743aa
923552d5ad6dfacdab56da328d68e83eb5f37f09
refs/heads/master
2016-09-05T22:12:21.976461
2015-10-15T14:55:41
2015-10-15T14:55:41
20,522,477
0
0
null
null
null
null
UTF-8
C++
false
false
5,720
cpp
inflate.cpp
#include "inflate.h" bool Inflate::readBuf() { bool isFinal = _bi->readBool(); int type = _bi->readBits(2); _buf.clear(); switch (type) { case 0: _decRaw(_buf); break; case 1: _decHuff(_lit, _dist, _buf); break; case 2: { Pair2 temp = _makePair(); _decHuff(temp.a, temp.b, _buf); } break; default: throw "Assertion Error"; } _it = _buf.begin(); _itinit = true; _nodeDump.clear(); return isFinal; } bool Inflate::read(ostream &os) { bool isFinal = readBuf(); for (vector<uint8_t>::iterator it = _buf.begin(); it != _buf.end(); it++) os.put(*it); return isFinal; } int Inflate::read() { if (!_itinit) _isFinal = readBuf(); //if (_it >= _buf.end() && !_isFinal) if (_it == _buf.end() && !_isFinal) _isFinal = readBuf(); //return _it >= _buf.end() ? -1 : *_it++; return _it == _buf.end() ? -1 : *_it++; } int Inflate::_decDist(int sym) { int i = sym / 2 - 1; return sym <= 3 ? sym + 1 : (sym % 2 + 2 << i) + 1 + _bi->readBits(i); } Pair2 Inflate::_makePair() { int nlit = _bi->readBits(5) + 257, ndist = _bi->readBits(5) + 1, ncode = _bi->readBits(4) + 4; Nau a(19, 0); a.set(16, _bi->readBits(3)); a.set(17, _bi->readBits(3)); a.set(18, _bi->readBits(3)); a.set(0, _bi->readBits(3)); for (int i = 0; i < ncode - 4; i++) { int j = i % 2 == 0 ? 8 + i / 2 : 7 - i / 2; int x = _bi->readBits(3); a.set(j, x); } Node b = _toct(a); Nau c(nlit + ndist, 0); for (int i = 0, runVal = -1, runLen = 0, sym; i < c.length(); i++) { if (runLen > 0) { c.set(i, runVal); runLen--; } else { switch (sym = _decSym(&b)) { case 16: runLen = _bi->readBits(2) + 3; i--; break; case 17: runVal = 0; runLen = _bi->readBits(3) + 3; i--; break; case 18: runVal = 0; runLen = _bi->readBits(7) + 11; i--; break; default: c.set(i, sym); runVal = sym; } } } Nau litLenCodeLen = c.copyOf(nlit); Node litLenCode = _toct(litLenCodeLen); Nau distCodeLen = c.copyOfRange(nlit, c.length()); Node distCode = _toct(distCodeLen); return Pair2(litLenCode, distCode); } Inflate::Inflate(BitInput2 *bi) : _bi(bi), _dict(32 * 1024) { vector<int> llcodelens(288); fill_n(llcodelens.begin(), 144, 8); fill_n(llcodelens.begin() + 144, 112, 9); fill_n(llcodelens.begin() + 256, 24, 7); fill_n(llcodelens.begin() + 280, 8, 8); Nau llcodeLens2(llcodelens); _lit = _toct(llcodeLens2); Nau distcodelens(32, 5); _dist = _toct(distcodelens); } void CircularDict::append(int b) { _data[_index] = (uint8_t)b; _index = _mask != 0 ? (_index + 1) & _mask : (_index + 1) % _data.size(); } void CircularDict::copy(int dist, int len, vector<uint8_t> &os) { for (int readIndex = (_index - dist + _data.size()) & _mask; len > 0 && _mask != 0; len--) { os.push_back(_data[readIndex]); _data[_index] = _data[readIndex]; readIndex = (readIndex + 1) & _mask; _index = (_index + 1) & _mask; } for (int j = (_index - dist + _data.size()) % _data.size(); len > 0 && _mask == 0; len--) { os.push_back(_data[j]); _data[_index] = _data[j]; j = (j + 1) % _data.size(); _index = (_index + 1) % _data.size(); } } Nau Nau::copyOfRange(int start, int end) const { Nau r(end - start); for (int i = 0; i < end - start; i++) r.set(i, _a[i + start]); return r; } int Inflate::_decRaw(vector<uint8_t> &os) { int len = _bi->readBits(16); _bi->ignore(16); for (int i = 0; i < len; i++) { int temp = _bi->readByte(); os.push_back(temp); _dict.append(temp); } return len; } void Inflate::_decHuff(Node lit, Node dist, vector<uint8_t> &os) { for (int sym; (sym = _decSym(&lit)) != 256;) { if (sym < 256) { os.push_back(sym); _dict.append(sym); } else { int len = _decRll(sym), distSym = _decSym(&dist); _dict.copy(_decDist(distSym), len, os); } } } int Inflate::_decSym(Node *n) { Node *next = _bi->readBool() ? n->right : n->left; for (n = next; next->type == 1; n = next) next = _bi->readBool() ? n->right : n->left; return next->symbol; } int Inflate::_decRll(int sym) { int i = (sym - 261) / 4; if (sym <= 264) return sym - 254; if (sym <= 284) return ((sym - 265) % 4 + 4 << i) + 3 + _bi->readBits(i); return 258; } Node Inflate::_toct(Nau &x) { vector<Node *> nodes; for (int i = x.max(); i >= 1; i--) { vector<Node *> newNodes; for (int j = 0; j < x.length(); j++) { if (x.get(j) == i) { _nodeDump.push_back(Node(j)); newNodes.push_back(&_nodeDump.back()); } } for (uint32_t j = 0; j < nodes.size(); j+= 2) { _nodeDump.push_back(Node(nodes.at(j), nodes.at(j + 1))); newNodes.push_back(&_nodeDump.back()); } nodes.clear(); for (vector<Node *>::const_iterator it = newNodes.cbegin(); it != newNodes.cend(); it++) nodes.push_back(*it); } return Node(nodes.at(0), nodes.at(1)); }
7cd5f51d45668e9028936a9582a0c5ed269cedd3
ce1e8b29ffd9d97ffc5c693fe3bd4ee358b5e1d5
/src/Main/Help/HelpLinkHandler.cpp
16904fc59eadd63f8399a0fd5962125c48d08057
[ "MIT" ]
permissive
voxie-viewer/voxie
d76fe7d3990b14dea34e654378d82ddeb48f6445
2b4f23116ab1c2fd44b134c4265a59987049dcdb
refs/heads/master
2023-04-14T13:30:18.668070
2023-04-04T10:58:24
2023-04-04T10:58:24
60,341,017
6
1
MIT
2022-11-29T06:52:16
2016-06-03T10:50:54
C++
UTF-8
C++
false
false
5,663
cpp
HelpLinkHandler.cpp
/* * Copyright (c) 2014-2022 The Voxie Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "HelpLinkHandler.hpp" #include <Voxie/Component/HelpCommon.hpp> #include <Main/Gui/HelpWindow.hpp> #include <Main/Gui/SidePanel.hpp> #include <Main/Root.hpp> #include <VoxieBackend/Component/Extension.hpp> #include <QDesktopServices> using namespace vx::help; using namespace vx; HelpLinkHandler::HelpLinkHandler(gui::HelpWindow* window) : window(window) {} void HelpLinkHandler::handleLink(QUrl url) { if (url.scheme() == Protocol) { QString suffix = "//" + url.authority() + url.path(); if (suffix.startsWith(commands::Help)) { openHelp(url.toString()); } else if (suffix.startsWith(commands::Create)) { createNodeByName(suffix.mid(commands::Create.length())); } else if (suffix.startsWith(commands::EditMarkdown)) { openMarkdown(suffix.mid(commands::EditMarkdown.length())); } else if (suffix.startsWith(commands::EditSource)) { openSourceCode(suffix.mid(commands::EditSource.length())); } else if (suffix.startsWith(commands::DBus)) { QString path = suffix.mid(commands::DBusNoSlash.length()); // qDebug() << "Opening link:" << path; auto obj = ExportedObject::lookupWeakObject(QDBusObjectPath(path)); // auto obj = ExportedObject::lookupObject(QDBusObjectPath(path)); if (!obj) { qWarning() << "Attempting to open link pointing to non-existing object:" << url; return; } // Support links for other object types? auto node = dynamic_cast<Node*>(obj); // auto node = dynamic_cast<Node*>(obj.data()); if (!node) { qWarning() << "Attempting to open link pointing to object which is not " "a Node:" << url; return; } Root::instance() ->mainWindow() ->sidePanel->dataflowWidget->clearSelectedNodes(); Root::instance()->mainWindow()->sidePanel->dataflowWidget->selectNode( node); } else { qWarning() << "Unhandled URL:" << url; } } else if (url.scheme() == "doi") { QDesktopServices::openUrl( "https://dx.doi.org/" + QString::fromUtf8(QUrl::toPercentEncoding(url.path()))); } else { QDesktopServices::openUrl(url); } } void HelpLinkHandler::openMarkdown(QString prototypeName) { // TODO: This currently does not work if the help file is in the script folder QString filePath = Root::instance()->directoryManager()->docPrototypePath() + "/" + prototypeName + ".md"; // need to create the file first? if (!QFileInfo(filePath).exists()) { QFile file(filePath); file.open(QIODevice::WriteOnly | QIODevice::Text); file.close(); } QDesktopServices::openUrl( QUrl::fromLocalFile(QFileInfo(filePath).absoluteFilePath())); } void HelpLinkHandler::openSourceCode(QString prototypeName) { if (Root::instance()->prototypeMap().contains(prototypeName)) { auto extension = qSharedPointerDynamicCast<Extension>( Root::instance()->prototypeMap()[prototypeName]->container()); if (extension) { auto scriptFilename = extension->scriptFilename(); QDesktopServices::openUrl(QUrl::fromLocalFile(scriptFilename)); } else { qWarning() << "Could not find source for prototype" << prototypeName; } } else { qWarning() << "Attempt open source code for invalid prototype" << prototypeName << "from URL"; } } void HelpLinkHandler::createNodeByName(QString prototypeName) { if (Root::instance()->prototypeMap().contains(prototypeName)) { Root::instance()->prototypeMap()[prototypeName]->create({}, {}, {}); Root::instance()->mainWindow()->activateWindow(); } else { qWarning() << "Attempt create invalid node" << prototypeName << "from URL"; } } void HelpLinkHandler::openHelp(QString uri) { // Enqueue this for later to avoid problems if this is called as a link // handler if (!this->window) { enqueueOnMainThread([uri]() { auto window = Root::instance()->helpWindow(); window->openHelpForUri(uri); // Raise and activate the window to make sure the help is visible // window->raise(); window->activateWindow(); }); } else { // Use the help window where the link was clicked (if there are multiple // help windows at some point) // Note: There should be no need to raise/activate the window QPointer<vx::gui::HelpWindow> helpWin = window; enqueueOnMainThread([uri, helpWin]() { if (helpWin) helpWin->openHelpForUri(uri); }); } }
61cbdf632d7a7c3a38a878526053340aac082f97
3e5bda41c14806ff2e459acb15e63022ba5eeb47
/OnlineJudge/PTA/基础编程题目集/编程题/念数字.cpp
07adb27271e2d44137bd5029f56cc6b48165ba22
[]
no_license
CrazyIEEE/algorithm
d3ab6e50b3e54a99d86924c6e4a86b8c491b2a40
89755fc95c2bace7e644af189ec29df9a2ffb277
refs/heads/master
2022-12-31T11:13:03.868343
2020-10-14T13:18:49
2020-10-14T13:18:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
cpp
念数字.cpp
/* 7-25 念数字 (15 分) 输入一个整数,输出每个数字对应的拼音。当整数为负数时,先输出fu字。十个数字对应的拼音如下: 0: ling 1: yi 2: er 3: san 4: si 5: wu 6: liu 7: qi 8: ba 9: jiu 输入格式: 输入在一行中给出一个整数,如:1234。 提示:整数包括负数、零和正数。 输出格式: 在一行中输出这个整数对应的拼音,每个数字的拼音之间用空格分开,行末没有最后的空格。如 yi er san si。 输入样例: -600 输出样例: fu liu ling ling */ #include "iostream" #include "string" #include "map" int main() { const std::map<int, std::string> map{{0, "ling"}, {1, "yi"}, {2, "er"}, {3, "san"}, {4, "si"}, {5, "wu"}, {6, "liu"}, {7, "qi"}, {8, "ba"}, {9, "jiu"}}; std::string num; std::cin >> num; int size = num.size(); for (int i = 0; i < size; i++) { if (num[i] == '-') { std::cout << "fu"; } else { std::cout << map.at(num[i] - '0'); } if (i != size - 1) { std::cout << ' '; } } return 0; }
35a7a8120ee97a15be3d9936919925a8c3d6a673
f458eed2608bf9683facceafb8b528595edc0710
/src/OrderedListKerningPairsProc.h
9a3591eeea9b4ced3ab3f68ade2280c8fe3c0b3c
[ "ICU" ]
permissive
testerjp/icu-le-aat
0bda384f7b930fb4177b442b3481c5eaea5f2857
0aea390c3f63c464259d04e3dedff286977716c6
refs/heads/master
2020-06-01T01:17:31.396853
2020-01-27T14:27:23
2020-01-27T14:27:23
23,158,133
3
0
null
null
null
null
UTF-8
C++
false
false
1,349
h
OrderedListKerningPairsProc.h
#ifndef _ORDEREDLISTKERNINGPAIRSPROC_H #define _ORDEREDLISTKERNINGPAIRSPROC_H /** * \file * \internal */ #include "LETypes.h" #include "LETableReference.h" #include "SubtableProcessor.h" #include "OrderedListKerningPairs.h" U_NAMESPACE_BEGIN class OrderedListKerningPairsProcessor : public SubtableProcessor { public: void process(LEGlyphStorage &glyphStorage, LEErrorCode &success); OrderedListKerningPairsProcessor(LEReferenceTo<OrderedListKerningPairsHeader> header, LEErrorCode &success); protected: OrderedListKerningPairsProcessor(); virtual ~OrderedListKerningPairsProcessor(); const KerningPair *search(le_uint32 key, LEErrorCode &success) const; le_uint16 nPairs; le_uint16 searchRange; le_uint16 entrySelector; le_uint16 rangeShift; LEReferenceTo<OrderedListKerningPairsHeader> orderedListKerningPairsHeader; LEReferenceToArrayOf<KerningPair> pairs; private: OrderedListKerningPairsProcessor(const OrderedListKerningPairsProcessor &other); // forbid copying of this class OrderedListKerningPairsProcessor &operator=(const OrderedListKerningPairsProcessor &other); // forbid copying of this class }; U_NAMESPACE_END #endif
62414f205825f4d0563d021d753bc51651383db1
b1655969f756480bfc1c5c7fc448a197ce7bc311
/Programming_Assignments/Final Project SourceCode/final.cpp
3e89f862c9d56a7988e0c1012562872d92deb4f2
[]
no_license
MarcusBlaisdell/ParallelProgramming
90747ae71e02db5386479787792d036dc52f9abb
c1abffd871cb29c19b246d0f0e940cad9a9894fb
refs/heads/main
2023-05-31T22:07:20.208172
2021-06-17T21:08:22
2021-06-17T21:08:22
377,959,040
0
0
null
null
null
null
UTF-8
C++
false
false
13,796
cpp
final.cpp
/************************************* * Marcus Blaisdell * Cpt_S 411 * * Final Project: * Parallel PageRank Estimator * * final.cpp * *************************************/ #include "final.h" // function buildProbabilityArray // Accepts a probability value, // returns an array of size 1000 of // evenly distributed heads and tails // based on the given probability // distribution from the user. // This array will be used for the // coin toss by allowing us to choose // a random number between 0 and 999 // to select a coin from the array. // Since the distribution of the // heads and tails in the array is // in the proportion of the given // probability, selecting one position // at random is the effective result of // flipping a coin that has that probability. // Since the probability is the same // for every iteration, this array // should only be built once and then // referenced for each coin toss void buildProbabilityArray (float D, int * coin) { int Heads = D * 1000; int Tails = 1000 - Heads; int modVal = 0; int j = 0; if (Heads > Tails) { modVal = Heads / Tails; } // end if Heads > Tails else { modVal = Tails / Heads; } // end else, Heads < Tails /* cout << "D: " << D << endl; cout << "Heads: " << Heads << endl; cout << "Tails: " << Tails << endl; cout << "modVal: " << modVal << endl; */ // first, populate an array of size 1000 // with a rough approximation of our // probability value distribution of // 1's and 0's: for (j = 0; j < 1000; j++) { if ((j % modVal) == 0) { if (Heads > Tails) { coin[j] = 0; } // end if Head > Tails, populate with Tails else { coin[j] = 1; } // end else, populate with Heads } // end if else { if (Heads > Tails) { coin[j] = 1; } // end if Head < Tails, populate with Heads else { coin[j] = 0; } // end else, populate with Tails } // end else, heads } // end for loop /* for (j = 0; j < 1000; j++) { cout << coin[j]; } cout << endl; */ } // end function buildProbabilityArray // function flipCoin // accepts a probability, D // and uses this to flip a coin // and return the result // 0 is tails, 1 is heads // To use D to create a probability, // I first multiply D by 1000 to obtain // my Heads count. // The Tails count is then 1000 - Heads Count // I then create a single array of // (count of heads) 1's, and (count of tails) 0's // interlaced in the array int flipCoin (int * coin, int i) { int randomValue = 0; // select a random value between 0 and 1000: srand(time(NULL) + i); randomValue = rand () % 1000; return coin[randomValue]; } // end function flipCoin // function getNodeCount: // accepts a string // and reads the value for Nodes // and returns it as an int // Assumes that the string it receives // is in the form: // # Nodes: xxxxxx Edges: yyyyy int getNodeCount (string line) { int Nodes = 0; int i = 9; // read each digit in the number // and build the full value: while (line[i] != ' ') { // we will successively build the full value by // multiplying the current value by ten, // and adding the next digit: Nodes *= 10; Nodes += line[i++] - '0'; } // end for loop return Nodes; } // end function getNodeCount // function loadGraph: // accepts a pointer to a filename, // and a pointer to an int to store the total // number of nodes and // creates a local copy of a Graph Array and // loads the data from the text file into the array // and returns the array to the caller Graph * loadGraph (char * filename, int * NodesCount) { string line; string theNodeString; string outEdgeString; int Nodes = 0, startNode = 0; int theNodeInt = 0; int outEdgeInt = 0; int currentNode = 0; int i = 0, x = 0; Graph * theGraph; ifstream inFile; // open the file for reading: inFile.open (filename); // read the file in to our array: // some of the nodes are missing // missing nodes will still be represented in the Array // but will have a 0 edge count // Note: a node can be present and have no outgoing edges, // this will be represented as an edge count of 0 and // notes that the node does exist but has no links while (getline (inFile, line) ) { // remove the line break: // ******************************************************** // (Use this for all files except the facebook file) // (For some reason, the facebook file is formatted) // (differently and removing the last char removes actual) // (data and not a line break) // ******************************************************** line.pop_back (); // reset position to 0: i = 0; // if we have comments, // read through them looking // for a Node count: if (line[0] == '#') { while (line[0] == '#') { // !!!This could be improved **FIX** if (line[2] == 'N' && line[3] == 'o' && line[4] == 'd' && line[5] == 'e' && line[6] == 's' && line[7] == ':') { // if we have found a line that contains the string 'Nodes: ', // parse it into a node count: Nodes = getNodeCount (line); *NodesCount = Nodes; //cout << "Nodes: " << Nodes << endl; } // end get number of nodes getline (inFile, line); // ******************************************************** // (Use this for all files except the facebook file) // (For some reason, the facebook file is formatted) // (differently and removing the last char removes actual) // (data and not a line break) // ******************************************************** line.pop_back (); } // end look through commented lines // Now that we know how many nodes we have, // make our graph the right size: theGraph = (Graph*) malloc (Nodes * sizeof (Graph)); } // end if we have commented lines // parse the input: // everything up to the first space/tab is the node id: while (line[i] != '\t' and line[i] != ' ') { theNodeString += line[i]; i++; } // end concatenate all numerics into node id // the outgoing edge is everything to the end of the line: while (line[i]) { outEdgeString += line[i]; i++; } // end get the id of the outgoing edge // convert the nodeID from string to int: theNodeInt = stoi (theNodeString); // There are two possible conditions here: // // 1: the node we are currently pointing to // is the node we need to store the // out edge to // If we are currently pointing to // the node we are storing values for, // then just add the outgoing edge // onto the current node out edge array, // // 2: the node id we just read is past the // current node we are pointing to // In this case, increment the // node we are pointing to // and check if we are now at the // right node, if yes, add the // out edge onto this node, // if not, then we have empty nodes // between the last node we had edges for // and this current node, and we need to // note that there are nodes that do not // have outgoing edges by storing a 0 // for the edge count at those nodes: outEdgeInt = stoi(outEdgeString); if (theNodeInt == currentNode) { // If the nodeID has not been updated to match // the currentNode, update it: if (theGraph[currentNode].nodeID != currentNode) { theGraph[currentNode].nodeID = currentNode; } // end update nodeID // I had to add a counter to keep track of the number of edges // since there isn't an easy way to get an array size in C // so, whenever we add an edge to a node, increment this counter // and since we're using dynamic memory, we need to increase the // allocation using realloc and then add the new edge: theGraph[currentNode].edgeCount++; theGraph[currentNode].outEdge = (int *) realloc (theGraph[currentNode].outEdge, theGraph[currentNode].edgeCount * sizeof(int)); theGraph[currentNode].outEdge[theGraph[currentNode].edgeCount - 1] = outEdgeInt; } // end push on edge else { // if the current node doesn't match the node we just read, // then we have just encountered our next node and we need // to test if there are empty nodes between the last node // we added edges to and this node // move to the next node and evaluate: theGraph[currentNode].nodeID = currentNode; currentNode++; // If the new node we just moved to // does not match the node we have an out edge for, // then we are pointing to a node that does not have // an out edge and we need to note this by storing a // 0 at that nodes edge count and then progress // to the next node: while (currentNode != theNodeInt) { // If there are no edges to add to a node, // We will leave the edge count at default 0 // and skip over doing anything with this node: theGraph[currentNode].nodeID = currentNode; currentNode++; } // end increment currentNode to match the actual node // we should now have moved to the next valid node // for which we have an outgoing edge // and we still have our outEdge from our last read // so we need to add that to this current node: theGraph[currentNode].edgeCount++; theGraph[currentNode].outEdge = (int *) realloc (theGraph[currentNode].outEdge, theGraph[currentNode].edgeCount * sizeof(int)); theGraph[currentNode].outEdge[theGraph[currentNode].edgeCount - 1] = outEdgeInt; } // end move to correct node //cout << "theNodeString: " << theNodeString << endl; //cout << "outEdgeString: " << outEdgeString << endl; theNodeString.clear (); outEdgeString.clear (); } // end read nodes from file // return the populated graph: return theGraph; } // end function loadGraph // function choose_d_u: // accepts an int value that is the // number of nodes to choose from // with equal probability, // chooses a number from 0 to this value // randomly and returns it: int choose_d_u (int d_u, int i) { int randomValue = 0; srand(time(NULL) + i); randomValue = rand () % d_u; return randomValue; } // end function choose_d_u // printTop5 function // accepts a pointer to a Graph array, // finds the top 5 ranked nodes and prints them void printTop5 (Graph * theGraph, int NodesCount) { // store the nodeID's and page ranks of the top 5 nodes int theTop[5][2] = {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}}; int i = 0; while (i < NodesCount) { /* cout << "theGraph[" << i << "]: " << theGraph[i].pageRank << endl; cout << "theTop[0][1]" << theTop[0][1] << endl; cout << "theTop[1][1]" << theTop[1][1] << endl; cout << "theTop[2][1]" << theTop[2][1] << endl; cout << "theTop[3][1]" << theTop[3][1] << endl; cout << "theTop[4][1]" << theTop[4][1] << endl; */ if (theGraph[i].pageRank > theTop[0][1]) { //cout << theGraph[i].pageRank << " > " << theTop[0][1] << endl; theTop[4][0] = theTop[3][0]; theTop[4][1] = theTop[3][1]; theTop[3][0] = theTop[2][0]; theTop[3][1] = theTop[2][1]; theTop[2][0] = theTop[1][0]; theTop[2][1] = theTop[1][1]; theTop[1][0] = theTop[0][0]; theTop[1][1] = theTop[0][1]; theTop[0][0] = theGraph[i].nodeID; theTop[0][1] = theGraph[i].pageRank; i++; continue; } // end if greater than top 1 else if (theGraph[i].pageRank > theTop[1][1]) { //cout << theGraph[i].pageRank << " > " << theTop[1][1] << endl; theTop[4][0] = theTop[3][0]; theTop[4][1] = theTop[3][1]; theTop[3][0] = theTop[2][0]; theTop[3][1] = theTop[2][1]; theTop[2][0] = theTop[1][0]; theTop[2][1] = theTop[1][1]; theTop[1][0] = theGraph[i].nodeID; theTop[1][1] = theGraph[i].pageRank; i++; continue; } // end if greater than top 2 else if (theGraph[i].pageRank > theTop[2][1]) { //cout << theGraph[i].pageRank << " > " << theTop[2][1] << endl; theTop[4][0] = theTop[3][0]; theTop[4][1] = theTop[3][1]; theTop[3][0] = theTop[2][0]; theTop[3][1] = theTop[2][1]; theTop[2][0] = theGraph[i].nodeID; theTop[2][1] = theGraph[i].pageRank; i++; continue; } // end if greater than top 3 else if (theGraph[i].pageRank > theTop[3][1]) { //cout << theGraph[i].pageRank << " > " << theTop[3][1] << endl; theTop[4][0] = theTop[3][0]; theTop[4][1] = theTop[3][1]; theTop[3][0] = theGraph[i].nodeID; theTop[3][1] = theGraph[i].pageRank; i++; continue; } // end if greater than top 4 else if (theGraph[i].pageRank > theTop[4][1]) { //cout << theGraph[i].pageRank << " > " << theTop[4][1] << endl; theTop[4][0] = theGraph[i].nodeID; theTop[4][1] = theGraph[i].pageRank; } // end if greater than top 5 i++; } // end iterate through the graph for (i = 0; i < 5; i++) { cout << "rank " << i + 1 << ": " << theTop[i][0] << " : " << theTop[i][1] << endl; } // end print top 5 node id's and page ranks } // end printTop5 function
f315e52d9a471db46c4934ab3c27bf1642de64fa
276ee0e4eedffc995c344ae592b94a87a10d1462
/List.h
42e6051a737ac44274ce96dbd74364a97ec3263b
[]
no_license
epigeneticschick/proj06
c68214557007c4a3c204e60f750576f9eb175f38
a604ccef704a55aa6173be57e4393874d675907d
refs/heads/master
2020-04-04T15:16:18.184671
2018-11-03T22:59:59
2018-11-03T22:59:59
156,031,074
0
0
null
null
null
null
UTF-8
C++
false
false
9,893
h
List.h
/*List.h adds functionality to a list * List.h * Lorrayya Williams and Andrew Baker * Created on: Oct 9, 2018 * Author: llw5 */ #ifndef LIST_H_ #define LIST_H_ #include <iostream> #include <fstream> #include <stdexcept> #include <cassert> using namespace std; template <class Item> class List { public: List(); unsigned getSize() const; Item getFirst() const; Item getLast() const; void append(const Item& it); ~List(); List(const List& original); List& operator=(const List& original); bool operator!=(const List& original); void writeTo(ostream& out, char sep) const; void readFrom(const string& fileName); unsigned getIndexOf(unsigned value); Item remove(int index); bool operator==(const List& next); void readFrom(istream& in); void writeTo(const string& fileName, char sep) const; void prepend(const Item& pre); void insert(const Item& add, unsigned index); bool insertAfter(Item otherName, Item yourName); bool insertBefore(Item otherName,Item yourName); private: struct Node { Item myItem; Node*myNext; Node(); Node(Item it, Node*next); ~Node(); }; unsigned mySize; Node * myFirst; Node * myLast; friend class ListTester; }; //Default Constructor template <class Item> List<Item>::List(){ mySize = 0; myFirst = NULL; myLast = NULL; } //Default Node Constructor template <class Item> List<Item>::Node::Node() { myItem = Item(); myNext = NULL; } //Node Constructor template <class Item> List<Item>::Node::Node(Item it, Node*next){ myItem = it; myNext = next; } //Accessor for Size template <class Item> unsigned List<Item>::getSize() const{ return mySize; } //Accessor for myFirst template <class Item> Item List<Item>::getFirst() const{ if(mySize < 0 || myFirst == NULL){ throw underflow_error("There is no First Node!"); } else{ return myFirst->myItem; } } //Accessor for myLast template <class Item> Item List<Item>::getLast() const{ if(mySize < 0 || myFirst == NULL){ throw underflow_error("There is no First Node!"); } else{ return myLast->myItem; } } //Appends the item to a list template <class Item> void List<Item>::append(const Item& it){ Node *nodePtr= new Node(it, NULL); if(myFirst == NULL){ myFirst = nodePtr; } else{ myLast->myNext = nodePtr; } myLast = nodePtr; mySize += 1; } // List Destructor template <class Item> List<Item>::~List() { delete myFirst; // delete first node, invoking ~Node() (does nothing if myFirst == NULL) myFirst = myLast = NULL; // clear myFirst and myLast (optional) mySize = 0; // clear mySize (optional) } //Node Destructor template <class Item> List<Item>::Node::~Node() { // cout << "~Node() is deallocating the node containing item " // << myItem << endl; delete myNext; // delete the next node, invoking ~Node() in it // (does nothing if myNext == NULL) } //List Deep Copy Constructor template <class Item> List<Item>::List(const List& original) { myFirst = myLast = NULL; // set pointers mySize = 0; // and size to 'empty' values Node* oPtr = original.myFirst; // start at the first node while (oPtr != NULL) { // while there are nodes to copy: append(oPtr->myItem); // append the item in that node oPtr = oPtr->myNext; // advance to next node } } //List deep assignment operator template <class Item> List<Item>& List<Item>::operator=(const List& original){ if (myFirst != original.myFirst){ myFirst = myLast = NULL; // set pointers delete myFirst; mySize = 0; // and size to 'empty' values Node* nPtr = original.myFirst; // start at the first node while (nPtr != NULL) { // while there are nodes to copy: append(nPtr->myItem); // append the item in that node nPtr = nPtr->myNext; // advance to next node } } return *this; } /*Written by Lorrayya Williams * Performs inequality operation for list * Param: List * Return: boolean*/ template <class Item> bool List<Item>::operator!=(const List& original){ if(mySize == original.mySize){ return false; } if(myFirst == original.myFirst) { if(myLast == original.myLast){ Node* nPtr = myFirst; Node* nPtr2 = original.myFirst; while(nPtr != NULL){ nPtr->myItem == nPtr2->myItem; nPtr = nPtr->myNext; } } } else { return true; } } /*Written by Lorrayya Williams * Writes values from a list to a file * Param: * Return: */ template <class Item> void List<Item>::writeTo(ostream& out, char sep) const{ Node *nPtr = myFirst; for(unsigned i= 0; i< mySize; i++){ out << nPtr->myItem << sep; nPtr= nPtr->myNext; } out <<endl; } /*Written by Lorrayya Williams * Reads values from a file * Param: fileNAme * Return: in */ template <class Item> void List<Item>::readFrom(const string& fileName) { ifstream in(fileName.c_str()); assert(in.is_open()); Item it; while(!in.eof()){ in >> it; append(it); } in.close(); } /*Written by Lorrayya Williams * Accessor for Index of Value * Param: Value * Return: unsigned integer which is index*/ template <class Item> unsigned List<Item>::getIndexOf(unsigned value){ Node* nPtr = myFirst; unsigned index = 0; while(nPtr != NULL){ if(nPtr->myItem == value){ return index; } nPtr = nPtr->myNext; index += 1; } throw invalid_argument("That number is not in the list!"); } /*Written by Lorrayya Williams * Removes items from a list based upon index * Param: Index * Return: value of index*/ template <class Item> Item List<Item>::remove(int index) { //removes a value from a list at index if (mySize == 0) { throw range_error("list is empty"); } int intmySize; intmySize = mySize; //to get rid of compilation warnings Node *bremPtr = myFirst; //before remove Node *remPtr = myFirst; //remove Item val; if (index <= 0) { myFirst = remPtr->myNext; val = remPtr->myItem; mySize -= 1; //decrement size remPtr = NULL; delete remPtr; //delete node return val; //return val at index } if (index+1 >= intmySize) { remPtr = remPtr->myNext; //first increment of remPtr for (unsigned i=0; i != mySize-1; ++i) { remPtr = remPtr->myNext; bremPtr = bremPtr->myNext; } myLast = bremPtr; bremPtr->myNext = remPtr->myNext; //updates my last to the ptr before remove myLast->myItem = bremPtr->myItem; val = remPtr->myItem; remPtr = NULL; delete remPtr; mySize -= 1; return val; } else { remPtr = remPtr->myNext; //first increment of remPtr for (int i=0; i <= index; i++) { if (i == index-1) { //before rem idx to ptr after rem idx bremPtr->myNext = remPtr->myNext; val = remPtr->myItem; remPtr = NULL; delete remPtr; mySize -= 1; return val; } //increment each idx remPtr = remPtr->myNext; bremPtr = bremPtr->myNext; } } return myFirst->myItem; //returns myFirst if all else fails } /* * Written by Andrew Baker * Tests equality between to lists, returns true or false * Param: second List * Return: boolean */ template <class Item> bool List<Item>::operator==(const List& next){ if (mySize != next.mySize){ return false; } Node* oPtr = myFirst; Node* nPtr = next.myFirst; while(nPtr){ if(oPtr->myItem != nPtr->myItem){ return false; } oPtr = oPtr->myNext; nPtr = nPtr->myNext; } return true; } /* * Written by Andrew Baker * Reads from stream, returns void * Param: stream type * Return: Void */ template <class Item> void List<Item>::readFrom(istream& in) { Item it; while(in.peek() != '\n'){ in >> it; append(it); } } /* * Written by Andrew Baker * Writes the contents of a list in to a file, separated by a chosen value * Param: String * Return: void */ template <class Item> void List<Item>::writeTo(const string& fileName, char sep) const{ ofstream fout(fileName.c_str()); assert(fout.is_open()); Node* ptr = myFirst; while(ptr){ fout << sep << ptr->myItem; ptr = ptr->myNext; } fout << endl; fout.close(); } /* * Written by Andrew Baker * adds node with item to the beginning of the list * Param: Item * Return: void */ template <class Item> void List<Item>::prepend(const Item& pre){ if (mySize == 0){ append(pre); } else{ myFirst = new Node(pre, myFirst); mySize++; } } /* * Written by Andrew Baker * Inserts Node with item at chosen index, if <0 prepends, if >mySize appends * Param: Item, unsigned * Return: void */ template <class Item> void List<Item>::insert(const Item& add, unsigned index) { if (index >= mySize) { append(add); } else if (index <= 0) { prepend(add); } else { List<Item>::Node* nPtr = myFirst; for (unsigned u = 0; u < index - 1; u++) { nPtr = nPtr->myNext; } nPtr->myNext = new Node(add, nPtr->myNext); mySize++; } } /*Written by Lorrayya Williams Inserts an Item after the a a particular item passed through parameters then it returns a boolean*/ template <class Item> bool List<Item>::insertAfter(Item otherName,Item yourName){ Node* nPtr = myFirst; for(int i=0; i <= mySize; i++){ if(nPtr->myItem == otherName){ insert(yourName, i+1); return true; } nPtr =nPtr->myNext; } return false; } /*Written by Lorrayya Williams Inserts item before a particular item passed through parameters then it returns a boolean*/ template <class Item> bool List<Item>::insertBefore(Item otherName,Item yourName){ Node* nPtr = myFirst; for(int i=0; i <= mySize; i++){ if(nPtr->myItem == otherName){ insert(yourName, i); return true; } nPtr =nPtr->myNext; } return false; } //FIX ME /*Written by Lorrayya Williams Adds all items in a list to the ostream and returns that stream<<*/ template <class Item> ostream& operator<<(ostream& out, const List<Item>& alist){ alist.writeTo(out, '\t'); return out; } #endif /* LIST_H_ */
67fedfca910962ac15cd02b485a0c626b7a17eee
a2d9deb33db578292517e84f35aeef001cd6cd80
/codeup100/1034_16224073(AC).cpp
f0ec352ecf46c2268d2d6a7b63ef12ae884d043b
[]
no_license
nays111/algorithm
49124f641d919a64d13991f61c2199cdc02ad990
b4026c3c9586c014b9460edf53f116d81b3a1032
refs/heads/master
2023-05-02T21:38:46.675914
2021-05-21T11:50:32
2021-05-21T11:50:32
315,214,778
1
0
null
null
null
null
UTF-8
C++
false
false
130
cpp
1034_16224073(AC).cpp
#include <iostream> #include <iomanip> using namespace std; int main(){ int n; scanf("%o", &n); printf("%d", n); }
3c4ac5dab20f6c4e94f5a82c09c6a5dd17939316
6b2985d7ea8b289badbeade95efe45f02409cf1b
/leavemsg.h
07f1f7948c97cec2f7de7e169c14ddde708b22fc
[]
no_license
feengg/SanTang
e92a3f7cca8766fe047739501d558bab3c326087
83577a464b251c96f26f75e13e7a557aa477a0ed
refs/heads/master
2021-05-18T00:18:29.374704
2020-05-03T15:02:10
2020-05-03T15:02:10
251,019,653
0
0
null
null
null
null
UTF-8
C++
false
false
931
h
leavemsg.h
#ifndef LEAVEMSG_H #define LEAVEMSG_H #include <QWidget> #include "widget.h" #include "emailframe.h" namespace Ui { class LeaveMsg; } class LeaveMsg : public QWidget { Q_OBJECT public: explicit LeaveMsg(QWidget *parent = 0); ~LeaveMsg(); void mousePressEvent(QMouseEvent * event); void mouseMoveEvent(QMouseEvent * event); void mouseReleaseEvent(QMouseEvent *event); private slots: void on_pushButton_close_clicked(); void on_pushButton_leaveMsg_clicked(); void getMsgFromSubFormSlot(int picNum,bool ifAnonymous,QString msgContent); void showMsgHtmlToTextEdit(); void flushTextEditHtmlSlot();//定时下载刷新html void on_pushButton_flush_clicked(); private: Ui::LeaveMsg *ui; bool dragWindow; QPoint position; QString msgHeader; //is write msg falg bool isWrittingMsgFlag = false; QTimer * flushHtmlTimer = nullptr; }; #endif // LEAVEMSG_H
960f74e3da2f7dcb9692475b2d364e36742931ef
b02f9e59b2c1d4282bfb1201ed3de36cdc9c786b
/src_technotitlan/System_Controller/Arduino_code/TTTControladorCentral/TTTControladorCentral.ino
acc126847c5d128af5df0b85fb115d47bfd4beeb
[]
no_license
EduardoSAAT/Technotitlan_IoT
cb077ba4d355f7c8bfa1bf6fb0a1f88b8c95ae59
49946833641c1917ec231cd8045ce2703aa4321f
refs/heads/main
2023-03-02T18:27:27.386256
2021-02-09T13:39:37
2021-02-09T13:39:37
330,812,876
0
0
null
null
null
null
UTF-8
C++
false
false
12,501
ino
TTTControladorCentral.ino
//DEFINIR VARIABLES DEL SISTEMA// String ms; //CONFIG_SYSTEM //Resurekcion - System// long timeLastRespond; long timeActual; long diference; long timeMaxWait; //Sistema de Enfriamiento// long timeLastFrio; long timeActualFrio; long diferenceFrio; long timeWaitFrio; long timeStillFrio; long timeLastStillFrio; long timeActualStillFrio; long diferenceStillFrio; bool VENTILADOR; int pinVENTILADOR=8; //Sistema de Timbres y Alarmas - Seguridad// long timeLastVoice; long timeActualVoice; long diferenceVoice; long timeStillVoice; long timeLastStillVoice; long timeActualStillVoice; long diferenceStillVoice; bool TimbreMensaje; bool BOCINA; int pinTIMBRE=13; int pinBOCINA=12; //Sistema Electrico - CONFIG_ELECTRICIDAD// bool FUENTE_CFE; int pinFUENTE_CFE=2; bool UPS_DATA_CENTER; int pinUPS_DATA_CENTER=9; bool POWER_RACK; int pinPOWER_RACK=4; //Servidores - CONFIG_SERVERS// bool PC_CENTRAL; int pinPC_CENTRAL=11; bool PC_DATA; int pinPC_DATA=10; //Sistema de Ilumniacion - CONFIG_ILUMINACION// bool LUZ_LAB_MASTER; int pinLUZ_LAB_MASTER; bool LUZ_LAB_TALLER; int pinLUZ_LAB_TALLER; bool LUZ_LAB_PASILLO_A; int pinLUZ_LAB_PASILLO_A; bool LUZ_LAB_PASILLO_B; int pinLUZ_LAB_PASILLO_B; bool LUZ_LAB_BANO; int pinLUZ_LAB_BANO; //*************** CUERPO DEL MASTER_THREAD ****************** void setup() { //Configuracion del Sistema// Serial.begin(9600); //CONFIG_SYSTEM// //Sistema Electrico - CONFIG_ELECTRICIDAD// pinMode(pinFUENTE_CFE,INPUT); pinMode(pinUPS_DATA_CENTER,OUTPUT); pinMode(pinPOWER_RACK,OUTPUT); //Servidores - CONFIG_SERVERS// pinMode(pinPC_CENTRAL,OUTPUT); pinMode(pinPC_DATA,OUTPUT); //Sistema de enfriamiento// pinMode(pinVENTILADOR,OUTPUT); //Sistema de Timbre y Alarmas// pinMode(pinTIMBRE,INPUT); pinMode(pinBOCINA,OUTPUT); //Inicializar Sistema// InicializarSistema(); } void loop() { //Evaluar su hay algun mensaje en el Serial if(Serial.available()){ //Actualizar el tiempo de este ultimo mensaje timeLastRespond = millis(); //Leer el mensaje del monitor Serial ms = Serial.readStringUntil("\n"); //Comprobar que tipo de mensaje es Recibido if(ms=="OK\n"){ //Solo hacer funciones de Monitoreo Monitoreo(); //Responder al OK- Anunciar la precencia del Controlador Central Serial.println("OK-Recibido"); }else{ //Si es un mensaje de reconfiguracion// if(ms.indexOf("CONFIG")>=0){ Reconfig(ms); } } //Si no hay ningun mensaje en el Serial }else{ //Verificar PC_CENTRAL// if(PC_CENTRAL==false){ //Solo hacer funciones de Monitoreo Monitoreo(); }else{ //Evaluar la resurekcion del sistema EvaluarResurekcion(); } } } //************ FUNCIONES DEL SISTEMA **************** void InicializarSistema(){ setDefaultConfig(); } void setDefaultConfig(){ //Colocar la configuracion por defecto al Sistema //Resurekcion - System// timeMaxWait = 120000; timeActual = millis(); diference = 0; timeLastRespond = timeActual; //Sistema de enfriamiento// VENTILADOR = false; timeLastFrio = timeActual; timeActualFrio = timeActual; timeWaitFrio=60000; //3600000 timeStillFrio=10000; //120000 diferenceFrio = 0; timeLastStillFrio=timeActual; timeActualStillFrio=timeActual; diferenceStillFrio=0; //Sistema de Timbres y Alarmas// timeLastVoice=timeActual; timeActualVoice=timeActual; timeLastStillVoice=timeActual; TimbreMensaje=false; diferenceVoice=0; timeStillVoice=15000; BOCINA=false; //Sistema Electrico - CONFIG_ELECTRICIDAD// bool FUENTE_PODER=false; bool POWER_RACK=false; //Servidores - CONFIG_SERVERS// bool PC_CENTRAL=false; bool PC_DATA=false; //Sistema de Ilumniacion - CONFIG_ILUMINACION// bool LUZ_LAB_MASTER=false; bool LUZ_LAB_TALLER=false; bool LUZ_LAB_PASILLO_A=false; bool LUZ_LAB_PASILLO_B=false; bool LUZ_LAB_BANO=false; } void EvaluarResurekcion(){ timeActual = millis(); diference = timeLastRespond-timeActual; if(diference>timeMaxWait){ //Mandar Resurekcion// ResurekcionPC_MASTER(); } } void ResurekcionPC_MASTER(){ //Corroborar el sistema electrico Principal// if(CheckElectricSystemEstability()==true){ //Corroborar el Sistema Electrico Secundario// if(UPS_DATA_CENTER==true){ //Solo Intentar levantar la PC_CENTRAL setConfig_PC_CENTRAL(true); }else{ //Encender UPS_DATA_CENTER primero digitalWrite(pinUPS_DATA_CENTER,HIGH); //Intentar levantar la PC_CENTRAL setConfig_PC_CENTRAL(true); } }else{ //Si no funciona el sistema electrico, solo esperar } } //************ FUNCIONES DE MONITOREO **************** void Monitoreo(){ //Sistema electrico CheckElectricSystem(); //Sistema de Timbres CheckTimbreSystem(); CheckBOCINA(); //Sistema de Enfriamiento CheckEnfriamientoSystem(); //Sistema de Iluminacion } //Evaluar la estabilidad del sistema electrico de la CFE// bool CheckElectricSystemEstability(){ bool sondeo1=false; bool sondeo2=false; bool sondeo3=false; if(CheckElectricCFE()==true){ sondeo1=true; }else{ sondeo1=false; } //Esperar 5 Minutos para la siguiente evaluacion delay(300000); if(CheckElectricCFE()==true){ sondeo2=true; }else{ sondeo2=false; } //Esperar 5 Minutos para la siguiente evaluacion delay(300000); if(CheckElectricCFE()==true){ sondeo3=true; }else{ sondeo3=false; } //Evaluar el Resultado de los Sondeos// if(sondeo1==sondeo2==sondeo3==true){ return true; //La red Electrica es confiable }else{ return false; //La red Electrica no es confiable } } //Evaluar el Sistema Electrico Principal en el Momento CFE// bool CheckElectricCFE(){ if(digitalRead(pinFUENTE_CFE) == HIGH){ return true; }else{ return false; } } //Evaluar el sistema electricpo y tomar desiciones void CheckElectricSystem(){ if(CheckElectricCFE==false){ //Si no funciona - mandar a apagar todo setConfig_PC_DATA(false); setConfig_PC_CENTRAL(false); } } //Evaluar el sistema de enfriamiento void CheckEnfriamientoSystem(){ //Si el ventilador esta Activado - comprobar tiempo de Activacion if(VENTILADOR==true){ //Obtener la diferencia de tiempo para manter timeActualStillFrio=millis(); diferenceStillFrio=timeActualStillFrio-timeLastStillFrio; //Si ya paso el tiempo de enfriamiento terminar frio// if(diferenceStillFrio>timeStillFrio){ digitalWrite(pinVENTILADOR,LOW); VENTILADOR = false; Serial.println("Apagando frio"); timeLastFrio=timeActualStillFrio; } }else{ //Si no esta activado - comprobar tiempo para ser Activado //Obtener la diferencia de tiempo timeActualFrio = millis(); diferenceFrio = timeActualFrio - timeLastFrio; //Si ya paso el tiempo maximo activar enfriamiento if(diferenceFrio>timeWaitFrio){ Serial.println("Encendiendo frio"); digitalWrite(pinVENTILADOR,HIGH); VENTILADOR = true; //Actualizar los tiempos timeLastStillFrio=timeActualFrio; timeLastFrio=timeActualFrio; } } } void CheckTimbreSystem(){ //Si se Activa el timbre mandar Alerta if(digitalRead(pinTIMBRE) == HIGH){ //Activar la Alarma setConfig_BOCINA(true); //Verificar si no se a enviado el mensaje// if(TimbreMensaje==false){ TimbreMensaje=true; Serial.println("ALERT - Timbre Activado"); } } } //Evaluar sistema de vocina para dejarlo encendo o mandarlo a apagar void CheckBOCINA(){ //Si la vocina esta activada - comprobar tiempo de Activacion if(BOCINA){ //Obtener la diferencia de tiempo para manter timeActualStillVoice=millis(); diferenceStillVoice=timeActualStillVoice-timeLastStillVoice; //Si ya paso el tiempo de Sonido, apagar// if(diferenceStillVoice>timeStillVoice){ setConfig_BOCINA(false); //Tambien cambiar el estado del mensaje TimbreMensaje=false; } } } //************ FUNCIONES DE CONFIGURACION **************** void Reconfig(String data){ //Sistema electrico if(data.indexOf("(ELECTRIC)")>=0){ //Config UPS_DATA_CENTER if(data.indexOf("UPS_DATA_CENTER")>=0){ if(data.indexOf("(ON)")>=0){ setConfigUPS_DATA_CENTER(true); }else{ setConfigUPS_DATA_CENTER(false); } } //Config POWER_RACK if(data.indexOf("POWER_RACK")>=0){ if(data.indexOf("(ON)")>=0){ setConfigPOWER_RACK(true); }else{ setConfigPOWER_RACK(false); } } }else{ //Sistema de PC_CENTRAL if(data.indexOf("(DATA_CENTER)")>=0){ //Config PC_CENTRAL if(data.indexOf("PC_CENTRAL")>=0){ if(data.indexOf("(ON)")>=0){ setConfig_PC_CENTRAL(true); }else{ setConfig_PC_CENTRAL(false); } } //Config PC_DATA if(data.indexOf("PC_DATA")>=0){ if(data.indexOf("(ON)")>=0){ setConfig_PC_DATA(true); }else{ setConfig_PC_DATA(false); } } }else{ //Sistema de Iluminacion if(data.indexOf("(ILUMINACION)")>=0){ //Config..... } } } } void setConfigUPS_DATA_CENTER(bool state){ if(state==true){ digitalWrite(pinUPS_DATA_CENTER, HIGH); UPS_DATA_CENTER = true; Serial.println("SET_CONFIG/UPS_DATA_CENTER(ON)"); }else{ //Comprobar previamente que los sistemas que dependen de este, esten apagados if((PC_CENTRAL == false) && (PC_DATA == false)){ //Mandar a apagar el UPS digitalWrite(pinUPS_DATA_CENTER, LOW); UPS_DATA_CENTER = false; Serial.println("SET_CONFIG/UPS_DATA_CENTER(OFF)"); }else{ //Mandar mensaje de alerta, imposible apagar if(PC_DATA == true){ Serial.println("ALERTA - Imposible apagar UPS_DATA_CENTER: Sistema dependiente ACTIVO: PC_DATA"); } if(PC_CENTRAL == true){ Serial.println("ALERTA - Imposible apagar UPS_DATA_CENTER: Sistema dependiente ACTIVO: PC_CENTRAL"); } } } } void setConfigPOWER_RACK(bool state){ //Comprobar previamente que los sistemas que dependen de este, esten apagados if(state==true){ digitalWrite(pinPOWER_RACK, HIGH); POWER_RACK = true; Serial.println("SET_CONFIG/POWER_RACK(ON)"); }else{ //Mandar a apagar el UPS digitalWrite(pinPOWER_RACK, LOW); POWER_RACK = false; Serial.println("SET_CONFIG/POWER_RACK(OFF)"); } } void setConfig_PC_CENTRAL(bool state){ if(state==true){ //Mandar la instruccion de Encedido if(PC_CENTRAL==true){ //No hay necesidad, de reencender, ya esta encendido Serial.println("SET_CONFIG-PC_CENTRAL(ON)PRUEBA"); }else{ //Entonces encender// PC_CENTRAL=true; digitalWrite(pinPC_CENTRAL, HIGH); delay(800); digitalWrite(pinPC_CENTRAL, LOW); //Esperar a leer algun mensaje Serial.readStringUntil("\n"); Serial.println("SET_CONFIG/PC_CENTRAL(ON)"); } }else{ //Mandar la instruccion de Apagado PC_CENTRAL=false; Serial.println("SET_CONFIG/PC_CENTRAL(OFF)"); } } void setConfig_PC_DATA(bool state){ if(state==true){ //Mandar la instruccion de Encedido if(PC_DATA==true){ //No hay necesidad, de reencender, ya esta encendido Serial.println("SET_CONFIG/PC_DATA(ON)"); }else{ //Entonces encender// PC_DATA=true; digitalWrite(pinPC_DATA, HIGH); delay(800); digitalWrite(pinPC_DATA, LOW); //Mandar la instruccion de Endendido Serial.println("SET_CONFIG/PC_DATA(ON)"); } }else{ //Mandar la instruccion de Apagado PC_DATA=false; Serial.println("SET_CONFIG/PC_DATA(OFF)"); } } //Activar o Desactivar VOCINA DEL TIMBRE void setConfig_BOCINA(bool state){ if(state==true){ digitalWrite(pinBOCINA,HIGH); BOCINA=true; timeLastStillVoice=millis(); }else{ digitalWrite(pinBOCINA,LOW); BOCINA=false; } }
3ba10000995e2d483c07f7a959c6c1ccd222da31
a9e20c14dddd43583ad78d08c06416807af7f6db
/LowSeller.cpp
5758b285ce9333b8fcb00476f8382db7f8a7016a
[]
no_license
linbokobza/markets-managment
96eb8005b85a099127756580ad690d4579560b16
049bc9da66a56f40eea9f5c4156ec120b4bceab5
refs/heads/main
2023-06-10T18:41:23.957737
2021-06-30T12:42:16
2021-06-30T12:42:16
381,698,054
1
1
null
null
null
null
UTF-8
C++
false
false
1,537
cpp
LowSeller.cpp
/* Assignment: 3 Author:Lin Bokobza, ID: 209482801 */ #include <iostream> #include <string> #include "LowSeller.h" using namespace std; //ctor LowSeller::LowSeller(string Name, string ID, float BaseSalary, int JobPresent) :Employee(Name, ID, BaseSalary, JobPresent), ShoppingTotalAmount(0), ShoppingTotalList(NULL) {} //calculate the salary of low Seller float LowSeller::CalSalary()const { return (BaseSalary + getAvg() + ShoppingTotalAmount) * JobPresent / 100; } // prints low seller info void LowSeller::Print() { Employee::Print(); cout << "I'm a Low Seller!" << endl; cout << "I have " << ShoppingTotalAmount << " orders: " << endl; for (size_t i = 0; i < ShoppingTotalAmount; i++) { cout << ShoppingTotalList[i] << ", "; } cout << endl; } //adds shop to the shops list void LowSeller::addShopToList(float Purchases) { if (!ShoppingTotalList) { ShoppingTotalList = new float[++ShoppingTotalAmount]; ShoppingTotalList[0] = Purchases; return; } float* temp = new float[++ShoppingTotalAmount]; for (int i = 0; i < ShoppingTotalAmount - 1; i++) { temp[i] = ShoppingTotalList[i]; } delete[] ShoppingTotalList; ShoppingTotalList = temp; ShoppingTotalList[ShoppingTotalAmount - 1] = Purchases; } //return the shopping's average float LowSeller::getAvg()const { float sum = 0; if (ShoppingTotalAmount == 0) return 0; for (size_t i = 0; i < ShoppingTotalAmount; i++) { sum += ShoppingTotalList[i]; } return sum / ShoppingTotalAmount; }
5e159a6248a2b463af1b820cb6e39400fe22e35e
6a76f7a4206d8ba18ff1be638a43ef01cbd061f6
/CADContainer/DistCommands/Dlg_TKYongDi.h
e3b1028eb8812c98ddb81870ec2fee1c7e5cc967
[]
no_license
presscad/cadof72bian
586d90d097a3b240f89123049529751a2191dba7
ca919f72912a0b782f54acca7723389a44dda6fb
refs/heads/master
2021-05-17T13:17:33.615789
2009-12-28T04:31:06
2009-12-28T04:31:06
250,794,358
0
0
null
2020-03-28T12:52:54
2020-03-28T12:52:53
null
GB18030
C++
false
false
830
h
Dlg_TKYongDi.h
#pragma once //----------------------------------------------------------------------------- #include "acui.h" #include "resource.h" //----------------------------------------------------------------------------- class CTKYongDiDlg : public CAcUiDialog { DECLARE_DYNAMIC (CTKYongDiDlg) public: CTKYongDiDlg (CWnd *pParent =NULL, HINSTANCE hInstance =NULL) ; enum { IDD = IDD_TK_YONGDI} ; CString strBicode; // 项目编号 CString strOwner; // 用地单位 CString strOwnerProperty; // 用地性质 CString strDate; // 日期 CStringArray arrayTag, arrayValue; public: virtual BOOL OnInitDialog(); protected: virtual void DoDataExchange (CDataExchange *pDX) ; afx_msg LRESULT OnAcadKeepFocus (WPARAM, LPARAM) ; DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); } ;
2d714580ffe814b0770aacb8be292aa8946daed7
51dc93b36bbdb550a058952ef281f21b2c3fae50
/JavaMsgDefine.cpp
bb3403251f9f70e905f8b69760fbd7a42648ab72
[]
no_license
FeelyChau/CapsFactory
d576f50a0ae8c412feaf5c3c9189e01f45d5a877
a2f65fe50437448271ff5fd35201ddf9cb3ffaa7
refs/heads/master
2021-07-08T09:54:58.835309
2020-08-19T04:43:40
2020-08-19T04:43:40
158,350,348
2
1
null
2020-08-19T04:43:42
2018-11-20T07:46:52
C++
UTF-8
C++
false
false
5,213
cpp
JavaMsgDefine.cpp
// // Created by 周飞宇 on 2018/11/20. // #include "JavaMsgDefine.h" #include "JavaFieldDefine.h" #include "Common.h" JavaMsgDefine::~JavaMsgDefine() { } string JavaMsgDefine::create_code_string(const string &tab, CodeType ct) { static const char* const Template_Msg_Class = "//%s\n" "public class %s {\n" "%s" "%s" "};\n\n"; //members string members; for(auto &field : fields) members += field->create_class_member(TB, CodeType::SOURCE); string getter; //field getter for(auto &field : fields) getter += field->create_get_function(TB, CodeType::SOURCE); //field setter string setter; for(auto &field : fields) setter += field->create_set_function(TB, CodeType::SOURCE); //serialize string serialize = create_serialize(TB, CodeType::SOURCE); //deserialize string deserialize = create_deserialize(TB, CodeType::SOURCE); //serialize for caps obj string serialize_for_caps_obj = create_serialize_for_caps_obj(TB, CodeType::SOURCE); //deserialize for caps obj string deserialize_for_caps_obj = create_deserialize_for_caps_obj(TB, CodeType::SOURCE); RETURN_CODEFORMAT(tab.c_str(), Template_Msg_Class, comment.c_str(), msg_name.c_str(), members.c_str(), (getter + setter + serialize + deserialize + serialize_for_caps_obj + deserialize_for_caps_obj).c_str()); } string JavaMsgDefine::create_serialize(const string &tab, CodeType ct) { static const char* const Template_Serialize = "\n/*\n * serialize this object as buffer\n */\n" "public byte[] serialize(int byteOder) throws CapsException {\n" TB"Caps caps = Caps.create();\n" TB"caps.write(MessageType.TYPE_%s);\n" "%s" TB"return caps.serialize(byteOder);\n" "}\n\n"; string field_serialize; for(auto &field : fields) field_serialize += field->create_serialize_function(TB, CodeType::SOURCE); RETURN_CODEFORMAT(tab.c_str(), Template_Serialize, Common::to_upper(msg_name.c_str()).c_str(), field_serialize.c_str()); } string JavaMsgDefine::create_deserialize(const string &tab, CodeType ct) { static const char* const Template_Deserialize = "\n/*\n * deserialize this object from buffer\n */\n" "public void deserialize(byte[] buf) throws CapsException {\n" TB"Caps caps = Caps.parse(buf, 0, buf.length);\n" TB"int msgType = caps.readInt();\n" TB"if (msgType != MessageType.TYPE_%s) return;\n" "%s" "}\n\n"; string field_deserialize; for(auto &field : fields) field_deserialize += field->create_deserialize_function(TB, CodeType::SOURCE); RETURN_CODEFORMAT(tab.c_str(), Template_Deserialize, msg_name_upper.c_str(), field_deserialize.c_str()); } string JavaMsgDefine::create_serialize_for_caps_obj(const string &tab, CodeType ct) { static const char * const Template_SerializeForCapsObj = "\n/*\n * serialize this object as caps (without message type)\n */\n" "public Caps serializeForCapsObj() throws CapsException {\n" TB"Caps caps = Caps.create();\n" "%s" TB"return caps;\n" "}\n\n"; string field_function_str; for(auto &field : fields) field_function_str += field->create_serialize_function(TB, CodeType::SOURCE); RETURN_CODEFORMAT(tab.c_str(), Template_SerializeForCapsObj, field_function_str.c_str()); } string JavaMsgDefine::create_deserialize_for_caps_obj(const string &tab, CodeType ct) { static const char * const Template_DeserializeForCapsObj = "\n/*\n * deserialize this object from caps (without message type)\n */\n" "public void deserializeForCapsObj(Caps caps) throws CapsException {\n" "%s" "}\n\n"; string field_deserialize; for(auto &field : fields) field_deserialize += field->create_deserialize_function(TB, CodeType::SOURCE); RETURN_CODEFORMAT(tab.c_str(), Template_DeserializeForCapsObj, field_deserialize.c_str()); } shared_ptr<BaseFieldDefine> JavaMsgDefine::new_field_define() { return make_shared<JavaFieldDefine>(); }
1a3455498271e5b15b5459efc0d0c829fafa9978
23aed60b50fce7a6f4667bc495b28238cf14e205
/include/Operator.h
663d85a5287fe410e8c42730ea37aaba58633ef8
[]
no_license
bvrstich/mpsqmc
75033647de536dde8c974df8563b7a57caabf6b1
21dd1c7d2811fbb51725458ac7104d4244eeaddc
refs/heads/master
2020-12-24T13:52:54.082397
2014-01-02T23:29:42
2014-01-02T23:29:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
h
Operator.h
#ifndef OPERATOR_H #define OPERATOR_H #include <stdlib.h> #include <iostream> /* Written by Sebastian Wouters <sebastianwouters@gmail.com> on August 29, 2013 */ using namespace std; class Operator{ public: //Get the size of the local Hilbert space int gPhys_d() const; //Get an element of of the operator; j is the column [C_i = sum_j OP(i,j) C_j] virtual double operator()(const int i, const int j) const = 0; //Print its contents friend ostream& operator<<(ostream& os, const Operator& theOp); //Am I the zero operator virtual bool AmIOp0() const = 0; //Am I the unity matrix virtual bool AmIOpI() const = 0; protected: //The physical dimension (local Hilbert space size) int phys_d; //Storage for what you want to store (can be used sparse though) double * storage; }; #endif
972cef3ce8fbd3a9eaf70d4d7683910c4093e6ab
eab7ed289146cc5211463e441300f303cfb9857e
/acmicpc/string/prob10809.cpp
8253eabc7b8e9c334cd01f36364e77030a75d6bc
[]
no_license
AmosDoan/provlemSolving
100faad7485abcef1987a48f7bed30325e24ddb4
bb2df8824dbaed0a2cba70ee547c58ed567b4e8e
refs/heads/master
2022-12-22T18:03:52.333967
2020-10-06T10:24:32
2020-10-06T10:24:32
229,028,434
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
prob10809.cpp
// // Created by Amos on 2020/02/22. // #include <iostream> #include <vector> using namespace std; string s; int main() { cin >> s; vector<int> solution = vector<int>(26, -1); for (int i = 0; i < s.size(); i++) { char current = s[i]; int idx = current - 'a'; if (solution[idx] == -1) { solution[idx] = i; } } for (int &s : solution) { cout << s << ' '; } cout << '\n'; return 0; }
77f967f00834fae88cfeac1631f5093bb597663f
ff979d4b1bc5ca56ee9ed52e99b4189cc84c66ba
/project/yuartdock.cpp
6bfed168ba2ff9f80ec869ec13a02141b0ae22a8
[ "MIT" ]
permissive
clark4code/YYDebug
52b9a879405a2f14662ad78459ff9105f1a558bc
4398ff6bb34a218265a0cc06e83619286a307242
refs/heads/master
2020-04-04T17:59:08.060701
2018-11-05T02:06:32
2018-11-05T02:06:32
156,145,025
0
1
null
null
null
null
UTF-8
C++
false
false
10,029
cpp
yuartdock.cpp
#include "yuartdock.h" #include <QFormLayout> #include <QGroupBox> #include <QLabel> #include <QScrollArea> #include <QSerialPortInfo> #include <QVBoxLayout> #include <QDebug> #include <sobject.h> #include <ymainwindow.h> #define addLog(msg) qDebug()<<(msg) YUartDock::YUartDock(SObject *pObj, YMainWindow *parent) : YCommDock(pObj, parent) { QString strPortName; QScrollArea* pScrollArea = new QScrollArea(this); QGroupBox* pGroups[2]; QFormLayout* pFLayout[2]; QVBoxLayout* pVLayout[1]; QWidget* pScrollWidget = new QWidget(this); pGroups[0] = new QGroupBox(tr("Port"), this); m_combos[CB_UART] = new QComboBox(this); m_buttons[PB_OPEN] = new QPushButton(tr("Open"), this); m_buttons[PB_OPEN]->setAutoFillBackground(true); pFLayout[0] = new QFormLayout(pGroups[0]); pFLayout[0]->addRow(m_combos[CB_UART], m_buttons[PB_OPEN]); pGroups[0]->setLayout(pFLayout[0]); foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { m_combos[CB_UART]->addItem(info.portName()); } strPortName = pObj->property("port_name").toString(); if(!strPortName.isEmpty() && m_combos[CB_UART]->findText(strPortName) >= 0) m_combos[CB_UART]->setCurrentText(strPortName); if(m_combos[CB_UART]->count() == 0) m_buttons[PB_OPEN]->setEnabled(false); QPalette pal = m_buttons[PB_OPEN]->palette(); pal.setColor(QPalette::Button, Qt::red); m_buttons[PB_OPEN]->setPalette(pal); pGroups[1] = new QGroupBox(tr("Parameters"), this); m_combos[CB_BAUDRATE] = new QComboBox(this); foreach (qint32 nRate, QSerialPortInfo::standardBaudRates()) { m_combos[CB_BAUDRATE]->addItem(QString::number(nRate), nRate); } m_combos[CB_BAUDRATE]->setCurrentText(pObj->property("baud_rate").toString()); m_combos[CB_DATA_BITS] = new QComboBox(this); m_combos[CB_DATA_BITS]->addItem("5", 5); m_combos[CB_DATA_BITS]->addItem("6", 6); m_combos[CB_DATA_BITS]->addItem("7", 7); m_combos[CB_DATA_BITS]->addItem("8", 8); m_combos[CB_DATA_BITS]->setCurrentText(pObj->property("data_bits").toString()); m_combos[CB_STOP_BITS] = new QComboBox(this); m_combos[CB_STOP_BITS]->addItem("1", 1); m_combos[CB_STOP_BITS]->addItem("1.5", 3); m_combos[CB_STOP_BITS]->addItem("2", 2); m_combos[CB_STOP_BITS]->setCurrentText(pObj->property("stop_bits").toString()); m_combos[CB_PARITY] = new QComboBox(this); m_combos[CB_PARITY]->addItem("No", 0); m_combos[CB_PARITY]->addItem("Even", 2); m_combos[CB_PARITY]->addItem("Odd", 3); m_combos[CB_PARITY]->addItem("Space", 4); m_combos[CB_PARITY]->addItem("Mark", 5); m_combos[CB_PARITY]->setCurrentText(pObj->property("parity").toString()); pFLayout[1] = new QFormLayout(pGroups[1]); pFLayout[1]->addRow(new QLabel(tr("Baud Rate"), this), m_combos[CB_BAUDRATE]); pFLayout[1]->addRow(new QLabel(tr("Data Bits"), this), m_combos[CB_DATA_BITS]); pFLayout[1]->addRow(new QLabel(tr("Stop Bits"), this), m_combos[CB_STOP_BITS]); pFLayout[1]->addRow(new QLabel(tr("Parity"), this), m_combos[CB_PARITY]); pGroups[1]->setLayout(pFLayout[1]); pVLayout[0] = new QVBoxLayout(pScrollWidget); pVLayout[0]->addWidget(pGroups[0]); pVLayout[0]->addWidget(pGroups[1]); pScrollWidget->setLayout(pVLayout[0]); pScrollArea->setWidget(pScrollWidget); setWidget(pScrollArea); startTimer(1000); setWindowTitle(tr("Uart")); connect(m_buttons[PB_OPEN], SIGNAL(clicked()), SLOT(clickedOpenBt())); connect(m_combos[CB_BAUDRATE], SIGNAL(currentIndexChanged(int)), SLOT(resetParameters(int))); connect(m_combos[CB_DATA_BITS], SIGNAL(currentIndexChanged(int)), SLOT(resetParameters(int))); connect(m_combos[CB_STOP_BITS], SIGNAL(currentIndexChanged(int)), SLOT(resetParameters(int))); connect(m_combos[CB_PARITY], SIGNAL(currentIndexChanged(int)), SLOT(resetParameters(int))); updateUartStatus(); } bool YUartDock::commOpen() { if(m_serialPort.isOpen()){ return true; } QMutexLocker locker(&mutex()); QString serialPortName = m_combos[CB_UART]->currentText(); m_serialPort.setPortName(serialPortName); if (!m_serialPort.open(QIODevice::ReadWrite)) { addLog(QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(m_serialPort.error())); return false; } int nBaudRate = m_combos[CB_BAUDRATE]->currentData().toInt(); if (!m_serialPort.setBaudRate(nBaudRate)) { addLog(QObject::tr("Failed to set %1 baud for port %2, error: %3").arg(nBaudRate).arg(serialPortName).arg(m_serialPort.errorString())); } if (!m_serialPort.setDataBits((QSerialPort::DataBits)m_combos[CB_DATA_BITS]->currentData().toInt())) { addLog(QObject::tr("Failed set 8 data bits for port %1, error: %2").arg(serialPortName).arg(m_serialPort.errorString())); } if (!m_serialPort.setParity((QSerialPort::Parity)m_combos[CB_PARITY]->currentData().toInt())) { addLog(QObject::tr("Failed to set no parity for port %1, error: %2").arg(serialPortName).arg(m_serialPort.errorString())); } if (!m_serialPort.setStopBits((QSerialPort::StopBits)m_combos[CB_STOP_BITS]->currentData().toInt())) { addLog(QObject::tr("Failed to set 1 stop bit for port %1, error: %2").arg(serialPortName).arg(m_serialPort.errorString())); } connect(&m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead())); connect(&m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError))); emit connectedStatus(true); m_buttons[PB_OPEN]->setText(tr("Close")); QPalette pal = m_buttons[PB_OPEN]->palette(); pal.setColor(QPalette::Button, Qt::green); m_buttons[PB_OPEN]->setPalette(pal); return true; } int YUartDock::commWrite(const void *pData, uint uSize, uint uTimeOut) { if(!m_serialPort.isOpen()) return -1; qint64 nWritten = m_serialPort.write((char*)pData, (qint64)uSize); int nTimeOut; if(uTimeOut == ~(uint(0))) nTimeOut = -1; else nTimeOut = (int)uTimeOut; if(nWritten == -1 || nWritten != (qint64)uSize || !m_serialPort.waitForBytesWritten(nTimeOut)) return false; mainWindow()->addTxCounter(nWritten); return (int)nWritten; } bool YUartDock::commIsOpen() { return m_serialPort.isOpen(); } void YUartDock::commClose() { if(m_serialPort.isOpen()){ emit connectedStatus(false); m_serialPort.close(); m_buttons[PB_OPEN]->setText(tr("Open")); QPalette pal = m_buttons[PB_OPEN]->palette(); pal.setColor(QPalette::Button, Qt::red); m_buttons[PB_OPEN]->setPalette(pal); } } void YUartDock::updateSObject() { SObject* pObj = sobject(); pObj->setProperty("port_name", m_combos[CB_UART]->currentText()); pObj->setProperty("baud_rate", m_combos[CB_BAUDRATE]->currentText()); pObj->setProperty("data_bits", m_combos[CB_DATA_BITS]->currentText()); pObj->setProperty("stop_bits", m_combos[CB_STOP_BITS]->currentText()); pObj->setProperty("parity", m_combos[CB_PARITY]->currentText()); YCommDock::updateSObject(); } void YUartDock::updateUartStatus() { QString strMsg; if(m_serialPort.isOpen()){ strMsg = tr("UART: %1 has been opened. %2bps %3 %4 %5") .arg(m_serialPort.portName()) .arg(m_serialPort.baudRate()) .arg(m_serialPort.dataBits()) .arg(m_combos[CB_STOP_BITS]->currentText()) .arg(m_combos[CB_PARITY]->currentText()); }else{ strMsg = tr("UART: No port has been connected."); } updateStatusBar(strMsg); } void YUartDock::initSObject(SObject *pObj) { YCommDock::initSObject(pObj); pObj->setProperty("type", "uart"); pObj->setProperty("port_name", ""); pObj->setProperty("baud_rate", "115200"); pObj->setProperty("data_bits", "8"); pObj->setProperty("stop_bits", "1"); pObj->setProperty("parity", "No"); } void YUartDock::timerEvent(QTimerEvent *evt) { Q_UNUSED(evt) QStringList lstUart; foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { lstUart << info.portName(); } for(int nIndex = 0; nIndex < m_combos[CB_UART]->count();){ if(lstUart.contains(m_combos[CB_UART]->itemText(nIndex))){ nIndex++; continue; } m_combos[CB_UART]->removeItem(nIndex); } foreach (QString strName, lstUart) { if(m_combos[CB_UART]->findText(strName) >= 0) continue; m_combos[CB_UART]->addItem(strName); } } void YUartDock::handleReadyRead() { QByteArray baData = m_serialPort.readAll(); emit receivedData((uchar*)baData.data(), baData.size()); } void YUartDock::handleError(QSerialPort::SerialPortError err) { const char* szErr[] = { "NoError", "DeviceNotFoundError", "PermissionError", "OpenError", "ParityError", "FramingError", "BreakConditionError", "WriteError", "ReadError", "ResourceError", "UnsupportedOperationError", "UnknownError", "TimeoutError", "NotOpenError" }; if(err != 0) addLog(tr("UART error: %1").arg(szErr[err])); } void YUartDock::clickedOpenBt() { if(m_serialPort.isOpen()) commClose(); else commOpen(); updateUartStatus(); } void YUartDock::resetParameters(int) { if(!m_serialPort.isOpen()) return; m_serialPort.setBaudRate(m_combos[CB_BAUDRATE]->currentData().toInt()); m_serialPort.setDataBits((QSerialPort::DataBits)m_combos[CB_DATA_BITS]->currentData().toInt()); m_serialPort.setParity((QSerialPort::Parity)m_combos[CB_PARITY]->currentData().toInt()); m_serialPort.setStopBits((QSerialPort::StopBits)m_combos[CB_STOP_BITS]->currentData().toInt()); updateUartStatus(); }
62ebcf26bd03bb3aedf14bae8a2055a127d84d45
e8b5f05df5115e4d8aa692107e2c1338c1e8ccb6
/software_1/二叉树/线索二叉树.cpp
c4f28fdd90c007581175d221fbd35cf10cf35843
[]
no_license
trx594324215/lab4_test
ff583d079ed87b545b9670498a0225b6871ab7cb
4702ef86a41121440308f43bc6717c582ef12ef4
refs/heads/master
2021-01-10T01:57:36.892472
2015-11-10T12:24:57
2015-11-10T12:24:57
45,909,116
0
0
null
2015-11-10T12:29:10
2015-11-10T11:59:57
C++
GB18030
C++
false
false
2,875
cpp
线索二叉树.cpp
#include <iostream> #define max 100 using namespace std; typedef struct node { struct node *leftChild; struct node *rightChild; char data; bool ltag; bool rtag; }BiTreeNode, *BiTree; typedef struct Stack { BiTree Data[max]; int top; int flag; }STACK; //BiTree pre = NULL; BiTree test[max]; int i = 0; BiTree pre; void createBiTree(BiTree &T)//递归建立二叉树// { char c; cin >> c; if ('#' == c) T = NULL; else { T = new BiTreeNode; T->data = c; createBiTree(T->leftChild); createBiTree(T->rightChild); } } void PreOrder(BiTree BT)//递归前序遍历// { if (BT != NULL) { cout << BT->data; test[i] = BT; i++; if (BT->leftChild == NULL) { BT->ltag = false; } if (BT->rightChild == NULL) { BT->rtag = false; } PreOrder(BT->leftChild); PreOrder(BT->rightChild); } } void InOrderTh(BiTree p) //将二叉树 p前序线索化 { //cout << p->data; if (p) { //p 非空时,当前访问的结点是 p p->ltag = (p->leftChild) ? true : false; //左(右)孩子 非空 p->rtag = (p->rightChild) ? true : false; //时,标志1,否: 0 if (pre) { //若*p 的前驱*pre 存在 if (pre->rtag == false) // *p的前驱右标志为线索 pre->rightChild = p; // 令 *pre 的右线索指向前序后 继 if (p->ltag == false) // *p的左标志为线索 p->leftChild = pre; //令 *p的左线索指向前序 前驱 } pre = p; // 令pre 是下一个访问的前序前驱 if (p->ltag == true) { InOrderTh(p->leftChild); } //左子树线索化 if (p->rtag == true) { InOrderTh(p->rightChild); } } } BiTree fNext(BiTree p)//前序的后一个 { BiTree q; if (p->rtag == false) { q = p->rightChild; return q; } else { if (p->ltag == true) { q = p->leftChild; } else q = p->rightChild; } return q; } BiTree parent(BiTree t,char a)//求父节点 { if (t->ltag == true) { if (t->leftChild->data == a) { return t; } } if (t->rtag == true) { if (t->rightChild->data == a) { return t; } } t = fNext(t); parent(t,a); } BiTree InNext(BiTree p,BiTree T)//中序的下一个 { BiTree Q; if (p->rtag != false) { Q = p->rightChild; while (Q->ltag != false) { Q = Q->leftChild; } } else { Q = p->rightChild; if (Q != NULL) { Q = parent(T, Q->data); } } return (Q); } void midorder(BiTree T,BiTree t) { BiTree Q; cout << T->data; Q=InNext(T,t); if (Q != NULL) { //cout << Q->data; midorder(Q,t); } } void preorder(BiTree T) { if (T != NULL) { cout << T->data; T = fNext(T); preorder(T); } } int main() { BiTree Q, T,t; createBiTree(T); InOrderTh(T); t = T; preorder(t); cout << endl; /*Q = InNext(T->rightChild,T); cout << Q->data << endl;*/ while (T->ltag != false) { T = T->leftChild; } //Q = InNext(T,t); //cout << Q->data; midorder(T,t); return 0; }
8ca2210559f2ddc0dfff8d25a8fd282c9242dd5c
050c8a810d34fe125aecae582f9adfd0625356c6
/A. Greed/main.cpp
189e266968518d2e836784170c8214b6a7580521
[]
no_license
georgerapeanu/c-sources
adff7a268121ae8c314e846726267109ba1c62e6
af95d3ce726325dcd18b3d94fe99969006b8e138
refs/heads/master
2022-12-24T22:57:39.526205
2022-12-21T16:05:01
2022-12-21T16:05:01
144,864,608
11
0
null
null
null
null
UTF-8
C++
false
false
451
cpp
main.cpp
#include <iostream> #include <algorithm> using namespace std; int B[100005]; long long T; int N; int main() { cin.sync_with_stdio(false);cin.tie(0); cout.sync_with_stdio(false);cout.tie(0); cin>>N; for(int i=1;i<=N;i++) { int val; cin>>val; T+=val; } for(int i=1;i<=N;i++) cin>>B[i]; sort(B+1,B+1+N); if(T==1)cout<<"NO"; else cout<<(B[N]+B[N-1]>=T ? "YES":"NO"); return 0; }
affd813f88433998d4240688bb5f64e80aa707f6
03f579c344e6f2987df91cab88795242e713b7fc
/Combination Sum II.cpp
0f4a962bb0354350d71437a50f723f450b8f3142
[]
no_license
wwqqqqq/LeetCode-Solution
8610dc1c97ec7b43f0ab13f634c9a69afd22e597
63305d9cb0068d51f354e7aa8e381ca2320702bb
refs/heads/master
2021-06-04T18:00:04.923506
2021-01-11T23:49:51
2021-01-11T23:49:51
126,013,705
0
0
null
null
null
null
UTF-8
C++
false
false
1,762
cpp
Combination Sum II.cpp
class Solution { public: vector<vector<int>> findCS(map<int,int>& count, int target) { vector<vector<int>> result; if(count.size() == 0 && target != 0) return result; if(target == 0 || count.size() == 0) { vector<int> temp; result.push_back(temp); return result; } auto iter = count.end(); iter--; int x = iter->first; int c = iter->second; int i; count.erase(iter); if(x > target) { result = findCS(count, target); count.insert(pair<int,int>(x,c)); return result; } // sets that have x for(int i = 1; i <= c; i++) { if(i * x > target) break; vector<vector<int>> r1 = findCS(count, target - i * x); vector<int> t(i, x); for(int j = 0; j < r1.size(); j++) { r1[j].insert(r1[j].end(), t.begin(), t.end()); } result.insert(result.end(), r1.begin(), r1.end()); } // sets that don't have x vector<vector<int>> r2 = findCS(count, target); result.insert(result.end(), r2.begin(), r2.end()); count.insert(pair<int,int>(x,c)); return result; } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); map<int,int> count; for(int i = 0; i < candidates.size(); i++) { int n = candidates[i]; auto iter = count.find(n); if(iter != count.end()) iter->second++; else count.insert(pair<int,int>(n, 1)); } return findCS(count, target); } };
dd84b16c0dcba371a081456386de8e86151deddd
2e15882fa701f7183fe834b98b8158e05ca6a7ca
/Creatures/bodypart.h
820d1c67dfda4522d6954279cc90d97ac6b8d705
[]
no_license
lonski/amarlon_textgame
882ed5b68f1b52dfcda35a31bf67616e3679c7dd
681f748e5bc37b4f843d95f99c9cdc7f08c5e050
refs/heads/master
2020-04-11T10:38:19.621477
2014-09-14T11:55:40
2014-09-14T11:55:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,118
h
bodypart.h
#ifndef BODYPART_H #define BODYPART_H #include "Equipment/item.h" #include "Include/enums/e_damagelevel.h" #include "Include/damage.h" class BodyPart { public: BodyPart(); BodyPart(BodyPartType type, BodyRegion region, BodySide side); BodyPart(std::string str, std::vector<ItemPtr > &eq_items); ~BodyPart() {} std::string toStr(); bool fromStr(std::string str, std::vector<ItemPtr > &eq_items); void equip(ItemPtr item); ItemPtr unequip(ItemType itype); std::vector<ItemPtr > unequip(); bool accept(ItemType itype); BodyRegion region() const; BodySide side() const; BodyPartType type() const; DamageLevel damage() const; Damage armor() const; std::weak_ptr<Item> equipped(ItemType itype); std::vector<std::weak_ptr<Item> > equipped(); void setRegion(BodyRegion region); void setSide(BodySide side); void setType(BodyPartType type); void setDamage(DamageLevel damage); private: BodyRegion _region; BodySide _side; BodyPartType _type; DamageLevel _damage; Damage _armor; std::map<ItemType, ItemPtr > _equipped; void calc_armor(); }; #endif // BODYPART_H
e68ac1cf14ec99d0d8e8e20218975800294082e0
a9b03f4730534da6e25e8a52ea0cd870db7c28b4
/framework/examples/component_watchdog/watchdog.h
bfce2b10ab59acff3899b54f64a1e244bee9f612
[ "Apache-2.0" ]
permissive
zhuangli1987/apollo
6bcf2ddebb23377e701ec9bf2b56c1ea4632bab9
2210bef1ef5aadfeccb48949c07b31de4e581b25
refs/heads/master
2020-03-28T00:31:50.529228
2018-09-25T01:29:51
2018-09-25T01:31:39
147,425,981
0
0
null
2018-09-04T22:11:18
2018-09-04T22:11:18
null
UTF-8
C++
false
false
1,690
h
watchdog.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef EXAMPLES_COMPONENT_WATCHDOG_WATCHDOG_H_ #define EXAMPLES_COMPONENT_WATCHDOG_WATCHDOG_H_ #include <cstdint> #include <mutex> #include <string> enum SurvivalCondition { DEAD = 0, ALIVE }; struct DogConfig { DogConfig() : food("pork"), min_feed_interval(0), max_feed_interval(1000000) {} std::string food; uint64_t min_feed_interval; // unit: us uint64_t max_feed_interval; // unit: us }; struct DogStat { DogStat() : activated(false), condition(SurvivalCondition::ALIVE), last_eat_timestamp(0) {} bool activated; SurvivalCondition condition; uint64_t last_eat_timestamp; // unit: us }; class Watchdog { public: Watchdog(); Watchdog(const DogConfig& cfg); virtual ~Watchdog(); SurvivalCondition Feed(const std::string& food); private: DogConfig cfg_; DogStat stat_; std::mutex mutex_; }; #endif // EXAMPLES_COMPONENT_WATCHDOG_WATCHDOG_H_
4f167ee2bc61ff4404ab4701e9d88926e88c5cb7
ea47f676b998cc00da94ad59782f37dddec52995
/hack/MenuV2.cpp
e8a73f403ddb7528f7ad095628fcaf8a30e8f8d5
[]
no_license
ChoZenTime/moneysense
6765576be41765a8ac40b88b972753e67cd181ee
94bde9661fd5202c378ab69af41edaa2b46ddfcb
refs/heads/master
2020-06-06T03:14:28.747695
2019-04-17T09:08:43
2019-04-17T09:08:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,623
cpp
MenuV2.cpp
#include "../ImGui/imgui.h" #include <cctype> #include <shlobj.h> #include <shlwapi.h> #include <algorithm> #define NOMINMAX #include <Windows.h> #include <chrono> #include "../ImGui/imgui_internal.h" #include "../ImGui/directx9_example/imgui_impl_dx9.h" #include "NewMenu.h" #include "../menu/cmenu.hpp" bool selected = false; bool selected1 = false; bool selected2 = false; bool selected3 = false; bool selected4 = false; bool selected11 = false; bool selected12 = false; bool selected13 = false; bool selected14 = false; bool selected15 = false; bool selected21 = false; bool selected22 = false; bool selected23 = false; bool selected24 = false; // ========================================================= // // These are the tabs on the sidebar // // ========================================================= static char* sidebar_tabs[] = { "Aimbot", "Visuals", "Skins", "Misc", "Config", "Style" }; static ConVar* cl_mouseenable = nullptr; constexpr static float get_sidebar_item_width() { return 150.0f; } constexpr static float get_sidebar_item_height() { return 50.0f; } namespace ImGuiEx { inline bool ColorEdit4(const char* label, Color* v, bool show_alpha = true) { auto clr = ImVec4{ v->r() / 255.0f, v->g() / 255.0f, v->b() / 255.0f, v->a() / 255.0f }; if (ImGui::ColorEdit4(label, &clr.x, show_alpha)) { v->SetColor(clr.x, clr.y, clr.z, clr.w); return true; } return false; } inline bool ColorEdit3(const char* label, Color* v) { return ColorEdit4(label, v, false); } } int get_fps() { using namespace std::chrono; static int count = 0; static auto last = high_resolution_clock::now(); auto now = high_resolution_clock::now(); static int fps = 0; count++; if (duration_cast<milliseconds>(now - last).count() > 1000) { fps = count; count = 0; last = now; } return fps; } ImVec2 get_sidebar_size() { constexpr float padding = 10.0f; constexpr auto size_w = padding * 2.0f + get_sidebar_item_width(); constexpr auto size_h = padding * 2.0f + (sizeof(sidebar_tabs) / sizeof(char*)) * get_sidebar_item_height(); return ImVec2{ size_w, ImMax(325.0f, 380.0f) }; } void NewMenu::Render() { } void NewMenu::Shutdown() { //ImGui_ImplDX9_Shutdown(); cl_mouseenable->SetValue(true); } void NewMenu::OnDeviceLost() { //ImGui_ImplDX9_InvalidateDeviceObjects(); } void NewMenu::OnDeviceReset() { //ImGui_ImplDX9_CreateDeviceObjects(); } void NewMenu::Show() { _visible = true; cl_mouseenable->SetValue(false); } void NewMenu::Hide() { _visible = false; cl_mouseenable->SetValue(true); } void NewMenu::Toggle() { _visible = !_visible; cl_mouseenable->SetValue(!_visible); } void NewMenu::CreateStyle() { style.Colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style.Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_PopupBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style.Colors[ImGuiCol_Border] = ImVec4(0.07f, 0.07f, 0.07f, 1.00f); style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f); style.Colors[ImGuiCol_FrameBg] = ImVec4(0.07f, 0.07f, 0.07f, 1.00f); style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.07f, 0.07f, 0.07f, 1.00f); style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.07f, 0.07f, 0.07f, 1.00f); style.Colors[ImGuiCol_TitleBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style.Colors[ImGuiCol_CheckMark] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style.Colors[ImGuiCol_Button] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style.Colors[ImGuiCol_Header] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style.Colors[ImGuiCol_Column] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style.Colors[ImGuiCol_ColumnHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style.Colors[ImGuiCol_ColumnActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style.Colors[ImGuiCol_ResizeGrip] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style.Colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f); style.Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(1.00f, 0.98f, 0.95f, 0.73f); }
77ca35efd699609b1724536aab17cb131a06ac7b
be93b9ffb49ec6f73d2558cedd02cd50a4060858
/Online judge solutions/Codeforces/339D.cpp
481a3f81f6393fcc9298d50a77a7d78be1c34760
[]
no_license
salonimohta/competitive-programming
ceec3c2c87eb8078b051166654c3faac5ce27d0b
2639a14acf4beb453bb9277779ad5d705c6fa97a
refs/heads/master
2020-08-09T02:12:27.005619
2019-10-14T08:07:46
2019-10-14T08:07:46
213,975,049
2
0
null
2019-10-09T16:59:36
2019-10-09T16:59:36
null
UTF-8
C++
false
false
4,193
cpp
339D.cpp
#include<bits/stdc++.h> using namespace std; #define MOD 1000000007 #define N 100010 typedef double lf; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef set<ll> sll; typedef vector<ll> vll; typedef vector<pair<ll,ll > >vpll; typedef vector<vll > vvll; #define sd(a) scanf("%d",&a) #define sstr(a) scanf("%s",a) #define sl(a) scanf("%lld",&a) #define debug(a) printf("check%d\n",a) #define clr(a) memset(a,0,sizeof(a)) #define rtn return #define gc getchar #define pb push_back #define ff first #define ss second #define mp(x,y) make_pair(x,y) #define all(a) a.begin(),a.end() #define allr(a) a.rbegin(),a.rend() #define lp(i,b) for(ll i = ll(0); i<ll(b) ; i++) #define lpit(it,a) for(__typeof(a.begin()) it = a.begin(); it != a.end(); ++it) #define mid(s,e) (s+(e-s)/2) #define min3(a,b,c) min(a,min(b,c)) #define max3(a,b,c) max(a,max(b,c)) ll ip(){ ll x = 0; bool isNeg = false; char c; c = gc(); if(c == '-') isNeg = true , c = gc(); for( ; c >= '0' && c <= '9' ; c = gc()); x = (x << 1) + (x << 3) + c - '0'; if(isNeg) x *= -1; return x; } //////////////////////////////////////////// CONTAINERS FOR FUNCTIONS MENTIONED IN TEMPLATE /////////////////////////////////// #define MAX 100005 //bool isPrime[MAX]; //int spf[MAX]; //////////////////////////////////////////// FUNCTIONS THAT NEED COMMENTED OUT CONTAINERS //////////////////////////////////// //void prime_sieve(){ for(ll i=2 ; i*i<=MAX ; i++){ if(!isPrime[i]){ for(ll j=i*i ; j<=MAX ; j+=i) isPrime[j] = 1;} } } //void spf_sieve(){ for(ll i=2 ; i<MAX ; i+=2) spf[i] = 2; // for(ll i=3 ; i<MAX ; i+=2){ if(!isPrime[i]){ spf[i] = i; for(ll j=i ; (j*i)<MAX ; j+=2){ if(!isPrime[i*j]) isPrime[i*j] = true , spf[i*j] = i; } } } //} ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline ll ncr(ll n,ll r){ ll ans = 1 ; if(r > n-r) r = n-r; lp(i,r+1){ans*=(n-i) ; ans/=(i+1); } rtn ans; } inline ll gcd(ll a,ll b){if(!a) rtn b; rtn gcd(b%a,a); } inline ll fme(ll x,ll n){ll ans=1;x%=MOD;while(n>0){if(n&1){ ans*=x;ans%=MOD;} x*=x;x%=MOD;n>>=1;}rtn ans%MOD;} inline bool isPalin(string &s){ int len = s.size()-1;lp(i,(len/2)+2){if(!(s[i]==s[len-i])) rtn false;} rtn true;} inline ll lcm(ll a,ll b){rtn (a*b)/gcd(a,b); } inline ll fmm(ll a,ll b) {ll r=0;a%=MOD;b%=MOD;while(b>0){if(b&1){r+=a;r%=MOD;}a+=a;a%=MOD;b>>=1;}rtn r%MOD;} inline ll sfme(ll a,ll b) {ll r=1;a%=MOD;while(b>0){if(b&1)r=fmm(r,a);a=fmm(a,a);b>>=1;}rtn r%MOD;} ll makeNum(string &str){ll a = 0; lpit(it, str){ int num = *it - '0'; a = a*10 + num;} return a;} inline int in(){ int NR=0; register char c=gc(); while( c < 48 || c > 57 ){c=gc();} while(c>47 && c< 58){ NR = (NR << 3) + (NR << 1) + (c - 48); c=gc();} return NR; } ll dx[] = {0,0,1,-1}, dy[] = {1,-1,0,0}; //--------------------------------TEMPLATE ENDS HERE--------------------------------------------------// ll arr[1<<18], seg[1<<20]; ll merge(int l, int r, int level){ if( level & 1 ){ return seg[l] | seg[r]; }else{ return seg[l] ^ seg[r]; } } int build(int pos, int lo, int hi){ if( lo > hi ) return -1; if( lo == hi ){ seg[pos] = arr[lo]; return 1; } int mid = (lo+hi)>>1, l = pos + pos + 1, r = l + 1; int level1 = build(l, lo, mid); int level2 = build(r, mid+1, hi); int level; if( level1 != -1 ) level = level1; else level = level2; seg[pos] = merge(l, r, level); return level + 1; } int update(int pos, int lo, int hi, int index, int val){ if( lo > hi || index < lo || index > hi ){ return -1; } if( lo == hi ){ arr[lo] = seg[pos] = val; return 1; } int mid = (lo+hi)>>1, l = pos + pos + 1, r = l + 1; int level1 = update(l, lo, mid, index, val); int level2 = update(r, mid+1, hi, index, val); int level; if( level1 != -1 ) level = level1; else level = level2; seg[pos] = merge(l, r, level); return level + 1; } int main(){ ll t, n, m, v, p, q, k, a, b, c, d, e , f, type, x, y, z; // START HERE // cin >> n >> m; lp(i, 1<<n ){ cin >> arr[i]; } build(0, 0, (1<<n)-1); while( m-- ){ ll index, val; cin >> index >> val; update(0, 0, (1<<n)-1, index-1, val); cout << seg[0] << "\n"; } return 0; }
ffbfa971a553fedbad6dee48818c27c20da010c3
3dd91d71dcd0ec7a0c21709edd7093e9972bcbe9
/restrequestbuilder.h
2886f29213ab939d667d51fbb0c9cf2bb8ceb5b1
[ "MIT" ]
permissive
OldFrostDragon/JenkinsPlugin
bcf6ae39073e46d98c75e0540ce678cf37f13474
a3179a188ef4b5d4bd57adec5a765d485faa7ac4
refs/heads/master
2020-04-10T13:27:48.937044
2016-12-18T13:56:46
2016-12-18T13:56:46
51,691,858
2
1
null
null
null
null
UTF-8
C++
false
false
1,512
h
restrequestbuilder.h
#ifndef RESTREQUESTBUILDER_H #define RESTREQUESTBUILDER_H #include "jenkinssettings.h" #include <QNetworkRequest> namespace JenkinsCI { namespace Internal { /*! * \brief The RestRequestBuilder class builds QNetworkRequest objects to specified Jenkins instance. * Built QNetworkRequest use JSON REST API url with port and authorization options if they are set. */ class RestRequestBuilder : public QObject { Q_OBJECT public: RestRequestBuilder(const JenkinsSettings &settings); static QString urlToRestApiUrl(const QString &url); /// add /api/json to the end if absent static QString cutRestApiUrlPart(const QString &url); /// remove /api/json from end of URL static QString lastBuildUrlToJobUrl(QString buildUrl); QUrl buildUrl(QString urlString) const; /// create REST URL using Jenkins instance settings QUrl buildThisOrDefaultViewUrl(QString urlString) const; QNetworkRequest buildRequest(const QString urlString) const; QNetworkRequest buildAvaliableJobsRequest(QUrl viewUrl) const; QNetworkRequest buildBuildInfoRequest(const QString url) const; QNetworkRequest buildLastBuildInfoRequest(const QString &jobUrl) const; JenkinsSettings jenkinsSettings() const; void setJenkinsSettings(const JenkinsSettings &jenkinsSettings); signals: void settingsChanged(); private: static const QString REST_API_URL_SUFFIX; static const QString LAST_BUILD_URL_SUFFIX; JenkinsSettings _jenkinsSettings; }; } } #endif // RESTREQUESTBUILDER_H
51383c52b8ba61a01ee81b2a6da39ef28fab1c33
1baf23a2c1d86c1a9cf45e323fe262a275ea948f
/mankuNo.cpp
a05b2f5db27585a4ec677255f80c0aa7f776b775
[]
no_license
sheshanathkumar/coding
7e409010f819aa7ebfdbc79d01438957c04826dc
cab013e1e316a2b5cbef458968146c26c9ee168d
refs/heads/master
2022-12-14T20:17:09.892037
2020-09-07T16:59:56
2020-09-07T16:59:56
293,581,113
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
mankuNo.cpp
#include <bits/stdc++.h> using namespace std; int main(){ int test; cin>>test; while (test--){ int num, temp=0, k=1, str[1000] = {0}; cin>>num; while (temp < num) temp = temp + pow (2,k++); --k; int tempo = num - (pow(2, k) - 1); int size = k-1; while (tempo >0){ str[size] = tempo % 2; tempo /= 2; size--; } for (int i = 0; i < k; i++){ if (str[i] == 0) str[i] = 5; else str[i] = 6; } for (int i = 0; i < k; i++) cout<<str[i]; cout<<"\n"; } return 0; }
3628c0c916897ed6f1d66b51b6035df24aee1f10
13366dff5e92133f5411074e47a2888e1bef9dad
/AnalogClock.h
a3f83810ab3e29d7223c189199d10edeaa427b38
[ "CC-BY-4.0", "MIT" ]
permissive
Dragonos/Analog-Wall-Clock
65dafa768c71c0467640c2fce4dcad7ccda07e07
5ee16b5f2d6ab66d552ef0a7dc33fc3fcff6cb46
refs/heads/master
2021-01-20T23:11:51.340190
2015-09-12T22:20:08
2015-09-12T22:20:08
42,183,443
2
0
null
null
null
null
UTF-8
C++
false
false
1,850
h
AnalogClock.h
/* The MIT License (MIT) Copyright (c) 2015 Amine Ben Hassouna (https://github.com/Dragonos) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ANALOGCLOCK_H #define ANALOGCLOCK_H #include <Wire.h> #include <RTClib.h> #include <Electro_PushButton.h> #include "AnalogClockMatrix.h" class AnalogClock { public: AnalogClock(IC_74164_x2 *dualIC, uint8_t rowsPins[7], uint8_t btnH, uint8_t btnM); void begin(); void render(); private: uint8_t renderAndCheckConfig(uint32_t millis); uint8_t config(); private: RTC_DS1307 m_rtc; // Current time DateTime m_now; AnalogClockMatrix m_matrix; // Configuration Mode uint8_t m_configMode, // Skip next up m_skipNextUp; // Buttons PushButton m_btnH, m_btnM; }; #endif // ANALOGCLOCK_H
3dfade1639c47722f927781755a5dce078930d36
292d156d3b9b1a352d64d30c089a9afc97a503c3
/RayTracer/shape/Group.h
594f81d78aadc4945c08c03f96e617e8b3ed3c4c
[]
no_license
Postea/CppRaytracer
908910a7c287cdcaa5cbd40d6096e88776fe03bd
13aea7e6de0d42d1dc9e1f873280d8d890f52642
refs/heads/master
2022-05-09T00:33:16.624346
2022-04-28T10:12:08
2022-04-28T10:12:08
216,021,060
3
0
null
null
null
null
UTF-8
C++
false
false
873
h
Group.h
#pragma once #include <vector> #include "../tools/Mat4.h" #include "../tools/Transformation.h" #include "Shape.h" #include "ShapeSingleGroup.h" namespace shapes { class Group : public Shape { public: Group(const util::Transformation& trans, bool rebuild_bb = true); Group(const util::Mat4& matrix, bool rebuild_bb = true); std::optional<cam::Hit> intersect(const cam::Ray& r) const override; util::AxisAlignedBoundingBox bounds() const override; void set_bounds(const util::AxisAlignedBoundingBox& bb); void add(const Group& group); void add(const ShapeSingleGroup& group); void add(const std::shared_ptr<shapes::Shape>& shape); protected: std::vector<std::shared_ptr<Shape>> shape_list; private: void rebuild_boundingbox(); bool rebuild_bb; util::AxisAlignedBoundingBox bounding_box; util::Transformation transform; }; } // namespace shapes
1d308da97210aab509a60b8a8f973d8d73968cef
a064c40cd1bc29b2eb70ef9515f6096917d1cb2e
/m2033core/model.h
abfec067de1ce23d367f76663fa421432dfb03b9
[]
no_license
code-google-com/metro2033-tools
bfc9979c68b454e4bd90f4f5745e6c44cf745d27
d58546c91e3a230135a312d3ac3c84d8d768abd2
refs/heads/master
2021-01-19T21:28:55.533210
2014-03-14T17:20:28
2014-03-14T17:20:28
32,267,378
4
1
null
null
null
null
UTF-8
C++
false
false
2,759
h
model.h
/****************************************************************************** This source file is part of metro2033-tools For the latest info, see http://code.google.com/p/metro2033-tools/ Copyright (c) 2010-2011 Ivan Shishkin <codingdude@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #ifndef __M2033_MODEL_H__ #define __M2033_MODEL_H__ #include "prerequisites.h" namespace m2033 { class model { public: enum { STATIC, DYNAMIC }; inline model(); inline ~model(); bool load( const std::string & path ); inline void clear(); void add_mesh( mesh &m ); void set_skeleton( const skeleton &s ); inline void set_type( uint32_t type ); inline mesh_ptr get_mesh( uint32_t idx ) const; inline unsigned get_num_meshes() const; inline skeleton_ptr get_skeleton() const; inline int get_type() const; private: void split_string( const std::string& string, char splitter, string_list& result ); uint32_t load_meshes( reader_ptr r ); mesh_vector meshes_; skeleton_ptr skeleton_; int type_; }; inline model::model() : type_(-1) {} inline model::~model() { clear(); } inline void model::clear() { meshes_.clear(); skeleton_.release(); type_ = -1; } inline void model::set_type( uint32_t type ) { type_ = type; } inline mesh_ptr model::get_mesh( uint32_t idx ) const { assert( idx < meshes_.size() ); return meshes_[idx]; } inline unsigned model::get_num_meshes() const { return meshes_.size(); } inline skeleton_ptr model::get_skeleton() const { return skeleton_; } inline int model::get_type() const { return type_; } } #endif // __M2033_MODEL_H__
42d996e3e2e53395cae6de5bc8cdb243f0c05521
e3c126ea17fee019a067ccaa8df32b7a847b9ee4
/backend/deployments/deployment_zmq_json_singlethread/RnDZmqTimeForwarderApp.cpp
fbec15d614a2525faf303b105f67374f9b0b6070
[]
no_license
faunX/ogame-2
6ba5550ea6c98467412e8305780546108e75d882
eb175bd7d16f83e670f5cbc5a9375cd5fcd5b506
refs/heads/master
2023-08-21T19:50:45.880660
2021-04-06T08:31:19
2021-04-06T08:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
RnDZmqTimeForwarderApp.cpp
#include <zmq.hpp> #include <string> #include "TimeForwardRequest.hpp" #include "ClearDatabaseRequest.hpp" #include "SerializableRequest.hpp" #include "toJson.hpp" RndRequest parseReq(int argc, char* argv[]) { if(argc < 2) { throw std::logic_error{"empty parameters"}; } std::string type = argv[1]; if(type == "forwardTime" and argc > 2) { return {TimeForwardRequest{.duration = Duration{std::stoi(argv[2])}}}; } if(type == "clearDb") { return {ClearDatabaseRequest{}}; } throw std::logic_error{"wrong parameters"}; } int main(int argc, char* argv[]) { if(argc < 2) { return -1; } RndRequest req{parseReq(argc, argv)}; SerializableRequest serializable{req}; zmq::context_t context{1}; zmq::socket_t socket{context, zmq::socket_type::req}; socket.connect("tcp://localhost:5555"); Json j; j = serializeFrom(serializable); socket.send(zmq::buffer(j.dump()), zmq::send_flags::none); zmq::message_t reply; socket.recv(reply, zmq::recv_flags::none); return 0; }
8a6d467d3ac5f46a0bd6291880a3cc6eb90932da
90bc4133eff3eb8d542f8722875e55c5e79f3cba
/Source/Invoker.hpp
04d317365bde72b9587c8df0786c811acd0f23dd
[]
no_license
ramagottfried/symbolist
c5d0a0d686a41bd2e0a49fa570364917b0e89668
bc41e75445113ba607ceaca392582aa500e743b9
refs/heads/master
2021-10-20T16:19:41.400300
2021-10-16T22:01:49
2021-10-16T22:30:45
90,850,122
15
4
null
2018-04-24T14:56:07
2017-05-10T10:06:33
Max
UTF-8
C++
false
false
534
hpp
Invoker.hpp
#ifndef Invoker_hpp #define Invoker_hpp #include <stdio.h> #include <vector> #include <queue> #include "Command.hpp" #include "SymbolistHandler.h" using namespace std; /** * Executes a command, and stores it into a command history. * * Commands from the history can be done and undone, in order to implement * the undo and redo actions. */ class Invoker { public: void execute(Command* command); private: queue<unique_ptr<Command> > command_history; SymbolistHandler* command_receiver; }; #endif /* Invoker_hpp */
4c5dad9517be9a5a58fb2816e3d6c8cb69516902
f6ad1c5e9736c548ee8d41a7aca36b28888db74a
/others/SOJ/SR 15/A/A.cpp
8f64a8704a5cbaf37364a1b2128d198039974840
[]
no_license
cnyali-czy/code
7fabf17711e1579969442888efe3af6fedf55469
a86661dce437276979e8c83d8c97fb72579459dd
refs/heads/master
2021-07-22T18:59:15.270296
2021-07-14T08:01:13
2021-07-14T08:01:13
122,709,732
0
3
null
null
null
null
UTF-8
C++
false
false
2,319
cpp
A.cpp
/* Problem: A.cpp Time: 2021-02-18 16:14 Author: CraZYali E-Mail: yms-chenziyang@outlook.com */ #define REP(i, s, e) for (register int i(s), end_##i(e); i <= end_##i; i++) #define DEP(i, s, e) for (register int i(s), end_##i(e); i >= end_##i; i--) #define DEBUG fprintf(stderr, "Passing [%s] in Line %d\n", __FUNCTION__, __LINE__) #define chkmax(a, b) (a < (b) ? a = (b) : a) #define chkmin(a, b) (a > (b) ? a = (b) : a) #include <iostream> #include <cstdio> using namespace std; const int maxn = 2e5 + 10; template <typename T> inline T read() { T ans = 0, flag = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') flag = -1; c = getchar(); } while (isdigit(c)) { ans = ans * 10 + (c - 48); c = getchar(); } return ans * flag; } #define file(FILE_NAME) freopen(FILE_NAME".in", "r", stdin), freopen(FILE_NAME".out", "w", stdout) int n, k, l[maxn]; const int LIM = 8; int a[maxn], fail[maxn], x; string mem[maxn][1 << LIM]; void calc(int n) { int sta = 0; for (int x = fail[n]; x; x = fail[x]) sta |= (1 << x - 1); string res = ""; REP(i, 1, n) res += a[i]; if (!mem[n][sta].size() || res < mem[n][sta]) mem[n][sta] = res; } void dfs(int x = 0, int cur = 'a') { if (x) calc(x); if (x >= LIM) return; x++; REP(i, 'a', min((int)'z', cur + 1)) { a[x] = i; if (x > 1) { int k = fail[x - 1]; while (k && a[k + 1] != i) k = fail[k]; if (a[k + 1] == i) k++; fail[x] = k; } dfs(x, max(i, cur)); } } int main() { #ifdef CraZYali file("A"); #endif dfs(); register int T = read<int>(); while (T--) { n = read<int>();k = read<int>(); static int l[maxn]; REP(i, 1, k) l[i] = read<int>(); if (!k) { REP(i, 1, n - 1) putchar('a'); puts("b"); continue; } if (k == n - 1) { REP(i, 1, n) putchar('a'); puts(""); continue; } if (n > LIM) {puts("GG");continue;} int sta = 0; REP(i, 1, k) sta |= (1 << l[i] - 1); string res = mem[n][sta]; if (res.size()) { cout << res << '\n'; continue; } int ard = 1e9; for (int U = (1 << n - 1) - 1, V = U ^ sta, x = V; ; x = (x - 1) & V) { if (mem[n][sta | x].size() && ard >= __builtin_popcount(x) && (!res.size() || res > mem[n][sta | x])) res = mem[n][sta | x], ard = __builtin_popcount(x); if (!x) break; } cout << res << '\n'; } return 0; }
7ea93b6fdec88ba51903cf361f37ef23759f8f9c
521685507e5b26ec9be38b39a249bdc1ee638138
/Qt/Components/pqComparativeVisPanel.cxx
b5feeb28c0f783290a204bfadb2d5f3d71b40dfa
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
matthb2/ParaView-beforekitwareswtichedtogit
6ad4662a1ad8c3d35d2c41df209fc4d78b7ba298
392519e17af37f66f6465722930b3705c1c5ca6c
refs/heads/master
2020-04-05T05:11:15.181579
2009-05-26T20:50:10
2009-05-26T20:50:10
211,087
1
2
null
null
null
null
UTF-8
C++
false
false
14,170
cxx
pqComparativeVisPanel.cxx
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ========================================================================*/ #include "pqComparativeVisPanel.h" #include "ui_pqComparativeVisPanel.h" // Server Manager Includes. #include "vtkProcessModule.h" #include "vtkSMAnimationCueProxy.h" #include "vtkSmartPointer.h" #include "vtkSMComparativeViewProxy.h" #include "vtkSMProxyManager.h" #include "vtkSMProxyProperty.h" #include "vtkSMDoubleVectorProperty.h" // Qt Includes. #include <QHeaderView> #include <QPointer> #include <QScrollArea> // ParaView Includes. #include "pqActiveView.h" #include "pqAnimationCue.h" #include "pqAnimationKeyFrame.h" #include "pqAnimationModel.h" #include "pqAnimationTrack.h" #include "pqApplicationCore.h" #include "pqComparativeChartView.h" #include "pqComparativeRenderView.h" #include "pqPipelineSource.h" #include "pqPropertyLinks.h" #include "pqServerManagerModel.h" #include "pqSignalAdaptors.h" #include "pqSMAdaptor.h" class pqComparativeVisPanel::pqInternal : public Ui::ComparativeView { public: QPointer<pqView> View; pqPropertyLinks Links; pqSignalAdaptorComboBox* ModeAdaptor; pqSignalAdaptorComboBox* ViewUpdateModeAdaptor; }; //----------------------------------------------------------------------------- pqComparativeVisPanel::pqComparativeVisPanel(QWidget* p):Superclass(p) { this->Internal = new pqInternal(); /* TODO: Why does this never work for me :( ? QVBoxLayout* vboxlayout = new QVBoxLayout(this); vboxlayout->setSpacing(0); vboxlayout->setMargin(0); vboxlayout->setObjectName("vboxLayout"); QWidget* container = new QWidget(this); container->setObjectName("scrollWidget"); container->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); QScrollArea* s = new QScrollArea(this); s->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); s->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); s->setWidgetResizable(true); s->setObjectName("scrollArea"); s->setFrameShape(QFrame::NoFrame); s->setWidget(container); vboxlayout->addWidget(s); this->Internal->setupUi(container); */ this->Internal->setupUi(this); this->Internal->ModeAdaptor = new pqSignalAdaptorComboBox(this->Internal->Mode); this->Internal->ViewUpdateModeAdaptor = new pqSignalAdaptorComboBox(this->Internal->ViewUpdateMode); this->Internal->Links.setUseUncheckedProperties(false); // When mode changes we want to hide the non-related GUI components. QObject::connect( this->Internal->ModeAdaptor, SIGNAL(currentTextChanged(const QString&)), this, SLOT(modeChanged(const QString&)), Qt::QueuedConnection); this->Internal->YAxisGroup->setVisible(false); // Call updateView when "Update" pushbutton is clicked. QObject::connect(this->Internal->Update, SIGNAL(clicked()), this, SLOT(updateView()), Qt::QueuedConnection); // FIXME: move connection to pqMainWindowCore. QObject::connect(&pqActiveView::instance(), SIGNAL(changed(pqView*)), this, SLOT(setView(pqView*))); //this->Internal->XObject->setUpdateCurrentWithSelection(true); //this->Internal->YObject->setUpdateCurrentWithSelection(true); pqServerManagerModel* smmodel = pqApplicationCore::instance()->getServerManagerModel(); // Add source to pqSourceComboBox when source is added to pipeline QObject::connect(smmodel, SIGNAL(sourceAdded(pqPipelineSource*)), this->Internal->XObject, SLOT(addSource(pqPipelineSource*))); QObject::connect(smmodel, SIGNAL(sourceAdded(pqPipelineSource*)), this->Internal->YObject, SLOT(addSource(pqPipelineSource*))); // Remove source from pqSourceComboBox when source is remove from pipeline QObject::connect(smmodel, SIGNAL(preSourceRemoved(pqPipelineSource*)), this->Internal->XObject, SLOT(removeSource(pqPipelineSource*))); QObject::connect(smmodel, SIGNAL(preSourceRemoved(pqPipelineSource*)), this->Internal->YObject, SLOT(removeSource(pqPipelineSource*))); // Set pqAnimatablePropertiesComboBox when pqSourceComboBox changes QObject::connect( this->Internal->XObject, SIGNAL(currentIndexChanged(vtkSMProxy*)), this->Internal->XProperty, SLOT(setSource(vtkSMProxy*))); QObject::connect( this->Internal->YObject, SIGNAL(currentIndexChanged(vtkSMProxy*)), this->Internal->YProperty, SLOT(setSource(vtkSMProxy*))); // Call propertyChanged() when pqAnimatablePropertiesComboBox changes QObject::connect( this->Internal->XProperty, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(xpropertyChanged())); QObject::connect( this->Internal->YProperty, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(ypropertyChanged())); this->Internal->XProperty->setUseBlankEntry(true); this->Internal->YProperty->setUseBlankEntry(true); this->setEnabled(false); } //----------------------------------------------------------------------------- pqComparativeVisPanel::~pqComparativeVisPanel() { delete this->Internal->ModeAdaptor; delete this->Internal->ViewUpdateModeAdaptor; delete this->Internal; } //----------------------------------------------------------------------------- void pqComparativeVisPanel::setView(pqView* view) { if (this->Internal->View == view) { return; } this->Internal->Links.removeAllPropertyLinks(); this->Internal->View = view; this->Internal->AnimationWidget->setComparativeView( view? view->getProxy() : 0); // View must be a comparative render/plot view if ( !qobject_cast<pqComparativeRenderView*>(view) && !qobject_cast<pqComparativeChartView*>(view)) { this->Internal->View = 0; this->setEnabled(false); return; } vtkSMComparativeViewProxy* viewProxy = vtkSMComparativeViewProxy::SafeDownCast(view->getProxy()); this->setEnabled(true); // Connect XFrames spinbox value to vtkSMComparativeViewProxy's "Dimensions" property this->Internal->Links.addPropertyLink( this->Internal->XFrames, "value", SIGNAL(valueChanged(int)), viewProxy, viewProxy->GetProperty("Dimensions"), 0); // Connect YFrames spinbox value to vtkSMComparativeViewProxy's "Dimensions" property this->Internal->Links.addPropertyLink( this->Internal->YFrames, "value", SIGNAL(valueChanged(int)), viewProxy, viewProxy->GetProperty("Dimensions"), 1); // Connect show timesteps check button this->Internal->Links.addPropertyLink( this->Internal->ShowTimeStepsCheck, "checked", SIGNAL(stateChanged(int)), viewProxy, viewProxy->GetProperty("ShowTimeSteps"), 1); // Connect mode combobox to vtkSMComparativeViewProxy's "Mode" property this->Internal->Links.addPropertyLink( this->Internal->ModeAdaptor, "currentText", SIGNAL(currentTextChanged(const QString&)), viewProxy, viewProxy->GetProperty("Mode")); // Connect combobox to vtkSMComparativeViewProxy's "ViewUpdateMode" property this->Internal->Links.addPropertyLink( this->Internal->ViewUpdateModeAdaptor, "currentText", SIGNAL(currentTextChanged(const QString&)), viewProxy, viewProxy->GetProperty("ViewUpdateMode")); } //----------------------------------------------------------------------------- void pqComparativeVisPanel::updateView() { if (this->Internal->View) { this->Internal->Links.accept(); // This could be handled differently, but for now lets // set the timerange to the currently selected source object's // TimestepValues (if it has them) if (this->Internal->XObject->currentSource()) { this->setTimeRangeFromSource(this->Internal->XObject->currentSource()->getProxy()); } vtkSMComparativeViewProxy* viewProxy = vtkSMComparativeViewProxy::SafeDownCast(this->Internal->View->getProxy()); // Call UpdateVisualization with 1 to force the update viewProxy->UpdateVisualization(1); } } //----------------------------------------------------------------------------- void pqComparativeVisPanel::modeChanged(const QString& mode) { if (mode == "Film Strip") { this->Internal->YAxisGroup->setVisible(false); } else { this->Internal->YAxisGroup->setVisible(true); } } //----------------------------------------------------------------------------- void pqComparativeVisPanel::xpropertyChanged() { if (this->Internal->View) { // Locate the X animation cue for this property (if none exists, a new one will // be created) and make it the only enabled cue in the XCues property. vtkSMProxy* proxy = this->Internal->XProperty->getCurrentProxy(); QString pname = this->Internal->XProperty->getCurrentPropertyName(); int index = this->Internal->XProperty->getCurrentIndex(); // Locate cue for the selected property. this->activateCue( this->Internal->View->getProxy()->GetProperty("XCues"), proxy, pname, index); this->Internal->View->getProxy()->UpdateVTKObjects(); } } //----------------------------------------------------------------------------- void pqComparativeVisPanel::ypropertyChanged() { if (this->Internal->View) { // Locate the Y animation cue for this property (if none exists, a new one will // be created) and make it the only enabled cue in the YCues property. vtkSMProxy* proxy = this->Internal->YProperty->getCurrentProxy(); QString pname = this->Internal->YProperty->getCurrentPropertyName(); int index = this->Internal->YProperty->getCurrentIndex(); // Locate cue for the selected property. this->activateCue( this->Internal->View->getProxy()->GetProperty("YCues"), proxy, pname, index); this->Internal->View->getProxy()->UpdateVTKObjects(); } } //----------------------------------------------------------------------------- void pqComparativeVisPanel::setTimeRangeFromSource(vtkSMProxy* source) { if (!source || !this->Internal->View) { return; } // Get TimeRange property vtkSMDoubleVectorProperty* timeRangeProp = vtkSMDoubleVectorProperty::SafeDownCast( this->Internal->View->getProxy()->GetProperty("TimeRange")); // Try to get TimestepValues property from the source proxy vtkSMDoubleVectorProperty* tsv = vtkSMDoubleVectorProperty::SafeDownCast( source->GetProperty("TimestepValues")); // Set the TimeRange to the first and last of TimestepValues. if (tsv && timeRangeProp && tsv->GetNumberOfElements()) { double tBegin = tsv->GetElement(0); double tEnd = tsv->GetElement(tsv->GetNumberOfElements()-1); timeRangeProp->SetElement(0, tBegin); timeRangeProp->SetElement(1, tEnd); this->Internal->View->getProxy()->UpdateProperty("TimeRange"); } } //----------------------------------------------------------------------------- void pqComparativeVisPanel::activateCue( vtkSMProperty* cuesProperty, vtkSMProxy* animatedProxy, const QString& animatedPName, int animatedIndex) { if (!cuesProperty || !animatedProxy || animatedPName.isEmpty()) { return; } // Try to locate the cue, if already present. vtkSMProxyProperty* pp = vtkSMProxyProperty::SafeDownCast(cuesProperty); vtkSmartPointer<vtkSMAnimationCueProxy> cueProxy; for (unsigned int cc=0; cc < pp->GetNumberOfProxies(); ++cc) { vtkSMAnimationCueProxy* cur = vtkSMAnimationCueProxy::SafeDownCast( pp->GetProxy(cc)); if (cur && cur->GetAnimatedProxy() == animatedProxy && cur->GetAnimatedPropertyName() == animatedPName && cur->GetAnimatedElement() == animatedIndex) { cueProxy = cur; } else if (cur) { pqSMAdaptor::setElementProperty(cur->GetProperty("Enabled"), 0); cur->UpdateVTKObjects(); } } if (!cueProxy) { vtkSMProxyManager *pxm = vtkSMProxyManager::GetProxyManager(); // Create a new cueProxy. cueProxy.TakeReference( vtkSMAnimationCueProxy::SafeDownCast(pxm->NewProxy("animation", "KeyFrameAnimationCue"))); cueProxy->SetServers(vtkProcessModule::CLIENT); cueProxy->SetConnectionID(this->Internal->View->getProxy()->GetConnectionID()); pqSMAdaptor::setElementProperty(cueProxy->GetProperty("AnimatedPropertyName"), animatedPName); pqSMAdaptor::setElementProperty(cueProxy->GetProperty("AnimatedElement"), animatedIndex); pqSMAdaptor::setProxyProperty(cueProxy->GetProperty("AnimatedProxy"), animatedProxy); // This cueProxy must be registered so that state works fine. For that // purpose we just make it an helper of the view. this->Internal->View->addHelperProxy("AnimationCues", cueProxy); // We want to add default keyframes to this cue. pqServerManagerModel* smmodel = pqApplicationCore::instance()->getServerManagerModel(); pqAnimationCue* pqcue = smmodel->findItem<pqAnimationCue*>(cueProxy); pqcue->insertKeyFrame(0); pqcue->insertKeyFrame(1); } pqSMAdaptor::addProxyProperty(cuesProperty, cueProxy); pqSMAdaptor::setElementProperty(cueProxy->GetProperty("Enabled"), 1); cueProxy->UpdateVTKObjects(); }
10dbe5bfd89e5c65af0f7ae6cc984536cd5876c0
2adfe84d1014165aa96735e7ab68b785f13f9fee
/node.h
eb729e13b58144d68fa30f0d86301e2c39389bcf
[ "MIT" ]
permissive
TailonR/CS411_UAF_Homework7
9d777b0d549048a65d65df27166e7f40435db4f4
5cac107bf6b07efacf9739ef580acad7dda5a597
refs/heads/master
2023-01-29T22:54:36.698125
2020-12-12T02:43:20
2020-12-12T02:43:20
318,969,145
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
node.h
// node.h // Author: Tailon Russell // Date: 12/5/2020. // The header file for class Node #ifndef HOMEWORK7_NODE_H #define HOMEWORK7_NODE_H //class Node // Invariants: None class Node{ public: int value; int priority; }; bool operator< (Node lhs, Node rhs); bool operator== (Node lhs, Node rhs); #endif //HOMEWORK7_NODE_H
30c9e4613f2a69b5541633b795011fc7accf6b18
7d93616b09afdd38ba25f70bf56e84d92d16f8e1
/willow/include/popart/popx/popprograms.hpp
3bfd4582b8d835c18360ccb1672e810616ca940e
[ "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
graphcore/popart
ac3c71617c5f0ac5dadab179b655f6b2372b453d
efa24e27f09b707865326fe4a30f4a65b7a031fe
refs/heads/sdk-release-3.0
2023-07-08T08:36:28.342159
2022-09-23T12:22:35
2022-09-23T15:10:23
276,412,857
73
13
NOASSERTION
2022-09-29T12:13:40
2020-07-01T15:21:50
C++
UTF-8
C++
false
false
13,347
hpp
popprograms.hpp
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #ifndef POPART_WILLOW_INCLUDE_POPART_POPX_POPPROGRAMS_HPP_ #define POPART_WILLOW_INCLUDE_POPART_POPX_POPPROGRAMS_HPP_ #include <iosfwd> #include <map> #include <memory> #include <set> #include <snap/Function.hpp> #include <snap/Program.hpp> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <popef/Types.hpp> #include <popart/graphid.hpp> #include <popart/names.hpp> #include <popart/popx/pritask.hpp> namespace poplar { class Function; class FunctionBuffer; enum class FunctionBufferMappingType; } // namespace poplar namespace snap { class Graph; } // namespace snap namespace popart { class Graph; class PipelineInfo; enum class ScheduledPreLoss; namespace popx { class IrLowering; /** * Class for managing the complete set of \c programs that a \c Devicex can run. * * A \c program in this context is the instance of the \c poplar::Program class * which represents a control program that executes operations on the graph. * * The state \c std::vector<snap::program::Sequence> \c seqs contains all these * programs, and is populated during \c IrLowering. The programs are passed to * \c poplar::compileGraph to construct the executable (see * \c IrLowering::getExecutable()). **/ class PopPrograms { public: // We may want to run some programs multiple times without having // to communicate with the host to call the 'run'. By supplying a // count, we can loop a repeatable program inside a Poplar repeat // program PopPrograms(IrLowering *ir_lowering_p_); enum ProgramIndex { WeightsFromHost = 0, OptimizerFromHost, RandomSeedFromHost, RandomSeedToHost, RngStateFromHost, Program, RngStateToHost, WeightsToHost, CycleCountTensorToHost, CustomProgramsStart, N // The number of enums }; static const std::unordered_map<popef::ProgramFlow::ProgramIndexType, std::string> commonPrograms; // Order of these enums is used for scheduling enum class ProgramFragmentIndex { StreamWeightsFromHost = 0, StreamOptimizerFromHost, RandomSeedFromHost, RandomSeedToHost, RngStateFromHost, Init, PreForward, Forward, Backward, VarUpdateFromAccumulator, RngStateToHost, WeightsToHost, ToHostFinalCopy, CycleCountTensorToHost, N // The number of program fragments }; // Program fragments are not necessarily complete program that can be given to // a poplar engine. const snap::program::Sequence &streamWeightsFromHostFragment() const; snap::program::Sequence &streamWeightsFromHostFragment(); const snap::program::Sequence &streamOptimizerFromHostFragment() const; snap::program::Sequence &streamOptimizerFromHostFragment(); const snap::program::Sequence &randomSeedFromHostFragment() const; snap::program::Sequence &randomSeedFromHostFragment(); const snap::program::Sequence &randomSeedToHostFragment() const; snap::program::Sequence &randomSeedToHostFragment(); const snap::program::Sequence &cycleCountTensorToHostFragment() const; snap::program::Sequence &rngStateFromHostFragment(); const snap::program::Sequence &rngStateFromHostFragment() const; snap::program::Sequence &rngStateToHostFragment(); const snap::program::Sequence &rngStateToHostFragment() const; snap::program::Sequence &cycleCountTensorToHostFragment(); const snap::program::Sequence &toHostFinalCopyFragment() const; snap::program::Sequence &toHostFinalCopyFragment(); const snap::program::Sequence &initFragment() const; snap::program::Sequence &initFragment(); const snap::program::Sequence &preForwardFragment() const; snap::program::Sequence &preForwardFragment(); const snap::program::Sequence &forwardFragment() const; snap::program::Sequence &forwardFragment(); const snap::program::Sequence &backwardFragment() const; snap::program::Sequence &backwardFragment(); const snap::program::Sequence &accumulateOuterFragment() const; snap::program::Sequence &accumulateOuterFragment(); const snap::program::Sequence &weightsToHostFragment() const; snap::program::Sequence &weightsToHostFragment(); // If ScheduledPreLoss::Yes, then return forwardFragment(), else return // backwardFragment() snap::program::Sequence &forwardOrBackwardFragment(ScheduledPreLoss); // A list of programs that can be run by the Poplar engine. const std::vector<snap::program::Program> progs() const; snap::program::Sequence &programFragment(PopPrograms::ProgramFragmentIndex); // Sub-graph program fragments, getters and setters for poplar sequences and // functions for subgraphs. // The number of Poplar sequences associated with a graph. int getNumFragments(const Graph &graph) const; // Get a vector of all Poplar sequences associated with a graph. std::vector<snap::program::Sequence> &scopeFragments(const Graph &); // Get a specific Poplar sequence associated with a graph. snap::program::Sequence &scopeFragment(const Graph &, SubgraphPartIndex subgraphPart); // Determine if any Poplar sequences associated with a graph are allocated. bool containsFragments(const Graph &graph) const; // Determine whether a specific Poplar sequence associated with a graph has // been allocated. bool containsFragment(const Graph &graph, SubgraphPartIndex subgraphPart) const; // Ensure a specific Poplar sequence is allocated. void createFragment(const Graph &graph, SubgraphPartIndex subgraphPart); // Wrap all Poplar sequences associated with a graph in to a poplar function // that can be called and return them all. std::vector<snap::Function> &getFragmentFunctions(const Graph &graph, snap::Graph &snapGraph); // Wrap all Poplar sequences associated with a graph in to a poplar function // that can be called and return a specific one. snap::Function &getFragmentFunction(const Graph &graph, SubgraphPartIndex subgraphPart, snap::Graph &snapGraph); // Get the program fragment for a recomputed op. createRecomputeFragment must // be called first. std::vector<snap::program::Sequence>::iterator recomputeFragment(OpId); // Create the program fragment for a recomputed op. SequenceMap::SequenceInterval createRecomputeFragment(OpId); bool hasBeenRecomputed(OpId, ExecutionPhase) const; void recordRecomputed(OpId, ExecutionPhase); // Each Pipeline Stage is composed of these fragments. For a given Pipeline // Stage, any of these fragments may be empty. // // Note: the preForwardFragment and IpuCopy fragment do not require a // PipelineFragmentId, since they exist as a single fragment idependent of // pipeline stage, and are run every Pipeline Cycle. enum class PipelineFragmentId { ToDeviceStream = 0, Main, ToHostStream }; std::string getStrFromPipelineFragmentId(PipelineFragmentId) const; // Program fragments specific to pipelined model. Each method to return // a pipeline program fragment takes a 'description' string, that describes // the code being added to the returned fragment. This description is added // to pipelineDescs to build up a full description of the program. snap::program::Sequence & pipelineFragment(PipelineStage, PipelineFragmentId, const std::string &desc); snap::program::Sequence & pipelineToDeviceStreamFragment(PipelineStage pipelineStage, const std::string &desc); snap::program::Sequence &pipelineMainFragment(PipelineStage, const std::string &desc); // To stream anchors that are computed in the pipelineMainFragment snap::program::Sequence & pipelineToHostStreamFragment(PipelineStage, const std::string &desc); snap::program::Sequence &pipelineIpuCopyFragment(const std::string &desc); void addPipelineCycle(PipelineInfo pInfo, PipelineCycle pCycle, snap::program::Sequence &sq, std::ostringstream &ss) const; /** * Add a vector of pairs {f, buffer} for a given graph id. This is enough for * a [Internal|External]CodeCopy op to move code from the buffer in to * the function. Note the subgraphpartitioner may have split this into * multiple functions, so we require a vector of these for each graph. * * \param pair The graph id, FunctionBufferMappingType pair to add the * functions and buffers for. * \param funcVec The vector of functions and buffers. */ void addFunctionBuffers(const GraphId gid, poplar::FunctionBufferMappingType fbmt); // Shorthand storage type for storing functionbuffers. using FunctionBuffers = std::vector<std::pair<const poplar::Function, poplar::FunctionBuffer>>; /** * Get the Function Buffers for the given GraphId and * FunctionBufferMappingType * * \param gid The GraphId to lookup. * \param fbmt The FunctionBufferMappingType to lookup. * \returns FunctionBuffers the vector of functions and buffers. */ FunctionBuffers getFunctionBuffer(const GraphId gid, poplar::FunctionBufferMappingType fbmt) { return functionBuffers.at({gid, fbmt}); } /** * Returns true if a functionBuffer vector exists for the given graphId and * FunctionBufferMappingType. * * \param gid The graph id to lookup. * \param fbmt The FunctionBufferMappingType to lookup. * \returns true If pairs exist. * \returns false Otherwise. */ bool hasFunctionBuffer(const GraphId gid, poplar::FunctionBufferMappingType fbmt) { return functionBuffers.count({gid, fbmt}) > 0; } /** * Add a custom program * \param program Program to add * \return Index of the popart/snap/poplar program */ unsigned addCustomProgram(const snap::program::Program &program); IrLowering *ir_lowering_p; private: std::vector<snap::program::Sequence> seqs; // The sub-graph program fragments will be stored here std::unordered_map<std::string, std::vector<snap::program::Sequence>> scopeSeqs; std::unordered_map<std::string, std::vector<snap::Function>> funcs; // The recompute program fragments will be stored here. We store the sequences // in singleton vectors because grow code requires iterators to vectors. std::map<OpId, std::vector<snap::program::Sequence>> recomputeSeqs; // Pipelining fragments for each pipeline stage are stored here std::map<PipelineFragmentId, std::map<PipelineStage, snap::program::Sequence>> pipelineSeqs; // ... and their corresponding descriptions std::map<PipelineFragmentId, std::map<PipelineStage, std::string>> pipelineDescs; // IpuCopy program std::unique_ptr<snap::program::Sequence> pipelineIpuCopySeq; std::string pipelineIpuCopyDesc; // Implicit pipeline functions snap::Function zeroPipelineIndexFunction; // Functions containing the pipeline stages std::map<PipelineStage, snap::Function> mainPipelineFunctions; // Function copying all required tensors between consecutive pipeline stages snap::Function pipelineIpuCopyFunction; // Function containig the implicit stream copies from device to host for // tensors only streamed once for the whole program run // (see AnchorReturnTypeId::Final) snap::Function toHostFinalCopyFunction; // Custom programs std::vector<snap::program::Program> customPrograms; // Map of the {graph id, FunctionBufferMappingType}'s and their associated // functions and buffers for use in loading the code for the graph execution // on / off chip. Note that there may be multiple functions per graph so a // vector of functions / buffers is stored. Furthermore these are indexed by // {graphid, FunctionBufferMappingType} in case different // FunctionBufferMappingTypes are required for multiple call ops for the same // graph. std::map<std::pair<const GraphId, poplar::FunctionBufferMappingType>, FunctionBuffers> functionBuffers; public: void initWithSnapGraph(snap::Graph &); /** * Turn pipeline sequences into callable pipeline functions */ void createPipelineFunctions(); /** * Return the program based on the pipeline fragments. * * See docs/notes/transforms/pipelining.md#assemble-from-fragments for * detailed explanation. * * \return The program based on the pipeline fragments **/ snap::program::Sequence getFullProgramFromPipelineFragments(bool fwdOnly) const; private: std::set<std::pair<OpId, ExecutionPhase>> beenRecomputed; snap::program::Sequence weightsFromHost() const; snap::program::Sequence optimizerFromHost() const; snap::program::Sequence randomSeedFromHost() const; snap::program::Sequence randomSeedToHost() const; snap::program::Sequence rngStateFromHost() const; snap::program::Sequence cycleCountTensorToHost() const; snap::program::Sequence program() const; snap::program::Sequence rngStateToHost() const; snap::program::Sequence weightsToHost() const; }; } // namespace popx } // namespace popart #endif // POPART_WILLOW_INCLUDE_POPART_POPX_POPPROGRAMS_HPP_
bf4f9b8addd922c0a6431ef207b0dcc48d253000
0ff0c44885ccf687d8d00d407bff180f89f45a2a
/T1046判断闰年.cpp
edefde3020eec28b0dd2ecd54fb90436b2f960f3
[]
no_license
shareone2/JiSuanKeOj
dc3e06134b58a679d515aef343d7cbe48ee887d1
4771e5a50bea48cab278245fb979bffe9b4c5da6
refs/heads/master
2022-12-16T13:47:38.853626
2020-09-09T08:57:38
2020-09-09T08:57:38
294,057,513
0
0
null
null
null
null
UTF-8
C++
false
false
513
cpp
T1046判断闰年.cpp
/************************************************************************* > File Name: T1046判断闰年.cpp > Author: > Mail: > Created Time: 2019年04月05日 星期五 14时46分47秒 ************************************************************************/ #include<iostream> using namespace std; int main () { int year; cin >> year; if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { cout << 'Y' << endl; } else { cout << 'N' << endl; } return 0; }
f12decab0bb8f4225f21f22ab5385d9e20d1eb20
19fdd6e16106500a5abf16b6b6492a0d6cd6edb0
/aegis128L.cc
ca605d895849c6e7477ab18d809ce674b8ca3cad
[ "Apache-2.0" ]
permissive
burgerdev/aegis_cipher
a10924e2cfcaad3c77f395bf9c02d9d35e0be110
ba167ea7a064a207c86a10793325a9ad946c8641
refs/heads/master
2023-07-02T13:11:07.525476
2021-08-05T13:55:05
2021-08-05T13:55:59
393,082,580
0
0
Apache-2.0
2021-08-05T15:01:47
2021-08-05T14:58:59
null
UTF-8
C++
false
false
14,405
cc
aegis128L.cc
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "aegis128L.h" namespace security { namespace aegis { using internal::AegisStage, internal::DIRTY, internal::RESET, internal::AAD, internal::ENCRYPT, internal::DECRYPT, internal::FINALIZED, internal::VERIFIED; namespace { inline ABSL_ATTRIBUTE_ALWAYS_INLINE bool CompareTags(Aegis128LTag tag, const char *expected_tag) { return Vec128Eq(tag, Vec128Load(expected_tag)); } // This function determines if we can safely load "size" number of bytes from // ptr. On Intel (and this file is pretty Intel specific already), we cannot // cause a page-fault, unless we cross page boundaries. For instance, with 32 // bytes to not cross a page boundary, our 32-byte load must not start from the // last 32 bytes of a page. We check this by (ptr & 0xfe0) != 0xfe0, which is // only false for the range [0xfe1..0xfff], which amounts to what we want to // check. This trick generalises to all "size" values that are a power of two. // // While we could also use a dynamic page_size other than 4k by using, e.g. // sysconf(_SC_PAGE_SIZE), 4k is the most conservative choice, and hard-coding // this value allows the compiler to generate imm instructions, which are much // faster. inline ABSL_ATTRIBUTE_ALWAYS_INLINE bool IsWideLoadSafe(const void *ptr, size_t size) { #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \ !defined(THREAD_SANITIZER) #ifndef NDEBUG assert(!(size & (size - 1))); // Power of two? assert(size < 128); // Caller should use sane values. #endif constexpr uint16_t kPageSize = 4096; uint16_t mask = kPageSize - size; return ((reinterpret_cast<uint64_t>(ptr) & mask) != mask); #else // Sanitizers catches us accessing beyond the bounds of ptr, therefore we // disable wide loads in these cases. return false; #endif } inline ABSL_ATTRIBUTE_ALWAYS_INLINE Aegis128LBlock MaskedLoad(const char *data, size_t offset, size_t size) { #ifndef NDEBUG assert(size <= 32); #endif const char *data_aligned = data - offset; if ((offset == 0 && size == 32) || IsWideLoadSafe(data_aligned, 32)) { return Vec256Load(data_aligned); } // We cannot do a full-load from the memory directly, as a 32-bytes wide load // might cause page-fault. We copy to scratch space and do a 32-byte load from // there. char tmp[32]; memmove(tmp + offset, data, size); return Vec256Load(tmp); } void MaskedStore(Aegis128LBlock block, char *data, size_t offset, size_t size) { #ifndef NDEBUG assert(size + offset <= 32); #endif if (size == 0) { return; } if (size == 32) { Vec256Store(data, block); return; } char tmp[32]; Vec256Store(tmp, block); memmove(data, tmp + offset, size); } const Vec128 mask_0x20_0x11 = MakeVec128Epi64x(0x201f1e1d1c1b1a19, 0x1817161514131211); const Vec128 mask_0x10_0x01 = MakeVec128Epi64x(0x100f0e0d0c0b0a09, 0x0807060504030201); // Constants from the AEGIS paper used in preparation of the IV Vec128 const0() { return MakeVec128Epi64x(0x6279e99059372215, 0x0d08050302010100); } Vec128 const1() { return MakeVec128Epi64x(0xdd28b57342311120, 0xf12fc26d55183ddb); } inline ABSL_ATTRIBUTE_ALWAYS_INLINE Aegis128LBlock KeyStream(Vec128 S[8]) { Vec128 even = Vec128And(S[2], S[3]); even = Vec128Xor(Vec128Xor(S[1], S[6]), even); Vec128 odd = Vec128And(S[6], S[7]); odd = Vec128Xor(Vec128Xor(S[2], S[5]), odd); return MakeVec256(even, odd); } inline ABSL_ATTRIBUTE_ALWAYS_INLINE void StateUpdateRounds(Vec128 S[8], Vec128 S0, Vec128 S4) { Vec128 w = Vec128AesRound(S[7], S0); S[7] = Vec128AesRound(S[6], S[7]); S[6] = Vec128AesRound(S[5], S[6]); S[5] = Vec128AesRound(S[4], S[5]); S[4] = Vec128AesRound(S[3], S4); S[3] = Vec128AesRound(S[2], S[3]); S[2] = Vec128AesRound(S[1], S[2]); S[1] = Vec128AesRound(S[0], S[1]); S[0] = w; } inline ABSL_ATTRIBUTE_ALWAYS_INLINE void StateUpdate(Vec128 S[8], Aegis128LBlock msg, size_t offset, size_t size) { #ifndef NDEBUG assert(size + offset <= 32); #endif Vec128 ma; Vec128 mb; std::tie(ma, mb) = msg; if (offset == 0) { StateUpdateRounds(S, S[0], S[4]); } else { Vec128 a = MakeVec128BroadcastEpi8(offset); Vec128 mask_a = Vec128CmpLtEpi8(a, mask_0x10_0x01); Vec128 mask_b = Vec128CmpLtEpi8(a, mask_0x20_0x11); ma = Vec128And(ma, mask_a); mb = Vec128And(mb, mask_b); } size_t end = size + offset; if (end != 32) { Vec128 a = MakeVec128BroadcastEpi8(end); Vec128 mask_a = Vec128CmpLtEpi8(a, mask_0x10_0x01); Vec128 mask_b = Vec128CmpLtEpi8(a, mask_0x20_0x11); ma = Vec128AndNot(mask_a, ma); mb = Vec128AndNot(mask_b, mb); } S[0] = Vec128Xor(ma, S[0]); S[4] = Vec128Xor(mb, S[4]); } } // namespace namespace internal { inline ABSL_ATTRIBUTE_ALWAYS_INLINE void Initialize(Vec128 S[8], Vec128 key, Vec128 iv) { S[0] = Vec128Xor(key, iv); S[1] = const1(); S[2] = const0(); S[3] = const1(); S[4] = Vec128Xor(key, iv); S[5] = Vec128Xor(key, const0()); S[6] = Vec128Xor(key, const1()); S[7] = Vec128Xor(key, const0()); Aegis128LBlock msg = MakeVec256(iv, key); for (int i = 0; i < 10; i++) { StateUpdate(S, msg, 0, 32); } } inline ABSL_ATTRIBUTE_ALWAYS_INLINE Vec128 Finalize(Vec128 S[8], size_t aad_size_in_bytes, size_t pt_size_in_bytes) { uint64_t aad_bits = 8 * aad_size_in_bytes; uint64_t pt_bits = 8 * pt_size_in_bytes; Vec128 tmp0 = MakeVec128Epi64x(pt_bits, aad_bits); Vec128 tmp = Vec128Xor(tmp0, S[2]); Aegis128LBlock msg = MakeVec256(tmp, tmp); for (int i = 0; i < 7; i++) { StateUpdate(S, msg, 0, 32); } Vec128 tag = Vec128Xor(S[0], S[1]); tag = Vec128Xor(tag, S[2]); tag = Vec128Xor(tag, S[3]); tag = Vec128Xor(tag, S[4]); tag = Vec128Xor(tag, S[5]); tag = Vec128Xor(tag, S[6]); // https://eprint.iacr.org/2013/695.pdf computes the tag as sum over S[0..7], // while http://competitions.cr.yp.to/round1/aegisv1.pdf computes the tag // over S[0..6] // tag = Vec128Xor(tag, S[7]); return tag; } // ProcessBlock<direction> unifies data processing across AAD/ENCRYPT/DECRYPT // runs, and is instantiated inside of Process<direction>, and works as follows: // // direction == AAD , update state from the input , don't store output. // direction == ENCRYPT, update state from the input , store output. // direction == DECRYPT, update state from the output, store output. // template <AegisStage direction> // force inlining, as otherwise LLVM doesn't get the optimization in Process(..) inline ABSL_ATTRIBUTE_ALWAYS_INLINE void ProcessBlock( ResumableState *__restrict rs, const char *input, char *output, size_t offset, size_t size) { #ifndef NDEBUG assert(offset < 32); #endif /* This function is designed to completely be inlined including all the padding helpers. Those padding helpers are designed with bounds checking that can be optimized away when size is known at compile time. The intuition for the padding helpers are that they only opperate on the input up to n-th byte as given by the "size" argument, and will do nothing after that byte or assume zeros. */ if (!size) { return; } Aegis128LBlock in_block = MaskedLoad(input, offset, size); if (direction == AAD) { StateUpdate(rs->S, in_block, offset, size); } else if (direction == ENCRYPT || direction == DECRYPT) { // We resume a partial-block, the key-stream is stored in S[8]/S[9]. Aegis128LBlock key_stream = offset ? MakeVec256(rs->S[8], rs->S[9]) : KeyStream(rs->S); Aegis128LBlock out_block = Vec256Xor(in_block, key_stream); MaskedStore(out_block, output, offset, size); StateUpdate(rs->S, direction == ENCRYPT ? in_block : out_block, offset, size); if (offset + size != 32) { // We did not complete a block, store the key-stream in S[8]/S[9], so when // we pick up processing this partial block, the key-stream is available. rs->S[8] = std::get<0>(key_stream); rs->S[9] = std::get<1>(key_stream); } } } template <AegisStage direction> inline ABSL_ATTRIBUTE_ALWAYS_INLINE void Process( ResumableState *__restrict__ rs, const char *input, char *output, size_t previous_block_offset, size_t size) { #ifndef NDEBUG assert(previous_block_offset < 32); #endif /* This function processes the input mostly in 32-byte chunks. However, it also has to take care of any incomplete blocks from its last invocation (indicated by a non-zero previous_block_offset) and also has to partially process a block, if processing does not end on a block boundary. As ProcessBlock is designed to be inlined here, the loop in this function does the heavy-lifting. */ if (previous_block_offset) { size_t bytes_left_in_previous_block = 32 - previous_block_offset; if (size <= bytes_left_in_previous_block) { ProcessBlock<direction>(rs, input, output, previous_block_offset, size); // No more processing necessary. return; } else { ProcessBlock<direction>(rs, input, output, previous_block_offset, bytes_left_in_previous_block); input += bytes_left_in_previous_block; output += bytes_left_in_previous_block; size -= bytes_left_in_previous_block; } } size_t full_blocks = size / 16; size_t i = 0; // Unroll this loop twice, as this seems to give better vectorization for AES // instructions. #pragma unroll(2) for (; i + 1 < full_blocks; i += 2) { // Calling ProcessBlock with a fixed size=32, removes its bounds checks. ProcessBlock<direction>(rs, input + i * 16, output + i * 16, 0, 32); } ProcessBlock<direction>(rs, input + i * 16, output + i * 16, 0, size % 32); } } // namespace internal Aegis128LPreKeyed::Aegis128LPreKeyed(absl::string_view key, std::function<Aegis128LNonce()> get_nonce) : key_(Vec128Load(key.data())), get_nonce_(get_nonce) { assert(key.size() == 16); } void Aegis128LPreKeyed::Encrypt(absl::string_view plaintext, absl::string_view aad, std::string *ciphertext) { // So far we use a 16 byte IV and a 16 byte tag. const size_t kIvSize = 16; const size_t kTagSize = 16; size_t ciphertext_size = plaintext.size() + kIvSize + kTagSize; ciphertext->resize(ciphertext_size); char *buffer = &(*ciphertext)[0]; Aegis128LNonce nonce = get_nonce_(); Vec128Store(buffer, nonce); Aegis128LState state; state.Reset(key_, nonce); state.AssociateData(aad); state.Encrypt(plaintext, buffer + kIvSize); state.Finalize(&buffer[ciphertext_size - 16]); } bool Aegis128LPreKeyed::Decrypt(absl::string_view ciphertext, absl::string_view aad, std::string *plaintext) { const size_t kIvSize = 16; const size_t kTagSize = 16; if (ciphertext.size() < kIvSize + kTagSize) { return false; } Aegis128LNonce iv = LoadNonce(&ciphertext[0]); size_t plaintext_size = ciphertext.size() - kIvSize - kTagSize; Aegis128LState state; state.Reset(key_, iv); state.AssociateData(aad); absl::string_view raw_ciphertext(&ciphertext[kIvSize], plaintext_size); plaintext->resize(plaintext_size); state.Decrypt(raw_ciphertext, &(*plaintext)[0]); return state.Verify(&ciphertext[ciphertext.size() - kTagSize], [&]() { // We are free to clear plaintext, as the contract with the caller is that // we are free to override this string. memset(&(*plaintext)[0], 0, plaintext_size); plaintext->resize(0); }); } void Aegis128LState::Reset(Aegis128LKey key, Aegis128LNonce iv) { CheckStage(RESET, {DIRTY, RESET, AAD, ENCRYPT, DECRYPT, FINALIZED, VERIFIED}); aad_size_ = 0; payload_size_ = 0; internal::Initialize(rs_.S, key, iv); } void Aegis128LState::AssociateData(const char *aad, size_t s) { CheckStage(AAD, {RESET, AAD}); internal::Process<AAD>(&rs_, aad, nullptr, aad_size_ % 32, s); aad_size_ += s; } void Aegis128LState::Encrypt(const char *plaintext, size_t s, char *ciphertext) { CheckStage(ENCRYPT, {RESET, AAD, ENCRYPT}); internal::Process<ENCRYPT>(&rs_, plaintext, ciphertext, payload_size_ % 32, s); payload_size_ += s; } void Aegis128LState::Decrypt(const char *ciphertext, size_t s, char *plaintext) { CheckStage(DECRYPT, {RESET, AAD, DECRYPT}); internal::Process<DECRYPT>(&rs_, ciphertext, plaintext, payload_size_ % 32, s); payload_size_ += s; } Aegis128LTag Aegis128LState::Finalize() { CheckStage(internal::FINALIZED, {internal::RESET, internal::AAD, internal::ENCRYPT}); return internal::Finalize(rs_.S, aad_size_, payload_size_); } bool Aegis128LState::Verify(const char *expected_tag, absl::FunctionRef<void()> destroy_buffer) { CheckStage(internal::VERIFIED, {internal::RESET, internal::AAD, internal::DECRYPT}); Aegis128LTag tag = internal::Finalize(rs_.S, aad_size_, payload_size_); if (!CompareTags(tag, expected_tag)) { destroy_buffer(); return false; } return true; } } // namespace aegis } // namespace security
4c4d96e4b4741a44d1180a0140dd5e2dcba49df7
0ec7270058f86cfabf1b7e487588d623ecaf2470
/src/module_decl.cc
5dadfd99c71c842647f0a8c3c48ae7089349a875
[]
no_license
eklitzke/e
f3845d34fc2dd34abc126e2041be794927262739
dd5531b7fcab19bfdbea4199f64908144a5a43a8
refs/heads/master
2021-01-21T23:20:30.427160
2012-04-27T23:34:39
2012-04-27T23:34:39
3,369,197
3
0
null
null
null
null
UTF-8
C++
false
false
593
cc
module_decl.cc
// Copyright 2012, Evan Klitzke <evan@eklitzke.org> #include "./module_decl.h" #include "./assert.h" #include "./module.h" #include "./js_curses.h" #include "./js_errno.h" #include "./js_signal.h" #include "./js_sys.h" namespace { bool is_initialized = false; } namespace e { void InitializeBuiltinModules() { ASSERT(is_initialized == false); is_initialized = true; DeclareBuiltinModule("curses", &e::js_curses::Build); DeclareBuiltinModule("errno", &e::js_errno::Build); DeclareBuiltinModule("signal", &e::js_signal::Build); DeclareBuiltinModule("sys", &e::js_sys::Build); } }
75c7a4829c142efe31c07d8e33726cc56b93b006
e7d82fd27b051fbb8932658edfcdb45eb54c1f8c
/模板及进阶/Project1/Project1/Test.cpp
48216dd94bf3aad8f9d16bc377def2c96bfe6cce
[]
no_license
ChuckFan/ChuckTalk-cpp
8e0d52b4ed2b875b29c692e910ebf3c3cabd0e59
d7f42cae81a6d40b6939440127df71d512cedca0
refs/heads/master
2020-05-22T13:30:30.171869
2019-08-12T04:19:53
2019-08-12T04:19:53
186,360,618
0
0
null
null
null
null
GB18030
C++
false
false
2,135
cpp
Test.cpp
#define D_SCL_SECURE_NO_WARNINGS #include<iostream> using namespace std; //template<class T> //bool IsEqual(T& left, T& right) //{ // return left == right; //} //void Test() //{ // char* p1 = "hello"; // char* p2 = "world"; // // if (IsEqual(p1, p2)) // cout << p1 << endl; // else // cout << p2 << endl; //} //类型萃取 // 代表内置类型 struct TrueType { static bool Get() { return true ; } }; // 代表自定义类型 struct FalseType { static bool Get() { return false ; } }; template<class T> struct TypeTraits { typedef FalseType IsPODType; }; //实现对内置类型特例化 template<> struct TypeTraits<char> { typedef TrueType IsPODType; }; template<> struct TypeTraits<short> { typedef TrueType IsPODType; }; template<> struct TypeTraits<int> { typedef TrueType IsPODType; }; template<> struct TypeTraits<long> { typedef TrueType IsPODType; }; template<class T> void copy(T* dst, const T* src, size_t size) { if (TypeTraits<T>::IsPODType::Get()) { memcpy(dst, src, sizeof(T)*size); } else { for (size_t i = 0; i < size;++i) { dst[i] = src[i]; } } } int main() { int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int a2[10]; copy(a2, a1, 10); string s1[] = { "1111", "2222", "3333", "4444" }; string s2[4]; copy(s2, s1, 4); //Test(); system("pause"); return 0; } //1. 模板会导致代码膨胀问题,也会导致编译时间变长 //2. 出现模板编译错误时,错误信息非常凌乱,不易定位错误 //不用运算符实现n! //模板的特化,递归 //template<size_t n> //class sum{ //public: // enum // { // ret = n + sum<n - 1>::ret // }; //}; //template<> //class sum<1>{ //public: // enum // { // ret = 1 // }; //}; //用构造函数实现 //int sum = 0; //class add{ //public: // add() // { // n++; // sum += n; // } // static int n; //}; //int add::n = 0; //int main() //{ // //构造n个对象 // add a[100]; // cout << sum << endl; //}
6c163d2ce096d847ec7fb43901327420dd759e23
78de4c1a27c8ddca2c4a28ce6c09e03d444c533c
/4__brown_belt/week_5/009-lichnyi-biudzhiet-home-desktop-version/main.cpp
365190818cd27a2950a6f366771b265679e955f3
[]
no_license
altynbek132/yandex_CPP_specialization
f97676e06b47fe838a19c5f32ce734dfef69ad6a
838b165187eb7796d6ce028cd1e8b1206ae2b388
refs/heads/master
2023-07-08T16:55:34.044724
2021-07-28T11:04:26
2021-07-28T11:04:26
318,594,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
cpp
main.cpp
#include <bits/stdc++.h> #include "BudgetManager.h" #include "Query.h" #include "profile.h" #include "test_runner.h" using namespace std; #ifdef MASLO prerun maslo(true, false, false); #endif // MASLO vector<shared_ptr<Query::Query>> ReadQueries(istream& is = cin) { size_t Q; cin >> Q; cin.ignore(); vector<shared_ptr<Query::Query>> res; while (Q--) { res.push_back(Query::Read(is)); } return res; } ostream& ExecuteQueries(vector<shared_ptr<Query::Query>> queries, ostream& os = cout) { BudgetManager::Manager bm; for (auto& query : queries) { switch (query->type()) { case Query::Type::Earn: { bm.Earn(query->from, query->to, query->value); break; } case Query::Type::ComputeIncome: { os << bm.ComputeIncome(query->from, query->to) << endl; break; } case Query::Type::PayTax: { bm.PayTax(query->from, query->to); break; } default: throw runtime_error("chotam?"); } #ifdef MASLO1 std::cout << bm << std::endl << std::endl; #endif // MASLO } return os; } int main(int argc, const char** argv) { #ifndef MASLO cout.precision(25); #endif // MASLO ExecuteQueries(ReadQueries()); return 0; }
0a5f5eb58ee1da8e65d3f581ead46b8e1dd3e405
1443759dd6c44db7e6fff26f28c91b1eba9c383f
/Spike4_NonBlockingGridWorld/main.cpp
6a5e9019efe4a2f892c73334acdac1b2a3b6da89
[]
no_license
jessicavilaysak/GamesProgramming_7646895
303cb6c4806e75d63f6e1c0e2948a91b5732a432
dd00f39568d25c6a3df2fe7ada8eb030df9e2ec1
refs/heads/master
2021-06-05T11:11:24.012688
2016-11-02T11:19:26
2016-11-02T11:19:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,569
cpp
main.cpp
#include <time.h> #include <iostream> #include <streambuf> #include <thread> using namespace std; char pInput = ' '; void getInput() { cin >> pInput; } bool gameEnd = 0; int playerRow = 7; int playerCol = 2; string playerStatus; char playerInput; string consoleText; char moveArray[4]; char gridArray[8][8] = {{'#', '#', '#', '#', '#', '#', '#', '#'}, {'#', 'G', ' ', 'D', '#', 'D', ' ', '#'}, {'#', ' ', ' ', '#', '#', ' ', ' ', '#'}, {'#', '#', ' ', '#', '#', ' ', 'D', '#'}, {'#', ' ', ' ', '#', '#', ' ', ' ', '#'}, {'#', ' ', '#', '#', '#', '#', ' ', '#'}, {'#', ' ', ' ', ' ', ' ', ' ', ' ', '#'}, {'#', '#', 'S', '#', '#', '#', '#', '#'}}; void drawGrid() { for(int a=0; a<8; a++) { for(int b=0; b<8; b++) { if((a == playerRow) & (b == playerCol)) cout << "X"; else cout << gridArray[a][b]; if(b==7) cout << endl; } } } void input() { for(int c=0; c<4; c++) { moveArray[c] = 0; } if(playerRow == 7) { moveArray[0] = 'N'; cout << "You can move N:> "; } else { int i = 0; //right if(gridArray[playerRow][playerCol+1] != '#') { moveArray[i] = 'W'; i++; } //down if(gridArray[playerRow+1][playerCol] != '#') { moveArray[i] = 'S'; i++; } //left if(gridArray[playerRow][playerCol-1] != '#') { moveArray[i] = 'E'; i++; } //up if(gridArray[playerRow-1][playerCol] != '#') { moveArray[i] = 'N'; i++; } string output = "You can move "; for(int x=i-1; x>=0; x--) { output += moveArray[x]; if(x!=0) output += ", "; } output += ":> "; cout << output; } thread first(getInput); clock_t start_time = clock(); clock_t timer; while (pInput == ' ') { if(pInput != ' ') break; timer = clock() - start_time; if(timer > 2700000) { start_time = clock(); string output = "\nYou're taking sooOOoOOo long...\n"; cout << output; } } first.join(); first.~thread(); playerInput = pInput; pInput = ' '; } void update() { if(tolower(playerInput) == 'q') { consoleText = "You have quit! Thanks for playing :)\n"; gameEnd = 1; return; } bool check = 0; for(int i=0; i<4; i++) { //cout << moveArray[i] << ", " << playerInput << ", " << check << endl; if(tolower(moveArray[i]) == tolower(playerInput)) { consoleText = ""; check = 1; } } if(check == 0) { consoleText = "That's an invalid move.\n"; playerStatus = "wrongmove"; return; } switch(tolower(playerInput)) { case 'n': playerRow--; break; case 's': playerRow++; break; case 'e': playerCol--; break; case 'w': playerCol++; break; } if((playerRow == 1)&(playerCol == 1)) { playerStatus = "won"; consoleText = "Wow - you've discovered a large chest filled with GOLD coins !\nYOU WIN!\nThanks for playing. There probably won't be a next time.\n"; gameEnd = 1; } if( ((playerRow == 1)&(playerCol == 3)) | ((playerRow == 1)&(playerCol == 5)) | ((playerRow == 3)&(playerCol == 6))) { playerStatus = "lost"; consoleText = "Arrrrgh... you've fallen down a pit.\nYOU HAVE DIED!\nThanks for playing. Maybe next time.\n"; gameEnd = 1; } } void render() { if((playerStatus == "wrongmove") | (gameEnd == 1)) { playerStatus = ""; } else drawGrid(); cout << consoleText; } int main (int argc, char *argv[]) { cout << "Welcome to GridWorld: Quantised Excitement. Fate is waiting for You!\nWhat's your name: "; string playerName; cin >> playerName; cout << "Hi there, " << playerName << endl; cout << "Valid commands: N, S, E and W for direction. Q to quit the game.\nThe X represents your position.\n\n"; drawGrid(); while (!gameEnd) { input(); update(); render(); } return 0; }
b4430867ccf85a288abef8bcf2d6d9997544f979
bacd60fa61d01da77dbef1f2c8a0539132c98b46
/Week2/Multisets/first_unique_character_in_a_string.cpp
dbdb1dba43ec66a490f53012661cb08697db1905
[]
no_license
JohanF26/WBTraining
43e05b1e17ba5e399c8b2ec989ead2ffdcbc50ab
585f035707a8abf8552b0a57c11905f3e97cd087
refs/heads/master
2020-06-08T20:10:07.389459
2019-08-05T04:38:21
2019-08-05T04:38:21
193,298,845
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
first_unique_character_in_a_string.cpp
class Solution { public: int firstUniqChar(string s) { if(s.size() == 0) return -1; for(int i = 0; i < s.size(); i++){ if(s.find(s[i], s.find(s[i])+1) == string::npos){ return i; } } return -1; } };
093e686a84b5b8775b1cce1a538171022dac3758
fdc914341f1653e2a2becfc44d3fd09c188a5910
/Framework/include/containers/cont_bst.h
72a6e237bb72f2dbdca5643c505949d9ac882afe
[ "MIT" ]
permissive
roncato/realtime
9334d9636a330058fc906a5341265523d742d4d0
b0faeca49c28be9b5b68f16572d67188db926235
refs/heads/master
2021-01-24T16:14:28.831458
2020-06-06T01:42:27
2020-06-06T01:47:36
95,992,458
0
0
MIT
2020-06-06T01:47:38
2017-07-01T23:26:06
C++
UTF-8
C++
false
false
10,166
h
cont_bst.h
/* * Bst.h * * Created: 7/8/2017 2:35:32 PM * Author: roncato */ #ifndef BST_H_ #define BST_H_ #include <stdlib.h> #include "containers.h" #include "containers/cont_linkedlist.h" #include "containers/cont_stack.h" namespace { template <class K, class V> class TraversalNode { public: TraversalNode(containers::BinaryTreeNode<K, V>* node) : node{node} {} containers::BinaryTreeNode<K, V>* node; bool visited_left{}; bool visited_right{}; }; } namespace containers { template <class K, class V> class Bst { public: ~Bst() { Clear(); } bool Add(const K& key, const V& value); bool Get(const K& key, Entry<K, V>& entry); bool Remove(const K& key); bool Contains(const K& key); bool Ceiling(const K& key, Entry<K, V>& entry); bool Floor(const K& key, Entry<K, V>& entry); void Clear(); bool IsEmpty() { return size_ == 0; } bool Min(Entry<K, V>& entry); bool Max(Entry<K, V>& entry); bool RemoveMin(Entry<K, V>& entry); bool RemoveMax(Entry<K, V>& entry); bool Traverse(LinkedList<Entry<K, V>>& entries); bool TraverseRecursive(containers::LinkedList<containers::Entry<K, V>>& entries); private: uint16_t size_{}; BinaryTreeNode<K, V>* root_{nullptr}; BinaryTreeNode<K, V>* NewNode(const K& key, const V& value); BinaryTreeNode<K, V>* RemoveMin(BinaryTreeNode<K, V>* root); bool Min(containers::BinaryTreeNode<K, V>* root, containers::BinaryTreeNode<K, V>** min); bool Traverse(LinkedList<BinaryTreeNode<K, V>*>& nodes); void TraverseRecursive(containers::BinaryTreeNode<K, V>* root, LinkedList<BinaryTreeNode<K, V>*>& nodes); bool Floor(BinaryTreeNode<K, V>* root, const K& key, Entry<K, V>& entry); bool Ceiling(BinaryTreeNode<K, V>* root, const K& key, Entry<K, V>& entry); }; } // namespace containers template <class K, class V> containers::BinaryTreeNode<K, V>* containers::Bst<K, V>::NewNode(const K& key, const V& value) { auto const node = reinterpret_cast<containers::BinaryTreeNode<K, V>*>(malloc(sizeof(containers::BinaryTreeNode<K, V>))); if (node) { node->key = key; node->value = value; ++size_; } return node; } template <class K, class V> bool containers::Bst<K, V>::Add(const K& key, const V& value) { if (!root_) { root_ = NewNode(key, value); return root_; } else { auto root = root_; auto node = root_; while (1) { if (!node) { node = NewNode(key, value); if (key < root->key) { root->left = node; } else { root->right = node; } return node; } if (key < node->key) { root = node; node = node->left; } else if (key > node->key) { root = node; node = node->right; } else if (key == node->key) { node->value = value; return node; } } } } template <class K, class V> bool containers::Bst<K, V>::Get(const K& key, containers::Entry<K, V>& entry) { auto node = root_; while (1) { if (!node) { return false; } if (key < node->key) { node = node->left; } else if (key > node->key) { node = node->right; } else if (key == node->key) { entry = Entry<K, V>{node->key, node->value}; return true; } } } template <class K, class V> bool containers::Bst<K, V>::Contains(const K& key) { auto node = root_; while (1) { if (!node) { return false; } if (key < node->key) { node = node->left; } else if (key > node->key) { node = node->right; } else if (key == node->key) { return true; } } } template <class K, class V> void containers::Bst<K, V>::Clear() { containers::LinkedList<containers::BinaryTreeNode<K, V>*> list; if (Traverse(list)) { containers::LinkedListIterator<BinaryTreeNode<K, V>*> iterator(&list); while (iterator.HasNext()) { free(iterator.Current()); iterator.Advance(); } size_ = 0; root_ = nullptr; } } template <class K, class V> bool containers::Bst<K, V>::Min(containers::Entry<K, V>& entry) { if (size_ > 0) { containers::BinaryTreeNode<K, V>* node; if (Min(root_, &node)) { entry = containers::Entry<K, V>{node->key, node->value}; return true; } } return false; } template <class K, class V> bool containers::Bst<K, V>::Min(containers::BinaryTreeNode<K, V>* root, containers::BinaryTreeNode<K, V>** min) { if (size_ == 0) { return false; } auto node = root; while (node->left) { node = node->left; } *min = node; return true; } template <class K, class V> bool containers::Bst<K, V>::Max(Entry<K, V>& entry) { if (size_ == 0) { return false; } auto node = root_; while (node->right) { node = node->right; } entry = containers::Entry<K, V>{node->key, node->value}; return true; } template <class K, class V> bool containers::Bst<K, V>::RemoveMin(containers::Entry<K, V>& entry) { if (size_ == 0) { return false; } auto root = root_; auto node = root_; if (!root->left) { root_ = root->right; } else { while (node->left) { root = node; node = node->left; } root->left = node->right; } entry = Entry<K, V> {node->key, node->value}; free(node); --size_; return true; } template <class K, class V> bool containers::Bst<K, V>::RemoveMax(containers::Entry<K, V>& entry) { if (size_ == 0) { return false; } auto root = root_; auto node = root_; if (!root->right) { root_ = root->left; } else { while (node->right) { root = node; node = node->right; } root->right = node->left; } entry = Entry<K, V> {node->key, node->value}; free(node); --size_; return true; } template <class K, class V> containers::BinaryTreeNode<K, V>* containers::Bst<K, V>::RemoveMin(containers::BinaryTreeNode<K, V>* root) { if (!root->left) { return root->right; } else { containers::BinaryTreeNode<K, V>* h = root; while (root->left->left) { root = root->left; } root->left = root->left->right; return h; } } template <class K, class V> bool containers::Bst<K, V>::Remove(const K& key) { if (size_ == 0) { return false; } auto root = root_; auto node = root_; while (1) { if (!node) { return false; } if (key < node->key) { root = node; node = node->left; } else if (key > node->key) { root = node; node = node->right; } else if (key == node->key) { if (node->right == nullptr) { if (root->right == node) { root->right = node->left; } else if (root->left == node) { root->left = node->left; } else { // root root_ = node->left; } } else if (node->left == nullptr) { if (root->right == node) { root->right = node->right; } else if (root->left == node) { root->left = node->right; } else { root_ = node->right; } } else { containers::BinaryTreeNode<K, V>* t = node; if (Min(t->right, &node)) { node->right = RemoveMin(t->right); node->left = t->left; if (root->right == t) { root->right = node; } else if (root->left == t) { root->left = node; } else { root_ = node; } node = t; } else { return false; } } free(node); --size_; return true; } } } template <class K, class V> void containers::Bst<K, V>::TraverseRecursive(containers::BinaryTreeNode<K, V>* root, LinkedList<BinaryTreeNode<K, V>*>& nodes) { if (root->left) { TraverseRecursive(root->left, nodes); } nodes.Add(root); if (root->right) { TraverseRecursive(root->right, nodes); } } template <class K, class V> bool containers::Bst<K, V>::TraverseRecursive(containers::LinkedList<containers::Entry<K, V>>& entries) { if (size_ > 0) { containers::LinkedList<containers::BinaryTreeNode<K, V>*> list; TraverseRecursive(root_, list); containers::BinaryTreeNode<K, V>* node; while (!list.IsEmpty() && list.Dequeue(node)) { entries.Add(containers::Entry<K, V>{node->key, node->value}); } return entries.Size() == size_; } return false; } template <class K, class V> bool containers::Bst<K, V>::Traverse(containers::LinkedList<containers::BinaryTreeNode<K, V>*>& nodes) { if (!root_) { return false; } TraversalNode<K, V> current(root_); containers::Stack<TraversalNode<K, V>> stack; stack.Push(current); while (!stack.IsEmpty()) { if (stack.Pop(current)) { if (!current.visited_left && current.node->left) { current.visited_left = true; stack.Push(current); stack.Push(TraversalNode<K, V>(current.node->left)); continue; } if (!current.visited_right) { nodes.Add(current.node); if (current.node->right) { current.visited_right = true; stack.Push(current); stack.Push(TraversalNode<K, V>(current.node->right)); continue; } } } } return nodes.Size() == size_; } template <class K, class V> bool containers::Bst<K, V>::Traverse(containers::LinkedList<containers::Entry<K, V>>& entries) { containers::LinkedList<containers::BinaryTreeNode<K, V>*> list; if (Traverse(list)) { containers::BinaryTreeNode<K, V>* node; while (!list.IsEmpty() && list.Dequeue(node)) { entries.Add(containers::Entry<K, V>{node->key, node->value}); } return entries.Size() == size_; } return false; } template <class K, class V> bool containers::Bst<K, V>::Floor(const K& key, Entry<K, V>& entry) { return Floor(root_, key, entry); } template <class K, class V> bool containers::Bst<K, V>::Floor(containers::BinaryTreeNode<K, V>* root, const K& key, Entry<K, V>& entry) { while (root) { if (key < root->key) { root = root->left; } else if (key > root->key) { if (!Floor(root->right, key, entry)) { entry = Entry<K, V>{root->key, root->value}; } return true; } else { entry = Entry<K, V>{root->key, root->value}; return true; } } return false; } template <class K, class V> bool containers::Bst<K, V>::Ceiling(const K& key, Entry<K, V>& entry) { return Ceiling(root_, key, entry); } template <class K, class V> bool containers::Bst<K, V>::Ceiling(containers::BinaryTreeNode<K, V>* root, const K& key, Entry<K, V>& entry) { while (root) { if (key > root->key) { root = root->right; } else if (key < root->key) { if (!Ceiling(root->left, key, entry)) { entry = Entry<K, V>{root->key, root->value}; } return true; } else { entry = Entry<K, V>{root->key, root->value}; return true; } } return false; } #endif /* BST_H_ */
4b096c0f50fde8a802331a1c81f5926ffc357bef
4ba5dc1c000f184026c3f354e39aaaacfa0258ef
/list-stack-queuePointer/queue_p.cpp
d86dca3d77c0efdfdb483fbc990c94b9360f4956
[]
no_license
red1k/data-structure
c3cfa2528f8483b57a462f3c40e25808fafc510d
dd8ce7f2238a70dac531e9a69cebd8fa0f558aec
refs/heads/master
2020-03-26T23:15:24.302828
2018-12-23T10:32:22
2018-12-23T10:32:22
145,524,371
0
1
null
null
null
null
UTF-8
C++
false
false
3,358
cpp
queue_p.cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; struct Node { int data; struct Node *next; }; struct Queue { struct Node *head, *tail; int length; }; int error = 0; const char error_msg[][50] = { "", "Queue duuren!", "Queue xooson!" }; void init(struct Queue *p_qq, int n) { p_qq->head = p_qq->tail = NULL; p_qq->length = 0; } /* p-ийн зааж буй Queue хоосон бол 1 үгүй бол 0-ийг буцаана */ int empty(struct Queue *p_qq) { if (p_qq->head == NULL) return 1; return 0; } /* p-ийн зааж буй Queue-д x утгыг хийнэ */ void push_back(struct Queue *p_qq, int x) { struct Node *new_node = new Node(); new_node->data = x; if (p_qq->head == NULL) { new_node->next = NULL; p_qq->head = p_qq->tail = new_node; } else { new_node->next = NULL; p_qq->tail->next = new_node; p_qq->tail = new_node; } p_qq->length++; } /* p-ийн зааж буй Queue-с гарган буцаана */ int pop_front(struct Queue *p_qq) { struct Node *temp; int result; temp = p_qq->head; result = temp->data; p_qq->head = temp->next; p_qq->length--; delete temp; return result; } /* p-ийн зааж буй Queue-н утгуудыг хэвлэнэ */ void print(struct Queue *p_qq) { struct Node *temp; temp = p_qq->head; while(temp != NULL) { cout << temp->data << endl; temp = temp->next; } free(temp); } /* p-ийн зааж буй Queue-н хамгийн эхний элементийн утгыг буцаана. Гаргах үйлдэл хийхгүй. */ int front(struct Queue *p_qq) { return p_qq->head->data; } /* p-ийн зааж буй Queue-н хамгийн сүүлийн элементийн утгыг буцаана. Queue-д өөрчлөлт оруулахгүй. */ int back(struct Queue *p_qq) { return p_qq->tail->data; } /* p-ийн зааж буй Queue-д хэдэн элемент байгааг буцаана. Queue-д өөрчлөлт оруулахгүй. */ int size(struct Queue *p_qq) { return p_qq->length; } void release(struct Queue *p_qq) { while (empty(p_qq) == 0) pop_front(p_qq); } int main() { struct Queue st; init(&st, 10); int t, x; while (1) { printf("1: push_back, 2: pop_front, 3: print, 4: empty, 5: front," "6: back, 7: size, 8: exit\n"); scanf("%d", &t); error = 0; switch (t) { case 1: cout << "Queue-d oruulah utga: " << endl; scanf("%d", &x); push_back(&st, x); if (error) printf("Aldaa: %s\n", error_msg[error]); else printf("%d utga orloo\n", x); break; case 2: x = pop_front(&st); if (error) printf("Aldaa: %s\n", error_msg[error]); else printf("%d utga garlaa\n", x); break; case 3: print(&st); break; case 4: if (empty(&st)) printf("Queue xooson\n"); else printf("Queue xooson bish\n"); break; case 5: x = front(&st); if (error) printf("Aldaa: %s\n", error_msg[error]); else printf("%d utga xamgiin exend bna\n", x); break; case 6: x = back(&st); if (error) printf("Aldaa: %s\n", error_msg[error]); else printf("%d utga xamgiin suuld bna\n", x); break; case 7: x = size(&st); printf("Queue-d %d shirxeg element bna\n", x); break; default: exit(0); } } release(&st); return 0; }
0290d23eccb0632100e4797e1455256d0b2c42c7
4348c1e32daa4d88910c2cf66fc8ae098dc9e3bc
/学生成绩管理系统/学生成绩管理系统.cpp
37685b612463154bdafc433502829afe73b84e48
[]
no_license
wz20/c-
7b4d10e3adb709ce8a158f830e408fdb47833c46
7f6a57136b37e34d55b9aa5976b51feb47d4ad98
refs/heads/main
2023-03-19T02:11:29.885833
2021-03-08T00:34:15
2021-03-08T00:34:15
345,486,585
1
0
null
null
null
null
GB18030
C++
false
false
7,429
cpp
学生成绩管理系统.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include<windows.h> #define MAX 100 #define NAME_LEN 10 typedef struct { char name[NAME_LEN]; unsigned int score[3]; unsigned int sum; unsigned int avg; } Stu_i; Stu_i stu[MAX]; int num; //函数声明 Stu_i input_stu(void); // 通过提示引导用户正确地输入一条学生记录,并返回这条记录 void output_stu(int i); // 根据数组索引打印出对应的学生信息 int find_stu(void); // 通过提示引导用户查找记录,如果找到则显示查找到的记录,并返回数组索引,否则返回-1 void read_stu(const char *filename); // 根据文件名读入文件中的学生数据 void write_stu(const char *filename); // 将学生数据写入到指定的文件中 int confirm(const char *words); // 请求用户确认,输入y或Y返回1,输入n或N返回0,其他情况提示用户重新输入 void safe_flush(FILE *fp); // safe_flush(stdin)清理多余的输入,防止影响下次获取输入 void safe_flush(FILE *fp){ int ch; while ( ch = fgetc(fp), ch != EOF && ch != '\n'); } int confirm(const char *words) { char choice; puts(words); for (;;) { choice = getchar(); safe_flush(stdin); switch (choice) { default: puts("输入非法,重新输入!"); continue; case 'Y': case 'y': puts("已确认!"); return 1; case 'N': case 'n': puts("已取消!"); return 0; } } } Stu_i input_stu(void) { Stu_i ret; puts("依次输入姓名、语文、数学、外语成绩,空格分隔,成绩要求是整数:"); while ( 4 != scanf("%s%d%d%d", ret.name, &ret.score[0], &ret.score[1], &ret.score[2])) { safe_flush(stdin); puts("输入有误,请重新输入!"); } safe_flush(stdin); ret.sum = ret.score[0] + ret.score[1] + ret.score[2]; ret.avg = ret.sum/3; return ret; } void output_stu(int i) { if (i < 0 || i > MAX) return; printf("%s\t语:%d\t数:%d\t外:%d\t总分:%d\t平均成绩:%d\n", stu[i].name, stu[i].score[0], stu[i].score[1], stu[i].score[2], stu[i].sum, stu[i].avg ); } int find_stu(void) { char name[NAME_LEN]; int i; printf("输入姓名(限%d个字符):", NAME_LEN); scanf("%s", name); safe_flush(stdin); for (i = 0; i < num; i++) { if (0 == strcmp(stu[i].name, name)) { output_stu(i); return i; } } puts("没有找到记录!"); return -1; } void read_stu(const char *filename) { FILE *fp = fopen(filename, "rt"); if (NULL != fp) { fread(&num, sizeof(int), 1, fp); fread(stu, sizeof(Stu_i), num, fp); } fclose(fp); } void write_stu(const char* filename) { FILE *fp = fopen(filename, "wt"); if (NULL != fp) { fwrite(&num, sizeof(int), 1, fp); fwrite(stu, sizeof(Stu_i), num, fp); fclose(fp); puts("保存成功!"); } else puts("打开文件失败!"); } int main(void) { //设置窗口大小 system("mode con:cols=100 lines=35"); //设置窗口字体的颜色 system("color C"); const char *filename = "stu_info.txt"; read_stu(filename); // 导入数据 printf("************************欢迎使用学生成绩管理系统**************************\n" " \n" " \n" "****************-当前已有%d条记录,本程序限制%d条记录**********************\n" "-------------------------205宿舍学生管理系统------------------------------\n", num, MAX); for (;;) { char choice; int i, j; printf( " 菜单:\n" " ** 1.查找学生成绩 **\n" " ** 2.录入学生成绩 **\n" " ** 3.删除学生成绩 **\n" " ** 4.修改学生成绩 **\n" " ** 5.排序成绩(平均分) **\n" " ** 6.显示学生成绩 **\n" " ** 7.保 存 **\n" " ** 0.退 出 **\n" " 输入序号:"); choice = getchar(); safe_flush(stdin); switch (choice) { case '1': // 查找 find_stu(); break; case '2': // 录入 if (num < MAX) { stu[num] = input_stu(); output_stu(num); num++; puts("录入成功!"); } else puts("记录已满,无法录入!"); break; case '3': // 删除 i = find_stu(); if (-1 != i) { if (confirm("确认删除?Y OR N")) { while (i++ != num) { stu[i-1] = stu[i]; } num--; puts("删除成功!"); } } break; case '4': // 修改 i = find_stu(); if (-1 != i) { stu[i] = input_stu(); output_stu(i); puts("修改成功!"); } break; case '5': // 按照平均分排序 for (i = 0; i < num-1; i++) // 冒泡排序中已经排好的 for (j=0; j < num-1-i; j++) // 遍历没排好的 if ( stu[j].avg < stu[j+1].avg ) { Stu_i t = stu[j]; stu[j] = stu[j+1]; stu[j+1] = t; } puts("排序成功!"); /* fall through */ // 完成排序后自动显示 case '6': // 显示 for (i = 0; i < num; i++) { printf("%4d:\t", i+1); output_stu(i); } break; case '7': // 保存 write_stu(filename); break; case '0': // 退出 if (confirm("退出前保存?(Y/N)")) { write_stu(filename); } exit(0); default: puts("没有该序号!请重新输入"); break; } } // END for return 0; }
6f3f8d776653e0d3997a6063cb63f08494ddad3a
90ea0699804da6d5b17310ebc2023a5e034e9dcb
/qmhd/include/qmhdbody.h
ac655550d293d7704164d768f324bcddb868061f
[ "MIT" ]
permissive
wwhai/stm32-remote-update
e4fe34e7872c801699797579023d7e6db87f6e86
0e15a2d6fb1b9d61947bfc4238a786c60077eea2
refs/heads/master
2023-08-01T13:30:33.273297
2021-09-27T01:43:01
2021-09-27T01:43:01
410,707,699
1
0
null
null
null
null
UTF-8
C++
false
false
942
h
qmhdbody.h
#ifndef QMHDBODY_H #define QMHDBODY_H #include <QHash> #include <QString> #include "qmhdglobal.h" class QMHDBodyFile; class QMHDBodyPrivate; typedef QHash<QString,QMHDBodyFile*> QMHDBodyFiles; class QMHDBody { friend class QMHDRequestPrivate; public: QMHDBody(); ~QMHDBody(); private: QMHDBody(const QMHDBody& other); QMHDBody& operator=(const QMHDBody& other); public: QString param(const QString& name) const; bool paramExists(const QString& name) const; const QStringHash& params() const; QMHDBodyFile* file(const QString& name) const; bool fileExists(const QString& name) const; const QMHDBodyFiles& files() const; private: void setParam(const QString& name, const QString& value); void setFile(const QString& name, QMHDBodyFile* file); protected: QMHDBodyPrivate* const d; }; #endif // QMHDBODY_H
0bb7e012ccace3733b50703a7b258764ff037bf3
04899c4620f640922cfddc6f12c3393043c4ff60
/AnKi/Renderer/GenericCompute.cpp
0e16e2c141d2a60333451e5ffe50c55bee9c4834
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
galek/anki-3d-engine-1
51c3d56b8aeaf6773216749d95e0326aa75978de
48f9806364d35a12a53508b248e26c597188b542
refs/heads/master
2021-11-25T06:47:32.120582
2021-10-24T19:33:05
2021-10-24T19:33:21
59,970,766
0
0
null
2016-05-30T00:57:00
2016-05-30T00:57:00
null
UTF-8
C++
false
false
1,841
cpp
GenericCompute.cpp
// Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors. // All rights reserved. // Code licensed under the BSD License. // http://www.anki3d.org/LICENSE #include <AnKi/Renderer/GenericCompute.h> #include <AnKi/Renderer/Renderer.h> #include <AnKi/Renderer/DepthDownscale.h> #include <AnKi/Renderer/RenderQueue.h> namespace anki { GenericCompute::~GenericCompute() { } void GenericCompute::populateRenderGraph(RenderingContext& ctx) { if(ctx.m_renderQueue->m_genericGpuComputeJobs.getSize() == 0) { return; } ComputeRenderPassDescription& pass = ctx.m_renderGraphDescr.newComputeRenderPass("Generic compute"); pass.setWork([this, &ctx](RenderPassWorkContext& rgraphCtx) { run(ctx, rgraphCtx); }); pass.newDependency({m_r->getDepthDownscale().getHiZRt(), TextureUsageBit::SAMPLED_COMPUTE}); } void GenericCompute::run(const RenderingContext& ctx, RenderPassWorkContext& rgraphCtx) { ANKI_ASSERT(ctx.m_renderQueue->m_genericGpuComputeJobs.getSize() > 0); GenericGpuComputeJobQueueElementContext elementCtx; elementCtx.m_commandBuffer = rgraphCtx.m_commandBuffer; elementCtx.m_stagingGpuAllocator = &m_r->getStagingGpuMemoryManager(); elementCtx.m_viewMatrix = ctx.m_matrices.m_view; elementCtx.m_viewProjectionMatrix = ctx.m_matrices.m_viewProjection; elementCtx.m_projectionMatrix = ctx.m_matrices.m_projection; elementCtx.m_previousViewProjectionMatrix = ctx.m_prevMatrices.m_viewProjection; elementCtx.m_cameraTransform = ctx.m_matrices.m_cameraTransform; // Bind some state rgraphCtx.bindTexture(0, 0, m_r->getDepthDownscale().getHiZRt(), TextureSubresourceInfo()); for(const GenericGpuComputeJobQueueElement& element : ctx.m_renderQueue->m_genericGpuComputeJobs) { ANKI_ASSERT(element.m_callback); element.m_callback(elementCtx, element.m_userData); } } } // end namespace anki
86c1642db47fbe5b14ae89da116c1ccab6aea6d0
7512fb7d215fc024a4cc4e5df0d258adbfaad3cf
/Thermocheck/include/Core/Application.h
04189130fd2a7583a1bd625e55b14db643644d54
[]
no_license
DanielPresas/ThermocheckApp
80b4747439c51828477dc4bae84dfeb4c2a4022b
071c3f97e054edb35c3a89e1f127537c13c051f9
refs/heads/master
2022-12-09T11:54:32.547462
2020-09-08T22:48:23
2020-09-08T22:48:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
Application.h
#ifndef APPLICATION_H #define APPLICATION_H #include "CVInterface.h" #include "Core/Window.h" #include <queue> class Application { enum WorkType { CV_UPDATE = 0, IMGUI_RENDER = 1 }; using FutureVoids = std::vector<std::future<void>>; using WorkQueue = std::queue<WorkType>; using Mutex = std::mutex; public: Application(); Application(std::string&& title, uint32_t width, uint32_t height); virtual ~Application(); Application(const Application&) = delete; Application& operator=(const Application&) = delete; void run(); static void shutdown() { _instance->_isRunning = false; } static Window* getWindow() { return _instance->_window; } static CVState* getCVState() { return _instance->_cvState; } static void pushCvUpdate(CVState* state); static void pushImGuiRender(); private: bool _isRunning = true; Window* _window; CVState* _cvState; WorkQueue _commandQueue; FutureVoids _futures; Mutex _mutex; static Application* _instance; }; #endif
75ca82f22b9dbaedacdf610c82b850a41d32b021
b483dc71f3d07ca7c999f04e626d21a461b5ea83
/image_extractor.h
dc98914d4b79413fb2bb141cd25eb220ff4eae44
[ "MIT" ]
permissive
StevenHickson/VideoObjectProposals
7e863e0054b35a7d875fb184a301eb4d4a4b8ab7
a303fa7fe6c7b61707675c531efbd255397d4c0d
refs/heads/master
2021-09-13T15:35:17.650664
2018-05-01T16:32:43
2018-05-01T16:32:43
119,440,708
1
0
null
null
null
null
UTF-8
C++
false
false
3,934
h
image_extractor.h
#ifndef IMAGE_EXTRACTOR_H_ #define IMAGE_EXTRACTOR_H_ #include <map> #include <vector> #include "opencv2/core/core.hpp" namespace unsup_clustering { class ObjectInfo { public: ObjectInfo() {} ObjectInfo(int xMin, int yMin, int xMax, int yMax, int _label, int _instance) : x_min_(xMin), y_min_(yMin), x_max_(xMax), y_max_(yMax), label_(_label), instance_(_instance) {} int x_min_, y_min_, x_max_, y_max_; int label_; int instance_; }; class Extractor { public: Extractor() {} // Here we extract instances from the image and label them appropriately. The // output instanceMap is a map of ObjectInfo corresponding to each patches' // bounding box, instance id, and label. void ExtractInstanceData(const cv::Mat& image, const cv::Mat& labels, const cv::Mat& instances, const bool fully_unsup, std::map<int, ObjectInfo>* instanceMap); // This function creates background sample patches that don't overlap with the // positive sample patches. void CreateNegativePatches(const int input_width, const int input_height, const int patch_min_size, const int patch_max_size, const int numPatches, const std::vector<int>& positiveLabels, const std::map<int, ObjectInfo>& inputMap, std::map<int, ObjectInfo>* outputMap); // Here we modify both our negative and positive sample patches, correcting // for aspect ratio and formatting them properly. void CreateDataFromInstances(const int input_width, const int input_height, const int output_width, const int output_height, const int min_size, const float max_aspect_ratio, const bool keep_aspect_ratio, const std::map<int, ObjectInfo>& instanceMap, std::vector<ObjectInfo>* croppedList); // Here we equalize the data instances so there are an equal # per class. void EqualizeDataInstances(const int input_width, const int input_height, const int jitter, const std::vector<ObjectInfo>& instanceMap, std::vector<ObjectInfo>* croppedList); // The following FromVector functions are for debugging and using with Clif. void ExtractInstanceDataFromVector(const std::vector<int>& image, const std::vector<int>& labels, const std::vector<int>& instances, const int width, const int height, const int nChannels, const bool fully_unsup, std::vector<ObjectInfo>* instanceList); void CreateNegativePatchesFromVector(const int input_width, const int input_height, const int patch_min_size, const int patch_max_size, const int numPatches, const std::vector<int>& positiveLabels, const std::vector<ObjectInfo>& inputMap, std::vector<ObjectInfo>* outputMap); void CreateDataFromInstancesFromVector( const int input_width, const int input_height, const int output_width, const int output_height, const int min_size, const float max_aspect_ratio, const std::vector<ObjectInfo>& instanceList, std::vector<ObjectInfo>* croppedList); }; } // namespace unsup_clustering #endif // IMAGE_EXTRACTOR_H_
96bb27ff317debf609ea320e17246664047f3a2f
a27861c45699b53f108554a4d4528c281d990446
/ZeldaII_Remake/Game.h
e87b5adba42b86584be32fd149c08546bad9c1f0
[]
no_license
Aidisius/2D-Game-Engine-D3D11-
13b0dd5e18dca44a3d15f55dfb7ef502b7ec6df6
619e907094b26642e0ad6ef9ec1f37d54891c72c
refs/heads/master
2022-10-07T02:40:36.042665
2020-06-06T13:39:49
2020-06-06T13:39:49
269,774,880
0
0
null
null
null
null
UTF-8
C++
false
false
315
h
Game.h
#pragma once #include "Graphics.h" class Game { public: // Constructor and destructor Game(HWND hWnd); Game(const Game&) = delete; Game operator=(const Game) = delete; private: // Functions void GameLogicUpdate(); void GameGraphicsUpdate(); public: void Cycle(); private: // Variables Graphics gfx; };
77119ab9e8c0f3d3c655a8d2af5a979b58c8eefd
019b68af2f25d3953195de7bd7a5eefd58bbbdd2
/04-3 Abstract Factory Pattern/FactoryPattern_01/Pizza.h
9e25c750ebdd1bdf54a986de740b4d8de3425142
[]
no_license
jaruary/design-patterns-for-cpp
65c471998a085b04f140589f5ec52e3d379298d3
8cb34ddd1deda23dc7fcc2cdc46157318239b37a
refs/heads/master
2023-04-02T05:23:26.688507
2014-09-24T17:56:28
2014-09-24T17:56:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,725
h
Pizza.h
#pragma once #include <iostream> #include <vector> #include <iterator> #include <string> #include <iostream> #include "PizzaIngredientFactory.h" #include "Ingredient.h" // Abstract Class class Pizza { protected: std::string pizzaType; std::string name; private: Ingredient* dough; Ingredient* sauce; Ingredient* cheese; Ingredient* pepperoni; Ingredient* clams; std::vector<Ingredient*> veggies; public: Pizza() { } // must override this in the subclass virtual ~Pizza() { } virtual void setupIngredients(PizzaIngredientFactory *arg_ingredientFactory) { this->dough = arg_ingredientFactory->createDough(); this->sauce = arg_ingredientFactory->createSauce(); this->cheese = arg_ingredientFactory->createCheese(); this->veggies = arg_ingredientFactory->createVeggies(); } virtual void setName() { } virtual std::string getName() { return this->name; } virtual std::string getDough() { return this->dough->toString(); } virtual std::string getSauce() { return this->sauce->toString(); } virtual std::string getCheese() { return this->cheese->toString(); } virtual std::vector<Ingredient*> getVeggies() { return this->veggies; } virtual void prepare() { const std::vector<Ingredient*> vegToppings = getVeggies(); std::cout << "Preparing " << this->getName() << " with " << this->getDough() << " and " << this->getSauce() << " covered in " << this->getCheese() << ",\ntopped with"; if (vegToppings.empty() != true && this->pizzaType != "Cheese") { for (std::vector<Ingredient*>::const_iterator it = vegToppings.begin(); it != vegToppings.end(); ++it) { // Cast 'Ingredient*' to the dereferenced iterator, so we can call the 'toString()' method std::cout << " " << ((Ingredient*)*it)->toString(); // Get the next iterator so long as it's not the last element or the second last element (ie, -1 from the end) if (std::next(it) != vegToppings.end() && std::next(it) != vegToppings.end() - 1) { std::cout << ", "; } // If it is the second last element, print out ", and" after having printed the second last element if (std::next(it) == vegToppings.end() - 1) { std::cout << ", and "; } } } else { std::cout << " no toppings"; } std::cout << std::endl; } virtual void bake() { std::cout << "Baking " << this->getName() << std::endl; } virtual void cut() { std::cout << "Cutting " << this->getName() << " into diagonal slices" << std::endl; } virtual void box() { std::cout << "Boxing " << this->getName() << std::endl; } };
d63e4d2c111e839b8c7a724f77a1dddbf212a086
3d275f6ab7a2f1af8e147cb3e23f12049b47b664
/atis/third_party/roo/update_exposure.hpp
f8c54e6be9f3dbb7ab0134277ba1ec80489641f1
[]
no_license
neuromorphicsystems/deepblue
a7af9235cfea92407be6edc7dafa2b896921a6dc
101c174bf0c8a6e0fef95a3afe8d4209593ee326
refs/heads/main
2023-06-20T06:37:22.579075
2021-07-20T20:21:22
2021-07-20T20:21:22
337,473,122
0
0
null
null
null
null
UTF-8
C++
false
false
6,403
hpp
update_exposure.hpp
#pragma once #include <limits> namespace tarsier { /// update_exposure implements an auto-exposure algorithm. /// The algorithm also generates a tone-mapped frame. template <typename Time, typename HandleExposureAndFrameDuration, typename HandleTonemappedFrame> class update_exposure { public: update_exposure( float exposure_inertia, float tonemapping_inertia, float maximum_shutter, uint32_t maximum_pixel_value, Time minimum_exposure, Time maximum_exposure, Time initial_exposure, Time minimum_frame_duration, Time maximum_frame_duration, Time initial_frame_duration, HandleExposureAndFrameDuration&& handle_exposure_and_frame_duration, HandleTonemappedFrame&& handle_tonemapped_frame) : _exposure_inertia(exposure_inertia), _tonemapping_inertia(tonemapping_inertia), _maximum_shutter(maximum_shutter), _maximum_pixel_value(maximum_pixel_value), _minimum_exposure(minimum_exposure), _maximum_exposure(maximum_exposure), _minimum_frame_duration(minimum_frame_duration), _maximum_frame_duration(maximum_frame_duration), _exposure(initial_exposure), _frame_duration(initial_frame_duration), _handle_exposure_and_frame_duration( std::forward<HandleExposureAndFrameDuration>(handle_exposure_and_frame_duration)), _handle_tonemapped_frame(std::forward<HandleTonemappedFrame>(handle_tonemapped_frame)), _slope(1.0f / maximum_pixel_value), _intercept(0.0f) { if (_minimum_exposure > _maximum_exposure) { throw std::logic_error("the maximum exposure must be larger than the minimum exposure"); } if (_minimum_frame_duration > _maximum_frame_duration) { throw std::logic_error("the maximum frame duration must be larger than " "the minimum frame duration"); } if (_exposure_inertia < 0 || _exposure_inertia > 1) { throw std::logic_error("the exposure inertia must be in the range ]0, 1]"); } if (_tonemapping_inertia < 0 || _tonemapping_inertia > 1) { throw std::logic_error("the tonemapping inertia must be in the range ]0, 1]"); } if (_maximum_shutter <= 0 || maximum_shutter > 1) { throw std::logic_error("the maximum shutter must be in the range ]0, 1]"); } } update_exposure(const update_exposure&) = default; update_exposure(update_exposure&& other) = default; update_exposure& operator=(const update_exposure&) = default; update_exposure& operator=(update_exposure&& other) = default; virtual ~update_exposure() {} /// operator() handles a sensor frame. template <typename Pixel> void operator()(const std::vector<Pixel>& frame) { std::vector<uint32_t> histogram(_maximum_pixel_value, 0); for (const auto pixel : frame) { ++histogram[pixel]; } Pixel minimum = _maximum_pixel_value + 1; Pixel maximum = _maximum_pixel_value + 1; { uint32_t sum = 0; for (uint32_t index = 0; index < _maximum_pixel_value; ++index) { sum += histogram[index]; if (minimum == _maximum_pixel_value + 1 && sum > frame.size() / 20) { minimum = index; } if (maximum == _maximum_pixel_value + 1 && sum > frame.size() / 20 * 19) { maximum = index; } } } auto exposure = _exposure * (1 + (1 - _exposure_inertia) * (static_cast<float>(_maximum_pixel_value / 2) - (maximum + minimum) / 2) / _maximum_pixel_value); if (exposure < _minimum_exposure) { exposure = static_cast<float>(_minimum_exposure); } else if (exposure > _maximum_exposure) { exposure = static_cast<float>(_maximum_exposure); } auto frame_duration = exposure / _maximum_shutter; if (frame_duration < _minimum_frame_duration) { frame_duration = static_cast<float>(_minimum_frame_duration); } else if (frame_duration > _maximum_frame_duration) { exposure = _maximum_frame_duration * _maximum_shutter; frame_duration = static_cast<float>(_maximum_frame_duration); } _exposure = static_cast<Time>(exposure); _frame_duration = static_cast<Time>(frame_duration); _handle_exposure_and_frame_duration(_exposure, _frame_duration); std::vector<float> tonemapped_frame(frame.size()); if (minimum < maximum) { _slope = _slope * _tonemapping_inertia + 1.0f / (maximum - minimum) * (1 - _tonemapping_inertia); _intercept = _intercept * _tonemapping_inertia + (-_slope * minimum) * (1 - _tonemapping_inertia); ; } std::transform(frame.begin(), frame.end(), tonemapped_frame.begin(), [this, minimum, maximum](Pixel pixel) { if (pixel < minimum) { return 0.0f; } if (pixel > maximum) { return 1.0f; } return _slope * pixel + _intercept; }); _handle_tonemapped_frame(tonemapped_frame); } protected: const float _exposure_inertia; const float _tonemapping_inertia; const float _maximum_shutter; const uint32_t _maximum_pixel_value; const Time _minimum_exposure; const Time _maximum_exposure; const Time _minimum_frame_duration; const Time _maximum_frame_duration; Time _exposure; Time _frame_duration; HandleExposureAndFrameDuration _handle_exposure_and_frame_duration; HandleTonemappedFrame _handle_tonemapped_frame; float _slope; float _intercept; }; }
4a83b53a666c73adf8865e52db25761b6193455a
a35ac8d549761f33d34009da3796bd6c8c744ffc
/Executive/Executive.cpp
ffb5c276040c6acc2e8bf92af41beb70ef9fc0fd
[]
no_license
Shashankmishra3003/Multi-User-Test-Harness
c4977ed3802c3250c6ca1ec84531f37d6cd53460
f3bac93aea7c03ddbab71253f620642301e5f160
refs/heads/master
2020-04-30T20:15:42.398242
2019-03-22T02:57:10
2019-03-22T02:57:10
177,061,140
2
0
null
null
null
null
UTF-8
C++
false
false
8,357
cpp
Executive.cpp
///////////////////////////////////////////////////////////////////////////////// // Executie.cpp : single test class for demostrating the project3 requirements // // ver 1.1 // // // // Application : OOD F18 Project 4 // // Platform : VS17 Community - Windows 8.1 // // Modified : Shashank Mishra, CSE687 - OOD, Fall 2018 // // Author : Ammar Salman, EECS Department, Syracuse University // // 313/788-4694, hoplite.90@hotmail.com // ///////////////////////////////////////////////////////////////////////////// /* * Package description: * ====================== * This is a 'Executive' test driver DLL package. It follows the same * protocol defined in ITest.h package. For DllLoader, it doesn't care * if the TestDriver contains one or many Test Classes as it will attempt * to get the collection of ITest*. * * Required files: * ================= * StringUtilities.h, FileUtilities * ITest.h ** Maintenance History: * -------------------- * ver 1.0 : 05 Dec 2018 * - first release * */ #define IN_DLL #define ARG_SIZE 256 // for the manufactured cmd args #include "ITests.h" #include <iostream> #include<string.h> #include"../Utilities/StringUtilities/StringUtilities.h" #include"../Utilities/FileUtilities/FileUtilities.h" using namespace std; using Path = std::string; using Message = std::string; using Line = size_t; using File = std::string; using Files = std::vector<File>; class DemoRequirements : public ITest { public: DLL_DECL bool test(); DLL_DECL std::string name(); DLL_DECL std::string author(); DLL_DECL void requirement1(); DLL_DECL void requirement2(); DLL_DECL void requirement3a(); DLL_DECL void requirement3b(); DLL_DECL void requirement3c(); DLL_DECL void requirement4(); DLL_DECL void requirement5A(); DLL_DECL void requirement5B(); DLL_DECL void requirement6(); DLL_DECL void requirement7(); DLL_DECL void requirement8(); DLL_DECL void requirement9(); DLL_DECL void requirement10(); // get access to Hosted Resource DLL_DECL void acceptHostedResource(ILog* pRes) { pRes_ = pRes; } private: ILog* pRes_ = nullptr; }; DLL_DECL void DemoRequirements::requirement1() { Utilities::Title("Demonstrating Project #4 Requirements"); Message msg = "Requirement #1 - Demonstrates the use of C++"; Path path ="../Executive"; Utilities::showDirContents(path, msg); } DLL_DECL void DemoRequirements::requirement2() { Message msg = "Requirement #2 - Demonstrates the use of Windows Presentation Foundation for user Display"; Path path ="../ClientGui"; Utilities::showDirContents(path, msg); } DLL_DECL void DemoRequirements::requirement3a() { Message msg = "Requirement #3A - Showing the Line of code which Demonstrates the Assembly of Project 1,2 and 3"; Path path = "../Tester/Tester.cpp"; Utilities::showFileLines(path, 111, 123, msg); } DLL_DECL void DemoRequirements::requirement3b() { Message msg = "Requirement #3B - Showing the Line of code which Demonstrates Client-Server configuration, where Test Harness Accepts Test Requests from the client and Spawns Child Process to execute the Test Request"; Path path = "../TestHarnessCore/TestHarness.cpp"; Utilities::showFileLines(path, 139, 159, msg); } DLL_DECL void DemoRequirements::requirement3c() { Utilities::Title("Requirement #3C - Shows that the Client need not wait for a reply for a TestRequest from the TestHarness before sending additional TestRequests, We can continuesly send test requests from the Client GUI without waiting for response"); Utilities::Title("Result for Every Test Request is Stored in the TestLogClient Directory of the Client"); } DLL_DECL void DemoRequirements::requirement4() { Utilities::Title("The Client GUI interface demontrates that we have the Facility to select test libraries and send the selected test Files for testing"); Utilities::Title("The Test Result Tab shows the result file for every Test Request. Clicking on the file will display the content inside"); } DLL_DECL void DemoRequirements::requirement5A() { Message msg = "Requirement #5A - Showing the Line of code which Demonstrates Message design at Client end "; Path path = "../ClientGui/MainWindow.xaml.cs"; Utilities::showFileLines(path, 256, 265, msg); } DLL_DECL void DemoRequirements::requirement5B() { Message msg = "Requirement #5B - Showing the Line of code which Demonstrates Message design at Test Harness End "; Path path = "../TestHarnessCore/TestHarness.cpp"; Utilities::showFileLines(path, 125, 135, msg); } DLL_DECL void DemoRequirements::requirement6() { Message msg = "Requirement #6 - Showing the Line of code which Demonstrates that message is being sent from client to Test Harness. The File from TestLibraries directory is sent to "; Path path = "../ClientGui/MainWindow.xaml.cs"; Utilities::showFileLines(path, 228, 251, msg); } DLL_DECL void DemoRequirements::requirement7() { Message msg = "Requirement #7 - Demonstrates the line of code which shows that each TestRequest running in its own Process Pool child process"; Utilities::Title("Each Test request is executed Correctly as a sequesnce of Tests"); Path path = "../TestHarnessCore/TestHarness.cpp"; Utilities::showFileLines(path, 153, 172, msg); } DLL_DECL void DemoRequirements::requirement8() { Message msg = "Requirement #8 - Demonstrates the line of code which shows that test results are sent via a result message back to the client"; Path path = "../Tester/Tester.cpp"; Utilities::showFileLines(path, 153, 166, msg); } DLL_DECL void DemoRequirements::requirement9() { Utilities::Title("Requirement #9 - Demonstrates taht two concurrent clients are running"); Utilities::Title("We can see that there are two Client windows and each Client can send test request to the the Test Harness."); Utilities::Title("The test Harness Executes the tests and returns the result cak to client."); Utilities::Title("The test result can be fount at TestLogFromChildProcess, which is the directory at Client end"); } DLL_DECL void DemoRequirements::requirement10() { Message msg = "Requirement #10 - Demonstrates the Automated Test Suite, which shows the lines of code from the DLL which is executed by One of the Child Process Console which shows all the requirements."; Utilities::Title("Each Child process Sends the test result in a Log file back to the Client, this log file is at Directory, /TestLogFromChildProcess"); Utilities::Title("This shows the completion of Execution Cycle,Client sends Test request through UI and child Process sends the result back to the Client"); Path path = "../Executive/Executive.cpp"; Utilities::showFileLines(path, 76, 89, msg); } DLL_DECL bool DemoRequirements::test() { DemoRequirements::requirement1(); DemoRequirements::requirement2(); DemoRequirements::requirement3a(); DemoRequirements::requirement3b(); DemoRequirements::requirement3c(); DemoRequirements::requirement4(); DemoRequirements::requirement5A(); DemoRequirements::requirement5B(); DemoRequirements::requirement6(); DemoRequirements::requirement7(); DemoRequirements::requirement8(); DemoRequirements::requirement9(); DemoRequirements::requirement10(); return true; } DLL_DECL std::string DemoRequirements::name() { return string("Demonstrating project4 Requirements"); } DLL_DECL std::string DemoRequirements::author() { return string("Shashank Mishra"); } ////////////////////////////////////////////////////////////////////////////// // test collection class TestCollection : public ITests { DLL_DECL std::vector<ITest*> tests(); }; DLL_DECL std::vector<ITest*> TestCollection::tests() { std::vector<ITest*> tests_vec; tests_vec.push_back(new DemoRequirements); return tests_vec; } ////////////////////////////////////////////////////////////////////////////// // this section is where each Test Driver DLL completely differs from other // test drivers. Although the same name can be used in all TestDrivers, the // actual instance of TestCollection is different in the way it returns // different collection of ITest*. DLL_DECL ITests* get_ITests() { return new TestCollection; }
50fb261869d958543815ca78ea95bc5900950ba9
dac5254630fefae851da7c843dcab7f6a6af9703
/Linux/Sources/Application/Three_Pane/Preview/C3PanePreview.cp
743effb43a968ff37005a5d9c5007ea4f99cb1e0
[ "Apache-2.0" ]
permissive
gpreviato/Mulberry-Mail
dd4e3618468fff36361bd2aeb0a725593faa0f8d
ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a
refs/heads/master
2021-01-20T03:31:39.515653
2017-09-21T13:09:55
2017-09-21T13:09:55
18,178,314
5
2
null
null
null
null
UTF-8
C++
false
false
7,336
cp
C3PanePreview.cp
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Source for C3PanePreview class #include "C3PanePreview.h" #include "CAddressView.h" #include "CAdminLock.h" #include "CEventPreview.h" #include "CMessageView.h" #include "C3PaneAddress.h" #include "C3PaneEvent.h" #include "C3PaneMessage.h" #include "C3PaneWindow.h" #include <JXStaticText.h> #include <cassert> // Static // Static members // C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S // Default constructor C3PanePreview::C3PanePreview(JXContainer* enclosure, const HSizingOption hSizing, const VSizingOption vSizing, const JCoordinate x, const JCoordinate y, const JCoordinate w, const JCoordinate h) : C3PaneParentPanel(enclosure, hSizing, vSizing, x, y, w, h) { mMessage = NULL; mAddress = NULL; mEvent = NULL; } // Default destructor C3PanePreview::~C3PanePreview() { } // O T H E R M E T H O D S ____________________________________________________________________________ // Do various bits void C3PanePreview::OnCreate() { // Do inherited C3PaneParentPanel::OnCreate(); // begin JXLayout1 mViewPane = new JXWidgetSet(this, JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 300,200); assert( mViewPane != NULL ); // end JXLayout1 mView = mViewPane; // Always need these MakeMessage(); MakeAddress(); MakeEvent(); } void C3PanePreview::ListenTo_Message(long msg, void* param) { // Look for messages switch(msg) { // Change in message view contents case CBaseView::eBroadcast_ViewChanged: { C3PanePanel* broadcaster = NULL; if (reinterpret_cast<CMessageView*>(param) == GetMessageView()) broadcaster = mMessage; else if (reinterpret_cast<CAddressView*>(param) == GetAddressView()) broadcaster = mAddress; else if (reinterpret_cast<CEventPreview*>(param) == GetEventView()) broadcaster = mEvent; // Only if its one of ours if (broadcaster) { // Change title if view is displayed if (mCurrent == broadcaster) { SetTitle(broadcaster->GetTitle()); SetIcon(broadcaster->GetIconID()); } // Check active status if (broadcaster->IsSpecified()) broadcaster->Activate(); else { broadcaster->Deactivate(); // Make sure we reset zoom state on deactivate if (C3PaneWindow::s3PaneWindow->GetZoomPreview()) C3PaneWindow::s3PaneWindow->ZoomPreview(false); } } } break; default:; } } void C3PanePreview::MakeMessage() { // Read the message view resource mMessage = new C3PaneMessage(mView, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, 100, 100); mMessage->OnCreate(); mMessage->FitToEnclosure(kTrue, kTrue); mMessage->Hide(); // Setup listeners GetMessageView()->Add_Listener(this); // Create a toolbar for it MakeToolbars(GetMessageView()); } void C3PanePreview::MakeAddress() { // Read the message view resource mAddress = new C3PaneAddress(mView, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, 100, 100); mAddress->OnCreate(); mAddress->FitToEnclosure(kTrue, kTrue); mAddress->Hide(); // Setup listeners GetAddressView()->Add_Listener(this); // Create a toolbar for it MakeToolbars(GetAddressView()); } void C3PanePreview::MakeEvent() { // Don't do if admin locks it out if (CAdminLock::sAdminLock.mPreventCalendars) return; // Read the message view resource mEvent = new C3PaneEvent(mView, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, 300, 200); mEvent->OnCreate(); mEvent->FitToEnclosure(kTrue, kTrue); mEvent->Hide(); // Setup listeners GetEventView()->Add_Listener(this); // Create a toolbar for it MakeToolbars(GetEventView()); } bool C3PanePreview::IsSpecified() const { // Check that sub view is specified return mCurrent->IsSpecified(); } // Set the title for the preview void C3PanePreview::SetTitle(const cdstring& title) { if (mCurrent == mEvent) mEvent->SetTitle(title); } // Set the icon for the preview void C3PanePreview::SetIcon(unsigned int icon) { } bool C3PanePreview::TestClose() { // Test each pane that exists if (mMessage && !mMessage->TestClose()) return false; if (mAddress && !mAddress->TestClose()) return false; if (mEvent && !mEvent->TestClose()) return false; return true; } void C3PanePreview::DoClose() { // Close each pane that exists if (mMessage) mMessage->DoClose(); if (mAddress) mAddress->DoClose(); if (mEvent) mEvent->DoClose(); } void C3PanePreview::SetViewType(N3Pane::EViewType view) { // Only bother if different if (mViewType == view) return; // Hide current view if (mCurrent) mCurrent->Hide(); // Set the pane contents mViewType = view; switch(mViewType) { case N3Pane::eView_Mailbox: // Show the message preview if (!mMessage) MakeMessage(); mCurrent = mMessage; break; case N3Pane::eView_Contacts: // Show the address preview if (!mAddress) MakeAddress(); mCurrent = mAddress; break; case N3Pane::eView_Calendar: // Show the address preview if (!mEvent) MakeEvent(); mCurrent = mEvent; break; case N3Pane::eView_Empty: //case N3Pane::eView_IM: //case N3Pane::eView_Bookmarks: default:; // Delete the content of all views mCurrent = NULL; break; } // Show the new one if (mCurrent) { mCurrent->Show(); if (mCurrent->IsSpecified()) mCurrent->Activate(); else mCurrent->Deactivate(); // Change title and icon when view changed SetTitle(mCurrent->GetTitle()); SetIcon(mCurrent->GetIconID()); } } // Get message view from sub-pane CMessageView* C3PanePreview::GetMessageView() const { return mMessage ? mMessage->GetMessageView() : NULL; } // Get address view from sub-pane CAddressView* C3PanePreview::GetAddressView() const { return mAddress ? mAddress->GetAddressView() : NULL; } // Get address view from sub-pane CEventPreview* C3PanePreview::GetEventView() const { return mEvent ? mEvent->GetEventView() : NULL; } // Reset state from prefs void C3PanePreview::ResetState() { switch(mViewType) { case N3Pane::eView_Mailbox: if (GetMessageView()) GetMessageView()->ResetState(true); break; case N3Pane::eView_Contacts: if (GetAddressView()) GetAddressView()->ResetState(true); break; case N3Pane::eView_Calendar: if (GetEventView()) GetEventView()->ResetState(true); break; default:; } } // Save state in prefs void C3PanePreview::SaveDefaultState() { switch(mViewType) { case N3Pane::eView_Mailbox: if (GetMessageView()) GetMessageView()->SaveDefaultState(); break; case N3Pane::eView_Contacts: if (GetAddressView()) GetAddressView()->SaveDefaultState(); break; case N3Pane::eView_Calendar: if (GetEventView()) GetEventView()->SaveDefaultState(); break; default:; } }
ccfc47fedd87b493f9f78de7ac4db4e36075d919
c56ce76d2a9bd85538ec860cac815357b41fc3a4
/PR_HW1/FeatureData.h
597045e5c635710e30e7af4084da386425b2e8f4
[]
no_license
amon0424/PR_HW1
b9e35ea1cc846b0f07d6cbfba4f00c513b56465d
eb4bfe6d7279a8c834a91433b803b679904f1848
refs/heads/master
2016-09-06T10:52:13.651089
2011-04-28T17:55:35
2011-04-28T17:55:35
1,613,524
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
h
FeatureData.h
#ifndef _FEATURE_DATA_H #define _FEATURE_DATA_H #include <opencv/cv.h> #include <iostream> #include <iomanip> class FeatureData { public: int NumberOfFeatures; CvMat* FeatureVector; int ClassID; FeatureData(int nubmerOfFeatures) : NumberOfFeatures(nubmerOfFeatures) { FeatureVector = cvCreateMat(nubmerOfFeatures, 1, CV_32FC1); } FeatureData(const FeatureData& x) { this->FeatureVector = cvCreateMat(x.NumberOfFeatures, 1, CV_32FC1); cvCopy(x.FeatureVector, this->FeatureVector); ClassID = x.ClassID; NumberOfFeatures = x.NumberOfFeatures; } ~FeatureData() { cvReleaseMat(&FeatureVector); } FeatureData& operator=(const FeatureData& x) { cvCopy(x.FeatureVector, this->FeatureVector); ClassID = x.ClassID; NumberOfFeatures = x.NumberOfFeatures; return *this; } void Print() { std::stringstream s; //std::cout.width(20); //s << "(" << FeatureVector->data.fl[0] << "," << FeatureVector->data.fl[1] << "," << FeatureVector->data.fl[2] << "," << FeatureVector->data.fl[3] << ")"; s << "("; for(int i=0; i<NumberOfFeatures; i++) { if((float)((int)FeatureVector->data.fl[i]) == FeatureVector->data.fl[i]) s << std::left << std::setw(4) << FeatureVector->data.fl[i]; else s << std::left << std::setprecision(3) << std::setw(4) << FeatureVector->data.fl[i]; if(i!=NumberOfFeatures-1) s << ","; } s << ")"; std::cout << std::left << std::setw(22) << s.str(); //std::cout << std::left /*<< std::setw(20)*/ << s.str(); } }; #endif
afe2d2acc609f9187488bba611313fc2e2bb1549
890e07c50ea370449416393edaebf9842224a1fd
/Reference/20140710_SSC_Auto_9K_V1.0.0.0/20140710_SSC_Auto_9K_V1.0.0.0/SSC_GameEngine/Character.cpp
4faedc6fbe5f76ccc4d447153369fbd1d9fc6c42
[]
no_license
zidane168/AutoPlay
77c91519b1712b8b791d77020eea218c982d47dc
8eb85a0c92c7b8af334bbf4516bf00139155ca89
refs/heads/master
2021-01-10T20:56:58.002779
2015-09-15T02:00:07
2015-09-15T02:00:07
39,605,621
0
1
null
null
null
null
UTF-8
C++
false
false
102,917
cpp
Character.cpp
/* 20140613 - SangDH UPDATE game v2.36.1, khong thay doi nhiu: them 1 offset(158->159) ham ClickOnItem, offset(160->161) hamGetWorldMapAddress + them ham GetDoQuest(): xet trang thai lam nv, trong file GameEngine.cpp them phan Lich Luyen vao Chung pphan Lich Luyen va dieu doi 20140612-SangDH-Hàm IsInterval(): hàm cho phép gán thời gian delay cho 1 hành động dựa vào ID (true: tạm dừng | false: tiếp tục) + RemoveInterval(): xóa interval + Thay đổi delay cho các hàm + thay đổi hàm SearchNPCByName(): Search đúng NPC khi làm nhiệm vụ lịch luyện 20140611-SangDH-Thay đổi cách lấy base Address hàm Init() + Thêm hàm ConvertString() chuyển chuỗi sang Unicode //cap nhat base file Process.cpp //them mot so doan code hoan thien fix lõi nho: RecieveEscort(), GotoHorse //20140605 == Them code trong ham GoToHourse() xu ly nv chet quay lai cho cu, nhiem vu that bai quay ve nhan nv khac //20140604 == Them tinh nang dieu doi // Character.cpp : implementation file // //Interval: 1: di chuyen | 2: di chuyen cung map | 3: hồi thành | 4: mời party | 5: check đồng ý mời party */ #include "stdafx.h" #include <math.h> #include "Character.h" #include "GameInfo.h" #include "NPC.h" #include "Item.h" #include "Serialize.h" #include <string> char* chatMsg[] = { "Da co auto tai autongaokiem.com", "download auto tai autongaokiem.com", "Auto PK tai autongaokiem.com", "Dang su dung auto PK tai autongaokiem.com", "Da cap nhat tinh nang train quai" }; char* MpFood[] = { "Bánh Ngô", "Màn Thầu", "Bánh Hấp", "Bánh Bí Ngô", "Bánh Bao" }; // CCharacter const UINT WM_HOOK_WRITE = RegisterWindowMessage(L"WM_HOOK_WRITE"); using namespace std; CCharacter::CCharacter() { m_iOS = 0; m_hHandle = NULL; m_hwnd = NULL; m_szName = L""; t_szName = L""; m_szTitle=L""; m_szFamily = L""; m_sServerName=L""; m_iCurHP = 0; m_iMaxHP = 0; m_iCurMP = 0; m_iMaxMP = 0; m_iCurentTarget = 0; m_iCurMapId=0; m_siPkState =0; m_iState =0; m_iFaction = 0; m_iParty=0; m_iColor=0; m_iLevel=0; m_iActiveSkill=0; m_iPkTarget=0; //============================= m_iFight = 0; //Thong tin tinh nang m_bIsHooking = false; m_iPriority=0; m_iRange = 500; m_iRangePoint=1000; m_bPkFollowLead = false; m_bFollowLead = false; //true; m_bAutoRide=true; m_bPkFirst=false; m_bBlackList=false; m_bFightToDie = false; m_bNotFollow = false; m_iDistance=200; m_bAutoGoto=false; m_bAutoRevival=true; m_bAutoFight = true; m_iKeyFight=0; m_iHpLimit=50; m_iKeyHP=0; m_iKeyMP=0; m_bAutoEat = false; siCurMoster = 0; // iOldMap=0; bIsRunning = false; m_bAutoBackToTrain = true; m_bQuickAward = false; m_iTrainMap=0; m_mSkill.clear(); m_mBuff.clear(); m_bAutoQuest=false; m_bQuestInCave = false; m_iQuestNum=0; m_iCurQuest=0; m_mNPCQuest.clear(); // m_dwQuestTextAddress=0; // m_dwAwardTextAddress=0; m_arrAward = new byte[AWARD_SIZE+1]; m_arrAward[0] = AWARD_SIZE ; //index 0 is size of array m_mAward.clear(); iLag=0; m_npc = NULL; iNpcHP=0; iCountTime=COUNT_TIME; iDelayChat = 0; m_iTargetIdx = 0; serialize = NULL; m_arrElement = new byte[ELEMENT_SIZE+1]; m_arrElement[0] = ELEMENT_SIZE ; //index 0 is size of array m_arrFaction = new byte[FACTION_SIZE+1]; m_arrFaction[0] = FACTION_SIZE ; //index 0 is size of array //////////NghiaLP////////////// m_bPickBag=false; m_bInterParty=false; m_szNameParty=L""; m_bCreateParty = false; m_vMemberParty.clear(); //========Van Tieu========== bMenuSel = false; m_bEscort = false; m_iEscort = 0; m_iCurEscort = 0; m_iProsessType = 0; m_bReciveAdward = false; m_szState = L""; m_iBackHorse_MapID = 0; m_iBackHorse_X = 0; m_iBackHorse_Y = 0; //========Dieu Doi=========== m_bSendTeamDoQuest = false; m_bBC = false; m_iKindBC = 0; m_bTVP = false; m_bVT = false; m_bTN = false; m_bTVPhai = false; m_bWaiting = false; m_iQuesting = 0; } CCharacter::~CCharacter() { m_iOS = 0; m_hHandle = NULL; m_hwnd = NULL; m_szName = L""; t_szName = L""; m_szTitle=L""; m_szFamily = L""; m_sServerName=L""; m_siSafe =0; m_iCurHP = 0; m_iMaxHP = 0; m_iCurMP = 0; m_iMaxMP = 0; m_iCurentTarget=0; m_iCurMapId=0; m_iFaction = 0; m_iParty=0; m_iColor=0; m_siPkState =0; m_iLevel=0; m_iActiveSkill=0; m_iPkTarget=0; m_iFight = 0; m_bIsHooking = false; m_iPriority=0; m_iRangePoint=0; m_iRange = 0; delete m_npc; m_npc = NULL; m_iTargetIdx = 0; m_dwProId = 0; m_mSkill.clear(); m_mBuff.clear(); m_bPkFollowLead = false; m_bAutoRide=false; m_bFollowLead = false; ////////////////// m_bPkFirst=false; m_bBlackList=false; m_bFightToDie = false; m_bNotFollow = false; m_iDistance=0; m_bAutoGoto=false; m_bAutoRevival=false; m_bAutoFight = false; m_iKeyFight=0; m_iHpLimit=0; m_iKeyHP=0; m_iKeyMP=0; m_bAutoEat = false; m_bAutoQuest=false; m_bQuestInCave = false; m_iQuestNum=0; m_iCurQuest=0; m_mNPCQuest.clear(); // m_dwQuestTextAddress=0; // m_dwAwardTextAddress=0; m_mAward.clear(); m_mSkills.clear(); m_mBuff.clear(); m_mSkillDelay.clear(); m_lMonsters.clear(); if(serialize!=NULL) delete serialize; serialize = NULL; delete []m_arrElement; m_arrElement=NULL; delete []m_arrFaction; m_arrFaction=NULL; delete []m_arrAward; m_arrAward=NULL; iLag=0; iNpcHP=0; iCountTime=0; iDelayChat=0; siCurMoster = 0; // iOldMap=0; bIsRunning = false; m_bAutoBackToTrain=false; m_bQuickAward = false; m_iTrainMap=0; //////////NghiaLP////////////// m_bPickBag=false; m_bInterParty=false; m_szNameParty=L""; m_bCreateParty = false; m_vMemberParty.clear(); //========Van Tieu========== m_bEscort = false; m_iEscort = 0; m_iCurEscort = 0; m_iProsessType = 0; m_bReciveAdward = false; m_szState = L""; m_iBackHorse_MapID = 0; m_iBackHorse_X = 0; m_iBackHorse_Y = 0; //========Dieu Doi=========== m_bSendTeamDoQuest = false; m_bBC = false; m_iKindBC = 0; m_bTVP = false; m_bVT = false; m_bTN = false; m_bTVPhai = false; m_bWaiting = false; m_iQuesting = 0; } void CCharacter::Init(){ DWORD dwPlayerIndexAddress; //Get Base Address win64 //if(m_iOS==WIN_XP_64||m_iOS==WIN_7_64) // ReadProcessMemory(m_hHandle, (void*)GAME_BASE_ADDRESS, &dwGameBaseAddress, (DWORD)sizeof(dwGameBaseAddress), 0); ////Get Base Address win32 //else{ // if(m_iOS==WIN_XP_32){ // ReadProcessMemory(m_hHandle, (void*)GAME_BASE_ADDRESS_XP_32, &dwGameBaseAddress, (DWORD)sizeof(dwGameBaseAddress), 0); // } // else if(m_iOS==WIN_7_32){ // ReadProcessMemory(m_hHandle, (void*)GAME_BASE_ADDRESS_32, &dwGameBaseAddress, (DWORD)sizeof(dwGameBaseAddress), 0); // } // dwGameBaseAddress = dwGameBaseAddress + GAME_OFFSET_32; // ReadProcessMemory(m_hHandle, (void*)dwGameBaseAddress, &dwGameBaseAddress, (DWORD)sizeof(dwGameBaseAddress), 0); //} ////Đọc thông tin //dwGameBaseAddress = dwGameBaseAddress + GAME_OFFSET_1; //ReadProcessMemory(m_hHandle, (void*)dwGameBaseAddress, &dwGameBaseAddress, (DWORD)sizeof(dwGameBaseAddress), 0); // // //Get current map dwMapAddress = dwGameBaseAddress + GAME_OFFSET_MAPID; ReadProcessMemory(m_hHandle, (void*)dwMapAddress, &dwMapAddress, (DWORD)sizeof(dwMapAddress), 0); dwMapAddress = dwMapAddress + NPC_MAP; //Get player Index dwPlayerIndexAddress = dwGameBaseAddress + GAME_OFFSET_INDEX; ReadProcessMemory(m_hHandle, (void*)dwPlayerIndexAddress, &dwPlayerIndexAddress, (DWORD)sizeof(dwPlayerIndexAddress), 0); dwPlayerIndexAddress = dwPlayerIndexAddress + NPC_INDEX; ReadProcessMemory(m_hHandle, (void*)dwPlayerIndexAddress, &dwPlayerIndexAddress, (DWORD)sizeof(dwPlayerIndexAddress), 0); m_iIndex = dwPlayerIndexAddress; //Get player Info address dwGameInfoAddress = dwGameBaseAddress + GAME_OFFSET_INFO; ReadProcessMemory(m_hHandle, (void*)dwGameInfoAddress, &dwGameInfoAddress, (DWORD)sizeof(dwGameInfoAddress), 0); dwGameInfoAddress = dwGameInfoAddress + GAME_OFFSET_DATASIZE * dwPlayerIndexAddress; ReadProcessMemory(m_hHandle, (void*)dwGameInfoAddress, &dwGameInfoAddress, (DWORD)sizeof(dwGameInfoAddress), 0); //get server name DWORD dwServerName = dwGameBaseAddress + GAME_OFFSET_NAME; ReadProcessMemory(m_hHandle, (void*)dwServerName, &dwServerName, (DWORD)sizeof(dwServerName), 0); dwServerName = dwServerName + GAME_SERVER_OFFSET; char sValue[NPC_NAME_SIZE]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwServerName, &sValue, (DWORD)sizeof(sValue), 0); m_sServerName = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_sServerName.GetString() )); m_sServerName = wsResult.c_str(); //Chien Dau(Send F) dwDoFight = dwGameBaseAddress + NPC_STATEFIGHT; //get map ID // ReadProcessMemory(m_hHandle, (void*)dwMapAddress, &iOldMap, (DWORD)sizeof(iOldMap), 0); GetName(); } /************************************************************************ ReadCharacterName - 01/07/2014 Trả về giá trị tương ứng => DWORD PTR SS:[dwAddress] return: - CString: tên nhân vật tương ứng với handle *************************************************************************/ CString CCharacter::GetName() { // Current Player DWORD dwPlayerName = dwGameBaseAddress + GAME_OFFSET_NAME; ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); dwPlayerName = dwPlayerName + NPC_NAME; char sValue[NPC_NAME_SIZE]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &sValue, (DWORD)sizeof(sValue), 0); m_szName = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_szName.GetString() )); m_szName = wsResult.c_str(); if(m_szName != L"") t_szName = m_szName; // Get npc title dwPlayerName = dwGameInfoAddress + NPC_TITLE; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &sValue, (DWORD)sizeof(sValue), 0); m_szTitle = (CString)sValue; wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_szTitle.GetString() )); m_szTitle = wsResult.c_str(); return m_szName; } void CCharacter::GetInfo() { char sValue[NPC_NAME_SIZE]; // CurrentHP DWORD dwPlayerInfo= dwGameInfoAddress + NPC_CURRENT_HP;; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iCurHP, (DWORD)sizeof(m_iCurHP), 0); // CurrentMP dwPlayerInfo = dwGameInfoAddress + NPC_CURRENT_MP; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iCurMP, (DWORD)sizeof(m_iCurMP), 0); // MaxHP dwPlayerInfo = dwGameInfoAddress + NPC_MAX_HP; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iMaxHP, (DWORD)sizeof(m_iMaxHP), 0); // MaxMP dwPlayerInfo = dwGameInfoAddress + NPC_MAX_MP; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iMaxMP, (DWORD)sizeof(m_iMaxMP), 0); // Get target Index dwPlayerInfo = dwGameInfoAddress + NPC_TARGET; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iCurentTarget, (DWORD)sizeof(m_iCurentTarget), 0); //Get coor dwPlayerInfo = dwGameInfoAddress + NPC_COOR_X; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iTdX, (DWORD)sizeof(m_iTdX), 0); dwPlayerInfo = dwGameInfoAddress + NPC_COOR_Y; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iTdY, (DWORD)sizeof(m_iTdY), 0); // Get ride horse state dwPlayerInfo = dwGameInfoAddress + NPC_RIDE_HORSE; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_bIsRiding, (DWORD)sizeof(m_bIsRiding), 0); // Get npc faction dwPlayerInfo = dwGameInfoAddress + NPC_FACTION; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iFaction, (DWORD)sizeof(m_iFaction), 0); // Get npc faction dwPlayerInfo = dwGameInfoAddress + NPC_TITLE; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &sValue, (DWORD)sizeof(sValue), 0); m_szTitle = (CString)sValue; wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_szTitle.GetString() )); m_szTitle = wsResult.c_str(); // Get npc Level dwPlayerInfo = dwGameInfoAddress + NPC_LEVEL; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iLevel, (DWORD)sizeof(m_iLevel), 0); // Get npc state dwPlayerInfo = dwGameInfoAddress + NPC_STATE; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iState, (DWORD)sizeof(m_iState), 0); // Get npc PK state dwPlayerInfo = dwGameInfoAddress + NPC_PK_STATE; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_siPkState, (DWORD)sizeof(m_siPkState), 0); // Get active skill dwPlayerInfo = dwGameInfoAddress + NPC_ACTIVE_SKILL; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iActiveSkill, (DWORD)sizeof(m_iActiveSkill), 0); // Get family dwPlayerInfo = dwGameInfoAddress + NPC_FAMILY; memset(sValue, 0x0, (sizeof(sValue))); ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, sValue, (DWORD)(sizeof(sValue)), 0); m_szFamily = (CString)sValue; // Get fight status dwPlayerInfo = dwGameInfoAddress + NPC_SAFE; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_siSafe, (DWORD)sizeof(m_siSafe), 0); // Get party dwPlayerInfo = dwGameInfoAddress + NPC_PARTY; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iParty, (DWORD)sizeof(m_iParty), 0); // Get name color dwPlayerInfo = dwGameInfoAddress + NPC_NAME_COLOR; ReadProcessMemory(m_hHandle, (void*)dwPlayerInfo, &m_iColor, (DWORD)sizeof(m_iColor), 0); //Get current map ReadProcessMemory(m_hHandle, (void*)dwMapAddress, &m_iCurMapId, (DWORD)sizeof(m_iCurMapId), 0); } void CCharacter::AddNPC(int mapID,CString sName,int iCorX,int iCorY){ POS *pos = new POS(); pos->_iX = iCorX; pos->_iY = iCorY; pos->_iMapId = mapID; CString id; id.Format(L"%d"+sName,mapID); m_mNPCQuest.insert(make_pair(id,pos)); } POS* CCharacter::GetNPC(int mapID,CString sName){ CString id; id.Format(L"%d"+sName,mapID); std::map<CString,POS*>::iterator item; item = m_mNPCQuest.find(id); if(item==m_mNPCQuest.end()) return NULL; return item->second; } bool CCharacter::InitInfo(){ ////Tạo đối tượng mapping serialize = new XMLSerialized(L"Character\\" + m_szName + L".xml"); //tạo đối tượng NPC m_npc = new CNPC(m_hHandle,dwGameBaseAddress); //Get thông tin cơ bản GetInfo(); //Khởi tạo danh sách ngủ hành LoadElement(); //khởi tạo danh sách môn phái LoadFaction(); //Load danh sách skill LoadSkills(); //Load giải thưởng LoadAward(); //Load tọa độ bãi quái LoadPoint(); //load các skill & buff LoadSkillCfg(); LoadBuffCfg(); LoadMemberParty(); //Add npc nhiem vu AddNPC(180,L"Tâm Hà",673,389); //Tuong Duong AddNPC(176,L"Tâm Hà",737,357); //Thanh Do AddNPC(179,L"Tâm Hà",709,359); //bien kinh AddNPC(30,L"Tâm Hà",673,389); //Duong Chau AddNPC(178,L"Tâm Hà",676,360); //Phuong tuong AddNPC(285,L"Tâm Hà",230,436); //Thien Tam Coc AddNPC(180,L"Lâm Thiên Tâm",1017,376); //Tuong Duong AddNPC(176,L"Lâm Thiên Tâm",1096,332); //Thanh Do AddNPC(179,L"Lâm Thiên Tâm",1062,332); //bien kinh AddNPC(30,L"Lâm Thiên Tâm",1033,370); //Duong Chau AddNPC(178,L"Lâm Thiên Tâm",1032,338); //Phuong tuong AddNPC(180,L"Thẩm Chấn Uy",352,284); //Tuong Duong AddNPC(176,L"Thẩm Chấn Uy",439,249); //Thanh Do AddNPC(179,L"Thẩm Chấn Uy",411,248); //bien kinh AddNPC(30,L"Thẩm Chấn Uy",383,279); //Duong Chau AddNPC(178,L"Thẩm Chấn Uy",395,251); //Phuong tuong AddNPC(180,L"Nghiêm Nhiếp Ảnh",499,389); //Tuong Duong AddNPC(176,L"Nghiêm Nhiếp Ảnh",550,361); //Thanh Do AddNPC(179,L"Nghiêm Nhiếp Ảnh",524,350); //bien kinh AddNPC(30,L"Nghiêm Nhiếp Ảnh",507,392); //Duong Chau AddNPC(178,L"Nghiêm Nhiếp Ảnh",520,349); //Phuong tuong //Tạo thông tin lưu file serialize->Mapping(L"Info",L"", TagType::Root,DataType::None,NULL); serialize->Mapping(L"Name",L"/Info",TagType::Attribute,DataType::String,(DWORD)&m_szName); serialize->Mapping(L"Range",L"/Info",TagType::Element,DataType::Int,(DWORD)&m_iRange); serialize->Mapping(L"Priority",L"/Info",TagType::Element,DataType::Int,(DWORD)&m_iPriority); serialize->Mapping(L"Element",L"/Info",TagType::Element,DataType::ByteArray,(DWORD)m_arrElement); serialize->Mapping(L"Faction",L"/Info",TagType::Element,DataType::ByteArray,(DWORD)m_arrFaction); serialize->Mapping(L"PkFollowLead",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bPkFollowLead); //serialize->Mapping(L"FollowLead",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bFollowLead); serialize->Mapping(L"AutoRide",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoRide); serialize->Mapping(L"PeopleFirst",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bPkFirst); serialize->Mapping(L"BlackList",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bBlackList); serialize->Mapping(L"FightToDie",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bFightToDie); serialize->Mapping(L"NotFollow",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bNotFollow); serialize->Mapping(L"DistanceFollow",L"/Info",TagType::Element,DataType::Int,(DWORD)&m_iDistance); serialize->Mapping(L"GoTo",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoGoto); serialize->Mapping(L"Revival",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoRevival); serialize->Mapping(L"AutoFight",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoFight); serialize->Mapping(L"KeyFight",L"/Info",TagType::Element,DataType::Int,(DWORD)&m_iKeyFight); serialize->Mapping(L"HpRestore",L"/Info",TagType::Element,DataType::None,NULL); serialize->Mapping(L"value",L"/Info/HpRestore",TagType::Attribute,DataType::Int,(DWORD)&m_iHpLimit); serialize->Mapping(L"key",L"/Info/HpRestore",TagType::Attribute,DataType::Int,(DWORD)&m_iKeyHP); /////////tab bãi quái////// serialize->Mapping(L"AutoEat",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoEat); serialize->Mapping(L"MpRestore",L"/Info",TagType::Element,DataType::Int,(DWORD)&m_iKeyMP); serialize->Mapping(L"AutoGoBack",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoBackToTrain); /////========NghiaLP====20140401================Nhat tui serialize->Mapping(L"PickBag",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bPickBag); ///========ket thuc=============== ///////Tab nhiem vu/////////////////// serialize->Mapping(L"AutoQuest",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bAutoQuest); serialize->Mapping(L"Award",L"/Info",TagType::Element,DataType::ByteArray,(DWORD)m_arrAward); serialize->Mapping(L"QuickAward",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bQuickAward); serialize->Mapping(L"QuestInCave",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bQuestInCave); //======Van Tieu=========== serialize->Mapping(L"Escort",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bEscort); //==============Dieu Doi============================== serialize->Mapping(L"SendTeam",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bSendTeamDoQuest); serialize->Mapping(L"BC",L"/Info/SendTeam",TagType::Attribute,DataType::Bool,(DWORD)&m_bBC); serialize->Mapping(L"KindBiCanh",L"/Info",TagType::Element,DataType::Int,(DWORD)&m_iKindBC); serialize->Mapping(L"TVP",L"/Info/SendTeam",TagType::Attribute,DataType::Bool,(DWORD)&m_bTVP); serialize->Mapping(L"VT",L"/Info/SendTeam",TagType::Attribute,DataType::Bool,(DWORD)&m_bVT); serialize->Mapping(L"TN",L"/Info/SendTeam",TagType::Attribute,DataType::Bool,(DWORD)&m_bTN); serialize->Mapping(L"TVPhai",L"/Info/SendTeam",TagType::Attribute,DataType::Bool,(DWORD)&m_bTVPhai); //////Tab party///////////////// serialize->Mapping(L"AutoParty",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bInterParty); serialize->Mapping(L"LeaderName",L"/Info",TagType::Element,DataType::String,(DWORD)&m_szNameParty); serialize->Mapping(L"CreateParty",L"/Info",TagType::Element,DataType::Bool,(DWORD)&m_bCreateParty); //load thong tin tu file len doi tuong serialize->Deserialize(); return true; } void CCharacter::SaveInfo(){ if(serialize!=NULL) serialize->SaveInfo(); } void CCharacter::SaveSkillCfg(CString sName) { CMarkup xml=serialize->OpenFile(); xml.FindElem(); xml.IntoElem(); if(xml.FindElem(sName)){ xml.RemoveElem(); } xml.AddElem(sName); xml.IntoElem(); std::map<int,SKILL_CFG*> lst_cfg; if(sName==L"Skills") lst_cfg = m_mSkill; else lst_cfg = m_mBuff; std::map<int,SKILL_CFG*>::iterator skill_cfg; SKILL_CFG* objSkilCfg; for(skill_cfg= lst_cfg.begin(); skill_cfg != lst_cfg.end(); skill_cfg ++){ objSkilCfg = skill_cfg->second; xml.AddElem(L"Skill"); xml.AddAttrib(L"Id",objSkilCfg->m_iId); xml.AddAttrib(L"Range",objSkilCfg->m_iRange); xml.AddAttrib(L"Delay",objSkilCfg->m_iDelay); } serialize->SaveFile(&xml); } CString CCharacter::GetMapName(int mapId){ CMarkup xmlMap; xmlMap = XMLSerialized::OpenFile(L"Map.cfg"); if(xmlMap.GetDoc().GetLength()==0) return false; xmlMap.ResetPos(); //xmlMap->FindElem(L"Maps"); if (!xmlMap.FindElem(_T("Maps")) ) return false; if(xmlMap.IntoElem()){ while(xmlMap.FindElem()){ if(_tstoi(xmlMap.GetAttrib(_T("id")))==mapId){ return xmlMap.GetAttrib(_T("name")); } } } return L""; } int CCharacter::GetMapId(CString mapName){ CMarkup xmlMap; xmlMap = XMLSerialized::OpenFile(L"Map.cfg"); if(xmlMap.GetDoc().GetLength()==0) return false; xmlMap.ResetPos(); //xmlMap->FindElem(L"Maps"); if (!xmlMap.FindElem(_T("Maps")) ) return false; if(xmlMap.IntoElem()){ while(xmlMap.FindElem()){ if(xmlMap.GetAttrib(_T("name"))==mapName){ return _tstoi(xmlMap.GetAttrib(_T("id"))); } } } return -1; } void CCharacter::SavePoint() { CMarkup xml=serialize->OpenFile(); CString sName = L"Maps"; xml.FindElem(); xml.IntoElem(); if(xml.FindElem(sName)){ xml.IntoElem(); while(xml.FindElem(L"Map")){ int curMap = m_iCurMapId; if(m_iCurMapId != m_iTrainMap && m_iTrainMap!=0) curMap = m_iTrainMap; if(_ttoi( xml.GetAttrib(L"Id"))== curMap){ xml.RemoveElem(); break; } } xml.OutOfElem(); } else { xml.AddElem(sName); } if(m_lMonsters.size()==0){ serialize->SaveFile(&xml); return; } xml.IntoElem(); xml.AddElem(L"Map"); xml.AddAttrib(L"Id",m_iCurMapId); xml.AddAttrib(L"Name",GetMapName(m_iCurMapId)); xml.AddAttrib(L"Range",m_iRangePoint); xml.IntoElem(); std::vector<COOR>::iterator coor_item; m_iTrainMap=m_iCurMapId; for(coor_item= m_lMonsters.begin(); coor_item != m_lMonsters.end(); coor_item ++){ xml.AddElem(L"Point"); xml.AddAttrib(L"x",coor_item->_iX); xml.AddAttrib(L"y",coor_item->_iY); } serialize->SaveFile(&xml); } bool CCharacter::LoadSkills(){ CMarkup xml= XMLSerialized::OpenFile(L"Skill.cfg"); if(xml.GetDoc().GetLength()==0) return false; if(xml.FindElem(L"Skills")){ xml.IntoElem(); while(xml.FindElem()){ if(_tstoi(xml.GetAttrib(_T("id")))==m_iFaction){//tìm theo Id của môn phái xml.IntoElem(); while(xml.FindElem()){//Đọc thông tin từng skill SKILL_DATA* skill = new SKILL_DATA(); skill->m_iId = _tstoi(xml.GetAttrib(_T("id"))); skill->m_iLevel = _tstoi(xml.GetAttrib(_T("level"))); skill->m_sName = xml.GetAttrib(_T("name")); skill->m_iType= _tstoi(xml.GetAttrib(_T("type"))); CString sDelay = xml.GetAttrib(_T("delay")); if(sDelay==L"") skill->m_iDelay = 0; else skill->m_iDelay = _tstoi(sDelay); CString sRange = xml.GetAttrib(_T("range")); if(sRange==L"") skill->m_iRange = 0; else skill->m_iRange = _tstoi(sRange); std::map<CString,SKILL_DATA*>::iterator result = m_mSkills.find(skill->m_sName); if(result==m_mSkills.end())//Nếu chưa có thì load skill m_mSkills.insert(make_pair(skill->m_sName,skill)); else{ if(skill->m_iLevel <= m_iLevel)//load skill theo level m_mSkills[skill->m_sName]=skill; } } return true; } } } return false; } void CCharacter::LoadSkillCfg(){ CMarkup xml=serialize->OpenFile(); if(xml.GetDoc().GetLength()==0) return; if(serialize->FindPath(L"/Info/Skills",&xml)){ int i=0; m_mSkill.clear(); while(xml.FindElem()){//Đọc thông tin từng skill SKILL_CFG* skilCfg = new SKILL_CFG(); skilCfg->m_iId = _tstoi(xml.GetAttrib(_T("Id"))); skilCfg->m_iRange = _tstoi(xml.GetAttrib(_T("Range"))); skilCfg->m_iDelay = _tstoi(xml.GetAttrib(_T("Delay"))); m_mSkill.insert(make_pair( i,skilCfg)); i++; } } } void CCharacter::LoadBuffCfg(){ CMarkup xml=serialize->OpenFile(); if(xml.GetDoc().GetLength()==0) return; if(serialize->FindPath(L"/Info/Buffs",&xml)){ int i=0; m_mBuff.clear(); while(xml.FindElem()){//Đọc thông tin từng skill SKILL_CFG* skilCfg = new SKILL_CFG(); skilCfg->m_iId = _tstoi(xml.GetAttrib(_T("Id"))); skilCfg->m_iRange = _tstoi(xml.GetAttrib(_T("Range"))); skilCfg->m_iDelay = _tstoi(xml.GetAttrib(_T("Delay"))); m_mBuff.insert(make_pair( i,skilCfg)); i++; } } } bool CCharacter::LoadPoint() { m_lMonsters.clear(); if(m_iTrainMap==0) return false; CMarkup xml=serialize->OpenFile(); if(xml.GetDoc().GetLength()==0) return false; CString sName = L"Maps"; xml.FindElem(); xml.IntoElem(); if(!xml.FindElem(sName)){ return false; } xml.IntoElem(); while(xml.FindElem(L"Map")){ if(_ttoi( xml.GetAttrib(L"Id"))== m_iTrainMap){ m_iRangePoint = _ttoi(xml.GetAttrib(L"Range")); xml.IntoElem(); while(xml.FindElem(L"Point")){ COOR cCoor; cCoor._iX = _ttoi(xml.GetAttrib(L"x")); cCoor._iY = _ttoi(xml.GetAttrib(L"y")); m_lMonsters.push_back( cCoor); } return true; } } return false; } bool CCharacter::LoadTrain(std::map<int,CString> &lst){ CMarkup xml= serialize->OpenFile(); if(xml.GetDoc().GetLength()==0) return false; CString sName = L"Maps"; xml.FindElem(); xml.IntoElem(); if(!xml.FindElem(sName)){ return false; } xml.IntoElem(); lst.clear(); int i=0; while(xml.FindElem(L"Map")){ lst.insert(make_pair(i,xml.GetAttrib(L"Id"))); i++; } return true; } void CCharacter::LoadElement(){ m_arrElement[1]=1; m_arrElement[2]=2; m_arrElement[3]=3; m_arrElement[4]=4; m_arrElement[5]=5; } void CCharacter::LoadFaction(){ m_arrFaction[1]=1; m_arrFaction[2]=2; m_arrFaction[3]=3; m_arrFaction[4]=4; m_arrFaction[5]=5; m_arrFaction[6]=6; m_arrFaction[7]=7; m_arrFaction[8]=8; m_arrFaction[9]=9; m_arrFaction[10]=10; } void CCharacter::LoadAward(){ m_mAward.insert(make_pair(1,L"Kinh Nghiệm")); m_mAward.insert(make_pair(2,L"Vàng Khóa")); m_mAward.insert(make_pair(3,L"Bạc Khóa")); m_mAward.insert(make_pair(4,L"Cống Hiến Sư Môn")); m_mAward.insert(make_pair(5,L"Truyện Ký")); m_mAward.insert(make_pair(6,L"Thủy Tinh")); m_arrAward[1]=1; m_arrAward[2]=2; m_arrAward[3]=3; m_arrAward[4]=4; m_arrAward[5]=5; m_arrAward[6]=6; } void CCharacter::ConvertMapToScreen(COOR* cCoor){ int _iXMap,_iYMap; ReadProcessMemory(m_hHandle, (void*)(dwGameBaseAddress+GAME_OFFSET_MAP_X), &_iXMap, (DWORD)sizeof(_iXMap), 0); ReadProcessMemory(m_hHandle, (void*)(dwGameBaseAddress+GAME_OFFSET_MAP_Y), &_iYMap, (DWORD)sizeof(_iYMap), 0); cCoor->_iX=cCoor->_iX <<4; cCoor->_iY=cCoor->_iY <<5; cCoor->_iX += _iXMap; cCoor->_iY += _iYMap; } void CCharacter::ConvertScreenToMap(COOR* cCoor){ int _iXMap,_iYMap; ReadProcessMemory(m_hHandle, (void*)(dwGameBaseAddress+GAME_OFFSET_MAP_X), &_iXMap, (DWORD)sizeof(_iXMap), 0); ReadProcessMemory(m_hHandle, (void*)(dwGameBaseAddress+GAME_OFFSET_MAP_Y), &_iYMap, (DWORD)sizeof(_iYMap), 0); cCoor->_iX -= _iXMap; cCoor->_iY -= _iYMap; cCoor->_iX=cCoor->_iX >>4; cCoor->_iY=cCoor->_iY >>5; } int CCharacter::GetDistance(COOR coor){ int dX,dY,dZ; dX = coor._iX - m_iTdX; dY = coor._iY - m_iTdY; dZ = (int)sqrt((float)dX*dX+(float)dY*dY); return dZ; } int CCharacter::GetDistance(POS pos){ int dX,dY,dZ; dX = pos._iX - m_iTdX; dY = pos._iY - m_iTdY; dZ = (int)sqrt((float)dX*dX+(float)dY*dY); return dZ; } void CCharacter::GetCaptain(){ int iCaptainId=0; DWORD dwParty = dwGameBaseAddress + GAME_OFFSET_PARTY; ReadProcessMemory(m_hHandle, (void*)(dwParty), &dwParty, (DWORD)sizeof(dwParty), 0); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_CAPTAIN_ID), &iCaptainId, (DWORD)sizeof(iCaptainId), 0); m_cLead.m_iId = 0; if(iCaptainId==0) return; for (int i=0;i<PARTY_SIZE;i++){ int indx = i * PARTY_DATA_SIZE; ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_ID+indx), &m_cLead.m_iId, (DWORD)sizeof(m_cLead.m_iId), 0); if(m_cLead.m_iId==iCaptainId){ char sValue[NPC_NAME_SIZE]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_NAME+indx), &sValue, (DWORD)sizeof(sValue), 0); m_cLead.m_sName = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_cLead.m_sName.GetString() )); m_cLead.m_sName = wsResult.c_str(); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_MAP+indx), &m_cLead.m_iCurMap, (DWORD)sizeof(m_cLead.m_iCurMap), 0); if(m_iCurMapId==m_cLead.m_iCurMap){ ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_X+indx), &m_cLead.m_iCurX, (DWORD)sizeof(m_cLead.m_iCurX), 0); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_Y+indx), &m_cLead.m_iCurY, (DWORD)sizeof(m_cLead.m_iCurY), 0); } return; } } } void CCharacter::Search(){ int idZ,iTemp; CNPC npc(m_hHandle,dwGameBaseAddress); mResult.clear(); for(int i=1;i<NPC_MAX_SIZE;i++){ if(i==m_iIndex || i == iLag)//bỏ qua npc lag và nhân vật continue; m_npc->m_iIndex = i; m_npc->GetInfo(); if( m_npc->m_szName==L"")//Không tìm thấy target bỏ qua continue; if( m_npc->m_iState==15 || m_npc->m_iCurHP<=0)//NPC đã chết continue; if(m_npc->m_iType == 5)//vòng xoáy continue; if(m_npc->m_iType == 3)//NPC continue; if(m_npc->m_iType==1){ if(m_iParty==1 && m_npc->m_iParty==1){//cùng party bỏ qua continue; } } if(wcscmp( m_szName,m_szTitle)==0){ //ngoài chiến trường if(m_npc->m_iType==1){ if (m_siPkState==0 || m_npc->m_siPkState==0 )//đang luyện công thì bỏ qua continue; if(m_szFamily.GetLength()>0 && m_npc->m_szFamily.GetLength()>0){//nếu có gia tộc CString FaName =m_szFamily.Left(5); if(m_npc->m_szFamily.Find(FaName)!=-1 )//Cùng gia tộc bỏ qua continue; } } }else{//trong chiến trường if(m_npc->m_iType==3)//bỏ qua npc continue; CString sTeam = m_szTitle.Left(5); if(m_npc->m_szName.Find(sTeam)!=-1 || m_npc->m_iColor == m_iColor)//Cùng phe bỏ qua continue; } //Tìm theo khoảng cách COOR coor; coor._iX = m_npc->m_iTdX; coor._iY = m_npc->m_iTdY; idZ = GetDistance(coor); if(idZ> m_iRange) continue; switch (m_npc->m_iType){ case 0://Quái (monster) if( mResult[L"monster"]==0)//nếu chưa có trong danh sách thì thêm vào mResult[L"monster"]=i; else{ npc.m_iIndex = mResult[L"monster"]; npc.GetInfo(); coor._iX = npc.m_iTdX; coor._iY = npc.m_iTdY; iTemp = GetDistance(coor); if(idZ<iTemp) mResult[L"monster"]=i; } //Lượng máu if( mResult[L"hpMonster"]==0)//nếu chưa có trong danh sách thì thêm vào mResult[L"hpMonster"]=i; else{ npc.m_iIndex = mResult[L"hpMonster"]; npc.GetInfo(); if(m_npc->m_iCurHP < npc.m_iCurHP) mResult[L"hpMonster"]=i; } break; case 1://Người CString element; //Ngũ hành element.Format(L"Ele%d",m_npc->m_iElement); if( mResult[element]==0) mResult[element]=i; else{ npc.m_iIndex = mResult[element]; npc.GetInfo(); coor._iX = npc.m_iTdX; coor._iY = npc.m_iTdY; iTemp = GetDistance(coor); if(idZ<iTemp) mResult[element]=i; } CString faction; //Môn phái faction.Format(L"Fac%d",m_npc->m_iFaction); if( mResult[faction]==0) mResult[faction]=i; else{ npc.m_iIndex = mResult[faction]; npc.GetInfo(); coor._iX = npc.m_iTdX; coor._iY = npc.m_iTdY; iTemp = GetDistance(coor); if(idZ<iTemp) mResult[faction]=i; } //Lượng máu if( mResult[L"hp"]==0)//nếu chưa có trong danh sách thì thêm vào mResult[L"hp"]=i; else{ npc.m_iIndex = mResult[L"hp"]; npc.GetInfo(); if(m_npc->m_iCurHP < npc.m_iCurHP) mResult[L"hp"]=i; } //Khoang cach if( mResult[L"people"]==0)//nếu chưa có trong danh sách thì thêm vào mResult[L"people"]=i; else{ npc.m_iIndex = mResult[L"people"]; npc.GetInfo(); coor._iX = npc.m_iTdX; coor._iY = npc.m_iTdY; iTemp = GetDistance(coor); if(idZ<iTemp) mResult[L"people"]=i; } break; } if( mResult[L"distance"]==0)//nếu chưa có trong danh sách thì thêm vào mResult[L"distance"]=i; else{ npc.m_iIndex = mResult[L"distance"]; npc.GetInfo(); coor._iX = npc.m_iTdX; coor._iY = npc.m_iTdY; iTemp = GetDistance(coor); if(idZ<iTemp) mResult[L"distance"]=i; } } } bool CCharacter::SearchNPC(){ if(!m_siSafe)//nếu trong thành thì ko tìm return false; //if(bIsRunning)//đang di chuyển đến bãi quái // return false; /////////Nếu đánh theo đội trưởng và không phải đang làm nv///////////// if(m_bPkFollowLead&&m_bFollowLead&&!m_bAutoQuest){ m_npc->m_iIndex = GetPkTarget(); if(m_npc->m_iIndex==0) return false; m_npc->GetInfo(); if(m_npc->m_iState==15 || m_npc->m_iCurHP<=0) m_npc->m_iIndex=0; if(m_npc->m_iIndex>NPC_MAX_SIZE) m_npc->m_iIndex=0; if(m_npc->m_iIndex!=0) return true; return false; } //////////////Tự tìm đánh/////////////////// CNPC npc(m_hHandle,dwGameBaseAddress); //COOR coor; //int iTemp=0; Search(); if(mResult.size()==0) return false; //Xet uu tien switch(m_iPriority){ case 0://khoang cach if(mResult[L"people"]==0){ m_npc->m_iIndex = mResult[L"monster"]; return true; } if(mResult[L"monster"]==0){ m_npc->m_iIndex = mResult[L"people"]; return true; } if(m_bPkFirst){//Uu tien danh nguoi trc m_npc->m_iIndex = mResult[L"people"]; return true; } m_npc->m_iIndex = mResult[L"distance"]; return true; case 1://ngu hanh for(int i=1;i<=ELEMENT_SIZE;i++){ CString element; element.Format(L"Ele%d",m_arrElement[i]); if(mResult[element]>0){ m_npc->m_iIndex = mResult[element]; return true; } } m_npc->m_iIndex = mResult[L"monster"]; return true; case 2://mon phai for(int i=1;i<=FACTION_SIZE;i++){ CString faction; faction.Format(L"Fac%d",m_arrFaction[i]); if(mResult[faction]>0){ m_npc->m_iIndex = mResult[faction]; return true; } } m_npc->m_iIndex = mResult[L"monster"]; return true; case 3://luong mau if(mResult[L"hp"]==0){ m_npc->m_iIndex = mResult[L"hpMonster"]; return true; } if(mResult[L"hpMonster"]==0){ m_npc->m_iIndex = mResult[L"hp"]; return true; } if(m_bPkFirst){//Uu tien danh nguoi trc m_npc->m_iIndex = mResult[L"hp"]; return true; } m_npc->m_iIndex = mResult[L"hpMonster"]; npc.m_iIndex = mResult[L"hp"]; npc.GetInfo(); if(m_npc->m_iCurHP > npc.m_iCurHP) m_npc->m_iIndex = mResult[L"hp"]; return true; } return false; } void CCharacter ::DoFight(){ if(!m_bIsHooking) return; /*if(!m_bAutoFight && !m_bAutoQuest){ return; }*/ if(m_siSafe==0) //nếu trong thành thì bỏ qua return; if(m_iTargetIdx != m_npc->m_iIndex) iNpcHP = 0; /*m_iTargetIdx=0; SetTarget();*/ m_npc->GetInfo(); if(m_npc->m_szName==L"" ){ return; } if(m_npc->m_iCurHP<=0 ){ return; } if(IsLag()) { return; } int iFight; ReadProcessMemory(m_hHandle, (void*)dwDoFight, &iFight, (DWORD)sizeof(iFight), 0); if(iFight == 0) ::PostMessage(m_hwnd, WM_KEYDOWN, 70, 0x0); //std::map<int,SKILL_CFG*>::iterator skill_item; ////Kiem tra ket qua tim kiem // // m_iTargetIdx = m_npc->m_iIndex; SetTarget(); // //if(m_mSkill.size()==0){ // SKILL_DATA* data = m_mSkills.begin()->second; // SetTarget(); // SetSkill(data->m_iId); // return; //} // //for(skill_item= m_mSkill.begin(); skill_item != m_mSkill.end(); skill_item ++){ // SKILL_CFG* objskill = skill_item->second; // time_t timer; // time(&timer); // double seconds; // seconds = difftime(timer,m_mSkillDelay[objskill->m_iId]); // if(m_mSkillDelay[objskill->m_iId]==0 || seconds> objskill->m_iDelay){ // if(m_iTargetIdx !=0){//skill pk // // COOR coor; // coor._iX = m_npc->m_iTdX; // coor._iY = m_npc->m_iTdY; // if(objskill->m_iRange < GetDistance(coor)){//Nếu đang đánh thì kiểm tra tầm đánh // if(m_iState!=2){ // MoveTo(); // } // continue; // } // if(m_bIsRiding==1 && m_bAutoRide ) //đang trên ngựa thì xuong ngua // RideHorse(); // SetSkill(objskill->m_iId); // SetTarget(); // m_mSkillDelay[objskill->m_iId]=timer; // //if(objskill->m_iDelay >0) // Sleep(800); // } // } //} /* /*CString str; str.Format(L"%d",m_iTargetIdx); SetWindowTextA(m_hwnd,(LPCSTR)(LPCTSTR) str);*/ } void CCharacter ::DoBuff(){ if(!m_bIsHooking) return; if(m_bIsRiding) //nếu cưỡi ngựa thì bỏ qua return; if(!m_siSafe) //trong thành thì bỏ qua return; if(m_mBuff.size()==0){ return; } if(m_iState==7) return; std::map<int,SKILL_CFG*>::iterator buff_item; //Kiem tra ket qua tim kiem for(buff_item= m_mBuff.begin(); buff_item != m_mBuff.end(); buff_item ++){ SKILL_CFG* objbuff = buff_item->second; time_t timer; time(&timer); double seconds; seconds = difftime(timer,m_mSkillDelay[objbuff->m_iId]); if(m_mSkillDelay[objbuff->m_iId]==0 || seconds> objbuff->m_iDelay+1){ if(DoRightSkill(objbuff->m_iId,m_iTargetIdx,1000))//nếu buff thành công thì gán lại delay m_mSkillDelay[objbuff->m_iId]=timer; } } } bool CCharacter::IsLag(){ //m_npc->m_iIndex =m_iTargetIdx; if(m_npc==NULL || m_npc->m_iIndex == 0) return false; m_npc->GetInfo(); if(iNpcHP != m_npc->m_iCurHP){ iLag = 0; iCountTime= COUNT_TIME; iNpcHP = m_npc->m_iCurHP; return false; } iCountTime--; if(iCountTime<=0){ iLag = m_npc->m_iIndex; m_iTargetIdx=0; iNpcHP =0; return true; } return false; } //Get Leader's target int CCharacter::GetPkTarget(){ if(m_cLead.m_iId == 0) return 0; //Get player Info address DWORD dwAddress = dwGameBaseAddress + GAME_OFFSET_INFO; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); CNPC npc(m_hHandle,dwGameBaseAddress); int index =0; //m_cLead->m_iIndex; m_iPkTarget=0; for(int i=1;i<NPC_MAX_SIZE;i++){ if(i==m_iIndex) continue; npc.m_iIndex = i; npc.GetInfo(); if(npc.m_szName==m_cLead.m_sName){ index = i; break; } } if(index==0) return 0; dwAddress = dwAddress + GAME_OFFSET_DATASIZE * index; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // Get target PK Index dwAddress = dwAddress + NPC_PK_TARGET; ReadProcessMemory(m_hHandle, (void*)dwAddress, &m_iPkTarget, (DWORD)sizeof(m_iPkTarget), 0); return m_iPkTarget; } void CCharacter::RideHorse(){ ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_RIDE,0); } void CCharacter::MoveTo(){ MoveTo(m_npc->m_iTdX,m_npc->m_iTdY); } bool CCharacter::MoveTo(int iNpcX,int iNpcY ){ //20140418--SangDH--Cap nhat ham di chuyen moi /*LONG_PTR lparam; byte sign = 0; iNpcX=iNpcX- m_iTdX; iNpcY=iNpcY-m_iTdY; if(iNpcX<0 && iNpcY >0) sign = 1; else if(iNpcX>0 && iNpcY <0) sign = 2; else if(iNpcX<0 && iNpcY <0) sign = 3;*/ /*lparam = sign * 100000000; lparam = lparam + (abs(iNpcX) * 10000); lparam = lparam + (abs(iNpcY)/2); bool result = (bool)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_MOVE,(LPARAM)lparam);*/ ////////////////////////////////////////////////////////////// //20140418--SangDH--Cap nhat ham di chuyen moi LONG_PTR lparam; lparam = ((iNpcX-0x10)>>5) * 10000; lparam = lparam + ((iNpcY-0x10)>>5); bool result = (bool)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_MOVE,(LPARAM)lparam); return result; } void CCharacter::SetTarget(){ ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_FIGHT,m_iTargetIdx); } void CCharacter::SetAutoFight(){ ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_AUTOFIGHT,m_bAutoFight); } void CCharacter::SetSkill(int iSkillId){ ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_SKILL,iSkillId); } bool CCharacter::DoRightSkill(int iSkillId,int iTarget,int delay){ //m_iTargetIdx=0; //SetTarget(); //SetSkill(iSkillId); int iPar = iSkillId + (10000 * iTarget); bool bResult = ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_RIGHT_SKILL,iPar); Sleep(delay); return bResult; } bool CCharacter::GoingtoLead(){ //từ bỏ mục tiêu m_iTargetIdx=0; SetTarget(); //Lấy thông tin đội trưởng GetCaptain(); if(m_cLead.m_iId ==0) return false; if(m_cLead.m_iCurMap != m_iCurMapId){//không cùng map với captain if(m_bAutoGoto) return FindingAWay(m_cLead.m_iCurMap,0,0); } else{ bIsRunning=false; COOR coor; coor._iX =m_cLead.m_iCurX; coor._iY = m_cLead.m_iCurY; if(GetDistance(coor)<m_iDistance) return false; if(!m_bIsRiding && m_bAutoRide) RideHorse(); MoveTo(coor._iX,coor._iY); } return false; } bool CCharacter::GoingToTrain(){ //từ bỏ mục tiêu m_iTargetIdx=0; SetTarget(); return FindingAWay(m_iTrainMap,0,0); } bool CCharacter::CheckSupport(){ if(!m_bIsHooking) return false; if(m_siSafe==0) //nếu trong thành thì bỏ qua return false; if((m_iCurHP*100)/m_iMaxHP < m_iHpLimit){ KeyPress(m_iKeyHP+48); } if(m_bAutoEat) if((m_iCurMP*100)/m_iMaxMP < 20){ //KeyPress(m_iKeyMP+48); AutoEat(); } return true; } void CCharacter::KeyPress(int iKey){ ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_KEYDOWN,iKey); } void CCharacter::AutoChat(){ iDelayChat--; if(iDelayChat<0) iDelayChat=CHAT_TIME; if(CHAT_TIME==0 || iDelayChat!= CHAT_TIME) return; int rnd = rand()% MSG_SIZE; char* szChatMsg = chatMsg[rnd]; ::PostMessage(m_hwnd, WM_KEYDOWN, VK_RETURN, 0x001C0001); ::PostMessage(m_hwnd, WM_KEYDOWN, VK_DOWN, 0x00500001); while (szChatMsg[0]) { ::PostMessage(m_hwnd, WM_CHAR, LOBYTE(szChatMsg[0]), 0); szChatMsg++; } ::PostMessage(m_hwnd, WM_KEYDOWN, VK_RETURN, 0x001C0001); } void CCharacter::ShowMessage(CString sMsg){ wchar_t* szChatMsg=sMsg.GetBuffer(sMsg.GetLength()); sMsg.ReleaseBuffer(); ::PostMessage(m_hwnd, WM_KEYDOWN, VK_RETURN, 0x001C0001); ::PostMessage(m_hwnd, WM_KEYDOWN, VK_DOWN, 0x00500001); while (szChatMsg[0]) { ::PostMessage(m_hwnd, WM_CHAR, LOBYTE(szChatMsg[0]), 0); szChatMsg++; } ::PostMessage(m_hwnd, WM_KEYDOWN, VK_RETURN, 0x001C0001); } void CCharacter::BackToCity(){ if(IsInterval(3,1)) return; ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_BACK_CITY,0); //Sleep(1000); Reset(); } void CCharacter::AutoEat(){ //Bánh Ngô, Màn Thầu, Bánh Hấp, Bánh Bí Ngô, Bánh Bao CString sName =(CString) MpFood[m_iKeyMP]; int item = GetItemInPack(sName); if(item ==-1 ) return; bool result = ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_ITEM_CLICK,item); } void CCharacter::Reset(){ bIsRunning=false; m_iCurQuest=0; m_iCurMapId=0; } bool CCharacter::MovingToTrainPoint(bool bNext){ if(m_lMonsters.size()==0){ bIsRunning=false; return false; } if(bNext) siCurMoster++; if(siCurMoster >= m_lMonsters.size()) siCurMoster = 0; if(m_iTrainMap==m_iCurMapId) return GoingToPoint(); /*COOR cor = m_lMonsters[siCurMoster]; cTarget._iX = cor._iX; cTarget._iY = cor._iY;*/ if(m_bAutoBackToTrain) FindingAWay(m_iTrainMap,0,0); return true; } bool CCharacter::GoingToPoint(){ //if(m_lMonsters.size() ==0) // return false; // //if(!bIsRunning){ int iCur = siCurMoster; COOR cCoor = m_lMonsters[iCur]; if(GetDistance(cCoor)>m_iRangePoint || bIsRunning){ cTarget._iX = cCoor._iX; cTarget._iY = cCoor._iY; //siCurMoster=iCur; //MovingToTarget(); return MovingToTarget(); } //} return false; } bool CCharacter::FindingAWay(int iDes,int iX,int iY,bool clickLink){ //tự tìm đường trong cùng map if(m_iCurMapId == iDes){ bIsRunning =false; cTarget._iX =iX; cTarget._iY =iY; cTarget._iMapId = iDes; if(cTarget._iX!=0&& cTarget._iY!=0 &&cTarget._iY<10000){ COOR cCor; cCor._iX = iX; cCor._iY = iY; ConvertMapToScreen(&cCor); cTarget._iX =cCor._iX; cTarget._iY =cCor._iY; } if(GetDistance(cTarget)<=50){ bIsRunning = false; cTarget._iX =0; cTarget._iY =0; return false; } if(IsInterval(2,1)) return true; return MovingToTarget(); } //Set time delay if(m_iState==2 ){ return true; } /*time_t timer; time(&timer); double seconds; seconds = difftime(timer,tMoveDelay); if(seconds<3 && tMoveDelay>0) return true; time(&tMoveDelay);*/ if(IsInterval(1,3)) return true; if(clickLink){//nếu đang làm nhiệm vụ thì click link để di chuyển if(GetDistance(cTarget)<50){ bIsRunning = false; return false; } bIsRunning = true; ClickOnLink(); return true; } CMarkup xmlMap; xmlMap = XMLSerialized::OpenFile(L"Map.cfg"); if(xmlMap.GetDoc().GetLength()==0) return false; xmlMap.ResetPos(); if (!xmlMap.FindElem(_T("Maps")) ) return false; if(xmlMap.IntoElem()){ while(xmlMap.FindElem()){ if(_tstoi(xmlMap.GetAttrib(_T("id")))==iDes){ int mapIndx = _tstoi(xmlMap.GetAttrib(_T("Index"))); //time(&tMoveDelay); /*::PostMessage(m_hwnd, WM_KEYDOWN, VK_TAB, 0xc00f0001); Sleep(100); */ ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_MOVE_AWAY,mapIndx); //::PostMessage(m_hwnd, WM_KEYDOWN, VK_TAB, 0xc00f0001); bIsRunning = true; return true; } } } return false; } bool CCharacter::MovingToTarget(){ //từ bỏ mục tiêu m_iTargetIdx=0; SetTarget(); if(cTarget._iX ==0 && cTarget._iY ==0) return false; if(GetDistance(cTarget)<=50){ bIsRunning = false; cTarget._iX =0; cTarget._iY =0; return false; } bIsRunning = true; ////len ngua if(!m_bIsRiding && m_bAutoRide) RideHorse(); // if(m_iState!=2 ) return MoveTo(cTarget._iX,cTarget._iY); } //Thuc hien nhiem vu lich luyen bool CCharacter::ChooseMenu(int iMenuIndex){ Sleep(500); bool LResult= (bool)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_MENU_CLICK,iMenuIndex); return LResult; } //Chọn phần thưởng nhiệm vụ lịch luyện bool CCharacter::ChooseAward(){ Sleep(200); int award=1; for(int i=1;i<=m_arrAward[0];i++){ award=GetAwardIndex(m_mAward[m_arrAward[i]]); if(award!=0) break; } if(award==0) award = 1; bool LResult= (bool)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_AWARD_CLICK,award); return LResult; } int CCharacter::GetAwardIndex(CString szTitle){ DWORD dwAddress ; CString szQuestText; DWORD m_dwAwardTextAddress; char sValue[300]; //if(m_dwAwardTextAddress==NULL){ dwAddress = dwGameBaseAddress + QUEST_AWARD_BASE_ADDRESS; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); for(int i=0;i<12;i++){ if(i==0 || i==6|| i==7|| i==11) dwAddress = dwAddress + GAME_MENU_OFFSET_2; else dwAddress = dwAddress + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); } m_dwAwardTextAddress = dwAddress; //} memset(sValue, 0x0, sizeof(sValue)); for(int i=0;i<3;i++){ if (m_iOS==WIN_XP_64 || m_iOS==WIN_7_64){ if(i==0) dwAddress = m_dwAwardTextAddress +QUEST_AWARD_TEXT_1; if(i==1) dwAddress = m_dwAwardTextAddress +QUEST_AWARD_TEXT_2; if(i==2) dwAddress = m_dwAwardTextAddress +QUEST_AWARD_TEXT_3; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); if(i>0) dwAddress = dwAddress +QUEST_AWARD_TEXT_SIZE_XP; } else{ dwAddress = m_dwAwardTextAddress +0x840; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); dwAddress=dwAddress+ (i*QUEST_AWARD_TEXT_SIZE); } ReadProcessMemory(m_hHandle, (void*)dwAddress, &sValue, (DWORD)sizeof(sValue), 0); szQuestText = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( szQuestText.GetString() )); szQuestText = wsResult.c_str(); if(szQuestText.MakeLower().Find(szTitle.MakeLower())>-1) return i+1; } return 0; } bool CCharacter::ClickOnLink(){ int iIndex = -1; if(m_iQuesting == 2) iIndex = GetQuestIndex(L"<pic=58><color=yellow>Vận Tiêu"); else if(m_iQuesting == 3) iIndex = GetQuestIndex(L"<pic=60><color=yellow>Lịch Luyện"); if(iIndex==-1) return false; bool LResult= (bool)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_QUEST_LINK_CLICK,iIndex); return LResult; } bool CCharacter::GetLinkPos(CString szLinkText){ //<link=pos:Mã Hoành,69,52429,103513> //phân loại nhiệm vụ //======nếu nv lịch luyện if(m_iQuesting == 2) { m_iProsessType = 2; //Dang Hộ tống if(szLinkText.Find(L"Về thành tìm Tổng Tiêu Đầu")!=-1) m_iProsessType = 3; //Hộ tống hoàn thành else if(szLinkText.Find(L"1/")!=-1) m_iProsessType = 1; //Toi cho nguoi uy thac nhận tiêu } else if(m_iQuesting == 3) { m_iQuestType = 3; if(szLinkText.Find(L"lời nhắn")!=-1) m_iQuestType = 1; else if(szLinkText.Find(L"dùng")!=-1) m_iQuestType = 2; } int iStartIndx = szLinkText.Find(L"link=pos:"); if(iStartIndx==-1) return false; iStartIndx+=9; int iEndIndx; iEndIndx = szLinkText.Find(L",",iStartIndx); m_szQuestTarget = szLinkText.Mid(iStartIndx,iEndIndx-iStartIndx); iStartIndx = iEndIndx+1; iEndIndx = szLinkText.Find(L",",iStartIndx); cTarget._iMapId =_ttoi( szLinkText.Mid(iStartIndx,iEndIndx-iStartIndx)); iStartIndx = iEndIndx+1; iEndIndx = szLinkText.Find(L",",iStartIndx); cTarget._iX =_ttoi( szLinkText.Mid(iStartIndx,iEndIndx-iStartIndx)); iStartIndx = iEndIndx+1; iEndIndx = szLinkText.Find(L">",iStartIndx); cTarget._iY =_ttoi( szLinkText.Mid(iStartIndx,iEndIndx-iStartIndx)); iStartIndx = iEndIndx+1; // if(m_iQuestType !=3) //FindingAWay(cTarget._iMapId,cTarget._iX,cTarget._iY); return true; //int LResult= (int)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_LINK_CLICK,iBlockIndex); //return LResult!=0; } int CCharacter::AskNPC(CString szName,bool clickLink){ if(!clickLink){ POS* pos; pos = GetNPC(m_iCurMapId,szName); if(pos!=NULL){ cTarget._iX = pos->_iX; cTarget._iY = pos->_iY; cTarget._iMapId= m_iCurMapId; }else{ pos = GetNPC(179,szName); if(pos==NULL){ return -1; } cTarget._iX = pos->_iX; cTarget._iY = pos->_iY; cTarget._iMapId= pos->_iMapId; } } //Dung Hoi thanh thach if(m_bQuickAward){//){//có dùng hồi thành thạch if(OpenGoBackRock()){ //Nếu có hồi thành thạch if(ChooseMenu(100)){ ChooseMenu(100); Sleep(10000); } return -1; } } if( FindingAWay(cTarget._iMapId,cTarget._iX,cTarget._iY,clickLink)){//chạy tới vị trí NPC return -1; } //đã chạy tới NPC, tìm NPC CNPC npc(m_hHandle,dwGameBaseAddress); for(int i=1;i<NPC_MAX_SIZE;i++){ if(i==m_iIndex)//bỏ qua nhân vật continue; npc.m_iIndex = i; npc.GetInfo(); if( npc.m_szName==L"")//Không tìm thấy target bỏ qua continue; if( npc.m_iType!=3)//không phải NPC bỏ qua continue; if(npc.m_szName==szName){//lấy NPC bIsRunning=false; int LResult= (int)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_OPEN_MENU,0); if(LResult==0){ m_iTargetIdx=i; SetTarget(); } return LResult; } } return -1; } bool CCharacter::FightMonster(CString szText){ GetLinkPos(szText); if(GetDistance(cTarget)>1000){ FindingAWay(cTarget._iMapId, cTarget._iX ,cTarget._iY,true); return false; } int iIndex = SearchNPCByName(m_szQuestTarget); if(iIndex>0){ //m_iIndex m_npc->m_iIndex=iIndex; DoFight(); } return true; } CString CCharacter::GetQuestText(int iIndex){ if(iIndex>4) return L""; DWORD dwAddress ; CString szQuestText=L""; //CString szTitle = L"Giang Hồ Lịch Luyện"; char sValue[300]; // if(m_dwQuestTextAddress==NULL){ dwAddress = dwGameBaseAddress + QUEST_BASE_ADDRESS; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); for(int i=0;i<9;i++){ dwAddress = dwAddress + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); } dwAddress = dwAddress + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); dwAddress = dwAddress + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); dwAddress = dwAddress + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); dwAddress = dwAddress + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); /////////////////////////////20150512_thay đổi địa chỉ block text dùng chung win7 và xp//////////////////////////// for(int i=0;i<iIndex;i++){ dwAddress = dwAddress + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); } //if (m_iOS!=5164 && m_iOS!=5264 && iIndex>=2){//không phải winxp 64bit và là block 3 & 4 & 5 // dwAddress = dwAddress + GAME_MENU_OFFSET_1; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // dwAddress = dwAddress + GAME_MENU_OFFSET_1; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // if(iIndex>=3){ //block 4 & 5 // dwAddress = dwAddress + GAME_MENU_OFFSET_1; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // } //} dwAddress = dwAddress + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // m_dwQuestTextAddress = dwAddress; // } /////////////////////////////20150512_thay đổi địa chỉ block text dùng chung win7 và xp//////////////////////////// //if (m_iOS==5164 || m_iOS==5264){//win XP64 // dwAddress = m_dwQuestTextAddress -0x30; // if(iIndex!=1) // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // switch(iIndex){ // case 0: // dwAddress = dwAddress+ QUEST_TEXT_0; // break; // case 1: // dwAddress = dwAddress + QUEST_TEXT_1; // break; // case 2: // dwAddress = dwAddress + QUEST_TEXT_2; // break; // case 3: // dwAddress = dwAddress + QUEST_TEXT_3; // break; // case 4: // dwAddress = dwAddress + QUEST_TEXT_4; // break; // } //} //else{ // //dwAddress = m_dwQuestTextAddress -0x30 + (iIndex*QUEST_DATA_SIZE); // dwAddress = m_dwQuestTextAddress -0x30; // switch(iIndex){ // case 2: // case 3: // dwAddress = m_dwQuestTextAddress -0x30; // break; // case 4: // dwAddress = dwAddress + QUEST_TEXT_1; // break; // default: // dwAddress = m_dwQuestTextAddress -0x30 + (iIndex*QUEST_DATA_SIZE); // break; // } //} dwAddress = dwAddress + QUEST_TEXT_OFFSET; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwAddress, &sValue, (DWORD)sizeof(sValue), 0); szQuestText = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( szQuestText.GetString() )); szQuestText = wsResult.c_str(); return szQuestText; } CString CCharacter::GetQuestText(CString szTitle){ CString szQuestText; for(int i=0;i<5;i++){ szQuestText = GetQuestText(i); if(szQuestText.Find(szTitle)>-1) return szQuestText; } return L""; } int CCharacter::GetQuestIndex(CString szTitle){ CString szQuestText; for(int i=0;i<5;i++){ szQuestText = GetQuestText(i); if(szQuestText.Find(szTitle)>-1) return i; } return -1; } bool CCharacter::UseQuestItem(){ int iIndx = GetQuestIndex(L"<pic=60><color=yellow>Lịch Luyện"); if(iIndx==-1) return false; int LResult= (int)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_QUEST_ITEM_CLICK,iIndx); return LResult!=0; } //Nhan nhiem vu bool CCharacter::ReceiveQuest(){ if(m_iCurQuest<0) return false; if(m_iCurQuest!=0 && m_iCurQuest!=6)//Đã nhận nhiệm vụ, đang thực hiện return true; CString str=L"<pic=60><color=yellow>Lịch Luyện"; if(m_iCurQuest==0){//nhận lần đầu tiên CString strText = GetQuestText(str); str = strText.Mid(str.GetLength(),6); if(strText!=L""){//nếu đã có nhiệm vụ if(strText.Find(L"Nhiệm vụ đã xong")==-1){//chưa hoàn thành nhiệm vụ đã nhận ShowMessage(L"Dang thuc hien nhiem vu lich luyen" + str); m_iCurQuest=1; return true; } /*else{ ShowMessage(L"Nhan thuong nhiem vu lich luyen " + str); m_iCurQuest=4; return true; }*/ } } int menu =-1; //nếu làm nhiệm vụ trong thiêm tâm cốc if(m_bQuestInCave && m_iCurMapId!=285){ menu = AskNPC(L"Lâm Thiên Tâm"); if(menu!=1){ return false; } if(!ChooseMenu(1)){//vào thiên tâm cốc return false; } //ShowMessage(L"Vao Thien Tam Coc"); } //Nếu chưa nhận nhiệm vụ menu = AskNPC(L"Tâm Hà"); if(menu==-1){//Chưa tìm dc NPC return false; } if(menu==2){//Nếu nhận thưởng ShowMessage(L"Quay ve tra nhiem vu nhan thuong"); m_iCurQuest=4; return true; } if(menu==1){//nếu nhiệm vụ if(ChooseMenu(2)){//nhận nhiệm vụ m_iQuestNum++; m_iCurQuest=1; return true; } } return false; } bool CCharacter::ProcessQuest(){ CString szQuestText; CString str=L"<pic=60><color=yellow>Lịch Luyện"; szQuestText = GetQuestText(str); int menu; if(szQuestText==L""){//Chưa nhận được nhiệm vụ thì nhận lại ShowMessage(L"Quay ve nhan nhiem vu"); m_iCurQuest = 0; return false; } if(m_iCurQuest == 4 || szQuestText.Find(L"Nhiệm vụ đã xong")!=-1){//Nếu đã hoàn thành nhiệm vụ thì nhận thưởng m_iCurQuest = 4; return ReceiveAward(szQuestText); } GetLinkPos(szQuestText); switch(m_iCurQuest){ case 1: if(m_iQuestType == 3){//&&m_iCurMapId!= cTarget._iMapId){//Nhiệm vụ đánh quái //nếu làm nhiệm vụ trong thiêm tâm cốc if(m_bQuestInCave && m_iCurMapId!=285&& m_iCurMapId!=286&& m_iCurMapId!=287){ menu = AskNPC(L"Lâm Thiên Tâm"); if(menu!=1){ return false; } if(!ChooseMenu(1)){//vào thiên tâm cốc return false; } ShowMessage(L"Vao Thien Tam Coc"); return false; } //tìm NPC đưa đến bãi quái if(m_iCurMapId != cTarget._iMapId){ int iIdx = 0; if(m_iCurMapId==285) iIdx = 1; menu = AskNPC(L"Tâm Hà"); if(menu!=1 || !ChooseMenu(iIdx)){//Chọn quay lại bãi quái m_iCurQuest = 1; return false; } } } str = szQuestText.Mid(str.GetLength(),6); ShowMessage(L"Bat dau thuc hien nhiem vu " + str); m_iCurQuest = 2; return false; case 2://di chuyen bằng cách click link if (!FindingAWay(cTarget._iMapId, cTarget._iX ,cTarget._iY,true)) m_iCurQuest = 3; break; case 3://xử lý switch(m_iQuestType){ case 1: if(AskNPC(m_szQuestTarget,true)==1){ if(ChooseMenu(0))//đối thoại if(ChooseMenu(0)==false){//chưa đóng được menu m_iCurQuest = 3; return false; } } break; case 2: UseQuestItem(); Sleep(5000); break; case 3: FightMonster(szQuestText); break; } break; } return false; } bool CCharacter::ReceiveAward(CString szQuestText){ GetLinkPos(szQuestText); //if (!FindingAWay(cTarget._iMapId, cTarget._iX ,cTarget._iY,true)){ // ShowMessage(L"Nhan thuong nhiem vu lich luyen"); if(AskNPC(m_szQuestTarget,true)==2){ if(ChooseAward()){ m_iCurQuest =6; return true; } m_iCurQuest =4; return false; } //} m_iCurQuest =0; return false; } //sangdh-20140601-kiểm tra khi bị đánh thì không dùng hồi thành thạch bool CCharacter::OpenGoBackRock(){ if( m_siSafe==0 || m_iState>5 || m_iCurMapId==cTarget._iMapId ||m_iCurMapId== 286||m_iCurMapId== 287 ){//trong thành, cùng map ,đang đánh hoặc chết, đang trong thiên tâm tháp return false; } //đang đánh quái thì chạy 3s mới dùng hồi thành thạch if(m_iQuestType==3){ if(GetHitMeTarget()!=0) return false; else MoveTo(m_iTdX,m_iTdY); } //kiểm tra hồi thành thạch trong rương int item = GetItemInPack(L"Hồi Thành Thạch"); if(item ==-1 ) return false; int LResult= (int)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_ITEM_CLICK,item); return LResult!=0; } int CCharacter::GetItemInPack(CString sName){ DWORD dwbase = dwGameBaseAddress + PACKAGE_CELL_ADDRESS; ReadProcessMemory(m_hHandle, (void*)dwbase, &dwbase, (DWORD)sizeof(dwbase), 0); dwbase = dwbase + PACKAGE_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwbase, &dwbase, (DWORD)sizeof(dwbase), 0); DWORD dwTempAdd; int itemPos=-1; for(int i=0;i<100;i++){ //moi 16 o tiep theo sau 36 o dau tien if(i<36){ dwTempAdd = dwbase + PACKAGE_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)dwTempAdd, &dwTempAdd, (DWORD)sizeof(dwTempAdd), 0); if(dwTempAdd==NULL) return -1; dwTempAdd = dwTempAdd + i*4; } else{ dwTempAdd = dwbase + PACKAGE_OFFSET_3 + ((int)((i-36)/16)*0x18); ReadProcessMemory(m_hHandle, (void*)dwTempAdd, &dwTempAdd, (DWORD)sizeof(dwTempAdd), 0); if(dwTempAdd==NULL) return -1; dwTempAdd = dwTempAdd + ((i-36)%16)*4; } ReadProcessMemory(m_hHandle, (void*)dwTempAdd, &itemPos, (DWORD)sizeof(itemPos), 0); if(GetItemNameByIndex(itemPos).Find(sName)!=-1){ return i; } } return -1; } CString CCharacter::GetItemNameByIndex(int iIndex){ //Get item index CString sItemName; DWORD dwbase = dwGameBaseAddress + ITEM_OFFSET_ADDRESS; ReadProcessMemory(m_hHandle, (void*)dwbase, &dwbase, (DWORD)sizeof(dwbase), 0); dwbase = dwbase + ITEM_OFFSET_ADDRESS_1; ReadProcessMemory(m_hHandle, (void*)dwbase, &dwbase, (DWORD)sizeof(dwbase), 0); char sValue[NPC_NAME_SIZE]; //char sMember[SIZE_TEXT]; memset(sValue, 0x0, sizeof(sValue)); //memset(sMember, 0x0, sizeof(sMember)); dwbase = dwbase + ITEM_NAME_OFFSET+((iIndex-1)* ITEM_DATA_SIZE); ReadProcessMemory(m_hHandle, (void*)dwbase, &sValue, (DWORD)sizeof(sValue), 0); sItemName = (CString)sValue; wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( sItemName.GetString() )); sItemName = wsResult.c_str(); return sItemName; } ////==================NghiaLP-20140401 tab bãi quái=========================== int CCharacter::GetNumberBag() { DWORD dwbase = dwGameBaseAddress + OFFSET_PICK_BAG; ReadProcessMemory(m_hHandle, (void*)dwbase, &dwbase, (DWORD)sizeof(dwbase), 0); return dwbase; } bool CCharacter::PickBag() { if(m_bPickBag == false) return false; int iNumBag = GetNumberBag(); if(iNumBag != 0) { ::PostMessage(m_hwnd, WM_KEYDOWN, VK_SPACE, 0x00000000); if(iNumBag == 1) IsInterval(7,4); // iNumBag = GetNumberBag(); return true; } return false; } //===========================tab tổ đội========================== void CCharacter::InterParty() { if(!m_bInterParty ) //không đồng ý don xin to doi return; if(m_iParty==1)//nếu đã có party return; if(IsInterval(5,5)) return; //if(dwCheckInviteParty == NULL) // GetCheckInviteParty(); //lấy địa chỉ checkbox đồng ý //if(dwCheckInviteParty == NULL) // return; //if(m_szNameParty == L"") {//Nếu đồng ý tất cả party // ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_CHECK_AUTO_PARTY,1); //} //else{ // ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_CHECK_AUTO_PARTY,0); CString sName =GetNameParty(); if(sName==L"")//không có lời mời return; if(m_szNameParty.MakeLower() == sName.MakeLower() || m_szNameParty == L"") //đúng người mời { ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_AGREE_PARTY,1); return; } ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_AGREE_PARTY,0); //} } CString CCharacter::GetNameParty() { DWORD base = dwGameBaseAddress + OFSET_OPEN_DIALOG_PARTY; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); if(base == NULL) return false; for(int i = 0; i<12; i++) { base = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); if(base == 0) return false; } DWORD dwPlayerName = base; base = base + OPEN_DIALOG_PARTY; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); byte bol = byte(base); //Kiểm tra hộp thoại mở hay đóng if (bol!= 162) return L""; //lấy tên người mời dwPlayerName = dwPlayerName + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); dwPlayerName = dwPlayerName + OFFSET_NAME_PARTY; ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); char sValue[NPC_NAME_SIZE]; //char sMember[SIZE_TEXT]; memset(sValue, 0x0, sizeof(sValue)); //memset(sMember, 0x0, sizeof(sMember)); ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &sValue, (DWORD)sizeof(sValue), 0); //TachChuoi(sMember,sValue,'>','<'); CString m_sName = (CString)sValue; int iStartIndx = m_sName.Find(L">")+1; int iEndIndx = m_sName.Find(L"<",iStartIndx); m_sName=m_sName.Mid(iStartIndx,iEndIndx-iStartIndx); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_sName.GetString() )); m_sName = wsResult.c_str(); return m_sName; } void CCharacter::CreateParty() { if(!m_bCreateParty ) //không đồng ý don xin to doi return; if(GetPartySize()>=6){ return; } if(IsInterval(4,5)) return; InviteParty(); //dong y loi moi theo danh sach } void CCharacter::InviteParty() { char sValue[NPC_NAME_SIZE]; DWORD dwbaseMem = dwGameBaseAddress + OFSET_OPEN_DIALOG_PARTY; ReadProcessMemory(m_hHandle, (void*)dwbaseMem, &dwbaseMem, (DWORD)sizeof(dwbaseMem), 0); dwbaseMem = dwbaseMem + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwbaseMem, &dwbaseMem, (DWORD)sizeof(dwbaseMem), 0); dwbaseMem = dwbaseMem + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)dwbaseMem, &dwbaseMem, (DWORD)sizeof(dwbaseMem), 0); dwbaseMem = dwbaseMem + OFFSET_SAVE_NAME; //memset(sValue, 0x0, sizeof(sValue)); //strcpy(sValue,">:HiếpMi:<"); if(sizeof(m_vMemberParty) == 0) return; std::vector<CString>::iterator name_member; //INV_PARTY* objmem; for(name_member = m_vMemberParty.begin(); name_member != m_vMemberParty.end(); name_member++ ) { wstring str = (wstring)name_member->Trim(); string sResult =XMLSerialized::UnicodeToUTF8(str); if(IsMember((CString)sResult.c_str()))//đã là thành viên continue; for(int i = 0; i < sResult.length() ; i++) { sValue[i] = (char)(LPCTSTR)sResult[i]; } sValue[sResult.length()] ='\0'; //DWORD base = OFFSET_SAVE_NAME; WriteProcessMemory(m_hHandle, (LPVOID*)dwbaseMem, &sValue, sizeof(sValue), 0); ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_INVITE_LIST,dwbaseMem); } } int CCharacter::GetPartySize(){ int iCaptainId=0; DWORD dwParty = dwGameBaseAddress + GAME_OFFSET_PARTY; ReadProcessMemory(m_hHandle, (void*)(dwParty), &dwParty, (DWORD)sizeof(dwParty), 0); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_CAPTAIN_ID), &iCaptainId, (DWORD)sizeof(iCaptainId), 0); if(iCaptainId==0)//Không có đội trưởng return 0; int iSize=0; for (int i=0;i<PARTY_SIZE;i++){ int indx = i * PARTY_DATA_SIZE; int iMemId; ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_ID+indx), &iMemId, (DWORD)sizeof(iMemId), 0); if(iMemId!=0) iSize++; } return iSize; } bool CCharacter::IsMember(CString sName) { int iCaptainId=0; DWORD dwParty = dwGameBaseAddress + GAME_OFFSET_PARTY; ReadProcessMemory(m_hHandle, (void*)(dwParty), &dwParty, (DWORD)sizeof(dwParty), 0); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_CAPTAIN_ID), &iCaptainId, (DWORD)sizeof(iCaptainId), 0); if(iCaptainId==0)//chua co doi return false; for (int i=0;i<PARTY_SIZE;i++){ int indx = i * PARTY_DATA_SIZE; int iMemId; ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_ID+indx), &iMemId, (DWORD)sizeof(iMemId), 0); if(iMemId==0) continue; char sValue[NPC_NAME_SIZE]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)(dwParty + PARTY_MEM_NAME+indx), &sValue, (DWORD)sizeof(sValue), 0); CString m_sName = (CString)sValue; wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_sName.GetString())); m_sName = wsResult.c_str(); if(m_sName==L"") return false; if(m_sName.MakeLower() == sName.MakeLower()){ return true; } } return false; } void CCharacter::SaveMemberInvite() { CMarkup xml=serialize->OpenFile(); CString sName = L"Party"; xml.FindElem(); xml.IntoElem(); if(xml.FindElem(sName)){ xml.RemoveElem(); } if(m_vMemberParty.size()==0){ serialize->SaveFile(&xml); return; } xml.AddElem(sName); xml.IntoElem(); std::vector<CString>::iterator name_member; //INV_PARTY* objmem; for(name_member = m_vMemberParty.begin(); name_member != m_vMemberParty.end(); name_member++ ) { xml.AddElem(L"Member"); xml.AddAttrib(L"Role",name_member->Trim()); } serialize->SaveFile(&xml); } void CCharacter::LoadMemberParty() { CMarkup xml=serialize->OpenFile(); if(xml.GetDoc().GetLength()==0) return; //if(serialize->FindPath(L"/Info/ApplyMember", &xml)) // szNameMember = xml.GetElemContent(); if(serialize->FindPath(L"/Info/Party",&xml)){ m_vMemberParty.clear(); while(xml.FindElem()){//Đọc thông tin từng skill //INV_PARTY memCfg; CString memCfg = xml.GetAttrib(_T("Role")); m_vMemberParty.push_back(memCfg); } } } void CCharacter::AutoPartyCheck(byte check){ //0: uncheck đồng ý lời mời | 1: check đồng ý lời mời | 2: uncheck đồng ý đơn xin | 3: check đồng ý đơn xin ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_CHECK_AUTO_PARTY,check); } //=============Kết Thúc=================================== // // // // //void CCharacter::Recover(){ // if(m_bIsRiding)//Xuống ngựa // RideHorse(); // if(m_iState!=3) // ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_RECORVER,0); //} // // //void CCharacter::Quit(){ // ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_QUIT,0); //} // //bool CCharacter::MoveAway(){ // //Từ bỏ mục tiêu // if(m_iTargetIdx !=0){ // m_iTargetIdx = 0; // SetTarget(); // } // // if(!m_bIsRiding) // RideHorse(); // //Đang chạy thì không tìm tiếp // if(m_iState == 2) // return true; // // //Tìm đến 1 điểm trên map // xmlMap->ResetPos(); // if ( !xmlMap->FindElem(_T("Maps")) ) // return false; // if(xmlMap->IntoElem()){ // while(xmlMap->FindElem()){ // if(_tstoi(xmlMap->GetAttrib(_T("id")))==m_iCurMapId){ // if(xmlMap->IntoElem()){ // if(!xmlMap->FindElem(_T("NPC"))) // xmlMap->FindElem(_T("Door")); // //Convert map coor to screen coor // COOR _coor; // _coor._iX = _tstoi(xmlMap->GetAttrib(_T("x"))); // _coor._iY = _tstoi(xmlMap->GetAttrib(_T("y"))); // ConvertMapToScreen(&_coor); // if(GetDistance(_coor)>50)//call move function // MoveTo(_coor._iX,_coor._iY); // xmlMap->ResetPos(); // return true; // } // } // } // xmlMap->ResetPos(); // } // return false; //} //bool CCharacter::SearchNPC(){ // UINT nIndexMin=0; // int dZ,dMin=m_iRange; // m_npc->m_iIndex = 0; // for(int i=1;i<NPC_MAX_SIZE;i++){ // if(i==m_iIndex || i == iLag) // continue; // m_npc->m_iIndex = i; // dZ = GetDistance(); // if( m_npc->m_szName==L"" || m_npc->m_iType!=0){//Nếu không có NPC hoặc npc không phải quái thì bỏ qua // continue; // } // if (dZ < dMin && dZ != -1) { // dMin = dZ; // nIndexMin = i; // } // } // if(nIndexMin>0){ // m_npc->m_iIndex = nIndexMin; // m_iPeopleIdx = nIndexMin; // m_npc->GetInfo(); // iNpcHP = 0; // return true; // } // return false; //} // // // // // // // // //if(m_lMonsters.size()>0){//cập nhật bãi đánh quái // // int iDis = GetDistance(m_lMonsters[siCurMoster]); // // if(iDis<100){ // // siCurMoster++; // // if(siCurMoster >= m_lMonsters.size()) // // siCurMoster = 0; // // } // // if(!m_bPkOnMove){//Neu khong danh tren duong thi chi danh quanh diem // // COOR curPoint; // // if(siCurMoster>0) // // curPoint=(m_lMonsters[siCurMoster-1]); // // else // // curPoint=(m_lMonsters[m_lMonsters.size()-1]); // // if(GetDistance(curPoint)>m_iRangePoint){ // // m_iTargetIdx==0; // // SetTarget(); // // MoveToTarget(curPoint); // // return; // // } // // } // //} // // //Nếu không có target đang chọn hoặc bị lag thì tìm target mới // //// if(m_iTargetIdx==0 || IsLag()){ ////// bIsFighting = false; //// //// //m_npc = SearchNPC(); //// if(m_npc==NULL){//Nếu không tìm được target //// if(m_iState==2) //// return; //// //Nếu có nhiều bãi quái thì chuyển sang bãi mới //// if(m_lMonsters.size()>0 ){ //// if(siCurMoster >= m_lMonsters.size()) //// siCurMoster = 0; //// COOR nextMons = m_lMonsters[siCurMoster]; //// if(!m_bPkOnMove){//Không chọn đánh quái trên đường đi //// MoveToTarget(nextMons); //// } //// else{ //// MoveTo(nextMons._iX,nextMons._iY); //// } //// //// } //// return; //// } //// iNpcHP = 0; //// } //// //Kiểm tra điều kiện //// int iSelSkill=m_arrSelSkill[1]; //// //check skill delay //// if(CheckSkillDelay(true)){ //// iSelSkill=m_arrSelSkill[2]; //// if(CheckSkillDelay(false)) //// iSelSkill=m_arrSelSkill[3]; //// } //// //// if(iSelSkill!= m_iActiveSkill) //// SetSkill(iSelSkill); //// //// m_npc->GetInfo(); //// COOR coor; //// coor._iX = m_npc->m_iTdX; //// coor._iY = m_npc->m_iTdY; //// if(m_iRangeFight < GetDistance(coor)){//Nếu đang đánh thì kiểm tra tầm đánh //// if(m_iState!=2) //// MoveTo(); //// } //// else { //// if(m_bIsRiding && m_bAutoRide)//tự động xuống ngựa khi đánh //// RideHorse(); //// m_iTargetIdx = m_npc->m_iIndex; //// SetTarget(); //// } //} // //bool CCharacter::CheckSkillDelay(bool iOnLeft){ // byte delay; // DWORD dwAddress = dwGameBaseAddress + GAME_OFFSET_SKILL; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // for(int i=0;i<24;i++){ // if(i==16) // dwAddress = dwAddress + GAME_OFFSET_SKILL_2; // else // dwAddress = dwAddress + GAME_OFFSET_SKILL_1; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // } // dwAddress = dwAddress + GAME_OFFSET_SKILL_2; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // dwAddress = dwAddress + GAME_OFFSET_SKILL_3; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // dwAddress = dwAddress + GAME_OFFSET_SKILL_4; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // dwAddress = dwAddress + GAME_OFFSET_SKILL_5; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // dwAddress = dwAddress + GAME_OFFSET_SKILL_6; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); // dwAddress = dwAddress + GAME_OFFSET_SKILL_7; // if(iOnLeft) // dwAddress = dwAddress - GAME_OFFSET_SKILL_8; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &delay, (DWORD)sizeof(delay), 0); // // return (delay>0 && delay <59); //} //bool CCharacter::IsMoving(){ // if(!bIsRunning) // return false; // if(GetDistance(cTarget)<50){ // bIsRunning = false; // return false; // } // return true; //} // //bool CCharacter::IsClick(){ // //lấy tọa độ click chuột so sánh với tọa độ cũ. // COOR cCurMouse; // //Get coor X // DWORD dwAddress = dwGameBaseAddress + GAME_OFFSET_MOUSE_X; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &cCurMouse._iX, (DWORD)sizeof(cCurMouse._iX), 0); // //Get coor Y // dwAddress = dwGameBaseAddress + GAME_OFFSET_MOUSE_Y; // ReadProcessMemory(m_hHandle, (void*)dwAddress, &cCurMouse._iY, (DWORD)sizeof(cCurMouse._iY), 0); // // if(cCurMouse._iX != cLastClick._iX || cCurMouse._iY != cLastClick._iY ) // { // if(!bIsClick){ // bIsClick=true; // Sleep(100); // return true; // } // if(m_iState==3||m_iState==1 && bIsClick){ // cLastClick = cCurMouse; // bIsClick = false; // } // return true; // } // return false; //} // //bool CCharacter::SearchItem(){ // CItem* item; // for(int i=1;i<ITEM_MAX_SIZE;i++){ // item = new CItem(m_hHandle,i); // item->GetInfo(); // if(item->m_szName!=L""){ // m_iItemIdx = i; // PickItem(); // } // delete item; // item=NULL; // } // return true; //} // // // //bool CCharacter::CheckHotKey(byte shcutKey){ // byte byHotKey; // DWORD dwshortcut = dwShortcutBaseAddress + KEY_SHORTCUT_SIZE * (shcutKey-1); // ReadProcessMemory(m_hHandle, (void*)dwshortcut, &byHotKey, (DWORD)sizeof(byHotKey), 0); // return byHotKey; //} ////Tự bom máu //void CCharacter::BuffHP(){ // if(!CheckHotKey(m_iKeyHP)) // return; // if(m_iKeyHP==-1) // return; // WPARAM key = 0x30 + m_iKeyHP; // ::PostMessage(m_hwnd, WM_KEYDOWN, key, 1); //} // //void CCharacter::BuffMP(){ // if(!CheckHotKey(m_iKeyMP)) // return; // if(m_iKeyMP==-1) // return; // WPARAM key = 0x30 + m_iKeyMP; // ::PostMessage(m_hwnd, WM_KEYDOWN, key, 1); //} // // //void CCharacter::PickItem(){ // DWORD dwPlayerInfo = dwGameBaseAddress + PLAYER_ITEM_TARGET; // WriteProcessMemory(m_hHandle, (LPVOID*)dwPlayerInfo, &m_iItemIdx, sizeof(m_iItemIdx), 0); //} // // //======================Van Tieu======================== //void CCharacter::GetLocation(){ // DWORD dwPlayerName = dwGameBaseAddress + QUEST_BASE_ADDRESS; // ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); // for(int i = 0; i < 32; i++) // { // if(i == 26 || i == 27) // { // dwPlayerName = dwPlayerName + GAME_MENU_OFFSET_2; // ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); // } // else{ // dwPlayerName = dwPlayerName + GAME_MENU_OFFSET_1; // ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); // // } // } // dwPlayerName = dwPlayerName + OFFSET_NAME_PARTY; // ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); // //ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &dwPlayerName, (DWORD)sizeof(dwPlayerName), 0); // // char sValue[SIZE_TEXT]; // char sMember[SIZE_TEXT]; // memset(sValue, 0x0, sizeof(sValue)); //// memset(sMember, 0x0, sizeof(sMember)); // ReadProcessMemory(m_hHandle, (void*)dwPlayerName, &sValue, (DWORD)sizeof(sValue), 0); // // //TachChuoi(sMember,sValue,'>','<'); // // m_szLocation = (CString)sValue; // // //string converStr( ); // wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( m_szLocation.GetString() )); // m_szLocation = wsResult.c_str(); // // //} bool CCharacter::ClickRecived(){ Sleep(200); bool LResult= (bool)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_CHOOSE_ADWARD,0); return LResult; } int CCharacter::TotalLineMenu() { int total; DWORD base = dwGameBaseAddress + MENU_BASE_ADDRESS; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); if(base == NULL) return 0; for(int i = 0; i<47; i++) { base = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); if(base == 0) return 0; } DWORD base47 = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base47, &base47, (DWORD)sizeof(base47), 0); DWORD base48 = base47 + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base48, &base48, (DWORD)sizeof(base48), 0); DWORD base49 = NULL; if(base48 != NULL) { base49 = base48 + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base49, &base49, (DWORD)sizeof(base49), 0); } //if(bMenuSel && m_iOS==6164)//21040510 //{ // base = base + GAME_MENU_OFFSET_1; // ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); //} //bMenuSel=!bMenuSel; if(base49 != NULL) { base = base49 + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); } else if(base48 != NULL) { base = base48 + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); } else if(base47 != NULL) { base = base47 + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); } base = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); base = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); base = base + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); base = base + GAME_MENU_OFFSET_2; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); base = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); base = base + GAME_MENU_OFFSET_1; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); base = base + GAME_MENU_TOTAL_LINE; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); total = (int)base; return total; } int CCharacter::GetNPCInfo(CString szname) { //==========NghiaLP====20141604====Van tieu //Get name Ton Hieu(thong tin nguoi van tieu) DWORD base = dwGameBaseAddress + GAME_OFFSET_INFO; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); DWORD dwnameHorse = base; for(int i=1;i<NPC_MAX_SIZE;i++) { base = dwnameHorse + GAME_OFFSET_DATASIZE * i; ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); DWORD dwInf = base; base = base + NPC_NAMESTATE; char sValue[SIZE_TEXT]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)base, &sValue, (DWORD)sizeof(sValue), 0); CString szTonHieu = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( szTonHieu.GetString() )); szTonHieu = wsResult.c_str(); if(szname == szTonHieu) { m_iTargetIdx = i; m_npc->m_iIndex = i; m_npc->GetInfo(); m_cHorse.m_sName = szTonHieu; // name m_cHorse.m_iCurMap = m_iCurMapId; //Map DWORD dwX = dwInf + NPC_COOR_X; ReadProcessMemory(m_hHandle, (void*)dwX, &dwX, (DWORD)sizeof(dwX), 0); m_cHorse.m_iCurX = (int)dwX; //toa do X DWORD dwY = dwInf + NPC_COOR_Y; ReadProcessMemory(m_hHandle, (void*)dwY, &dwY, (DWORD)sizeof(dwY), 0); m_cHorse.m_iCurY = (int)dwY; //toa do Y //m_iBackHorse_MapID = m_iCurMapId; m_iBackHorse_X = m_cHorse.m_iCurX; m_iBackHorse_Y = m_cHorse.m_iCurY; return i; } } return 0; } //int CCharacter::Attacked(int TagetHorse) //{ // DWORD base = dwGameBaseAddress + GAME_OFFSET_INFO; // ReadProcessMemory(m_hHandle, (void*)dwGameBaseAddress, &base, (DWORD)sizeof(base), 0); // DWORD dwAtt = base; // int ack; // for(int i=1;i<NPC_MAX_SIZE;i++) // { // base = dwAtt + GAME_OFFSET_DATASIZE * i; // ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); // base = base + NPC_PK_TARGET; // ReadProcessMemory(m_hHandle, (void*)base, &base, (DWORD)sizeof(base), 0); // // ack = (int)base; // if(ack == TagetHorse) // return i; // } // return 0; //} void CCharacter::GotoHorse() { ////từ bỏ mục tiêu //m_iTargetIdx=0; //SetTarget(); ////Lấy thông tin đội trưởng CString szname = L"Do <color=yellow>" + m_szName + L"<color> áp tải"; int targetHorse = GetNPCInfo(szname); if(m_iBackHorse_MapID != m_iCurMapId){//không cùng map với tieu if(FindingAWay(m_iBackHorse_MapID, m_iBackHorse_X ,m_iBackHorse_Y)) return; } COOR dist; if(m_iBackHorse_X != 0 && m_iBackHorse_Y!= 0) { dist._iX = m_iBackHorse_X; dist._iY = m_iBackHorse_Y; if(GetDistance(dist) > 800) { MoveTo(m_iBackHorse_X,m_iBackHorse_Y); return; } } if(targetHorse ==0){ CString str = FindNPC(L"trạm "); if(str != L"") //Tim thay dich tram { if(AskNPC(str,true)==1) { Sleep(200); if(!ChooseMenu(0)) return; } else return; //MoveTo(m_iBackHorse_X,m_iBackHorse_Y); } /*else m_iCurEscort = 1; return;*/ } COOR coor; coor._iX =m_cHorse.m_iCurX; coor._iY = m_cHorse.m_iCurY; /*if(!m_bIsRiding && m_bAutoRide) RideHorse();*/ //m_iTargetIdx = GetNPCInfo(L"Cướp Tiêu"); int LResult = (int)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_OPEN_MENU,0); if(LResult == 1) ChooseMenu(-1); if(GetNPCInfo(L"Cướp Tiêu") == 0) // { if(GetDistance(coor)<m_iDistance) return; MoveTo(coor._iX,coor._iY); } else DoFight(); } bool CCharacter::ReceiveEscort(){ /*if(CheckFinishQuest(L"vận tiêu(0)")) { ShowMessage(L"Da Van Tieu Xong!!!!!"); return false; }*/ /*if(m_iCurMapId == 77) MoveTo(51555,103036);*/ if(m_iCurEscort<0 || !m_bEscort) return false; if((m_iCurEscort == 3 ||m_iCurEscort == 5) && m_bReciveAdward == false)//Đã nhận nhiệm vụ, tra nhiem vu return true; if(m_iCurEscort==0 || m_iCurEscort ==1) { CString strText = GetQuestText(L"<pic=58><color=yellow>Vận Tiêu"); if(strText!=L"") { GetLinkPos(strText); //lay doan link if(m_iCurEscort==1) // { if(m_iProsessType == 1) { m_iCurEscort = 4; return false; } } else if(m_iBackHorse_MapID != m_iCurMapId || m_iCurMapId != cTarget._iMapId) { if(m_iProsessType == 2) { //Toi nguoi UY thac m_iCurEscort=3; // Dang lam NV(dang ho tong) return true; //// goBack=true; }else if(m_iProsessType == 3) { m_iCurEscort = 5; //Giao nhiem vu return true; } else m_iCurEscort = 4; //O trong thanh nhan NV } else if(m_iProsessType == 3 && m_bReciveAdward == true) { //da giao NV m_iCurEscort=1; m_bReciveAdward == false; //return true; } else { m_iCurEscort = 3; m_bReciveAdward == false; return true; } } else m_iCurEscort = 1; } if(m_iCurEscort == 3 || m_iCurEscort == 5) { m_bReciveAdward = false; return false; } if(AskNPC(L"Thẩm Chấn Uy", false)==1) { if(m_iCurEscort == 1) { Sleep(800); if(!ChooseMenu(3)) return false; else m_iCurEscort = 4; if(TotalLineMenu() > 3) if(!ChooseMenu(3)) return false; Sleep(500); //AutoChat(L"Đã nhận nhiệm vụ vận tiêu"); m_bReciveAdward = false; if(ChooseMenu(1)) { //da nhan NV (chua giao NV) Sleep(1000); m_iCurEscort = 3; m_bReciveAdward == false; return true; } m_iCurEscort = 4; } if(m_iCurEscort == 4) { //Duy Chuyen toi nguoi uy thac Sleep(200); m_bReciveAdward == false; if(TotalLineMenu() == 1) { ClickOnLink(); m_bReciveAdward == false; m_iCurEscort=3; } else if(ChooseMenu(1)) { Sleep(1000); m_bReciveAdward == false; m_iCurEscort=3; return true; } //else //{ // //m_iCurQuest = 1; // return true; //} } } return false; } bool CCharacter::ProcessEscort(){ if(m_iCurEscort>3) return true; CString szQuestText = GetQuestText(L"<pic=58><color=yellow>Vận Tiêu"); CString szNameMap = GetNameMap(szQuestText); switch(m_iCurEscort){ //case 1: // //lấy text mô tả // Sleep(500); // if(szQuestText!=L"") // { // if(GetLinkPos(szQuestText)){ // if(ChooseMenu(1)==false){ // m_bReciveAdward == false; // m_iCurEscort = 2; // return false; // } // else // { // m_bReciveAdward == false; // m_iCurEscort = 3; // return true; // } // } // } // return false; //case 2://di chuyen // if(GetLinkPos(szQuestText)) // { // if(FindingAWay(cTarget._iMapId, cTarget._iX ,cTarget._iY)) // return false; // m_iCurEscort = 3; // m_bReciveAdward = false; // } // break; case 3://xử lý //GetLocation(); GetLinkPos(szQuestText); //lay trang thai m_iProsessType switch(m_iProsessType){ case 1: //if(AskNPC(L"Ủy thác " + m_szLocation)==0){ /*if(AskNPC(FindNPC(L"ủy thác"),true)==1 || AskNPC(FindNPC(L"Ủy thác"),true)==1 || AskNPC(FindNPC(L"Người ủy thác"),true)==1)*/ if(m_iBackHorse_MapID == m_iCurMapId) //Neu dung cung map { if(AskNPC(FindNPC(L"ủy thác"),true)==1) { Sleep(200); // ChooseMenu(0); if(ChooseMenu(0)) { //chưa đóng được menu GetLinkPos(L"<pic=58><color=yellow>Vận Tiêu");//m_iCurQuest = 4; //khong chon duoc chay ve thành //return true; } else { //m_iCurQuest = 3; return false; } } } break; case 2: GotoHorse(); break; } szQuestText = GetQuestText(L"<pic=58><color=yellow>Vận Tiêu"); if(szQuestText!=L""){ if(szQuestText.Find(L"Tổng Tiêu Đầu")!=-1){ m_iCurEscort = 5; return true; } /*else{ GetLinkPos(szQuestText); if(GetDistance(cTarget)>1000){ if (FindingAWay(cTarget._iMapId, cTarget._iX ,cTarget._iY)) m_iCurQuest = 2; }*/ //} } break; } return false; } bool CCharacter::ReceiveAward() { //AutoChat(L"Xong nhiệm vụ rồi! đi nhận thưởng thôi!"); CString szQuestText = GetQuestText(L"<pic=58><color=yellow>Vận Tiêu"); int menu =-1; if(szQuestText!=L""){ GetLinkPos(szQuestText); if(m_iCurEscort == 5 && m_bReciveAdward == false){ int menu = AskNPC(L"Thẩm Chấn Uy", true); if(menu==1) { Sleep(1000); /*if(TotalLineMenu() > 3) { m_bReciveAdward = true; m_iCurEscort = 1; }*/ if(!ChooseMenu(1)) return false; } Sleep(500); if(!ClickRecived()) return false; else{ m_bReciveAdward = true; m_iCurEscort = 1; m_iBackHorse_MapID = 0; } return true; //// ChooseMenu(1); //ChooseMenu(1); // m_iCurQuest == 0; // } } } return false; } /////////////////Van Tieu- 20140423============== CString CCharacter::FindNPC(CString szName) { CNPC npc(m_hHandle,dwGameBaseAddress); for(int i=1;i<NPC_MAX_SIZE;i++){ if(i==m_iIndex)//bỏ qua nhân vật continue; npc.m_iIndex = i; npc.GetInfo(); //CString szStr1 = ConvertLower(L"HỦ VỒ Ắ Ậ Ẩ"); CString szStr = ConvertLower(npc.m_szName); if( npc.m_szName==L"")//Không tìm thấy target bỏ qua continue; if( npc.m_iType!=3)//không phải NPC bỏ qua continue; if(szStr.Find(szName)!=-1){//lấy NPC cTarget._iMapId = m_iCurMapId; cTarget._iX = npc.m_iTdX; cTarget._iY = npc.m_iTdY; return npc.m_szName; } } return L""; } CString CCharacter::GetNameMap(CString szname) { CMarkup xmlMap; xmlMap = XMLSerialized::OpenFile(L"Map.cfg"); if(xmlMap.GetDoc().GetLength()==0) return false; xmlMap.ResetPos(); if (!xmlMap.FindElem(_T("Maps"))) return false; if(xmlMap.IntoElem()){ while(xmlMap.FindElem()){ if(szname.Find(xmlMap.GetAttrib(_T("name")))!=-1){ m_iBackHorse_MapID = _tstoi(xmlMap.GetAttrib(_T("id"))); return xmlMap.GetAttrib(_T("name")); } } } return L""; } //=============Kết Thúc=================================== CString CCharacter::ConvertLower(CString szName) { wstring str = (wstring)szName; string sResult =XMLSerialized::UnicodeToUTF8(str); //string sResult = (string)szName; char sValue[SIZE_TEXT]; for(int i = 0; i < sResult.length() ; i++) { sValue[i] = (char)(LPCTSTR)sResult[i]; } sValue[sResult.length()] ='\0'; for(int i = 0; i <= sResult.length(); ) { if((byte)sValue[i] >= 65 && (byte)sValue[i] <= 90) { sValue[i] = sValue[i] + 32; i++; } else if((byte)sValue[i] == 0xC3) { i++; if((byte)sValue[i] >= 0x80 && (byte)sValue[i] <= 0x9F) { sValue[i] = sValue[i] + 32; i++; } } else if((byte)sValue[i] == 0xE1) { i = i+2; if((byte)sValue[i] %2 ==0) { sValue[i] = sValue[i] + 1; i++; } } else if((byte)sValue[i] == 0xC4) { i++; if((byte)sValue[i] == 0x82 || (byte)sValue[i] == 0xA8) { sValue[i] = sValue[i] + 1; i++; } } else if((byte)sValue[i] == 0xC5) { i++; if((byte)sValue[i] == 0xA8) { sValue[i] = sValue[i] + 1; i++; } } else if((byte)sValue[i] == 0xC6) { i++; if((byte)sValue[i] == 0xA0 || (byte)sValue[i] == 0xAF) { sValue[i] = sValue[i] + 1; i++; } } else i++; } CString szStr = (CString)sValue; //string converStr( ); wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( szStr.GetString() )); szStr = wsResult.c_str(); return szStr; } ////////////SangDH--20140602--Fix lỗi dùng hồi thành thạch khi làm nhiệm vụ đánh quái // --Fix lỗi tìm đánh đúng quái khi làm nhiệm vụ //Get Beaten target int CCharacter::GetHitMeTarget(){ //Get player Info address DWORD dwAddress = dwGameBaseAddress + GAME_OFFSET_INFO; ReadProcessMemory(m_hHandle, (void*)dwAddress, &dwAddress, (DWORD)sizeof(dwAddress), 0); CNPC npc(m_hHandle,dwGameBaseAddress); int iTarget =0; for(int i=1;i<NPC_MAX_SIZE;i++){ if(i==m_iIndex) continue; DWORD dwTempAddress = dwAddress + GAME_OFFSET_DATASIZE * i; ReadProcessMemory(m_hHandle, (void*)dwTempAddress, &dwTempAddress, (DWORD)sizeof(dwTempAddress), 0); // Get target PK Index dwTempAddress = dwTempAddress + NPC_PK_TARGET; ReadProcessMemory(m_hHandle, (void*)dwTempAddress, &iTarget, (DWORD)sizeof(iTarget), 0); if(iTarget==m_iIndex) return iTarget; } return 0; } int CCharacter::SearchNPCByName(CString sName){ CNPC npc(m_hHandle,dwGameBaseAddress); COOR coor; int idZ,iIndex=0,iMin=0; for(int i=1;i<NPC_MAX_SIZE;i++){ if(i==m_iIndex)//bỏ qua nhân vật continue; npc.m_iIndex = i; npc.GetInfo(); if( npc.m_szName==L"")//Không tìm thấy target bỏ qua continue; if( npc.m_iType ==1)//bỏ qua người chơi continue; if(sName.Find(L"Thủ Lĩnh")!=-1 && npc.m_szName.Find(L"Thủ Lĩnh")==-1){ continue; } if(npc.m_szName.Find(L"Thủ Lĩnh")!=-1 && sName.Find(L"Thủ Lĩnh")==-1){ continue; } if(CompareString(sName,npc.m_szName) >=50){//lấy NPC //Tìm theo khoảng cách coor._iX = npc.m_iTdX; coor._iY = npc.m_iTdY; idZ = GetDistance(coor); if(idZ<= iMin || iMin==0){ iMin = idZ; iIndex = i; } } } return iIndex; } int CCharacter::CompareString(CString sStr1,CString sStr2, bool exact/*=false*/){ int iCount = 0; int iTotal = 0; CString curWord=L""; CString curLetter=L""; CString strCompare = ConvertLower(sStr1); CString strCompare1 = ConvertLower(sStr2); /*if(strCompare.GetLength() > strCompare1.GetLength()){ strCompare = sStr2; strCompare1 = sStr1; } strCompare = ConvertLower(strCompare); strCompare1 = ConvertLower(strCompare1);*/ int length = strCompare.GetLength(); for(int i=0;i<length;i++){ curLetter = strCompare.GetAt(i); if(curWord!=L"" && (curLetter==L"·" ||curLetter==L" " || i == length-1)){ if(strCompare1.Find(curWord)!=-1) iCount++; iTotal++; curWord = L""; }else{ curWord = curWord + curLetter; } } return iCount*100/iTotal; } //////////////////NghiaLP-20140604---Dieu Doi/////////////////////// bool CCharacter::OpenDialogQuest() { bool LResuft = ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_OPEN_QUEST,0); return LResuft; } bool CCharacter::ChooseQuest(int indx) { Sleep(200); bool LResuft = ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_CHOOSE_QUEST,indx); return LResuft; } bool CCharacter::SendTeamDoQuest() { if(IsInterval(6,4)) return false; if(m_iCurMapId == 77 && GetBaseText(-1) != m_szName) //Neu dang o gia vien nguoi khac { MoveTo(51555,103036); } if(m_iCurMapId == 77 && GetBaseText(-1) == m_szName) { if(GetBaseText(24).Find(L"Đang điều động") == -1 || GetNameParty() == L"Ngọc Nhi") { if(OpenDialogQuest()) { if(GetBaseText(24).Find(L"Đang rảnh") != -1) { SendTeamGoTo(); } else if(GetBaseText(24).Find(L"Đã điều động") != -1 || GetNameParty() == L"Ngọc Nhi") { ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_AGREE_PARTY,1); return ChooseQuest(-1); } } } if(GetBaseText(24).Find(L"Đang điều động") != -1) { ChooseQuest(-3); //Tat cua so dieu doi m_bWaiting = true; return false; } } else { if(GetBaseText(24).Find(L"Đang điều động") == -1 || GetNameParty() == L"Ngọc Nhi") { int menu = AskNPC(L"Nghiêm Nhiếp Ảnh"); if(menu!=1) { return false; } if(!ChooseMenu(3)) {//vào Gia Viên return false; } } } return false; } CString CCharacter::GetBaseText(int indx) { DWORD dwbase = ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_TEXT_QUEST,indx); char sValue[SIZE_TEXT]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwbase, &sValue, (DWORD)sizeof(sValue), 0); CString sName = (CString)sValue; /*int iStartIndx = m_sName.Find(L">")+1; int iEndIndx = m_sName.Find(L"<",iStartIndx); m_sName=m_sName.Mid(iStartIndx,iEndIndx-iStartIndx);*/ wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( sName.GetString() )); sName = wsResult.c_str(); return sName; } int CCharacter::ConvertToInt(int indx) { if(indx == 0) { CString szHealt = GetBaseText(indx); //int iStartIndx = m_sName.Find(L">")+1; int iEndIndx = szHealt.Find(L"/",0); szHealt=szHealt.Mid(0,iEndIndx); int iHealt = _ttoi(szHealt); return iHealt; } else { CString szCount = GetBaseText(indx); int iCount = _ttoi(szCount); return iCount; } } ////////================20140609===================== bool CCharacter::SendTeamGoTo() { if(m_bBC && ConvertToInt(13)!=0 && ConvertToInt(0) > 60) //Neu check bi canh { int LResult= (int)::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_OPEN_MENU,0); if(LResult == 1) { if(ChooseMenu(3-m_iKindBC)) { Sleep(2000); return true; } } else if(ChooseQuest(0)){ //Chon nv bi canh if(ChooseQuest(-1)) //nhan Nut Phai { if(LResult == 1) if(ChooseMenu(3-m_iKindBC)) { Sleep(2000); return true; } return false; } } } else if(m_bTVP && ConvertToInt(10)!=0 && ConvertToInt(0) > 60) { if(ChooseQuest(1)) //Chon nv bi canh if(ChooseQuest(-1)) //nhan Nut Phai if(ChooseQuest(-2)) { Sleep(2000); return true; } return false; } else if(m_bVT && ConvertToInt(5)!=0 && ConvertToInt(0) > 30) { if(ChooseQuest(2)) //Chon nv bi canh if(ChooseQuest(-1)) //nhan Nut Phai if(ChooseQuest(-2)) { Sleep(2000); return true; } return false; } else if(m_bTN && ConvertToInt(4)!=0 && ConvertToInt(0) > 20) { if(ChooseQuest(3)) //Chon nv bi canh if(ChooseQuest(-1)) //nhan Nut Phai if(ChooseQuest(-2)) { Sleep(2000); return true; } return false; } else if(m_bTVPhai && ConvertToInt(1)!=0 && ConvertToInt(0) > 60) { if(m_iLevel < 100) { if(ChooseQuest(4)) //Chon nv bi canh if(ChooseQuest(-1)) //nhan Nut Phai if(ChooseQuest(-2)) { Sleep(2000); return true; } return false; } // else ////Cap ban khong phu hop } return false; } //==========NghiaLP======UU tieu Nhiem Vu=== void CCharacter::PriorityQuest() { GetDoQuest(); switch(m_iQuesting){ case 1: SendTeamDoQuest(); break; case 2: if(ReceiveEscort()){ //===========Van Tieu============== if(ProcessEscort()) ReceiveAward(); } break; case 3: if(m_iCurMapId == 77) MoveTo(51555,103036); else if(ReceiveQuest()) ProcessQuest(); break; } //if(m_iQuesting == 1) // //else if(m_iQuesting == 2) //{ // if(ReceiveEscort()){ //===========Van Tieu============== // if(ProcessEscort()) // ReceiveAward(); // } //} //else if(m_iQuesting==3){ // if(m_iCurMapId == 77) // MoveTo(51555,103036); // if(ReceiveQuest()) // ProcessQuest(); //} } void CCharacter::GetDoQuest() { //SendTeamDoQuest(); //bool bTrue = CheckFinishQuest(L"cầu phúc(0)"); if(m_bReciveAdward || m_iCurQuest ==0 || m_iCurQuest==6) {//Da Nhan thuong NV van tieu if(GetNameParty() == L"Ngọc Nhi"){ //Da dieu doi xong m_bWaiting = false; } } if(m_bSendTeamDoQuest && !m_bWaiting){ //check NV dieu doi va KHong phai trang thai dang cho hoac da nhan thuong Van tieu m_iQuesting = 1; return; } //SendTeamDoQuest(); if(m_bWaiting || !m_bSendTeamDoQuest) //Dang cho dieu doi hoac ko check dieu doi { if(m_iCurMapId == 77) //Neu dang o gia vien thi di ra ngoai lam nv khac { MoveTo(51555,103036); } if(m_bEscort) { //if(!CheckFinishQuest(L"vận tiêu(0)")) //{ m_iQuesting = 2; //} /*else if(m_bAutoQuest) { m_iQuesting = 3; }*/ } else if(m_bAutoQuest) { /*if(!CheckFinishQuest(L"lịch luyện(0)")) {*/ m_iQuesting = 3; //} } else m_iQuesting = 0; } } bool CCharacter::CheckFinishQuest(CString szText) { for(int indx = 1; indx < 30; indx++) { DWORD dwbase = ::SendMessage(m_hwnd , WM_HOOK_WRITE,MSG_CHECK_FINISH,indx); char sValue[SIZE_TEXT]; memset(sValue, 0x0, sizeof(sValue)); ReadProcessMemory(m_hHandle, (void*)dwbase, &sValue, (DWORD)sizeof(sValue), 0); CString sName = (CString)sValue; wstring wsResult =XMLSerialized::UTF8ToUnicode( (string)CW2A( sName.GetString() )); sName = ConvertLower(wsResult.c_str()); if(sName == szText) { //ShowMessage(L"Nhiem vu hoan thanh"); return true; } } return false; } //---20140612--SangDH-- CString CCharacter::ConvertString(CString str){ wstring wsResult = XMLSerialized::UTF8ToUnicode( (string)CW2A( str.GetString())); return (CString) wsResult.c_str(); } bool CCharacter::IsInterval(int ID,int iDelay){ time_t timer; time(&timer); TIMER::iterator result = m_mDelay.find(ID); if(result==m_mDelay.end()){ m_mDelay.insert(make_pair(ID,timer)); return false; } double seconds; seconds = difftime(timer,m_mDelay[ID]); if(seconds<iDelay) return true; m_mDelay[ID]=timer; return false; } void CCharacter::RemoveInterval(int ID){ m_mDelay.erase(ID); }
0274e0828fb384cb13af2f41cd70fd80f581cdab
535e4f723b1a7ee6e7ba8799d9eb862c54abf005
/Classes/RollingBall.cpp
7ab12fbd5d5fc98a47de549158ba0f7e99d16029
[]
no_license
jypeitao/DemoRollingBall
f7823bb128e7ab4019f2e3d8cf05241e78e3eb99
dadcf1278aef517059d46a281fa202230a8f976a
refs/heads/master
2020-06-03T14:17:56.243894
2014-01-13T17:17:55
2014-01-13T17:17:55
16,061,300
1
2
null
null
null
null
UTF-8
C++
false
false
5,027
cpp
RollingBall.cpp
// // RollingBall.cpp // RollingBall // // Created by cocos on 14-1-13. // // #include "RollingBall.h" RollingBall::RollingBall(){} RollingBall::~RollingBall(){} Scene* RollingBall::createScene() { auto scene = Scene::createWithPhysics(); Size visibleSize = Director::getInstance()->getVisibleSize(); //choose whitch part need to draw, Joint, Shape, Contact, None or All scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); // the edge of the screen auto body = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); auto edgeNode = Node::create(); edgeNode->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); edgeNode->setPhysicsBody(body); scene->addChild(edgeNode); auto layer = RollingBall::create(); layer->setPhyWorld(scene->getPhysicsWorld()); scene->addChild(layer); //open the gravity sensor layer->setAccelerometerEnabled(true); return scene; } bool RollingBall::init() { if ( !Layer::init() ) { return false; } //the layout of the physics world demoLayout(); //turn on or off the debug draw toggleOfDebugDraw(); //collision detection physicsContact(); return true; } void RollingBall::physicsContact(){ auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_2(RollingBall::onContactCallBack, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); } void RollingBall::toggleOfDebugDraw(){ Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); auto toggleItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(RollingBall::btnDebugDrawCallback, this)); toggleItem->setPosition(Point(origin.x + visibleSize.width - toggleItem->getContentSize().width/2 , origin.y + toggleItem->getContentSize().height/2)); auto menu = Menu::create(toggleItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 1); } bool RollingBall::onContactCallBack(EventCustom *event, const PhysicsContact& contact) { auto sp = (Sprite*)contact.getShapeA()->getBody()->getNode(); int tag = sp->getTag(); log("onContactBegin: %d", tag); return true; } void RollingBall::demoLayout(){ Size visibleSize = Director::getInstance()->getVisibleSize(); Point verts1[] = { Point(-146.5f, 155.1f), Point(-146.5f, -87.6f), Point(-140.9f, -88.1f), Point(-140.8f, 155.5f), Point(162.8f, 154.6f), Point(162.9f, -27.7f), Point(12.0f, -29.0f), Point(12.0f, -33.9f), Point(167.6f, -34.6f), Point(168.7f, 154.4f), Point(235.0f, 155.1f), Point(235.3f, -91.6f), Point(238.8f, -93.2f), Point(239.8f, -91.5f), Point(239.1f, 159.2f), Point(-238.3f, 159.0f), Point(-238.7f, 155.0f), Point(-147.4f, 154.9f) }; Point verts2[] = { Point(-235.8f, 82.9f), Point(-235.2f, -154.1f), Point(-44.2f, -154.1f), Point(-44.3f, 98.6f), Point(101.1f, 99.6f), Point(101.1f, 95.5f), Point(-38.2f, 93.5f), Point(-38.8f, -153.6f), Point(161.7f, -154.2f), Point(161.7f, -97.9f), Point(12.0f, -98.3f), Point(12.3f, -94.0f), Point(167.0f, -92.2f), Point(167.1f, -153.8f), Point(239.3f, -154.7f), Point(239.0f, -157.8f), Point(-239.0f, -158.4f), Point(-237.6f, 81.9f) }; auto spEdgePolygon1 = Sprite::create("bg1.png"); spEdgePolygon1->setTag(1); auto borderUpper = PhysicsBody::createEdgePolygon(verts1,18); spEdgePolygon1->setPhysicsBody(borderUpper); spEdgePolygon1->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); this->addChild(spEdgePolygon1); auto spEdgePolygon2 = Node::create(); spEdgePolygon2->setTag(2); auto borderBottom = PhysicsBody::createEdgePolygon(verts2,18); spEdgePolygon2->setPhysicsBody(borderBottom); spEdgePolygon2->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); this->addChild(spEdgePolygon2); auto spBall = Sprite::create("ball.png"); spBall->setTag(0); auto body = PhysicsBody::createCircle(spBall->getContentSize().width / 2); spBall->setPhysicsBody(body); spBall->setPosition(Point(visibleSize.width/2,visibleSize.height-50)); this->addChild(spBall); } void RollingBall::btnDebugDrawCallback(Object* pSender) { if(_world->getDebugDrawMask() != PhysicsWorld::DEBUGDRAW_NONE) { _world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_NONE); } else { _world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); } }
92d9b3f360794a22efce5cc864c74b35e80bda81
b25bc563dbb37a12244d2375c5816de9231c6c63
/PowerPlant/Support Classes/LSIOUXAttachment.h
dd6b62f414d65c67cb72fb2e981cc8d203df5e0a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "ISC" ]
permissive
mattgallagher/Mines
cae97a293bea9431c173b62fbc6a7115bfa4828d
cb159c358b12787dca9b8328d7f6083f07377b52
refs/heads/master
2021-01-13T13:00:09.404274
2018-10-24T12:15:04
2018-10-24T12:15:04
78,709,769
28
3
null
null
null
null
WINDOWS-1252
C++
false
false
920
h
LSIOUXAttachment.h
// Copyright ©2005, 2006 Freescale Semiconductor, Inc. // Please see the License for the specific language governing rights and // limitations under the License. // =========================================================================== // LSIOUXAttachment.h PowerPlant 2.2.2 ©1995-2005 Metrowerks Inc. // =========================================================================== #ifndef _H_LSIOUXAttachment #define _H_LSIOUXAttachment #pragma once #include <LAttachment.h> #if PP_Uses_Pragma_Import #pragma import on #endif PP_Begin_Namespace_PowerPlant // --------------------------------------------------------------------------- class LSIOUXAttachment : public LAttachment { public: LSIOUXAttachment(); protected: virtual void ExecuteSelf( MessageT inMessage, void* ioParam); }; PP_End_Namespace_PowerPlant #if PP_Uses_Pragma_Import #pragma import reset #endif #endif
2d38264f4b3c9e0bb59566142d2b01512d7b98c2
e61a42b3e8936dafdfa5776adec17682cb7d077b
/SpaceInvaders/particle.h
603aca4fbb2ea5888072316ce1a4ed360698235e
[]
no_license
mariofbreis/SpaceInvaders
f17cdd0616a0a1b1c1ac8af1afc80c2741799f45
d76d6766bcc4db09618034a47e6d4593cb445436
refs/heads/master
2022-11-07T22:31:59.275080
2020-07-06T04:25:44
2020-07-06T04:25:44
277,228,805
0
0
null
null
null
null
UTF-8
C++
false
false
737
h
particle.h
#ifndef PARTICLE_H #define PARTICLE_H #include "spaceinvaders.h" #include "position.h" #define frand() ((float)rand()/RAND_MAX) class Particle { float life; // life float fade; // fade float r, g, b; // colour float x, y, z; // position float vx, vy, vz; // speed float ax, ay, az; // aceleration public: Particle(int t, Position p); Particle( const Particle & another) { *this = another; } const Particle & operator = ( const Particle & another); const bool Update( const float elapsedTime); void Draw() const; const bool IsAlive() const { return life>0.f; } const bool IsDead() const { return life<=0.0f; } static unsigned int LoadTexture( const string & textureBitmapFilename); }; #endif
561fadea0a4b3324944f6baa42bd893e0d6075cd
5338cd4e316f9ba4b7993c3b4db1b514a4ac6d45
/cc/sqnumbf.cpp
d75e56ff21e9832a25d64e8ba7724e74f826e616
[]
no_license
exopeng/Competitive-Programming
5371ed2ee7b585b36cf232b5557ed30c50ce67de
5d28c21d3e5df5fe50a86ec6251dbc2b7018da61
refs/heads/main
2023-07-08T13:20:23.946747
2021-08-15T17:43:28
2021-08-15T17:43:28
396,431,776
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
cpp
sqnumbf.cpp
#include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define mp make_pair #define pb push_back #define lb lower_bound #define ub upper_bound #define f first #define ll long long #define s second #define pii pair<int,int> #define pdd pair<double,double> #define pll pair<ll,ll> #define is insert const long long INF = 1e9; const long long MOD = 1e9+7; const int MAXN = 2e5; //store test cases here /* */ ll gcd(ll a,ll b) { if(b==0) return a; return gcd(b,a%b); } ll a[MAXN]; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin>>t; //if gcd of all pairs=1, for each pair, check up to fourth root for(int i=0;i<t;i++){ int n; cin>>n; for(int j=0;j<n;j++){ cin>>a[j]; } ll as=1; for(int j=0;j<n;j++){ for(int f=j+1;f<n;f++){ as=max(as,gcd(a[j],a[f])); } } if(as==1){ for(int j=0;j<n;j++){ bool g=true; for(ll f=2;f*f<=a[j];f++){ if(a[j]%(f*f)==0){ as=f; g=false; break; } } if(!g){ break; } } } cout<<as<<"\n"; } return 0; }
fd99ac8ab52cd1c8c85b758cd7112d5cd8ff94bf
5bb9c12ad26d7b332f06f9ce91ecb504c42ba8fa
/shortest_repeating_substring.cpp
8077783f67cb1b6305dee246a62fcdf879b1a896
[]
no_license
nandish145/codeEval
4f95c2bf9816990ea25909579c1e76f47fffe999
da7e701db9da2c418046e6bd9c0717b5388a0a4f
refs/heads/master
2021-01-23T22:37:57.759932
2014-04-14T07:09:17
2014-04-14T07:09:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
shortest_repeating_substring.cpp
#include<iostream> #include<string> #include<fstream> using namespace std; /*shortest repeating substring*/ int shortest_repeating_substring(string str) { int compare_index; int pattern_end = 1; for(int j = 1; j< str.length();j++) { compare_index = j% pattern_end; if( str[compare_index] != str[j]) pattern_end = j+1; } return str.substr(0,pattern_end).length(); } int main(int argc,char* argv[]) { if( argc != 2) { cout<<"File name required as argument"<<endl; return -1; } fstream file; file.open(argv[1],ios::in); while(!file.eof()) { string str; getline(file,str); if(str.length() == 0) continue; cout<<shortest_repeating_substring(str)<<endl; } file.close(); return 0; }
f8330f3239211447744f67b66327737eb06b9c58
8a568dccf7bac68ea7e8a860089611a5d9831c97
/src/SwitchCase.cpp
ad566e4449e573954cf689862a0a2aef73209dfb
[]
no_license
lukeylad19/6502-Shared-Library-Emulator
c0301e4596ed13b856b52bb1d90e969d6102f90c
f56af1ee8836bb9c05eccb26ab580a665b35348a
refs/heads/master
2020-05-04T19:27:48.876542
2019-05-10T01:01:13
2019-05-10T01:01:13
179,394,871
1
1
null
null
null
null
UTF-8
C++
false
false
57,810
cpp
SwitchCase.cpp
#include <iostream> #include <string> #include "instruction.h" #include "M6502.h" //#include "opcode.h" //void execute(uint8_t); /*------------------------------------Addressing Helpers------------------------------------------*/ uint8_t M6502_core::read_zpg(){ //read using zero page addressing return M->read(0x0000+(M->read(++PC))); } uint8_t M6502_core::read_zpg(uint8_t index){ //read using indexed zero page addressing pass X or Y register return M->read(0x0000+(M->read(++PC))+index); } uint16_t M6502_core::read_rel(){ //read using relative addressing uint16_t tmp = PC+2; uint16_t m = M->read(++PC); m = m|((m&0x80 ? 0xFF:0x00)<<8); return tmp+m; } uint8_t M6502_core::read_abs(){ //read using absolute addressing uint8_t temp = M->read(M->readWord(++PC)); PC++; return temp; } uint8_t M6502_core::read_abs(uint8_t index){ //read using indexed absolute addressing pass X or Y register uint8_t temp = M->read(M->readWord(++PC)+index); PC++; return temp; } uint16_t M6502_core::read_ind(){ //read using indirect addressing, returns a word uint16_t temp = M->readWord(M->readWord(++PC)); PC++; return temp; } uint8_t M6502_core::read_ind_x(){ //read using X-Indexed Indirext addressing return M->read(M->readWord(M->read(++PC)+X)); } uint8_t M6502_core::read_ind_y(){ //read using Indirect Y-Indexed addressing return M->read(M->readWord(M->read(++PC))+Y); } void M6502_core::store_zpg(uint8_t value){ //store to zero page index supplied by instruction M->write(M->read(++PC), value); } void M6502_core::store_zpg(uint8_t value, uint8_t offset){ //store to zero page (index supplied by instruction)+offset M->write(M->read(++PC)+offset,value); } void M6502_core::store_abs(uint8_t value){ //store to absolute address supplied by instruction M->write(M->readWord(++PC), value); PC++; } void M6502_core::store_abs(uint8_t value, uint8_t offset){ //store to absolute (address supplied by instruction)+offset M->write(M->readWord(++PC)+offset, value); PC++; } void M6502_core::store_ind_x(uint8_t value){ //store to address at (instruction argument + x) M->write(M->readWord(M->read(++PC)+X),value); } void M6502_core::store_ind_y(uint8_t value){ //store to (address at instruction argument) + y M->write(M->readWord(M->read(++PC))+Y,value); } /*------------------------------------------------------------------------------------------------*/ void M6502_core::execute(uint8_t val){ switch (val){ case instruct::BRK: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; nmi(); SR.B = 1; stack_push(read_SR()); stack_push(PC+2); break; case instruct::ORA_x_ind: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A |= read_ind_x(); SR.S = (A>>7); SR.Z = !A; break; case instruct::ORA_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A |= read_zpg(); SR.S = (A>>7); SR.Z = !A; break; case instruct::ASL_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(); SR.C = tmp&0x08; tmp = tmp<<1; M->write(M->read(PC-1),(tmp)); SR.S = (tmp)&0x08; SR.Z = !(tmp); } break; case instruct::PHP_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; stack_push(read_SR()); break; case instruct::ORA_n: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A |= M->read(++PC); SR.S = (A>>7); SR.Z = !A; break; case instruct::ASL_a: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; std::cout << "A expanded : " << std::hex << unsigned(A) << std::endl; SR.C=(A>>7); //std::cout << " Carry expanded : " << std::hex << unsigned((A>>7)) << std::endl; A = (A<<1); SR.S = (A>>7); SR.Z = !A; break; case instruct::ORA_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A|= read_abs(); SR.S = (A>>7); SR.Z = !A; break; case instruct::ASL_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp; tmp = read_abs(); SR.C=tmp&0x80; tmp = tmp<<1; M->write(M->readWord(PC-2),tmp); SR.S = (tmp)&0x08; SR.Z = !(tmp); } break; case instruct::BPL_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.S == 0){ PC = read_rel(); PC--; }else{ PC++; } break; case instruct::ORA_ind_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A|= read_ind_y(); SR.S = (A>>7); SR.Z = !A; break; case instruct::ORA_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A|= read_zpg(X); SR.S = (A>>7); SR.Z = !A; break; case instruct::ASL_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(X); SR.C=tmp&0x80; tmp = tmp <<1; M->write(M->read(PC-1)+X,tmp); SR.S = (tmp)&0x80; SR.Z = !(tmp); } break; case instruct::CLC_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; SR.C = 0; break; case instruct::ORA_abs_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A|= read_abs(Y); SR.S = (A>>7); SR.Z = !A; break; case instruct::ORA_abs_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A|= read_abs(X); SR.S = (A>>7); SR.Z = !A; break; case instruct::ASL_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(X); SR.C=tmp&0x80; tmp = tmp<<1; M->write(M->readWord(PC-2)+X,tmp); SR.S = (tmp)&0x80; SR.Z = !(tmp); } break; case instruct::JSR_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t PCL = (PC+2)&0xFF; uint8_t PCH = (PC+2)>>8; stack_push(PCH); stack_push(PCL); PC = M->readWord(++PC); PC--; } break; case instruct::AND_x_ind: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A & read_ind_x(); SR.S = (A>>7); SR.Z = !A; break; case instruct::BIT_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_zpg(); uint8_t temp = (m & A); SR.S = m >> 7; SR.V = m >> 6; SR.Z = !temp; } break; case instruct::AND_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = (A & read_zpg()); SR.S = (A>>7); SR.Z = !A; break; case instruct::ROL_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(); SR.C = tmp >> 7; tmp = (tmp << 1)+ (SR.C ? 1 : 0); M->write(M->read(PC-1),tmp); SR.Z = !tmp; SR.S = tmp>>7; } break; case instruct::PLP_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; write_SR(stack_pop()); break; case instruct::AND_n: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = (A & M->read(++PC)); SR.S = (A>>7); SR.Z = !A; break; case instruct::ROL_a:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; SR.C = A>>7; A = (A << 1)+ (SR.C ? 1 : 0); SR.Z = !A; SR.S = A>>7; } break; case instruct::BIT_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_abs(); uint8_t temp = (m & A); SR.S = m >> 7; SR.V = m >> 6; SR.Z = !temp; } break; case instruct::AND_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = (read_abs() & A); SR.S = (A>>7); SR.Z = !A; break; case instruct::ROL_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(); SR.C = tmp >> 7; tmp = (tmp << 1)+ (SR.C ? 1 : 0); M->write(M->readWord(PC-2),tmp); SR.Z = !tmp; SR.S = tmp>>7; } break; case instruct::BMI_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.S == 1){ PC = read_rel(); PC--; }else{ PC++; } break; case instruct::AND_ind_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A & read_ind_y(); SR.S = (A>>7); SR.Z = !A; break; case instruct::AND_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A&read_zpg(X); SR.S = (A>>7); SR.Z = !A; break; case instruct::ROL_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(X); SR.C = tmp >> 7; tmp = (tmp << 1)+ (SR.C ? 1 : 0); M->write(M->read(PC-1)+X,tmp); SR.Z = !tmp; SR.S = tmp>>7; } break; case instruct::SEC_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Sets Carry Flag SR.C = 1; break; case instruct::AND_abs_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A =(read_abs(Y) & A); SR.S = (A>>7); SR.Z = A; break; case instruct::AND_abs_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = (read_abs(X) & A); SR.S = (A>>7); SR.Z = !A; break; case instruct::ROL_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(X); SR.C = tmp >> 7; tmp = (tmp << 1)+ (SR.C ? 1 : 0); M->write(M->readWord(PC-2)+X,tmp); SR.Z = !tmp; SR.S = tmp>>7; } break; case instruct::RTI_impl:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; write_SR(stack_pop()); uint16_t PCL = stack_pop(); uint16_t PCH = stack_pop()<<8; PC = PCL|PCH; PC--; std::cout << "Set PC to :" << std::hex << std::uppercase << unsigned(PC) << std::endl; SR.I = false; } break; case instruct::EOR_x_ind: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_ind_x(); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::EOR_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_zpg(); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::LSR_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(); SR.Z = false; SR.C = tmp&0x01; M->write(M->read(PC-1),tmp >>1); SR.S = !(tmp>>1); } break; case instruct::PHA_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; stack_push(A); break; case instruct::EOR_n: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ (M->read(++PC)); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::LSR_a:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = A; SR.S = false; SR.C = tmp&0x01; A = tmp >>1; SR.Z = !A; } break; case instruct::JMP_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; PC = M->readWord(++PC); PC--; break; case instruct::EOR_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_abs(); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::LSR_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(); SR.S = false; SR.C = tmp&0x01; M->write(M->readWord(PC-2),tmp >>1); SR.Z = !(tmp>>1); } break; case instruct::BVC_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.V == 0){ PC = (read_rel() ); PC--; }else{ PC++; } break; case instruct::EOR_ind_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_ind_y(); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::EOR_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_zpg(X); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::LSR_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(X); SR.S = false; SR.C = tmp&0x01; M->write(M->read(PC-1)+X,tmp >>1); SR.Z = !(tmp>>1); } break; case instruct::CLI_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; SR.I = 0; break; case instruct::EOR_abs_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_abs(Y); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::EOR_abs_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = A ^ read_abs(X); if(A == 0){ SR.Z = 0; } SR.S = A >>7; break; case instruct::LSR_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(X); SR.S = false; SR.C = tmp&0x01; M->write(M->read(PC-2)+X,tmp >>1); SR.Z = !(tmp>>1); } break; case instruct::RTS_impl:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint16_t PCL = stack_pop(); uint16_t PCH = stack_pop()<<8; PC = PCL|PCH; } break; case instruct::ADC_x_ind:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_ind_x(); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ADC_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_zpg(); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ROR_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(); SR.C = tmp&0x01; tmp = (tmp >> 1)|(SR.C ? 0x80 : 0x00); M->write(M->read(PC-1),tmp); SR.Z = !tmp; SR.S = tmp >>7; } break; case instruct::PLA_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = stack_pop(); break; case instruct::ADC_n:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = M->read(++PC); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ROR_a:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; SR.C = A&0x01; A = (A >> 1)|(SR.C ? 0x80 : 0x00); SR.Z = !A; SR.S = A >>7; } break; case instruct::JMP_ind: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; PC = read_ind(); PC--; break; case instruct::ADC_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_abs(); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ROR_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(); SR.C = tmp&0x01; tmp = (tmp >> 1)|(SR.C ? 0x80 : 0x00); M->write(M->readWord(PC-2),tmp); SR.Z = !tmp; SR.S = tmp >>7; } break; case instruct::BVS_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.V == 1){ PC = (read_rel()); PC--; }else{ PC++; } break; case instruct::ADC_ind_y:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_ind_y(); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ADC_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_zpg(X); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ROR_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_zpg(X); SR.C = tmp&0x01; tmp = (tmp >> 1)|(SR.C ? 0x80 : 0x00); M->write(M->read(PC-1)+X,tmp); SR.Z = !tmp; SR.S = tmp >>7; } break; case instruct::SEI_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Sets Interrupt Disable Status SR.I = 1; break; case instruct::ADC_abs_y:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = read_abs(Y); unsigned int t = m + A +(SR.C ? 1 : 0); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = t > 0xFF; //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::ADC_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t temp; uint8_t checkV; temp = read_abs(X); checkV = (A>>7 & temp>>7); A = A+temp+SR.C; SR.Z = A; SR.S = A>>7; if(checkV){ SR.V= !(temp>>7 & A>>7); } } break; case instruct::ROR_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = read_abs(X); SR.C = tmp&0x01; tmp = (tmp >> 1)|(SR.C ? 0x80 : 0x00); M->write(M->readWord(PC-2)+X,tmp); SR.Z = !tmp; SR.S = tmp >>7; } break; case instruct::STA_x_ind: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_ind_x(A); break; case instruct::STY_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_zpg(Y); break; case instruct::STA_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_zpg(A); break; case instruct::STX_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_zpg(X); break; case instruct::DEY_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = Y-1; if(Y == 0){ SR.Z = 1; } SR.S = Y>>7; break; case instruct::TXA_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Transfers the X index to the Accumulator A = X; //Stets the Zero Flag to the value if it is zero SR.Z = A; //Sets the Negative/Status Flag to bit 7 of the value SR.S = A>>7; break; case instruct::STY_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_abs(Y); break; case instruct::STA_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_abs(A); break; case instruct::STX_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_abs(X); break; case instruct::BCC_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.C == 0){ PC = (read_rel()); PC--; }else{ PC++; } break; case instruct::STA_ind_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_ind_y(A); break; case instruct::STY_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_zpg(Y,X); break; case instruct::STA_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_zpg(A,X); break; case instruct::STX_zpg_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_zpg(X, Y); break; case instruct::TYA_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Transfers the Y index to the accumulator A = Y; //Sets the Zero Flag if the value was 0 SR.Z = A; //Gets bit 7 of the value and sets the Negative flag to that bit SR.S = A>>7; break; case instruct::STA_abs_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_abs(A,Y); break; case instruct::TXS_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Transfers the X index to the stack register SP = X; break; case instruct::STA_abs_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; store_abs(A,X); break; case instruct::LDY_n: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = M->read(++PC); if(Y == 0){ SR.Z = 1; } SR.S = Y >> 7; break; case instruct::LDA_x_ind: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_ind_x(); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::LDX_n: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = M->read(++PC); if(X == 0){ SR.Z = 1; } SR.S = X >> 7; break; case instruct::LDY_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = read_zpg(); if(Y == 0){ SR.Z = 1; } SR.S = Y >> 7; break; case instruct::LDA_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_zpg(); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::LDX_zpg: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = read_zpg(); if(X == 0){ SR.Z = 1; } SR.S = X >> 7; break; case instruct::TAY_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Transfers the Accumulator to the Y index Y = A; //Sets the Zero Flag to the value if it is zero SR.Z = Y; //Sets the Negative/Status register to bit 7 of the value SR.S = Y>>7; break; case instruct::LDA_n: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = M->read(++PC); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::TAX_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Transfers the Accumulator to the X index X = A; //Sets the Zero Flag to the value if it is zero SR.Z = X; //Sets the Negative/Status register to bit 7 of the value SR.S = X>>7; break; case instruct::LDY_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = read_abs(); if(Y == 0){ SR.Z = 1; } SR.S = Y >> 7; break; case instruct::LDA_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_abs(); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::LDX_abs: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = read_abs(); if(X == 0){ SR.Z = 1; } SR.S = X >> 7; break; case instruct::BCS_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.C == 1){ uint16_t tmp=read_rel(); PC = tmp; PC--; }else{ PC++; } break; case instruct::LDA_ind_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_ind_y(); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::LDY_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = read_zpg(X); if(Y == 0){ SR.Z = 1; } SR.S = Y >> 7; break; case instruct::LDA_zpg_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_zpg(X); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::LDX_zpg_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = read_zpg(Y); if(X == 0){ SR.Z = 1; } SR.S = X >> 7; break; case instruct::CLV_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; SR.V = 0; break; case instruct::LDA_abs_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_abs(Y); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::TSX_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Transfers the Stack Pointer to the X index X = SP; //Sets the Zero Flag to the value if it is zero SR.Z = X; //Sets the Negative/Status register to bit 7 of the value SR.S = X>>7; break; case instruct::LDY_abs_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = read_abs(X); if(Y == 0){ SR.Z = 1; } SR.S = Y >> 7; break; case instruct::LDA_abs_x: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; A = read_abs(X); if(A == 0){ SR.Z = 1; } SR.S = A >> 7; break; case instruct::LDX_abs_y: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = read_abs(Y); if(X == 0){ SR.Z = 1; } SR.S = X >> 7; break; case instruct::CPY_n:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (M->read(++PC)); unsigned int tmp = Y - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::CMP_x_ind:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_ind_x()); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::CPY_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_zpg()); unsigned int tmp = Y - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::CMP_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_zpg()); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::DEC_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = M->read(++PC); //read address needed M->write(0x0000+tmp,M->read(tmp)-1);//store address value-1 in zeropage if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::INY_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; Y = Y+1; if(Y == 0){ SR.Z = 1; } SR.S = Y>>7; break; case instruct::CMP_n:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (M->read(++PC)); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::DEX_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = X-1; if(X == 0){ SR.Z = 1; } SR.S = X>>7; break; case instruct::CPY_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_abs()); unsigned int tmp = Y - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::CMP_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_abs()); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::DEC_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint16_t tmp = M->readWord(++PC); //read address needed M->write(tmp, M->read(tmp)-1); if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::BNE_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.Z == 0){ PC = (read_rel()); PC--; }else{ PC++; } break; case instruct::CMP_ind_y:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_ind_y()); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::CMP_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_zpg(X)); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::DEC_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = M->read(++PC)+X; //read address needed M->write(0x0000+tmp,M->read(tmp)-1);//store address value-1 in zeropage if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::CLD_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; SR.D = 0; break; case instruct::CMP_abs_y:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_abs(Y)); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::CMP_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_abs(X)); unsigned int tmp = A - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::DEC_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint16_t tmp = M->readWord(++PC)+X; //read address needed M->write(tmp, M->read(tmp)-1); if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::CPX_n:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (M->read(++PC)); unsigned int tmp = X - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::SBC_x_ind:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_ind_x()); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::CPX_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_zpg()); unsigned int tmp = X - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::SBC_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_zpg()); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::INC_zpg:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = M->read(++PC); //read address needed M->write(0x0000+tmp,M->read(tmp)+1);//store address value-1 in zeropage if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::INX_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; X = X+1; if(X == 0){ SR.Z = 1; } SR.S = X>>7; break; case instruct::SBC_n:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = M->read(++PC); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest break; } case instruct::NOP_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; break; case instruct::CPX_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tm = (read_abs()); unsigned int tmp = X - tm; SR.S = (tmp&0x80) >> 7; SR.Z = (tmp==0); SR.C = (A >= tm); } break; case instruct::SBC_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_abs()); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::INC_abs:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint16_t tmp = M->readWord(++PC); //read address needed M->write(tmp, M->read(tmp)+1); if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::BEQ_rel: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; if(SR.Z == 1){ PC = (read_rel()); PC--; }else{ PC++; } break; case instruct::SBC_ind_y:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_ind_y()); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::SBC_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_zpg(X)); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::INC_zpg_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t tmp = M->read(++PC)+X; //read address needed M->write(0x0000+tmp,M->read(tmp)+1);//store address value-1 in zeropage if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::SED_impl: std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; //Sets Decimal Flag SR.D = 1; break; case instruct::SBC_abs_y:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_abs(Y)); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::SBC_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint8_t m = (read_abs(X)); unsigned int t = A - m -(SR.C ? 0 : 1); //if carry is set add 1 to result SR.Z = !(t&0xFF); //set the zero flag if the result will be zero SR.S = (t&0x80); //set the sign flag to bit 7 SR.V = (!((A^m)&0x80)&&((A^t)&0x80)); //if the sign changes set overflow SR.C = (t < 0x100); //if result is greater than 255 set carry A = t&0xFF; //A is only 8 bits so mask the rest } break; case instruct::INC_abs_x:{ std::cout << "Valid Code: " << std::hex << std::uppercase << unsigned(val) << std::endl; uint16_t tmp = M->readWord(++PC)+X; //read address needed M->write(tmp, M->read(tmp)+1); if((M->read(tmp)) == 0){ SR.Z = 1; } SR.S = (M->read(tmp))>>7; } break; case instruct::EXT: std::cout << "code EXT or 0xFF" << std::endl; break; default: std::cout << "I cant find this code!" << std::endl; break; } }
34adb1a9b3e0f058c5f1ae2b778622773dd21a55
29081a767c0b3c0cd6540a971f0269577b474d6c
/main.cpp
9a0038256f61dd32e875f923d63917e504c623cc
[]
no_license
cpalaka/sfml-MandelbrotSet
8f40a38aac14bd2bd2cda69c14bbfe3a707ac6ac
128b94e1b13e9d195fce4692851f202713cdad9e
refs/heads/master
2020-05-02T01:33:34.945468
2013-06-01T12:09:56
2013-06-01T12:09:56
10,418,993
1
1
null
null
null
null
UTF-8
C++
false
false
2,414
cpp
main.cpp
#include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include "Complex.h" #include <iostream> #include <array> #include <memory> const int WHEIGHT = 480; const int WWIDTH = 640; //const int MAXITER = 100; int color_no; int main() { int MAXITER = 1; int MAXMAXITER = 100; sf::RenderWindow window(sf::VideoMode(WWIDTH, WHEIGHT), "Mandelbrot Set"); sf::Texture texture; sf::Image image; sf::Sprite sprite; image.create(WWIDTH, WHEIGHT, sf::Color::White); Complex min(-2.0, -1.2); Complex max(1.0, 1.05); float Re_factor = (max.real - min.real)/(WWIDTH-1); float Im_factor = (max.imag - min.imag)/(WHEIGHT-1); while(window.isOpen()) { //Check events on window sf::Event evt; window.pollEvent(evt); window.setFramerateLimit(20); if((evt.type == sf::Event::Closed) || (evt.type == sf::Event::KeyPressed && evt.key.code == sf::Keyboard::Escape)) { window.close(); } for(unsigned y=0; y<WHEIGHT; ++y) { color_no = -1; float c_im = min.imag + y*Im_factor; for(unsigned x=0; x<WWIDTH; ++x) { color_no = -1; float c_re = min.real + x*Re_factor; Complex c(c_re, c_im); Complex c_const(c_re, c_im); bool isInside = true; for(unsigned n=0; n<MAXITER; ++n) { if(c.abs_squared() > 4.0) //if the absolute value of the complex number is greater than 2, then it escapes to infinity, and is not part of set { //Complex number is not part of the set //or, it is outside the black inside area color_no = n; //save the number of iterations it took to reach this point(infinity) isInside = false; break; } //z = z^2 + c Complex c2 = c.square(); //z = z^3 + c //Complex c2 = c.cube(); c = c2.add(c_const); } if(isInside == true) { //Color pixels belonging to set black image.setPixel(x, y, sf::Color::Black); } if(color_no >= 0 && color_no < MAXITER/2-1) { image.setPixel(x, y, sf::Color((5*color_no)%255, 0, 0)); } else if (color_no >= MAXITER/2 && color_no < MAXITER) { image.setPixel(x, y, sf::Color((color_no)%255, (color_no)%255, (color_no)%255)); } } } //if(MAXITER <= MAXMAXITER) MAXITER++; //else // MAXITER = MAXMAXITER; texture.loadFromImage(image); sprite.setTexture(texture); window.clear(sf::Color(255,255,255)); window.draw(sprite); window.display(); } return 0; }
bee20864bd32c9c0c2cfc2a6259ee34350626dd4
9a6b8ca29a6a6422b838d237916d2a872e4b808f
/00-CppHelloWorld/hello.cpp
1bb3082d6fe4339c0f655853304934ec0bd44990
[]
no_license
amandabenson/AED
f07be31dcda62ab3b275f78eb9e7a00da13700cb
8fe1de7b5d0f15a74ca8444b7210662bcc7ba9aa
refs/heads/master
2022-11-06T13:09:43.060028
2019-05-02T12:51:41
2019-05-02T12:51:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
135
cpp
hello.cpp
/* Hello World! Amanda Vanesa Benson 11/04/2019 */ #include <iostream> int main(){ std::cout << "Hello, World! :) \n"; }
095d127840a3489d816733735ea46ceafc919f0b
89f91ac3de03a78a7158bfa87b0d4d84a3c47109
/951.cpp
0bc90208d4e0798cbd34d4eb7e106f067ae536b8
[]
no_license
xyuanlu/Cultivation
65a8b098f407443aa35b2fe6d5d77419a1ab0e73
9a2dadc56ec17d5af1c780e9224936f1afa86786
refs/heads/master
2021-07-06T08:07:11.071012
2020-11-08T23:55:46
2020-11-08T23:55:46
201,869,574
0
0
null
null
null
null
UTF-8
C++
false
false
1,225
cpp
951.cpp
/* * 951. Flip Equivalent Binary Trees * For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. * * A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to * Y after some number of flip operations. * * Write a function that determines whether two binary trees are flip equivalent. * The trees are given by root nodes root1 and root2. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool flipEquiv(TreeNode* root1, TreeNode* root2) { if (root1==nullptr && root2==nullptr) { return true; } if (root1==nullptr || root2==nullptr) return false; if (root1->val == root2->val) { return ((flipEquiv(root1->left,root2->left) && flipEquiv(root1->right, root2->right)) || (flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left))); } return false; } };
0352a0f9dfd70699785e93292453cc9ee5f3a7d6
2ba27dc1b1ed0c00b5cc79eb3517ad86ee4fdca9
/DirectX12-FrameWork/CommandSignature.h
d7c1ed59a5b19cf13ecaba3f380d050794976c76
[ "MIT" ]
permissive
wangyongxina/DirectX12-Framework-
0d4f404fae6b2d0b26ba49ad5e896302fef6a5a5
b9e590555660c40cb19c3ef292c097c78d49a158
refs/heads/master
2023-03-15T04:50:46.101413
2020-08-29T04:39:29
2020-08-29T04:39:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
h
CommandSignature.h
#pragma once #include "stdafx.h" #include "d3dx12.h" #include <vector> class RootSignature; // all command should keep, draw, drawindex, dispatch at the last class CommandSignature { public: CommandSignature() : mCommandSignature(nullptr), paddingsize(0) { } bool initialize(ID3D12Device* device, RootSignature& rootsig); void release(); std::vector<CommandParameter> mParameters; D3D12_COMMAND_SIGNATURE_DESC mCommandSignatureDes; ID3D12CommandSignature* mCommandSignature; UINT paddingsize; };