blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
670aa681f3b16ad670d5acb4b91b78b3a2d4ce11 | ad78d2168925ec23d290d0186a5249ad4c6ea037 | /src/ENDFtk/section/1/451/src/makeDescription.hpp | f043d3bc6ca10a7f8babad8b5483ef540dd99547 | [
"BSD-2-Clause"
] | permissive | jkulesza/ENDFtk | f363a115f059df02195b9f248f81854935c8dbf4 | b6618b396f51e802b7ee19ba529533c27e6ac302 | refs/heads/master | 2023-03-11T01:36:52.086387 | 2020-10-29T17:36:01 | 2020-10-29T17:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | hpp | static
std::vector< TextRecord >
makeDescription( const std::string& description ) {
return ranges::view::split( description, '\n' )
| ranges::view::transform( [] ( const auto& line )
{ return TextRecord( line ); } );
}
| [
"whaeck@gmail.com"
] | whaeck@gmail.com |
71783e964b56fd9e6db119782faa9a2b23fc0a49 | bd367074bb6a012db58aefc8e765ecfcfb5c4fcf | /PICKY_PI/Cratere.h | f2788ada93fe34f6a43950560c459700ae2e3191 | [] | no_license | VegLeMeccano/EUROBOT-2017 | 3bf61c0111676748266756a71be3ecb6ad1e56e4 | 8dd4dc6fae69e41052932bc54071db710c8e0d7b | refs/heads/master | 2020-02-26T15:37:36.385801 | 2017-05-10T15:01:38 | 2017-05-10T15:01:38 | 69,698,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | #ifndef CRATERE_H
#define CRATERE_H
class Cratere
{
public:
Cratere(int nb_sphere_);
void vidange();
bool is_empty();
int get_nb_sphere();
protected:
private:
int nb_sphere;
bool transfert_marked;
};
#endif // CRATERE_H
| [
"loic.maxel@gmail.com"
] | loic.maxel@gmail.com |
4b9240ab79a6a9972c836fcb99e342104f61bc99 | 90f344dfaa930636ea3cac3068b1fda88fd50295 | /primer_plus/002_convert/002_convert/Main.cpp | a035909717cba17eec3db39a51f60af2071a04ec | [] | no_license | vladmyr/learning_cpp | 7753f8b5eab063c3d754663c1b887bedcee40a4c | 46d8a033d617d11a02da9fd327372976798ae4d1 | refs/heads/master | 2021-01-10T01:33:23.144498 | 2016-01-08T22:57:13 | 2016-01-08T22:57:13 | 49,299,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <iostream>
int stoneToLb(int); //function prototype
int main() {
using namespace std;
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
cin.get();
int pounds = stoneToLb(stone);
cout << stone << " stone = " << pounds << " pounds." << endl;
cin.get();
return 0;
}
int stoneToLb(int sts) {
return 14 * sts;
} | [
"khytsky.vladimir@gmail.com"
] | khytsky.vladimir@gmail.com |
ee65ff8b7cc44ad959487af2bd23f5fcd3392df4 | 72f92d054a0f900554288ec034e91648c67451c8 | /wikidata2vec/utils/tokenizer/jieba_tokenizer.cpp | af9fa9c851d2b3668d89a8d8917f1fb0d659ac4f | [
"Apache-2.0"
] | permissive | j40903272/wikidata2vec | c3c9d1fba929370d48b22bf58141ac72b47de616 | 228479f6f24ca8f8df6bcbd7c927d33b577206ce | refs/heads/master | 2022-11-11T09:46:46.359748 | 2020-06-29T17:49:56 | 2020-06-29T17:49:56 | 269,102,606 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 162,942 | cpp | /* Generated by Cython 0.29.19 */
#define PY_SSIZE_T_CLEAN
#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 < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)
#error Cython requires Python 2.6+ or Python 3.3+.
#else
#define CYTHON_ABI "0_29_19"
#define CYTHON_HEX_VERSION 0x001D13F0
#define CYTHON_FUTURE_DIVISION 0
#include <stddef.h>
#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
#define __PYX_COMMA ,
#ifndef HAVE_LONG_LONG
#if PY_VERSION_HEX >= 0x02070000
#define HAVE_LONG_LONG
#endif
#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_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 0
#undef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 0
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#if PY_VERSION_HEX < 0x03050000
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#undef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#undef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 1
#undef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 0
#undef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 0
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#undef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT 0
#undef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 0
#undef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS 0
#undef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK 0
#elif defined(PYSTON_VERSION)
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 1
#define CYTHON_COMPILING_IN_CPYTHON 0
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#undef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT 0
#undef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 0
#undef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS 0
#undef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK 0
#else
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 1
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYTYPE_LOOKUP
#define CYTHON_USE_PYTYPE_LOOKUP 0
#elif !defined(CYTHON_USE_PYTYPE_LOOKUP)
#define CYTHON_USE_PYTYPE_LOOKUP 1
#endif
#if PY_MAJOR_VERSION < 3
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#elif !defined(CYTHON_USE_PYLONG_INTERNALS)
#define CYTHON_USE_PYLONG_INTERNALS 1
#endif
#ifndef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 1
#endif
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#if PY_VERSION_HEX < 0x030300F0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#elif !defined(CYTHON_USE_UNICODE_WRITER)
#define CYTHON_USE_UNICODE_WRITER 1
#endif
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#ifndef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 1
#endif
#ifndef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 1
#endif
#ifndef CYTHON_PEP489_MULTI_PHASE_INIT
#define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000)
#endif
#ifndef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1)
#endif
#ifndef CYTHON_USE_DICT_VERSIONS
#define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1)
#endif
#ifndef CYTHON_USE_EXC_INFO_STACK
#define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3)
#endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#undef SHIFT
#undef BASE
#undef MASK
#ifdef SIZEOF_VOID_P
enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) };
#endif
#endif
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#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
#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
#ifndef CYTHON_MAYBE_UNUSED_VAR
# if defined(__cplusplus)
template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
# else
# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
# endif
#endif
#ifndef CYTHON_NCP_UNUSED
# if CYTHON_COMPILING_IN_CPYTHON
# define CYTHON_NCP_UNUSED
# else
# define CYTHON_NCP_UNUSED CYTHON_UNUSED
# endif
#endif
#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
#ifdef _MSC_VER
#ifndef _MSC_STDINT_H_
#if _MSC_VER < 1300
typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
#else
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
#endif
#endif
#else
#include <stdint.h>
#endif
#ifndef CYTHON_FALLTHROUGH
#if defined(__cplusplus) && __cplusplus >= 201103L
#if __has_cpp_attribute(fallthrough)
#define CYTHON_FALLTHROUGH [[fallthrough]]
#elif __has_cpp_attribute(clang::fallthrough)
#define CYTHON_FALLTHROUGH [[clang::fallthrough]]
#elif __has_cpp_attribute(gnu::fallthrough)
#define CYTHON_FALLTHROUGH [[gnu::fallthrough]]
#endif
#endif
#ifndef CYTHON_FALLTHROUGH
#if __has_attribute(fallthrough)
#define CYTHON_FALLTHROUGH __attribute__((fallthrough))
#else
#define CYTHON_FALLTHROUGH
#endif
#endif
#if defined(__clang__ ) && defined(__apple_build_version__)
#if __apple_build_version__ < 7000000
#undef CYTHON_FALLTHROUGH
#define CYTHON_FALLTHROUGH
#endif
#endif
#endif
#ifndef __cplusplus
#error "Cython files generated with the C++ option must be compiled with a C++ compiler."
#endif
#ifndef CYTHON_INLINE
#if defined(__clang__)
#define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
#else
#define CYTHON_INLINE inline
#endif
#endif
template<typename T>
void __Pyx_call_destructor(T& x) {
x.~T();
}
template<typename T>
class __Pyx_FakeReference {
public:
__Pyx_FakeReference() : ptr(NULL) { }
__Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { }
T *operator->() { return ptr; }
T *operator&() { return ptr; }
operator T&() { return *ptr; }
template<typename U> bool operator ==(U other) { return *ptr == other; }
template<typename U> bool operator !=(U other) { return *ptr != other; }
private:
T *ptr;
};
#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
#define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#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"
#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#else
#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)
#endif
#define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
#define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
#define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#ifndef METH_STACKLESS
#define METH_STACKLESS 0
#endif
#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL)
#ifndef METH_FASTCALL
#define METH_FASTCALL 0x80
#endif
typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs);
typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args,
Py_ssize_t nargs, PyObject *kwnames);
#else
#define __Pyx_PyCFunctionFast _PyCFunctionFast
#define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)))))
#else
#define __Pyx_PyFastCFunction_Check(func) 0
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
#define PyObject_Malloc(s) PyMem_Malloc(s)
#define PyObject_Free(p) PyMem_Free(p)
#define PyObject_Realloc(p) PyMem_Realloc(p)
#endif
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1
#define PyMem_RawMalloc(n) PyMem_Malloc(n)
#define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n)
#define PyMem_RawFree(p) PyMem_Free(p)
#endif
#if CYTHON_COMPILING_IN_PYSTON
#define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
#else
#define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
#endif
#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000
#define __Pyx_PyThreadState_Current PyThreadState_GET()
#elif PY_VERSION_HEX >= 0x03060000
#define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet()
#elif PY_VERSION_HEX >= 0x03000000
#define __Pyx_PyThreadState_Current PyThreadState_GET()
#else
#define __Pyx_PyThreadState_Current _PyThreadState_Current
#endif
#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT)
#include "pythread.h"
#define Py_tss_NEEDS_INIT 0
typedef int Py_tss_t;
static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) {
*key = PyThread_create_key();
return 0;
}
static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) {
Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t));
*key = Py_tss_NEEDS_INIT;
return key;
}
static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) {
PyObject_Free(key);
}
static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) {
return *key != Py_tss_NEEDS_INIT;
}
static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) {
PyThread_delete_key(*key);
*key = Py_tss_NEEDS_INIT;
}
static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) {
return PyThread_set_key_value(*key, value);
}
static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) {
return PyThread_get_key_value(*key);
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized)
#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n))
#else
#define __Pyx_PyDict_NewPresized(n) PyDict_New()
#endif
#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION
#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
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS
#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash)
#else
#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name)
#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_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u)
#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)
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
#else
#define CYTHON_PEP393_ENABLED 0
#define PyUnicode_1BYTE_KIND 1
#define PyUnicode_2BYTE_KIND 2
#define PyUnicode_4BYTE_KIND 4
#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_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
#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]))
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u))
#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
#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
#define PyUnicode_Contains(u, s) PySequence_Contains(u, s)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
#define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
#define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt)
#endif
#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? 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 && !defined(PyObject_ASCII)
#define PyObject_ASCII(o) PyObject_Repr(o)
#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
#ifndef PyObject_Unicode
#define PyObject_Unicode PyObject_Str
#endif
#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_Check(obj) || PyUnicode_Check(obj))
#define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#ifndef PySet_CheckExact
#define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
#endif
#if CYTHON_ASSUME_SAFE_MACROS
#define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq)
#else
#define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq)
#endif
#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_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
#ifndef PyUnicode_InternFromString
#define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
#endif
#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
#define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : (Py_INCREF(func), func))
#else
#define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
#endif
#if CYTHON_USE_ASYNC_SLOTS
#if PY_VERSION_HEX >= 0x030500B1
#define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
#define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
#else
#define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
#endif
#else
#define __Pyx_PyType_AsAsync(obj) NULL
#endif
#ifndef __Pyx_PyAsyncMethodsStruct
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
} __Pyx_PyAsyncMethodsStruct;
#endif
#if defined(WIN32) || defined(MS_WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
float value;
memset(&value, 0xFF, sizeof(value));
return value;
}
#endif
#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
#define __Pyx_truncl trunc
#else
#define __Pyx_truncl truncl
#endif
#define __PYX_MARK_ERR_POS(f_index, lineno) \
{ __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; }
#define __PYX_ERR(f_index, lineno, Ln_error) \
{ __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#define __PYX_HAVE__wikidata2vec__utils__tokenizer__jieba_tokenizer
#define __PYX_HAVE_API__wikidata2vec__utils__tokenizer__jieba_tokenizer
/* Early includes */
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)
#define CYTHON_WITHOUT_ASSERTIONS
#endif
typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;
#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8)
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_uchar_cast(c) ((unsigned char)c)
#define __Pyx_long_cast(x) ((long)x)
#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 int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) {
return (size_t) i < (size_t) limit;
}
#if defined (__cplusplus) && __cplusplus >= 201103L
#include <cstdlib>
#define __Pyx_sst_abs(value) std::abs(value)
#elif SIZEOF_INT >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) abs(value)
#elif SIZEOF_LONG >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) labs(value)
#elif defined (_MSC_VER)
#define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value))
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_sst_abs(value) llabs(value)
#elif defined (__GNUC__)
#define __Pyx_sst_abs(value) __builtin_llabs(value)
#else
#define __Pyx_sst_abs(value) ((value<0) ? -value : value)
#endif
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE const 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(const 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_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s))
#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s))
#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s)
#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s)
#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s)
#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s)
#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) {
const Py_UNICODE *u_end = u;
while (*u_end++) ;
return (size_t)(u_end - u - 1);
}
#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_NewRef(obj) (Py_INCREF(obj), obj)
#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b);
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
#define __Pyx_PySequence_Tuple(obj)\
(likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj))
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_ASSUME_SAFE_MACROS
#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
#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
#else
#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
#endif
#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(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;
PyObject* default_encoding = NULL;
PyObject* ascii_chars_u = NULL;
PyObject* ascii_chars_b = NULL;
const char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
if (strcmp(default_encoding_c, "ascii") == 0) {
__Pyx_sys_getdefaultencoding_not_ascii = 0;
} else {
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) goto bad;
ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(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_DECREF(ascii_chars_u);
Py_DECREF(ascii_chars_b);
}
Py_DECREF(default_encoding);
return 0;
bad:
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;
PyObject* default_encoding = NULL;
char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
__PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1);
if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
return -1;
}
#endif
#endif
/* Test for GCC > 2.95 */
#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* !__GNUC__ or GCC < 2.95 */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }
static PyObject *__pyx_m = NULL;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_cython_runtime = NULL;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static PyObject *__pyx_empty_unicode;
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[] = {
"wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx",
};
/*--- Type declarations ---*/
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer;
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer;
/* "base_tokenizer.pxd":5
*
*
* cdef class BaseTokenizer: # <<<<<<<<<<<<<<
* cpdef list tokenize(self, unicode)
* cdef list _span_tokenize(self, unicode)
*/
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer {
PyObject_HEAD
struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer *__pyx_vtab;
};
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":16
*
*
* cdef class JiebaTokenizer(BaseTokenizer): # <<<<<<<<<<<<<<
* cdef _rule
*
*/
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer {
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer __pyx_base;
PyObject *_rule;
};
/* "base_tokenizer.pxd":5
*
*
* cdef class BaseTokenizer: # <<<<<<<<<<<<<<
* cpdef list tokenize(self, unicode)
* cdef list _span_tokenize(self, unicode)
*/
struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer {
PyObject *(*tokenize)(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer *, PyObject *, int __pyx_skip_dispatch);
PyObject *(*_span_tokenize)(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer *, PyObject *);
};
static struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer *__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":16
*
*
* cdef class JiebaTokenizer(BaseTokenizer): # <<<<<<<<<<<<<<
* cdef _rule
*
*/
struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer {
struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer __pyx_base;
};
static struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer;
/* --- Runtime support code (head) --- */
/* Refnanny.proto */
#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);
#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
#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)
/* RaiseArgTupleInvalid.proto */
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);
/* KeywordStringCheck.proto */
static int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed);
/* PyObjectGetAttrStr.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name);
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif
/* GetBuiltinName.proto */
static PyObject *__Pyx_GetBuiltinName(PyObject *name);
/* PyDictVersioning.proto */
#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1)
#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag)
#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\
(version_var) = __PYX_GET_DICT_VERSION(dict);\
(cache_var) = (value);
#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\
static PY_UINT64_T __pyx_dict_version = 0;\
static PyObject *__pyx_dict_cached_value = NULL;\
if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\
(VAR) = __pyx_dict_cached_value;\
} else {\
(VAR) = __pyx_dict_cached_value = (LOOKUP);\
__pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\
}\
}
static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj);
static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj);
static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version);
#else
#define __PYX_GET_DICT_VERSION(dict) (0)
#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)
#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP);
#endif
/* GetModuleGlobalName.proto */
#if CYTHON_USE_DICT_VERSIONS
#define __Pyx_GetModuleGlobalName(var, name) {\
static PY_UINT64_T __pyx_dict_version = 0;\
static PyObject *__pyx_dict_cached_value = NULL;\
(var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\
(likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\
__Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\
}
#define __Pyx_GetModuleGlobalNameUncached(var, name) {\
PY_UINT64_T __pyx_dict_version;\
PyObject *__pyx_dict_cached_value;\
(var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\
}
static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value);
#else
#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name)
#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name)
static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name);
#endif
/* PyCFunctionFastCall.proto */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs);
#else
#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL)
#endif
/* PyFunctionFastCall.proto */
#if CYTHON_FAST_PYCALL
#define __Pyx_PyFunction_FastCall(func, args, nargs)\
__Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL)
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs);
#else
#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs)
#endif
#define __Pyx_BUILD_ASSERT_EXPR(cond)\
(sizeof(char [1 - 2*!(cond)]) - 1)
#ifndef Py_MEMBER_SIZE
#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
#endif
static size_t __pyx_pyframe_localsplus_offset = 0;
#include "frameobject.h"
#define __Pxy_PyFrame_Initialize_Offsets()\
((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\
(void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus)))
#define __Pyx_PyFrame_GetLocalsplus(frame)\
(assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset))
#endif
/* PyObjectCall.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif
/* PyObjectCall2Args.proto */
static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2);
/* PyObjectCallMethO.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg);
#endif
/* PyObjectCallOneArg.proto */
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg);
/* RaiseTooManyValuesToUnpack.proto */
static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
/* RaiseNeedMoreValuesToUnpack.proto */
static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
/* IterFinish.proto */
static CYTHON_INLINE int __Pyx_IterFinish(void);
/* UnpackItemEndCheck.proto */
static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected);
/* ListCompAppend.proto */
#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) {
PyListObject* L = (PyListObject*) list;
Py_ssize_t len = Py_SIZE(list);
if (likely(L->allocated > len)) {
Py_INCREF(x);
PyList_SET_ITEM(list, len, x);
Py_SIZE(list) = len+1;
return 0;
}
return PyList_Append(list, x);
}
#else
#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x)
#endif
/* PyObjectCallNoArg.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func);
#else
#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL)
#endif
/* CallNextTpDealloc.proto */
static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc);
/* CallNextTpTraverse.proto */
static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse);
/* CallNextTpClear.proto */
static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_dealloc);
/* TypeImport.proto */
#ifndef __PYX_HAVE_RT_ImportType_proto
#define __PYX_HAVE_RT_ImportType_proto
enum __Pyx_ImportType_CheckSize {
__Pyx_ImportType_CheckSize_Error = 0,
__Pyx_ImportType_CheckSize_Warn = 1,
__Pyx_ImportType_CheckSize_Ignore = 2
};
static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size);
#endif
/* GetVTable.proto */
static void* __Pyx_GetVtable(PyObject *dict);
/* PyObject_GenericGetAttrNoDict.proto */
#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000
static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name);
#else
#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr
#endif
/* PyObject_GenericGetAttr.proto */
#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000
static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name);
#else
#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr
#endif
/* SetVTable.proto */
static int __Pyx_SetVtable(PyObject *dict, void *vtable);
/* Import.proto */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level);
/* PyThreadStateGet.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate;
#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current;
#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type
#else
#define __Pyx_PyThreadState_declare
#define __Pyx_PyThreadState_assign
#define __Pyx_PyErr_Occurred() PyErr_Occurred()
#endif
/* PyErrFetchRestore.proto */
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL)
#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb)
#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb)
#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb)
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
#if CYTHON_COMPILING_IN_CPYTHON
#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL))
#else
#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
#endif
#else
#define __Pyx_PyErr_Clear() PyErr_Clear()
#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb)
#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb)
#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb)
#endif
/* CLineInTraceback.proto */
#ifdef CYTHON_CLINE_IN_TRACEBACK
#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0)
#else
static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line);
#endif
/* CodeObjectCache.proto */
typedef struct {
PyCodeObject* code_object;
int code_line;
} __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);
/* AddTraceback.proto */
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename);
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
/* CIntFromPy.proto */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
/* CIntFromPy.proto */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
/* FastTypeChecks.proto */
#if CYTHON_COMPILING_IN_CPYTHON
#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type)
static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b);
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type);
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2);
#else
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type)
#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2))
#endif
#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
/* CheckBinaryVersion.proto */
static int __Pyx_check_binary_version(void);
/* InitStrings.proto */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);
static PyObject *__pyx_f_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer__span_tokenize(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_v_self, PyObject *__pyx_v_text); /* proto*/
/* Module declarations from 'wikidata2vec.utils.tokenizer.base_tokenizer' */
static PyTypeObject *__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer = 0;
/* Module declarations from 'wikidata2vec.utils.tokenizer.jieba_tokenizer' */
static PyTypeObject *__pyx_ptype_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer = 0;
#define __Pyx_MODULE_NAME "wikidata2vec.utils.tokenizer.jieba_tokenizer"
extern int __pyx_module_is_main_wikidata2vec__utils__tokenizer__jieba_tokenizer;
int __pyx_module_is_main_wikidata2vec__utils__tokenizer__jieba_tokenizer = 0;
/* Implementation of 'wikidata2vec.utils.tokenizer.jieba_tokenizer' */
static const char __pyx_k_s[] = "^\\s*$";
static const char __pyx_k_re[] = "re";
static const char __pyx_k_six[] = "six";
static const char __pyx_k_WARN[] = "WARN";
static const char __pyx_k_main[] = "__main__";
static const char __pyx_k_name[] = "__name__";
static const char __pyx_k_test[] = "__test__";
static const char __pyx_k_class[] = "__class__";
static const char __pyx_k_jieba[] = "jieba";
static const char __pyx_k_match[] = "match";
static const char __pyx_k_import[] = "__import__";
static const char __pyx_k_compile[] = "compile";
static const char __pyx_k_logging[] = "logging";
static const char __pyx_k_tokenize[] = "tokenize";
static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__";
static const char __pyx_k_setLogLevel[] = "setLogLevel";
static const char __pyx_k_JiebaTokenizer[] = "JiebaTokenizer";
static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback";
static PyObject *__pyx_n_s_JiebaTokenizer;
static PyObject *__pyx_n_s_WARN;
static PyObject *__pyx_n_s_class;
static PyObject *__pyx_n_s_cline_in_traceback;
static PyObject *__pyx_n_s_compile;
static PyObject *__pyx_n_s_import;
static PyObject *__pyx_n_s_jieba;
static PyObject *__pyx_n_s_logging;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_match;
static PyObject *__pyx_n_s_name;
static PyObject *__pyx_n_s_pyx_vtable;
static PyObject *__pyx_n_s_re;
static PyObject *__pyx_kp_u_s;
static PyObject *__pyx_n_s_setLogLevel;
static PyObject *__pyx_n_s_six;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_n_s_tokenize;
static int __pyx_pf_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer___init__(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_v_self); /* proto */
static PyObject *__pyx_pf_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_2__reduce__(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_v_self); /* proto */
static PyObject *__pyx_tp_new_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
/* Late includes */
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":19
* cdef _rule
*
* def __init__(self): # <<<<<<<<<<<<<<
* self._rule = re.compile(r'^\s*$')
*
*/
/* Python wrapper */
static int __pyx_pw_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_pw_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__init__ (wrapper)", 0);
if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) {
__Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;}
if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 0))) return -1;
__pyx_r = __pyx_pf_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer___init__(((struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_pf_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer___init__(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_v_self) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__init__", 0);
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":20
*
* def __init__(self):
* self._rule = re.compile(r'^\s*$') # <<<<<<<<<<<<<<
*
* cdef list _span_tokenize(self, unicode text):
*/
__Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_re); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 20, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_compile); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 20, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = NULL;
if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) {
__pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3);
if (likely(__pyx_t_2)) {
PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3);
__Pyx_INCREF(__pyx_t_2);
__Pyx_INCREF(function);
__Pyx_DECREF_SET(__pyx_t_3, function);
}
}
__pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_kp_u_s) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_kp_u_s);
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_GIVEREF(__pyx_t_1);
__Pyx_GOTREF(__pyx_v_self->_rule);
__Pyx_DECREF(__pyx_v_self->_rule);
__pyx_v_self->_rule = __pyx_t_1;
__pyx_t_1 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":19
* cdef _rule
*
* def __init__(self): # <<<<<<<<<<<<<<
* self._rule = re.compile(r'^\s*$')
*
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("wikidata2vec.utils.tokenizer.jieba_tokenizer.JiebaTokenizer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":22
* self._rule = re.compile(r'^\s*$')
*
* cdef list _span_tokenize(self, unicode text): # <<<<<<<<<<<<<<
* return [(start, end) for (word, start, end) in jieba.tokenize(text)
* if not self._rule.match(word)]
*/
static PyObject *__pyx_f_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer__span_tokenize(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_v_self, PyObject *__pyx_v_text) {
PyObject *__pyx_v_word = NULL;
PyObject *__pyx_v_start = NULL;
PyObject *__pyx_v_end = NULL;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
Py_ssize_t __pyx_t_5;
PyObject *(*__pyx_t_6)(PyObject *);
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
PyObject *__pyx_t_9 = NULL;
PyObject *(*__pyx_t_10)(PyObject *);
int __pyx_t_11;
int __pyx_t_12;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("_span_tokenize", 0);
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":23
*
* cdef list _span_tokenize(self, unicode text):
* return [(start, end) for (word, start, end) in jieba.tokenize(text) # <<<<<<<<<<<<<<
* if not self._rule.match(word)]
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_jieba); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_tokenize); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = NULL;
if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) {
__pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4);
if (likely(__pyx_t_3)) {
PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4);
__Pyx_INCREF(__pyx_t_3);
__Pyx_INCREF(function);
__Pyx_DECREF_SET(__pyx_t_4, function);
}
}
__pyx_t_2 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_3, __pyx_v_text) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_v_text);
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) {
__pyx_t_4 = __pyx_t_2; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0;
__pyx_t_6 = NULL;
} else {
__pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 23, __pyx_L1_error)
}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
for (;;) {
if (likely(!__pyx_t_6)) {
if (likely(PyList_CheckExact(__pyx_t_4))) {
if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break;
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
__pyx_t_2 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 23, __pyx_L1_error)
#else
__pyx_t_2 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
#endif
} else {
if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break;
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
__pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 23, __pyx_L1_error)
#else
__pyx_t_2 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
#endif
}
} else {
__pyx_t_2 = __pyx_t_6(__pyx_t_4);
if (unlikely(!__pyx_t_2)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else __PYX_ERR(0, 23, __pyx_L1_error)
}
break;
}
__Pyx_GOTREF(__pyx_t_2);
}
if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) {
PyObject* sequence = __pyx_t_2;
Py_ssize_t size = __Pyx_PySequence_SIZE(sequence);
if (unlikely(size != 3)) {
if (size > 3) __Pyx_RaiseTooManyValuesError(3);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
__PYX_ERR(0, 23, __pyx_L1_error)
}
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
if (likely(PyTuple_CheckExact(sequence))) {
__pyx_t_3 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_7 = PyTuple_GET_ITEM(sequence, 1);
__pyx_t_8 = PyTuple_GET_ITEM(sequence, 2);
} else {
__pyx_t_3 = PyList_GET_ITEM(sequence, 0);
__pyx_t_7 = PyList_GET_ITEM(sequence, 1);
__pyx_t_8 = PyList_GET_ITEM(sequence, 2);
}
__Pyx_INCREF(__pyx_t_3);
__Pyx_INCREF(__pyx_t_7);
__Pyx_INCREF(__pyx_t_8);
#else
__pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_7);
__pyx_t_8 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_8);
#endif
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
} else {
Py_ssize_t index = -1;
__pyx_t_9 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_9);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_10 = Py_TYPE(__pyx_t_9)->tp_iternext;
index = 0; __pyx_t_3 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed;
__Pyx_GOTREF(__pyx_t_3);
index = 1; __pyx_t_7 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_7)) goto __pyx_L5_unpacking_failed;
__Pyx_GOTREF(__pyx_t_7);
index = 2; __pyx_t_8 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L5_unpacking_failed;
__Pyx_GOTREF(__pyx_t_8);
if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_9), 3) < 0) __PYX_ERR(0, 23, __pyx_L1_error)
__pyx_t_10 = NULL;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
goto __pyx_L6_unpacking_done;
__pyx_L5_unpacking_failed:;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_10 = NULL;
if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index);
__PYX_ERR(0, 23, __pyx_L1_error)
__pyx_L6_unpacking_done:;
}
__Pyx_XDECREF_SET(__pyx_v_word, __pyx_t_3);
__pyx_t_3 = 0;
__Pyx_XDECREF_SET(__pyx_v_start, __pyx_t_7);
__pyx_t_7 = 0;
__Pyx_XDECREF_SET(__pyx_v_end, __pyx_t_8);
__pyx_t_8 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":24
* cdef list _span_tokenize(self, unicode text):
* return [(start, end) for (word, start, end) in jieba.tokenize(text)
* if not self._rule.match(word)] # <<<<<<<<<<<<<<
*
* def __reduce__(self):
*/
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_rule, __pyx_n_s_match); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_7 = NULL;
if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_8))) {
__pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8);
if (likely(__pyx_t_7)) {
PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8);
__Pyx_INCREF(__pyx_t_7);
__Pyx_INCREF(function);
__Pyx_DECREF_SET(__pyx_t_8, function);
}
}
__pyx_t_2 = (__pyx_t_7) ? __Pyx_PyObject_Call2Args(__pyx_t_8, __pyx_t_7, __pyx_v_word) : __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_v_word);
__Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0;
if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_11 < 0)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_12 = ((!__pyx_t_11) != 0);
if (__pyx_t_12) {
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":23
*
* cdef list _span_tokenize(self, unicode text):
* return [(start, end) for (word, start, end) in jieba.tokenize(text) # <<<<<<<<<<<<<<
* if not self._rule.match(word)]
*
*/
__pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__Pyx_INCREF(__pyx_v_start);
__Pyx_GIVEREF(__pyx_v_start);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_start);
__Pyx_INCREF(__pyx_v_end);
__Pyx_GIVEREF(__pyx_v_end);
PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_end);
if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_2))) __PYX_ERR(0, 23, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":24
* cdef list _span_tokenize(self, unicode text):
* return [(start, end) for (word, start, end) in jieba.tokenize(text)
* if not self._rule.match(word)] # <<<<<<<<<<<<<<
*
* def __reduce__(self):
*/
}
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":23
*
* cdef list _span_tokenize(self, unicode text):
* return [(start, end) for (word, start, end) in jieba.tokenize(text) # <<<<<<<<<<<<<<
* if not self._rule.match(word)]
*
*/
}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_r = ((PyObject*)__pyx_t_1);
__pyx_t_1 = 0;
goto __pyx_L0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":22
* self._rule = re.compile(r'^\s*$')
*
* cdef list _span_tokenize(self, unicode text): # <<<<<<<<<<<<<<
* return [(start, end) for (word, start, end) in jieba.tokenize(text)
* if not self._rule.match(word)]
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_AddTraceback("wikidata2vec.utils.tokenizer.jieba_tokenizer.JiebaTokenizer._span_tokenize", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_word);
__Pyx_XDECREF(__pyx_v_start);
__Pyx_XDECREF(__pyx_v_end);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":26
* if not self._rule.match(word)]
*
* def __reduce__(self): # <<<<<<<<<<<<<<
* return (self.__class__, tuple())
*/
/* Python wrapper */
static PyObject *__pyx_pw_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/
static PyObject *__pyx_pw_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0);
__pyx_r = __pyx_pf_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_2__reduce__(((struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_2__reduce__(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__reduce__", 0);
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":27
*
* def __reduce__(self):
* return (self.__class__, tuple()) # <<<<<<<<<<<<<<
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 27, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyTuple_Type))); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 27, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 27, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2);
__pyx_t_1 = 0;
__pyx_t_2 = 0;
__pyx_r = __pyx_t_3;
__pyx_t_3 = 0;
goto __pyx_L0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":26
* if not self._rule.match(word)]
*
* def __reduce__(self): # <<<<<<<<<<<<<<
* return (self.__class__, tuple())
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("wikidata2vec.utils.tokenizer.jieba_tokenizer.JiebaTokenizer.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer __pyx_vtable_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer;
static PyObject *__pyx_tp_new_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer(PyTypeObject *t, PyObject *a, PyObject *k) {
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *p;
PyObject *o = __pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_new(t, a, k);
if (unlikely(!o)) return 0;
p = ((struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *)o);
p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer*)__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer;
p->_rule = Py_None; Py_INCREF(Py_None);
return o;
}
static void __pyx_tp_dealloc_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer(PyObject *o) {
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *p = (struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *)o;
#if CYTHON_USE_TP_FINALIZE
if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) {
if (PyObject_CallFinalizerFromDealloc(o)) return;
}
#endif
PyObject_GC_UnTrack(o);
Py_CLEAR(p->_rule);
#if CYTHON_USE_TYPE_SLOTS
if (PyType_IS_GC(Py_TYPE(o)->tp_base))
#endif
PyObject_GC_Track(o);
if (likely(__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer)) __pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_dealloc(o); else __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer);
}
static int __pyx_tp_traverse_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer(PyObject *o, visitproc v, void *a) {
int e;
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *p = (struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *)o;
e = ((likely(__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer)) ? ((__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_traverse) ? __pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_traverse(o, v, a) : 0) : __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer)); if (e) return e;
if (p->_rule) {
e = (*v)(p->_rule, a); if (e) return e;
}
return 0;
}
static int __pyx_tp_clear_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer(PyObject *o) {
PyObject* tmp;
struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *p = (struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer *)o;
if (likely(__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer)) { if (__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_clear) __pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_clear(o); } else __Pyx_call_next_tp_clear(o, __pyx_tp_clear_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer);
tmp = ((PyObject*)p->_rule);
p->_rule = Py_None; Py_INCREF(Py_None);
Py_XDECREF(tmp);
return 0;
}
static PyMethodDef __pyx_methods_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer[] = {
{"__reduce__", (PyCFunction)__pyx_pw_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_3__reduce__, METH_NOARGS, 0},
{0, 0, 0, 0}
};
static PyTypeObject __pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer = {
PyVarObject_HEAD_INIT(0, 0)
"wikidata2vec.utils.tokenizer.jieba_tokenizer.JiebaTokenizer", /*tp_name*/
sizeof(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer, /*tp_dealloc*/
#if PY_VERSION_HEX < 0x030800b4
0, /*tp_print*/
#endif
#if PY_VERSION_HEX >= 0x030800b4
0, /*tp_vectorcall_offset*/
#endif
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#endif
#if PY_MAJOR_VERSION >= 3
0, /*tp_as_async*/
#endif
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
0, /*tp_doc*/
__pyx_tp_traverse_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer, /*tp_traverse*/
__pyx_tp_clear_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
__pyx_pw_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer_1__init__, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
0, /*tp_version_tag*/
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
#if PY_VERSION_HEX >= 0x030800b1
0, /*tp_vectorcall*/
#endif
#if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000
0, /*tp_print*/
#endif
};
static PyMethodDef __pyx_methods[] = {
{0, 0, 0, 0}
};
#if PY_MAJOR_VERSION >= 3
#if CYTHON_PEP489_MULTI_PHASE_INIT
static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/
static int __pyx_pymod_exec_jieba_tokenizer(PyObject* module); /*proto*/
static PyModuleDef_Slot __pyx_moduledef_slots[] = {
{Py_mod_create, (void*)__pyx_pymod_create},
{Py_mod_exec, (void*)__pyx_pymod_exec_jieba_tokenizer},
{0, NULL}
};
#endif
static struct PyModuleDef __pyx_moduledef = {
PyModuleDef_HEAD_INIT,
"jieba_tokenizer",
0, /* m_doc */
#if CYTHON_PEP489_MULTI_PHASE_INIT
0, /* m_size */
#else
-1, /* m_size */
#endif
__pyx_methods /* m_methods */,
#if CYTHON_PEP489_MULTI_PHASE_INIT
__pyx_moduledef_slots, /* m_slots */
#else
NULL, /* m_reload */
#endif
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
#ifndef CYTHON_SMALL_CODE
#if defined(__clang__)
#define CYTHON_SMALL_CODE
#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
#define CYTHON_SMALL_CODE __attribute__((cold))
#else
#define CYTHON_SMALL_CODE
#endif
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_n_s_JiebaTokenizer, __pyx_k_JiebaTokenizer, sizeof(__pyx_k_JiebaTokenizer), 0, 0, 1, 1},
{&__pyx_n_s_WARN, __pyx_k_WARN, sizeof(__pyx_k_WARN), 0, 0, 1, 1},
{&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1},
{&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1},
{&__pyx_n_s_compile, __pyx_k_compile, sizeof(__pyx_k_compile), 0, 0, 1, 1},
{&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1},
{&__pyx_n_s_jieba, __pyx_k_jieba, sizeof(__pyx_k_jieba), 0, 0, 1, 1},
{&__pyx_n_s_logging, __pyx_k_logging, sizeof(__pyx_k_logging), 0, 0, 1, 1},
{&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
{&__pyx_n_s_match, __pyx_k_match, sizeof(__pyx_k_match), 0, 0, 1, 1},
{&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1},
{&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1},
{&__pyx_n_s_re, __pyx_k_re, sizeof(__pyx_k_re), 0, 0, 1, 1},
{&__pyx_kp_u_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 1, 0, 0},
{&__pyx_n_s_setLogLevel, __pyx_k_setLogLevel, sizeof(__pyx_k_setLogLevel), 0, 0, 1, 1},
{&__pyx_n_s_six, __pyx_k_six, sizeof(__pyx_k_six), 0, 0, 1, 1},
{&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
{&__pyx_n_s_tokenize, __pyx_k_tokenize, sizeof(__pyx_k_tokenize), 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 0}
};
static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) {
return 0;
}
static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);
__Pyx_RefNannyFinishContext();
return 0;
}
static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {
if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
return 0;
__pyx_L1_error:;
return -1;
}
static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/
static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/
static int __Pyx_modinit_global_init_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0);
/*--- Global init code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_variable_export_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0);
/*--- Variable export code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_function_export_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0);
/*--- Function export code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_type_init_code(void) {
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0);
/*--- Type init code ---*/
__pyx_t_1 = PyImport_ImportModule("wikidata2vec.utils.tokenizer.base_tokenizer"); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer = __Pyx_ImportType(__pyx_t_1, "wikidata2vec.utils.tokenizer.base_tokenizer", "BaseTokenizer", sizeof(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer), __Pyx_ImportType_CheckSize_Warn);
if (!__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer = (struct __pyx_vtabstruct_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer*)__Pyx_GetVtable(__pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer->tp_dict); if (unlikely(!__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer = &__pyx_vtable_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer;
__pyx_vtable_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.__pyx_base = *__pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer;
__pyx_vtable_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.__pyx_base._span_tokenize = (PyObject *(*)(struct __pyx_obj_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer *, PyObject *))__pyx_f_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_14JiebaTokenizer__span_tokenize;
__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.tp_base = __pyx_ptype_12wikidata2vec_5utils_9tokenizer_14base_tokenizer_BaseTokenizer;
if (PyType_Ready(&__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer) < 0) __PYX_ERR(0, 16, __pyx_L1_error)
#if PY_VERSION_HEX < 0x030800B1
__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.tp_print = 0;
#endif
if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.tp_dictoffset && __pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.tp_getattro == PyObject_GenericGetAttr)) {
__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.tp_getattro = __Pyx_PyObject_GenericGetAttr;
}
if (__Pyx_SetVtable(__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer.tp_dict, __pyx_vtabptr_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer) < 0) __PYX_ERR(0, 16, __pyx_L1_error)
if (PyObject_SetAttr(__pyx_m, __pyx_n_s_JiebaTokenizer, (PyObject *)&__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer) < 0) __PYX_ERR(0, 16, __pyx_L1_error)
__pyx_ptype_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer = &__pyx_type_12wikidata2vec_5utils_9tokenizer_15jieba_tokenizer_JiebaTokenizer;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_RefNannyFinishContext();
return -1;
}
static int __Pyx_modinit_type_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0);
/*--- Type import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_variable_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0);
/*--- Variable import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
static int __Pyx_modinit_function_import_code(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0);
/*--- Function import code ---*/
__Pyx_RefNannyFinishContext();
return 0;
}
#ifndef CYTHON_NO_PYINIT_EXPORT
#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC
#elif PY_MAJOR_VERSION < 3
#ifdef __cplusplus
#define __Pyx_PyMODINIT_FUNC extern "C" void
#else
#define __Pyx_PyMODINIT_FUNC void
#endif
#else
#ifdef __cplusplus
#define __Pyx_PyMODINIT_FUNC extern "C" PyObject *
#else
#define __Pyx_PyMODINIT_FUNC PyObject *
#endif
#endif
#if PY_MAJOR_VERSION < 3
__Pyx_PyMODINIT_FUNC initjieba_tokenizer(void) CYTHON_SMALL_CODE; /*proto*/
__Pyx_PyMODINIT_FUNC initjieba_tokenizer(void)
#else
__Pyx_PyMODINIT_FUNC PyInit_jieba_tokenizer(void) CYTHON_SMALL_CODE; /*proto*/
__Pyx_PyMODINIT_FUNC PyInit_jieba_tokenizer(void)
#if CYTHON_PEP489_MULTI_PHASE_INIT
{
return PyModuleDef_Init(&__pyx_moduledef);
}
static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) {
#if PY_VERSION_HEX >= 0x030700A1
static PY_INT64_T main_interpreter_id = -1;
PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp);
if (main_interpreter_id == -1) {
main_interpreter_id = current_id;
return (unlikely(current_id == -1)) ? -1 : 0;
} else if (unlikely(main_interpreter_id != current_id))
#else
static PyInterpreterState *main_interpreter = NULL;
PyInterpreterState *current_interpreter = PyThreadState_Get()->interp;
if (!main_interpreter) {
main_interpreter = current_interpreter;
} else if (unlikely(main_interpreter != current_interpreter))
#endif
{
PyErr_SetString(
PyExc_ImportError,
"Interpreter change detected - this module can only be loaded into one interpreter per process.");
return -1;
}
return 0;
}
static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) {
PyObject *value = PyObject_GetAttrString(spec, from_name);
int result = 0;
if (likely(value)) {
if (allow_none || value != Py_None) {
result = PyDict_SetItemString(moddict, to_name, value);
}
Py_DECREF(value);
} else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
} else {
result = -1;
}
return result;
}
static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) {
PyObject *module = NULL, *moddict, *modname;
if (__Pyx_check_single_interpreter())
return NULL;
if (__pyx_m)
return __Pyx_NewRef(__pyx_m);
modname = PyObject_GetAttrString(spec, "name");
if (unlikely(!modname)) goto bad;
module = PyModule_NewObject(modname);
Py_DECREF(modname);
if (unlikely(!module)) goto bad;
moddict = PyModule_GetDict(module);
if (unlikely(!moddict)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad;
if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad;
return module;
bad:
Py_XDECREF(module);
return NULL;
}
static CYTHON_SMALL_CODE int __pyx_pymod_exec_jieba_tokenizer(PyObject *__pyx_pyinit_module)
#endif
#endif
{
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannyDeclarations
#if CYTHON_PEP489_MULTI_PHASE_INIT
if (__pyx_m) {
if (__pyx_m == __pyx_pyinit_module) return 0;
PyErr_SetString(PyExc_RuntimeError, "Module 'jieba_tokenizer' has already been imported. Re-initialisation is not supported.");
return -1;
}
#elif PY_MAJOR_VERSION >= 3
if (__pyx_m) return __Pyx_NewRef(__pyx_m);
#endif
#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("__Pyx_PyMODINIT_FUNC PyInit_jieba_tokenizer(void)", 0);
if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#ifdef __Pxy_PyFrame_Initialize_Offsets
__Pxy_PyFrame_Initialize_Offsets();
#endif
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error)
__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error)
#ifdef __Pyx_CyFunction_USED
if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_FusedFunction_USED
if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_Coroutine_USED
if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_Generator_USED
if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_AsyncGen_USED
if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
#ifdef __Pyx_StopAsyncIteration_USED
if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __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 CYTHON_PEP489_MULTI_PHASE_INIT
__pyx_m = __pyx_pyinit_module;
Py_INCREF(__pyx_m);
#else
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4("jieba_tokenizer", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_d);
__pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_b);
__pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error)
Py_INCREF(__pyx_cython_runtime);
if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error);
/*--- Initialize various global constants etc. ---*/
if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __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_ERR(0, 1, __pyx_L1_error)
#endif
if (__pyx_module_is_main_wikidata2vec__utils__tokenizer__jieba_tokenizer) {
if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
}
#if PY_MAJOR_VERSION >= 3
{
PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error)
if (!PyDict_GetItemString(modules, "wikidata2vec.utils.tokenizer.jieba_tokenizer")) {
if (unlikely(PyDict_SetItemString(modules, "wikidata2vec.utils.tokenizer.jieba_tokenizer", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error)
}
}
#endif
/*--- Builtin init code ---*/
if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
/*--- Constants init code ---*/
if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
/*--- Global type/function init code ---*/
(void)__Pyx_modinit_global_init_code();
(void)__Pyx_modinit_variable_export_code();
(void)__Pyx_modinit_function_export_code();
if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error)
(void)__Pyx_modinit_type_import_code();
(void)__Pyx_modinit_variable_import_code();
(void)__Pyx_modinit_function_import_code();
/*--- Execution code ---*/
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error)
#endif
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":6
*
* from __future__ import unicode_literals
* import jieba # <<<<<<<<<<<<<<
* import logging
* import re
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_jieba, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_jieba, __pyx_t_1) < 0) __PYX_ERR(0, 6, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":7
* from __future__ import unicode_literals
* import jieba
* import logging # <<<<<<<<<<<<<<
* import re
* import six
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_logging, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 7, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_logging, __pyx_t_1) < 0) __PYX_ERR(0, 7, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":8
* import jieba
* import logging
* import re # <<<<<<<<<<<<<<
* import six
*
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_re, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_re, __pyx_t_1) < 0) __PYX_ERR(0, 8, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":9
* import logging
* import re
* import six # <<<<<<<<<<<<<<
*
* from .base_tokenizer cimport BaseTokenizer
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_six, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_six, __pyx_t_1) < 0) __PYX_ERR(0, 9, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":13
* from .base_tokenizer cimport BaseTokenizer
*
* jieba.setLogLevel(logging.WARN) # <<<<<<<<<<<<<<
*
*
*/
__Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_jieba); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_setLogLevel); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 13, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_logging); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WARN); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 13, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "wikidata2vec/utils/tokenizer/jieba_tokenizer.pyx":1
* # -*- coding: utf-8 -*- # <<<<<<<<<<<<<<
* # cython: profile=False
* # License: Apache License 2.0
*/
__pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/*--- Wrapped vars code ---*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
if (__pyx_m) {
if (__pyx_d) {
__Pyx_AddTraceback("init wikidata2vec.utils.tokenizer.jieba_tokenizer", __pyx_clineno, __pyx_lineno, __pyx_filename);
}
Py_CLEAR(__pyx_m);
} else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "init wikidata2vec.utils.tokenizer.jieba_tokenizer");
}
__pyx_L0:;
__Pyx_RefNannyFinishContext();
#if CYTHON_PEP489_MULTI_PHASE_INIT
return (__pyx_m != NULL) ? 0 : -1;
#elif PY_MAJOR_VERSION >= 3
return __pyx_m;
#else
return;
#endif
}
/* --- Runtime support code --- */
/* Refnanny */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
PyObject *m = NULL, *p = NULL;
void *r = NULL;
m = PyImport_ImportModule(modname);
if (!m) goto end;
p = PyObject_GetAttrString(m, "RefNannyAPI");
if (!p) goto end;
r = PyLong_AsVoidPtr(p);
end:
Py_XDECREF(p);
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
#endif
/* RaiseArgTupleInvalid */
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);
}
/* KeywordStringCheck */
static int __Pyx_CheckKeywordStrings(
PyObject *kwdict,
const char* function_name,
int kw_allowed)
{
PyObject* key = 0;
Py_ssize_t pos = 0;
#if CYTHON_COMPILING_IN_PYPY
if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0))
goto invalid_keyword;
return 1;
#else
while (PyDict_Next(kwdict, &pos, &key, 0)) {
#if PY_MAJOR_VERSION < 3
if (unlikely(!PyString_Check(key)))
#endif
if (unlikely(!PyUnicode_Check(key)))
goto invalid_keyword_type;
}
if ((!kw_allowed) && unlikely(key))
goto invalid_keyword;
return 1;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings", function_name);
return 0;
#endif
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
return 0;
}
/* PyObjectGetAttrStr */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
PyTypeObject* tp = Py_TYPE(obj);
if (likely(tp->tp_getattro))
return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
if (likely(tp->tp_getattr))
return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
return PyObject_GetAttr(obj, attr_name);
}
#endif
/* GetBuiltinName */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
if (unlikely(!result)) {
PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
"name '%U' is not defined", name);
#else
"name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
}
return result;
}
/* PyDictVersioning */
#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) {
PyObject *dict = Py_TYPE(obj)->tp_dict;
return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0;
}
static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) {
PyObject **dictptr = NULL;
Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset;
if (offset) {
#if CYTHON_COMPILING_IN_CPYTHON
dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj);
#else
dictptr = _PyObject_GetDictPtr(obj);
#endif
}
return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0;
}
static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) {
PyObject *dict = Py_TYPE(obj)->tp_dict;
if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict)))
return 0;
return obj_dict_version == __Pyx_get_object_dict_version(obj);
}
#endif
/* GetModuleGlobalName */
#if CYTHON_USE_DICT_VERSIONS
static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value)
#else
static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name)
#endif
{
PyObject *result;
#if !CYTHON_AVOID_BORROWED_REFS
#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1
result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash);
__PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version)
if (likely(result)) {
return __Pyx_NewRef(result);
} else if (unlikely(PyErr_Occurred())) {
return NULL;
}
#else
result = PyDict_GetItem(__pyx_d, name);
__PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version)
if (likely(result)) {
return __Pyx_NewRef(result);
}
#endif
#else
result = PyObject_GetItem(__pyx_d, name);
__PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version)
if (likely(result)) {
return __Pyx_NewRef(result);
}
PyErr_Clear();
#endif
return __Pyx_GetBuiltinName(name);
}
/* PyCFunctionFastCall */
#if CYTHON_FAST_PYCCALL
static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) {
PyCFunctionObject *func = (PyCFunctionObject*)func_obj;
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
PyObject *self = PyCFunction_GET_SELF(func);
int flags = PyCFunction_GET_FLAGS(func);
assert(PyCFunction_Check(func));
assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)));
assert(nargs >= 0);
assert(nargs == 0 || args != NULL);
/* _PyCFunction_FastCallDict() must not be called with an exception set,
because it may clear it (directly or indirectly) and so the
caller loses its exception */
assert(!PyErr_Occurred());
if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) {
return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL);
} else {
return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs);
}
}
#endif
/* PyFunctionFastCall */
#if CYTHON_FAST_PYCALL
static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na,
PyObject *globals) {
PyFrameObject *f;
PyThreadState *tstate = __Pyx_PyThreadState_Current;
PyObject **fastlocals;
Py_ssize_t i;
PyObject *result;
assert(globals != NULL);
/* XXX Perhaps we should create a specialized
PyFrame_New() that doesn't take locals, but does
take builtins without sanity checking them.
*/
assert(tstate != NULL);
f = PyFrame_New(tstate, co, globals, NULL);
if (f == NULL) {
return NULL;
}
fastlocals = __Pyx_PyFrame_GetLocalsplus(f);
for (i = 0; i < na; i++) {
Py_INCREF(*args);
fastlocals[i] = *args++;
}
result = PyEval_EvalFrameEx(f,0);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
return result;
}
#if 1 || PY_VERSION_HEX < 0x030600B1
static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) {
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject *closure;
#if PY_MAJOR_VERSION >= 3
PyObject *kwdefs;
#endif
PyObject *kwtuple, **k;
PyObject **d;
Py_ssize_t nd;
Py_ssize_t nk;
PyObject *result;
assert(kwargs == NULL || PyDict_Check(kwargs));
nk = kwargs ? PyDict_Size(kwargs) : 0;
if (Py_EnterRecursiveCall((char*)" while calling a Python object")) {
return NULL;
}
if (
#if PY_MAJOR_VERSION >= 3
co->co_kwonlyargcount == 0 &&
#endif
likely(kwargs == NULL || nk == 0) &&
co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
if (argdefs == NULL && co->co_argcount == nargs) {
result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals);
goto done;
}
else if (nargs == 0 && argdefs != NULL
&& co->co_argcount == Py_SIZE(argdefs)) {
/* function called with no arguments, but all parameters have
a default value: use default values as arguments .*/
args = &PyTuple_GET_ITEM(argdefs, 0);
result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals);
goto done;
}
}
if (kwargs != NULL) {
Py_ssize_t pos, i;
kwtuple = PyTuple_New(2 * nk);
if (kwtuple == NULL) {
result = NULL;
goto done;
}
k = &PyTuple_GET_ITEM(kwtuple, 0);
pos = i = 0;
while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) {
Py_INCREF(k[i]);
Py_INCREF(k[i+1]);
i += 2;
}
nk = i / 2;
}
else {
kwtuple = NULL;
k = NULL;
}
closure = PyFunction_GET_CLOSURE(func);
#if PY_MAJOR_VERSION >= 3
kwdefs = PyFunction_GET_KW_DEFAULTS(func);
#endif
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
else {
d = NULL;
nd = 0;
}
#if PY_MAJOR_VERSION >= 3
result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL,
args, (int)nargs,
k, (int)nk,
d, (int)nd, kwdefs, closure);
#else
result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL,
args, (int)nargs,
k, (int)nk,
d, (int)nd, closure);
#endif
Py_XDECREF(kwtuple);
done:
Py_LeaveRecursiveCall();
return result;
}
#endif
#endif
/* PyObjectCall */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyObject *result;
ternaryfunc call = func->ob_type->tp_call;
if (unlikely(!call))
return PyObject_Call(func, arg, kw);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = (*call)(func, arg, kw);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* PyObjectCall2Args */
static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) {
PyObject *args, *result = NULL;
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(function)) {
PyObject *args[2] = {arg1, arg2};
return __Pyx_PyFunction_FastCall(function, args, 2);
}
#endif
#if CYTHON_FAST_PYCCALL
if (__Pyx_PyFastCFunction_Check(function)) {
PyObject *args[2] = {arg1, arg2};
return __Pyx_PyCFunction_FastCall(function, args, 2);
}
#endif
args = PyTuple_New(2);
if (unlikely(!args)) goto done;
Py_INCREF(arg1);
PyTuple_SET_ITEM(args, 0, arg1);
Py_INCREF(arg2);
PyTuple_SET_ITEM(args, 1, arg2);
Py_INCREF(function);
result = __Pyx_PyObject_Call(function, args, NULL);
Py_DECREF(args);
Py_DECREF(function);
done:
return result;
}
/* PyObjectCallMethO */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) {
PyObject *self, *result;
PyCFunction cfunc;
cfunc = PyCFunction_GET_FUNCTION(func);
self = PyCFunction_GET_SELF(func);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = cfunc(self, arg);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* PyObjectCallOneArg */
#if CYTHON_COMPILING_IN_CPYTHON
static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) {
PyObject *result;
PyObject *args = PyTuple_New(1);
if (unlikely(!args)) return NULL;
Py_INCREF(arg);
PyTuple_SET_ITEM(args, 0, arg);
result = __Pyx_PyObject_Call(func, args, NULL);
Py_DECREF(args);
return result;
}
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(func)) {
return __Pyx_PyFunction_FastCall(func, &arg, 1);
}
#endif
if (likely(PyCFunction_Check(func))) {
if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) {
return __Pyx_PyObject_CallMethO(func, arg);
#if CYTHON_FAST_PYCCALL
} else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) {
return __Pyx_PyCFunction_FastCall(func, &arg, 1);
#endif
}
}
return __Pyx__PyObject_CallOneArg(func, arg);
}
#else
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) {
PyObject *result;
PyObject *args = PyTuple_Pack(1, arg);
if (unlikely(!args)) return NULL;
result = __Pyx_PyObject_Call(func, args, NULL);
Py_DECREF(args);
return result;
}
#endif
/* RaiseTooManyValuesToUnpack */
static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
PyErr_Format(PyExc_ValueError,
"too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected);
}
/* RaiseNeedMoreValuesToUnpack */
static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
PyErr_Format(PyExc_ValueError,
"need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack",
index, (index == 1) ? "" : "s");
}
/* IterFinish */
static CYTHON_INLINE int __Pyx_IterFinish(void) {
#if CYTHON_FAST_THREAD_STATE
PyThreadState *tstate = __Pyx_PyThreadState_Current;
PyObject* exc_type = tstate->curexc_type;
if (unlikely(exc_type)) {
if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) {
PyObject *exc_value, *exc_tb;
exc_value = tstate->curexc_value;
exc_tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
Py_DECREF(exc_type);
Py_XDECREF(exc_value);
Py_XDECREF(exc_tb);
return 0;
} else {
return -1;
}
}
return 0;
#else
if (unlikely(PyErr_Occurred())) {
if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) {
PyErr_Clear();
return 0;
} else {
return -1;
}
}
return 0;
#endif
}
/* UnpackItemEndCheck */
static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) {
if (unlikely(retval)) {
Py_DECREF(retval);
__Pyx_RaiseTooManyValuesError(expected);
return -1;
} else {
return __Pyx_IterFinish();
}
return 0;
}
/* PyObjectCallNoArg */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) {
#if CYTHON_FAST_PYCALL
if (PyFunction_Check(func)) {
return __Pyx_PyFunction_FastCall(func, NULL, 0);
}
#endif
#ifdef __Pyx_CyFunction_USED
if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func)))
#else
if (likely(PyCFunction_Check(func)))
#endif
{
if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) {
return __Pyx_PyObject_CallMethO(func, NULL);
}
}
return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL);
}
#endif
/* CallNextTpDealloc */
static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) {
PyTypeObject* type = Py_TYPE(obj);
while (type && type->tp_dealloc != current_tp_dealloc)
type = type->tp_base;
while (type && type->tp_dealloc == current_tp_dealloc)
type = type->tp_base;
if (type)
type->tp_dealloc(obj);
}
/* CallNextTpTraverse */
static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) {
PyTypeObject* type = Py_TYPE(obj);
while (type && type->tp_traverse != current_tp_traverse)
type = type->tp_base;
while (type && type->tp_traverse == current_tp_traverse)
type = type->tp_base;
if (type && type->tp_traverse)
return type->tp_traverse(obj, v, a);
return 0;
}
/* CallNextTpClear */
static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) {
PyTypeObject* type = Py_TYPE(obj);
while (type && type->tp_clear != current_tp_clear)
type = type->tp_base;
while (type && type->tp_clear == current_tp_clear)
type = type->tp_base;
if (type && type->tp_clear)
type->tp_clear(obj);
}
/* TypeImport */
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name,
size_t size, enum __Pyx_ImportType_CheckSize check_size)
{
PyObject *result = 0;
char warning[200];
Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
PyObject *py_basicsize;
#endif
result = PyObject_GetAttrString(module, class_name);
if (!result)
goto bad;
if (!PyType_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%.200s.%.200s is not a type object",
module_name, class_name);
goto bad;
}
#ifndef Py_LIMITED_API
basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
if (!py_basicsize)
goto bad;
basicsize = PyLong_AsSsize_t(py_basicsize);
Py_DECREF(py_basicsize);
py_basicsize = 0;
if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
goto bad;
#endif
if ((size_t)basicsize < size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
goto bad;
}
if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
goto bad;
}
else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) {
PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility. "
"Expected %zd from C header, got %zd from PyObject",
module_name, class_name, size, basicsize);
if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
}
return (PyTypeObject *)result;
bad:
Py_XDECREF(result);
return NULL;
}
#endif
/* GetVTable */
static void* __Pyx_GetVtable(PyObject *dict) {
void* ptr;
PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable);
if (!ob)
goto bad;
#if PY_VERSION_HEX >= 0x02070000
ptr = PyCapsule_GetPointer(ob, 0);
#else
ptr = PyCObject_AsVoidPtr(ob);
#endif
if (!ptr && !PyErr_Occurred())
PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type");
Py_DECREF(ob);
return ptr;
bad:
Py_XDECREF(ob);
return NULL;
}
/* PyObject_GenericGetAttrNoDict */
#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000
static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) {
PyErr_Format(PyExc_AttributeError,
#if PY_MAJOR_VERSION >= 3
"'%.50s' object has no attribute '%U'",
tp->tp_name, attr_name);
#else
"'%.50s' object has no attribute '%.400s'",
tp->tp_name, PyString_AS_STRING(attr_name));
#endif
return NULL;
}
static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) {
PyObject *descr;
PyTypeObject *tp = Py_TYPE(obj);
if (unlikely(!PyString_Check(attr_name))) {
return PyObject_GenericGetAttr(obj, attr_name);
}
assert(!tp->tp_dictoffset);
descr = _PyType_Lookup(tp, attr_name);
if (unlikely(!descr)) {
return __Pyx_RaiseGenericGetAttributeError(tp, attr_name);
}
Py_INCREF(descr);
#if PY_MAJOR_VERSION < 3
if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS)))
#endif
{
descrgetfunc f = Py_TYPE(descr)->tp_descr_get;
if (unlikely(f)) {
PyObject *res = f(descr, obj, (PyObject *)tp);
Py_DECREF(descr);
return res;
}
}
return descr;
}
#endif
/* PyObject_GenericGetAttr */
#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000
static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) {
if (unlikely(Py_TYPE(obj)->tp_dictoffset)) {
return PyObject_GenericGetAttr(obj, attr_name);
}
return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name);
}
#endif
/* SetVTable */
static int __Pyx_SetVtable(PyObject *dict, void *vtable) {
#if PY_VERSION_HEX >= 0x02070000
PyObject *ob = PyCapsule_New(vtable, 0, 0);
#else
PyObject *ob = PyCObject_FromVoidPtr(vtable, 0);
#endif
if (!ob)
goto bad;
if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0)
goto bad;
Py_DECREF(ob);
return 0;
bad:
Py_XDECREF(ob);
return -1;
}
/* Import */
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) {
PyObject *empty_list = 0;
PyObject *module = 0;
PyObject *global_dict = 0;
PyObject *empty_dict = 0;
PyObject *list;
#if PY_MAJOR_VERSION < 3
PyObject *py_import;
py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import);
if (!py_import)
goto bad;
#endif
if (from_list)
list = from_list;
else {
empty_list = PyList_New(0);
if (!empty_list)
goto bad;
list = empty_list;
}
global_dict = PyModule_GetDict(__pyx_m);
if (!global_dict)
goto bad;
empty_dict = PyDict_New();
if (!empty_dict)
goto bad;
{
#if PY_MAJOR_VERSION >= 3
if (level == -1) {
if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) {
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, 1);
if (!module) {
if (!PyErr_ExceptionMatches(PyExc_ImportError))
goto bad;
PyErr_Clear();
}
}
level = 0;
}
#endif
if (!module) {
#if PY_MAJOR_VERSION < 3
PyObject *py_level = PyInt_FromLong(level);
if (!py_level)
goto bad;
module = PyObject_CallFunctionObjArgs(py_import,
name, global_dict, empty_dict, list, py_level, (PyObject *)NULL);
Py_DECREF(py_level);
#else
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, level);
#endif
}
}
bad:
#if PY_MAJOR_VERSION < 3
Py_XDECREF(py_import);
#endif
Py_XDECREF(empty_list);
Py_XDECREF(empty_dict);
return module;
}
/* PyErrFetchRestore */
#if CYTHON_FAST_THREAD_STATE
static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) {
PyObject *tmp_type, *tmp_value, *tmp_tb;
tmp_type = tstate->curexc_type;
tmp_value = tstate->curexc_value;
tmp_tb = tstate->curexc_traceback;
tstate->curexc_type = type;
tstate->curexc_value = value;
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) {
*type = tstate->curexc_type;
*value = tstate->curexc_value;
*tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
}
#endif
/* CLineInTraceback */
#ifndef CYTHON_CLINE_IN_TRACEBACK
static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) {
PyObject *use_cline;
PyObject *ptype, *pvalue, *ptraceback;
#if CYTHON_COMPILING_IN_CPYTHON
PyObject **cython_runtime_dict;
#endif
if (unlikely(!__pyx_cython_runtime)) {
return c_line;
}
__Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback);
#if CYTHON_COMPILING_IN_CPYTHON
cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime);
if (likely(cython_runtime_dict)) {
__PYX_PY_DICT_LOOKUP_IF_MODIFIED(
use_cline, *cython_runtime_dict,
__Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback))
} else
#endif
{
PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback);
if (use_cline_obj) {
use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True;
Py_DECREF(use_cline_obj);
} else {
PyErr_Clear();
use_cline = NULL;
}
}
if (!use_cline) {
c_line = 0;
PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False);
}
else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) {
c_line = 0;
}
__Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback);
return c_line;
}
#endif
/* CodeObjectCache */
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 - start) / 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, ((size_t)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);
}
/* AddTraceback */
#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,
0,
0,
0,
0,
__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,
__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;
PyFrameObject *py_frame = 0;
PyThreadState *tstate = __Pyx_PyThreadState_Current;
if (c_line) {
c_line = __Pyx_CLineForTraceback(tstate, c_line);
}
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_frame = PyFrame_New(
tstate, /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
__pyx_d, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
__Pyx_PyFrame_SetLineNumber(py_frame, py_line);
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 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);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(long) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(long),
little, !is_unsigned);
}
}
/* CIntFromPyVerify */
#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0)
#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1)
#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\
{\
func_type value = func_value;\
if (sizeof(target_type) < sizeof(func_type)) {\
if (unlikely(value != (func_type) (target_type) value)) {\
func_type zero = 0;\
if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\
return (target_type) -1;\
if (is_unsigned && unlikely(value < zero))\
goto raise_neg_overflow;\
else\
goto raise_overflow;\
}\
}\
return (target_type) value;\
}
/* CIntFromPy */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 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(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (long) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0])
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) {
return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) {
return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) {
return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (long) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(long) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0])
case -2:
if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
}
#endif
if (sizeof(long) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#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_IntOrLong(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_IntOrLong(x);
if (!tmp) return (long) -1;
val = __Pyx_PyInt_As_long(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to long");
return (long) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
/* CIntFromPy */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 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(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0])
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) {
return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) {
return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) {
return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (int) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0])
case -2:
if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
}
#endif
if (sizeof(int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#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_IntOrLong(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_IntOrLong(x);
if (!tmp) return (int) -1;
val = __Pyx_PyInt_As_int(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to int");
return (int) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
/* FastTypeChecks */
#if CYTHON_COMPILING_IN_CPYTHON
static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) {
while (a) {
a = a->tp_base;
if (a == b)
return 1;
}
return b == &PyBaseObject_Type;
}
static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) {
PyObject *mro;
if (a == b) return 1;
mro = a->tp_mro;
if (likely(mro)) {
Py_ssize_t i, n;
n = PyTuple_GET_SIZE(mro);
for (i = 0; i < n; i++) {
if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
return 1;
}
return 0;
}
return __Pyx_InBases(a, b);
}
#if PY_MAJOR_VERSION == 2
static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) {
PyObject *exception, *value, *tb;
int res;
__Pyx_PyThreadState_declare
__Pyx_PyThreadState_assign
__Pyx_ErrFetch(&exception, &value, &tb);
res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0;
if (unlikely(res == -1)) {
PyErr_WriteUnraisable(err);
res = 0;
}
if (!res) {
res = PyObject_IsSubclass(err, exc_type2);
if (unlikely(res == -1)) {
PyErr_WriteUnraisable(err);
res = 0;
}
}
__Pyx_ErrRestore(exception, value, tb);
return res;
}
#else
static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) {
int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0;
if (!res) {
res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2);
}
return res;
}
#endif
static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) {
Py_ssize_t i, n;
assert(PyExceptionClass_Check(exc_type));
n = PyTuple_GET_SIZE(tuple);
#if PY_MAJOR_VERSION >= 3
for (i=0; i<n; i++) {
if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1;
}
#endif
for (i=0; i<n; i++) {
PyObject *t = PyTuple_GET_ITEM(tuple, i);
#if PY_MAJOR_VERSION < 3
if (likely(exc_type == t)) return 1;
#endif
if (likely(PyExceptionClass_Check(t))) {
if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1;
} else {
}
}
return 0;
}
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) {
if (likely(err == exc_type)) return 1;
if (likely(PyExceptionClass_Check(err))) {
if (likely(PyExceptionClass_Check(exc_type))) {
return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type);
} else if (likely(PyTuple_Check(exc_type))) {
return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type);
} else {
}
}
return PyErr_GivenExceptionMatches(err, exc_type);
}
static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) {
assert(PyExceptionClass_Check(exc_type1));
assert(PyExceptionClass_Check(exc_type2));
if (likely(err == exc_type1 || err == exc_type2)) return 1;
if (likely(PyExceptionClass_Check(err))) {
return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2);
}
return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2));
}
#endif
/* CheckBinaryVersion */
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);
return PyErr_WarnEx(NULL, message, 1);
}
return 0;
}
/* InitStrings */
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
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;
if (PyObject_Hash(*t->p) == -1)
return -1;
++t;
}
return 0;
}
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) {
return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str));
}
static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) {
Py_ssize_t ignore;
return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
#if !CYTHON_PEP393_ENABLED
static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
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
*length = PyBytes_GET_SIZE(defenc);
return defenc_c;
}
#else
static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
if (likely(PyUnicode_IS_ASCII(o))) {
*length = PyUnicode_GET_LENGTH(o);
return PyUnicode_AsUTF8(o);
} else {
PyUnicode_AsASCIIString(o);
return NULL;
}
#else
return PyUnicode_AsUTF8AndSize(o, length);
#endif
}
#endif
#endif
static CYTHON_INLINE const 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)) {
return __Pyx_PyUnicode_AsStringAndSize(o, length);
} else
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
if (PyByteArray_Check(o)) {
*length = PyByteArray_GET_SIZE(o);
return PyByteArray_AS_STRING(o);
} else
#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 int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) {
int retval;
if (unlikely(!x)) return -1;
retval = __Pyx_PyObject_IsTrue(x);
Py_DECREF(x);
return retval;
}
static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) {
#if PY_MAJOR_VERSION >= 3
if (PyLong_Check(result)) {
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"__int__ returned non-int (type %.200s). "
"The ability to return an instance of a strict subclass of int "
"is deprecated, and may be removed in a future version of Python.",
Py_TYPE(result)->tp_name)) {
Py_DECREF(result);
return NULL;
}
return result;
}
#endif
PyErr_Format(PyExc_TypeError,
"__%.4s__ returned non-%.4s (type %.200s)",
type_name, type_name, Py_TYPE(result)->tp_name);
Py_DECREF(result);
return NULL;
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) {
#if CYTHON_USE_TYPE_SLOTS
PyNumberMethods *m;
#endif
const char *name = NULL;
PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x) || PyLong_Check(x)))
#else
if (likely(PyLong_Check(x)))
#endif
return __Pyx_NewRef(x);
#if CYTHON_USE_TYPE_SLOTS
m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
if (m && m->nb_int) {
name = "int";
res = m->nb_int(x);
}
else if (m && m->nb_long) {
name = "long";
res = m->nb_long(x);
}
#else
if (likely(m && m->nb_int)) {
name = "int";
res = m->nb_int(x);
}
#endif
#else
if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) {
res = PyNumber_Int(x);
}
#endif
if (likely(res)) {
#if PY_MAJOR_VERSION < 3
if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) {
#else
if (unlikely(!PyLong_CheckExact(res))) {
#endif
return __Pyx_PyNumber_IntOrLongWrongResultType(res, name);
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
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))) {
if (sizeof(Py_ssize_t) >= sizeof(long))
return PyInt_AS_LONG(b);
else
return PyInt_AsSsize_t(b);
}
#endif
if (likely(PyLong_CheckExact(b))) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)b)->ob_digit;
const Py_ssize_t size = Py_SIZE(b);
if (likely(__Pyx_sst_abs(size) <= 1)) {
ival = likely(size) ? digits[0] : 0;
if (size == -1) ival = -ival;
return ival;
} else {
switch (size) {
case 2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
}
}
#endif
return PyLong_AsSsize_t(b);
}
x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) {
return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False);
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
return PyInt_FromSize_t(ival);
}
#endif /* Py_PYTHON_H */
| [
"b04902103@ntu.edu.tw"
] | b04902103@ntu.edu.tw |
215d4347382548ab310a6b8fa241763edc71eb32 | 90d4cc41fff688a1c051a6c51d9d1ce07dd151bc | /main/PISupervisor/common/src/PICommunicator.cpp | 33f9b784736b447180666a068a0613d76362a5ff | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sim1st/endpointdlp | 20389363ddffaec203c8a033d6aed87f868b611b | f5203f23e93b00c8242c45fa85c26d9b7419e50c | refs/heads/master | 2023-01-05T02:08:38.525279 | 2020-08-10T07:01:00 | 2020-08-10T07:01:00 | 285,734,269 | 0 | 0 | Apache-2.0 | 2020-08-07T04:09:55 | 2020-08-07T04:09:54 | null | UTF-8 | C++ | false | false | 8,619 | cpp | #ifndef _PICOMMUNICATOR_CPP
#define _PICOMMUNICATOR_CPP
#include"PICommunicator.h"
////////////////////////////////////////////////////////////////////////////////
//CPICommSupport
CPICommSupport::CPICommSupport(void) {
clear();
}
CPICommSupport::~CPICommSupport(void) {
}
void CPICommSupport::clear(void) {
savePacket = false;
savePacketPath = "";
}
bool CPICommSupport::save(const char* header, int fd, const void* buf, const size_t count) {
if( false == savePacket ) {
return true;
}
if( savePacketPath.empty() ) {
return false;
}
if( (NULL == buf) || (0 == count) ) {
return false;
}
static int seq = 0;
if( 999 < ++seq ) {
seq = 0;
}
// ----------
time_t t1;
struct tm localTime;
time( &t1 );
localTime = *localtime_r( &t1, &localTime );
char pathDateTime[1024] = {0x00,};
sprintf( pathDateTime, "%s/packet-%04d%02d%02d%02d%02d%02d-%03d-%s-%02d.dat",
savePacketPath.c_str(),
1900+localTime.tm_year, 1+localTime.tm_mon, localTime.tm_mday,
localTime.tm_hour, localTime.tm_min, localTime.tm_sec,
seq, header, fd);
// ----------
int fileFd = -1;
if((fileFd = open( pathDateTime, O_CREAT|O_RDWR|O_SYNC, S_IRUSR|S_IWUSR ))<0 ) {
return false;
}
bool result = true;
if( write( fileFd, buf, count) < 0 ) {
result = false;
}
close(fileFd);
fileFd = -1;
return result;
}
////////////////////////////////////////////////////////////////////////////////
// CPICommunicator
CPICommunicator::CPICommunicator() {
clear();
initialize();
}
CPICommunicator::~CPICommunicator() {
finalize();
}
bool CPICommunicator::initialize(void) {
clear();
pthread_mutex_init( &mutexSend, 0 );
pthread_mutex_init( &mutexRecv, 0 );
return CPIObject::initialize();
}
bool CPICommunicator::finalize(void) {
disconnectTCP();
pthread_mutex_trylock( &mutexSend );
listSend.clear();
pthread_mutex_unlock( &mutexSend );
pthread_mutex_destroy( &mutexSend );
pthread_mutex_trylock( &mutexRecv );
listRecv.clear();
pthread_mutex_unlock( &mutexRecv );
pthread_mutex_destroy( &mutexRecv );
return CPIObject::finalize();
}
void CPICommunicator::clear(void) {
CPIObject::clear();
remainedRecvBufSize = 0;
state = STATE_INACTIVE;
tcpState = TCPSTATE_NOTCONNECTED;
tcpFd = -1;
support.clear();
}
CPICommunicator::COMM_RESULT_T CPICommunicator::sendTCP(void) {
//DEBUG_LOG1( "begin");
COMM_RESULT_T result = RESULT_OK;
size_t listSendCount = listSend.size();
if( 0 == listSendCount ) {
result = RESULT_NOPACKET;
//DEBUG_LOG( "fd(%d) - stop - no_packet", tcpFd);
return result;
}
pthread_mutex_lock( &mutexSend );
if( 0 < listSend.size()) {
tcpState= TCPSTATE_SENDING;
bool isContinue = true;
std::list<CPIPacket>::iterator itr = listSend.begin();
while( (itr != listSend.end()) && (true == isContinue) ) {
const void* buf = itr->serialize();
const size_t count = itr->size();
//DEBUG_LOG( "fd(%d) - sending size(%d)", tcpFd, count);
support.save( "sent", tcpFd, buf, count);
long sent = write( tcpFd, buf, count);
//int errno_save = errno;
//DEBUG_LOG( "fd(%d) - sent(%d)", tcpFd, count);
//if( 0 > sent ) {
//DEBUG_LOG( "write - errno_save(%d:%s)", errno_save, strerror(errno_save));
//}
if( 0 < sent ) {
itr = listSend.erase(itr);
} else {
isContinue = false;
result = RESULT_ERROR;
tcpState= TCPSTATE_NOTCONNECTED;
}
}
if( TCPSTATE_NOTCONNECTED != tcpState) {
tcpState= TCPSTATE_CONNECTED;
}
}
pthread_mutex_unlock( &mutexSend );
//DEBUG_LOG( "fd(%d) - result(%d) - tcp_state(%d)", tcpFd, result, tcpState);
//DEBUG_LOG1( "end");
return result;
}
CPICommunicator::COMM_RESULT_T CPICommunicator::recvTCP(void) {
//DEBUG_LOG1( "begin");
const unsigned long MIN_LENGTH_PIPROTOCOL = sizeof(int);
long readSize = 0;
long readSum = 0;
long parsedSize = 0;
COMM_RESULT_T result = RESULT_OK;
while(true) {
unsigned char * buf = tcpRecvBuffer + remainedRecvBufSize + readSum;
size_t count = sizeof(tcpRecvBuffer) - remainedRecvBufSize - readSum;
readSize = read(tcpFd, buf, count);
//int errno_save = errno;
//DEBUG_LOG( "fd(%d) - read_buf(%d) - remained(%d), read_size(%d) - read_sum(%d)", tcpFd, count, remainedRecvBufSize, readSize, readSum);
if( 0 > readSize ) {
//DEBUG_LOG( "read - errno(%d:%s)", errno_save, strerror(errno_save));
ERROR_LOG("fd(%d) - read_size(%d)", tcpFd, readSize);
break;
}
if(0 == readSize) {
//DEBUG_LOG( "fd(%d) - diconnected", tcpFd);
state = STATE_INACTIVE;
tcpState = TCPSTATE_NOTCONNECTED;
break;
}
support.save( "recv_raw", tcpFd, buf , readSize);
readSum += readSize;
while( true ) {
if( (readSum - parsedSize) < MIN_LENGTH_PIPROTOCOL ) {
break; // need to receive more
}
int packetTotalBytes = 0;
memcpy( (void*)&packetTotalBytes, (void*)(buf + parsedSize), sizeof(int));
if( true == support.bigEndian ) {
packetTotalBytes = ntohl(packetTotalBytes);
}
//DEBUG_LOG( "fd(%d) - total_size(%d, 0x%02X%02X%02X%02X)", tcpFd, packetTotalBytes, buf[0], buf[1], buf[2], buf[3]);
if(MIN_LENGTH_PIPROTOCOL >= packetTotalBytes ) {
ERROR_LOG( "fd(%d) - invalid_total_size(%d, 0x%02X%02X%02X%02X)",
tcpFd, packetTotalBytes, buf[0], buf[1], buf[2], buf[3]);
parsedSize = readSum;
close(tcpFd);
tcpFd = -1;
result = RESULT_ERROR;
tcpState= TCPSTATE_NOTCONNECTED;
break; // error
}
if( (parsedSize + packetTotalBytes ) > readSum ) {
break; // need to receive more
} else {
void* pTemp = buf + parsedSize;
// parsing... bytes --> message
CPIPacket packet;
packet.support.unsignedType = false;
packet.support.bigEndian = support.bigEndian;
parsedSize += packet.deserialize((char*)pTemp);
support.save( "recv", tcpFd, pTemp, packet.size());
// add message to listRecv
pthread_mutex_lock( &mutexRecv );
listRecv.push_back( packet);
pthread_mutex_unlock( &mutexRecv );
}
}
remainedRecvBufSize = readSum - parsedSize;
if( 0 == remainedRecvBufSize ) {
break;
}
else {
memcpy((void*)tcpRecvBuffer, tcpRecvBuffer + parsedSize, remainedRecvBufSize );
}
}
//DEBUG_LOG1( "end");
return result;
}
bool CPICommunicator::initializeTCPClient(void) {
if( 0 == ipString.size() ) {
ERROR_LOG1( "Failed to create stream socket - invalid ip" );
return false;
}
if((tcpFd= socket(AF_INET, SOCK_STREAM, 0))<0) {
DEBUG_LOG( "Failed to create stream socket - %s", strerror(errno) );
return false;
}
memset(&sockAddr, 0x00, sizeof(sockAddr));
sockAddr.sin_family= AF_INET;
sockAddr.sin_addr.s_addr= inet_addr( ipString.c_str() );
sockAddr.sin_port= htons( tcpPort );
return true;
}
bool CPICommunicator::terminateTCPClient(void) {
return disconnectTCP();
}
CPICommunicator::COMM_RESULT_T CPICommunicator::connectTCP(void) {
switch( connect( tcpFd, (struct sockaddr*)&sockAddr, sizeof(sockAddr))) {
case -1 :
ERROR_LOG( "Unable to connect to server: %s", strerror(errno));
return RESULT_ERROR;
break;
default:
break;
}
state = STATE_ACTIVE;
tcpState = TCPSTATE_CONNECTED;
return RESULT_OK;
}
CPICommunicator::COMM_RESULT_T CPICommunicator::disconnectTCP(void) {
if( 0 < tcpFd ) {
if( close(tcpFd) == -1 ) {
//ERROR_LOG( "Unable to disconnect from server: %s", strerror(errno));
}
tcpFd = -1;
}
state = STATE_INACTIVE;
tcpState= TCPSTATE_NOTCONNECTED;
return RESULT_OK;
}
CPICommunicator::COMM_TCPSTATE_T CPICommunicator::selectTCP(void) {
//DEBUG_LOG1( "begin");
if( TCPSTATE_NOTCONNECTED == tcpState ) {
//DEBUG_LOG( "fd(%d)- stop - tcpState(%d)", tcpFd, tcpState);
return tcpState;
}
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
fd_set readfds;
FD_ZERO( &readfds );
FD_SET( tcpFd, &readfds );
long result = select( (tcpFd)+1, &readfds, (fd_set*)0, (fd_set*)0, &tv );
switch( result ) {
case 0:
//DEBUG_LOG1( "select - timeout");
tcpState = TCPSTATE_CONNECTED;
break;
case -1:
//DEBUG_LOG( "fd(%d)- error", tcpFd);
state = STATE_INACTIVE;
tcpState = TCPSTATE_NOTCONNECTED;
break;
default:
//DEBUG_LOG( "fd(%d)- on_recv", tcpFd);
tcpState = TCPSTATE_ONRECV;
break;
}
//DEBUG_LOG( "tcp_state(%d)", tcpState);
//DEBUG_LOG1( "end");
return tcpState;
}
#endif
| [
"sjinlee@somansa.com"
] | sjinlee@somansa.com |
3dbd69a2814badaf8634112a01d78ead3bf90dfa | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /third_party/blink/renderer/core/animation_frame/worker_animation_frame_provider.h | d06b7d02dd3d5ed005db8724150189265b24456e | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 2,526 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_FRAME_WORKER_ANIMATION_FRAME_PROVIDER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_FRAME_WORKER_ANIMATION_FRAME_PROVIDER_H_
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h"
#include "third_party/blink/renderer/platform/graphics/begin_frame_provider.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
class OffscreenCanvas;
// WorkerAnimationFrameProvider is a member of WorkerGlobalScope and it provides
// RequestAnimationFrame capabilities to Workers.
//
// It's responsible for registering and dealing with callbacks.
// And maintains a connection with the Display process, through
// CompositorFrameSink, that is used to v-sync with the display.
//
// OffscreenCanvases can notify when there's been a change on any
// OffscreenCanvas that is connected to a Canvas, and this class signals
// OffscreenCanvases when it's time to dispatch frames.
class CORE_EXPORT WorkerAnimationFrameProvider
: public GarbageCollected<WorkerAnimationFrameProvider>,
public BeginFrameProviderClient {
USING_GARBAGE_COLLECTED_MIXIN(WorkerAnimationFrameProvider);
public:
WorkerAnimationFrameProvider(
ExecutionContext* context,
const BeginFrameProviderParams& begin_frame_provider_params);
int RegisterCallback(FrameRequestCallbackCollection::FrameCallback* callback);
void CancelCallback(int id);
void Trace(Visitor* visitor) override;
// BeginFrameProviderClient
void BeginFrame(const viz::BeginFrameArgs&) override;
void RegisterOffscreenCanvas(OffscreenCanvas*);
void DeregisterOffscreenCanvas(OffscreenCanvas*);
static const int kInvalidCallbackId = -1;
private:
const Member<BeginFrameProvider> begin_frame_provider_;
DISALLOW_COPY_AND_ASSIGN(WorkerAnimationFrameProvider);
FrameRequestCallbackCollection callback_collection_;
HeapLinkedHashSet<WeakMember<OffscreenCanvas>> offscreen_canvases_;
Member<ExecutionContext> context_;
base::WeakPtrFactory<WorkerAnimationFrameProvider> weak_factory_{this};
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_FRAME_WORKER_ANIMATION_FRAME_PROVIDER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b8a94f9616e933852723d488dc62861735f2bfad | 0e846c2b93a09aa83064d8ad1a574f03184984af | /chapter10_Sorting_and_Searching/sortedMatrixSearch.cpp | 085af54fbe6929a157a555ece7b2dd71bb0fac4f | [] | no_license | ihsuy/CTCI | dcb49a2db03a70f9b3ba6fa7d54a1078c576db2d | b791e7325da3d3d9e8c1dabc33fee2068c5af850 | refs/heads/master | 2021-07-05T06:50:04.894758 | 2020-09-01T04:48:49 | 2020-09-01T04:48:49 | 174,632,606 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,408 | cpp | #include <math.h>
#include <algorithm>
#include <bitset>
#include <chrono>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
typedef long long ll;
inline int two(int n) {
return 1 << n;
}
inline int test(int n, int b) {
return (n >> b) & 1;
}
inline void set_bit(int& n, int b) {
n |= two(b);
}
inline void unset_bit(int& n, int b) {
n &= ~two(b);
}
inline int last_bit(int n) {
return n & (-n);
}
inline int ones(int n) {
int res = 0;
while (n && ++res)
n -= n & (-n);
return res;
}
template <typename T>
inline void inspect(T& t) {
typename T::iterator i1 = t.begin(), i2 = t.end();
while (i1 != i2) {
std::cout << (*i1) << ' ';
i1++;
}
std::cout << '\n';
}
/////////////////////////////////////////////////////////////
using namespace std;
/*
Sorted Matrix Search: Given an M x N matrix in which each row
and each column is sorted in ascending order, write a method
to find an element.
*/
pair<int, int> sortedMatrixSearch_dumb(const vector<vector<int>>& m,
const int& val) {
int width = m[0].size(), height = m.size();
vector<bool> isValidCol(width, true);
vector<bool> isValidRow(height, true);
// look at margin to elimiated invalid rows and colums
for (int i = 0; i < width; ++i) {
if (not(val >= m[0][i] and val <= m[height - 1][i])) {
isValidCol[i] = false;
}
if (val == m[0][i]) {
return {0, i};
}
if (val == m[height - 1][i]) {
return {height - 1, i};
}
}
for (int i = 0; i < height; ++i) {
if (not(val >= m[i][0] and val <= m[i][width - 1])) {
isValidRow[i] = false;
}
if (val == m[i][0]) {
return {i, 0};
}
if (val == m[i][width - 1]) {
return {i, width - 1};
}
}
for (int i = 1; i < height - 1; ++i) {
if (isValidRow[i]) {
for (int j = 1; j < width - 1; ++j) {
if (isValidCol[j]) {
if (m[i][j] == val) {
return {i, j};
}
if (m[i][j] > val) {
int r = i, c = j;
while (r < height - 1) {
isValidRow[r] = false;
r++;
}
while (c < width - 1) {
isValidCol[c] = false;
c++;
}
}
}
}
}
}
return {-1, -1};
}
pair<int, int> sortedMatrixSearch_optimal(const vector<vector<int>>& m,
const int& val) {
int width = m[0].size(), height = m.size();
// starting point
int r = 0;
int c = width - 1;
while (r < height and c < width) {
int cur = m[r][c];
if (cur == val) {
return {r, c};
}
if (cur > val) {
c--;
} else if (cur < val) {
r++;
}
}
return {-1, -1};
}
pair<int, int> sortedMatrixBinarySearch(const vector<vector<int>>& m,
const int& rowl,
const int& rowr,
const int& coll,
const int& colr,
const int& val) {
// cout << "rowl: " << rowl << " rowr: " << rowr << " coll: " << coll << "
// colr: " << colr << '\n';
int rl = rowl, rr = rowr, cl = coll, cr = colr;
if (rl > rr or cl > cr) {
return {-1, -1};
}
int prev_r = rl, prev_c = cl;
while (rl <= rr and cl <= cr) {
if (m[rl][cl] == val) {
return {rl, cl};
}
if (m[rl][cl] > val) {
// cout << "found diag: " << rl << " " << cl << endl;
auto result =
sortedMatrixBinarySearch(m, rl, rr, coll, prev_c, val);
if (result != pair<int, int>(-1, -1)) {
return result;
}
return sortedMatrixBinarySearch(m, rowl, prev_r, cl, colr, val);
}
// iterative alone diagonal
prev_r = rl;
prev_c = cl;
rl++;
cl++;
}
if (rl > rr and cl <= cr and val > m[prev_r][prev_c]) {
return sortedMatrixBinarySearch(m, rowl, prev_r, prev_c + 1, cr, val);
} else if (cl > cr and rl <= rr and val > m[prev_r][prev_c]) {
return sortedMatrixBinarySearch(m, prev_r + 1, rr, coll, prev_c, val);
}
return {-1, -1};
}
int main() {
vector<vector<int>> m{{1, 3, 4, 6, 7}, {4, 5, 5, 7, 9},
{5, 5, 6, 7, 10}, {6, 8, 9, 9, 10},
{7, 9, 10, 10, 11}, {8, 11, 19, 20, 21}};
auto result = sortedMatrixSearch_optimal(m, 8);
cout << "optimal r: " << result.first << " c: " << result.second << '\n';
result =
sortedMatrixBinarySearch(m, 0, m.size() - 1, 0, m[0].size() - 1, 19);
cout << "r: " << result.first << " c: " << result.second << '\n';
return 0;
}
| [
"jooehisaishi@gmail.com"
] | jooehisaishi@gmail.com |
e2abdceac1dbab70dd9f8ed9e7f72f8d7b18eb08 | 73f60774d2f915dad00a21eabd9cfd149794fcc8 | /GameEngine/GameEngine/src/graphics/ShaderUniform.h | 3e5b1a220d9bbab454e195fc7ae7f2c0b355f5a4 | [
"Apache-2.0"
] | permissive | SamCooksley/GameEngine | 58e015f6e21755193439c0d4afb75276320e9786 | 3c32eba545428c8aa3227abcb815d8d799ab92d9 | refs/heads/master | 2021-04-12T11:06:53.832122 | 2018-08-30T19:22:38 | 2018-08-30T19:22:38 | 126,532,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | h | #ifndef _ENGINE_GRAPHICS_SHADERUNIFORM_H_
#define _ENGINE_GRAPHICS_SHADERUNIFORM_H_
#include "TypeData.h"
#include "Texture2D.h"
#include "TextureCube.h"
namespace engine {
namespace graphics {
struct ShaderAttribute
{
String name;
Type type;
GLint location;
};
struct ShaderUniform
{
String name;
Type type;
uint size;
GLint location;
int offset;
};
struct ShaderSampler
{
String name;
TextureType type;
uint uniformIndex;
};
} } // engine::graphics
#endif //_ENGINE_GRAPHICS_SHADERUNIFORM_H_ | [
"samqweqwe3@hotmail.co.uk"
] | samqweqwe3@hotmail.co.uk |
7f848e16b3413adf246d8d334d051b8f23e7184f | 4e99270cb1792b540cd0cc7c3042470e2a86f80d | /sources/include/protocol_session/detail/Seller.hpp | a5364f14e6f7230c069916d8008ea1fde642020b | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | abigbug/protocol_session-cpp | ebdd1b3c8950d54a7acf8e61d50d9d2aa7a4acd4 | abb68575bc40d319b15e40725798a57e991525fb | refs/heads/master | 2020-03-27T04:39:58.663662 | 2018-04-09T02:03:56 | 2018-04-09T02:03:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,142 | hpp | /**
* Copyright (C) JoyStream - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Bedeho Mender <bedeho.mender@gmail.com>, February 17 2016
*/
#ifndef JOYSTREAM_PROTOCOLSESSION_SELLER_HPP
#define JOYSTREAM_PROTOCOLSESSION_SELLER_HPP
#include <string>
#include <cstdlib>
namespace joystream {
namespace protocol_session {
namespace status {
template <class ConnectionIdType>
struct Seller;
}
namespace detail {
template <class ConnectionIdType>
class Connection;
template <class ConnectionIdType>
class Seller {
public:
Seller();
Seller(Connection<ConnectionIdType> *);
// Used to request a piece for from the peer, returns total number of pieces awaiting arrival
// Returned value helps caller to determine wether to make additional requests
int requestPiece(int i);
std::queue<int> piecesAwaitingArrival() const;
int numberOfPiecesAwaitingValidation() const;
// Update state to reflect that a recently arrived full piece from this peer is being verified
// We expect the pieces to arrive in same order they were requested. Returns the expected index of the piece
// which arrived
int fullPieceArrived();
// Seller has been removed
void removed();
// Result of validating piece received from this seller
void pieceWasValid();
// Result of validating piece received from this seller
void pieceWasInvalid();
// Returns true ff there are any pieces pending arrival or waiting to be validated
bool isPossiblyOwedPayment() const;
// Status of seller
status::Seller<ConnectionIdType> status() const;
Connection<ConnectionIdType> * connection() const;
bool isGone() const { return _connection == nullptr; }
bool servicingPieceHasTimedOut(const std::chrono::duration<double> &) const;
private:
// Connection identifier for seller
Connection<ConnectionIdType> * _connection;
// Pieces we are expecting from peer in order they were requested
std::queue<int> _piecesAwaitingArrival;
int _numberOfPiecesAwaitingValidation;
// The earliest time the piece at the front of the queue is expected to arrive
// This is effectively the time the first piece request is sent, and updated on arrival of a piece
// This is used to determine if servicing the next piece has timed out.
std::chrono::high_resolution_clock::time_point _frontPieceEarliestExpectedArrival;
// Point in time when requests began. This is reset when the queue is drained and requests restart
// We use this reference point to allow a small window of time for the seller to service pieces
// and can't be considered to be be timed out.
std::chrono::high_resolution_clock::time_point _servicingStartedAt;
};
}
}
}
// Templated type defenitions
#include <protocol_session/detail/Seller.cpp>
#endif // JOYSTREAM_PROTOCOLSESSION_SELLER_HPP
| [
"mokhtar.naamani@gmail.com"
] | mokhtar.naamani@gmail.com |
40c30aa67da5b2b9a77b197dcb155004741a5c50 | d51f530078404a24f1844b53b037bbfed238a784 | /cpp/example_code/dynamodb/dynamodb_samples.h | c019e8d3e466b8781bfe319047f7a4514e725c70 | [
"CC-BY-NC-SA-4.0",
"Apache-2.0",
"MIT"
] | permissive | awsdocs/aws-doc-sdk-examples | fff85d1b4119fe3331174396a5723c7f054203eb | dec41fb589043ac9d8667aac36fb88a53c3abe50 | refs/heads/main | 2023-09-03T19:50:57.809260 | 2023-09-01T16:23:01 | 2023-09-01T16:23:01 | 66,023,605 | 8,240 | 6,037 | Apache-2.0 | 2023-09-14T16:52:02 | 2016-08-18T19:06:57 | Java | UTF-8 | C++ | false | false | 13,649 | h | /*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
#ifndef DYNAMODB_EXAMPLES_DYNAMODB_SAMPLES_H
#define DYNAMODB_EXAMPLES_DYNAMODB_SAMPLES_H
#include <aws/core/client/ClientConfiguration.h>
#include <aws/dynamodb/model/AttributeValue.h>
namespace AwsDoc {
namespace DynamoDB {
/**
* Constants for DynamoDB table creation and access.
*/
extern const Aws::String MOVIE_TABLE_NAME;
extern const Aws::String YEAR_KEY;
extern const Aws::String TITLE_KEY;
extern const Aws::String INFO_KEY;
extern const Aws::String RATING_KEY;
extern const Aws::String PLOT_KEY;
extern const int PROVISIONED_THROUGHPUT_UNITS;
extern const Aws::String ALLOCATION_TAG;
extern const int ASTERISK_FILL_WIDTH;
//! Scenario to modify and query an Amazon DynamoDB table using single PartiQL statements.
/*!
\sa partiqlExecuteScenario()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool partiqlExecuteScenario(
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Scenario to modify and query a DynamoDB table using PartiQL batch statements.
/*!
\sa partiqlBatchExecuteScenario()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool partiqlBatchExecuteScenario(
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Scenario to modify and query a DynamoDB table.
/*!
\sa dynamodbGettingStartedScenario()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool dynamodbGettingStartedScenario(
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Batch get items from different DynamoDB tables.
/*!
\sa batchGetItem()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool batchGetItem(const Aws::Client::ClientConfiguration &clientConfiguration);
//! Batch write items from a JSON file.
/*!
\sa batchWriteItem()
\param jsonFilePath: JSON file path.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool batchWriteItem(const Aws::String &jsonFilePath,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Create a DynamoDB table.
/*!
\sa createTable()
\param tableName: Name for the DynamoDB table.
\param primaryKey: Primary key for the DynamoDB table.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool createTable(const Aws::String &tableName,
const Aws::String &primaryKey,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Create a DynamoDB table with a composite key.
/*!
\sa createTableWithCompositeKey()
\param tableName: Name for the DynamoDB table.
\param partitionKey: Name for the partition (hash) key.
\param sortKey: Name for the sort (range) key.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool createTableWithCompositeKey(const Aws::String &tableName,
const Aws::String &partitionKey,
const Aws::String &sortKey,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Delete a DynamoDB table.
/*!
\sa deleteTable()
\param tableName: The DynamoDB table's name.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool deleteTable(const Aws::String &tableName,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Delete an item from a DynamoDB table.
/*!
\sa deleteItem()
\param tableName: The table name.
\param partitionKey: The partition key.
\param partitionValue: The value for the partition key.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool deleteItem(const Aws::String &tableName,
const Aws::String &partitionKey,
const Aws::String &partitionValue,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Describe a DynamoDB table.
/*!
\sa describeTable()
\param tableName: The DynamoDB table's name.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool describeTable(const Aws::String &tableName,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Get an item from a DynamoDB table.
/*!
\sa getItem()
\param tableName: The table name.
\param partitionKey: The partition key.
\param partitionValue: The value for the partition key.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool getItem(const Aws::String &tableName,
const Aws::String &partitionKey,
const Aws::String &partitionValue,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! List the DynamoDB tables for the current AWS account.
/*!
\sa getItem()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool listTables(const Aws::Client::ClientConfiguration &clientConfiguration);
//! Put an item in a DynamoDB table.
/*!
\sa putItem()
\param tableName: The table name.
\param artistKey: The artist key. This is the partition key for the table.
\param artistValue: The artist value.
\param albumTitleKey: The album title key.
\param albumTitleValue: The album title value.
\param awardsKey: The awards key.
\param awardsValue: The awards value.
\param songTitleKey: The song title key.
\param songTitleValue: The song title value.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool putItem(const Aws::String &tableName,
const Aws::String &artistKey,
const Aws::String &artistValue,
const Aws::String &albumTitleKey,
const Aws::String &albumTitleValue,
const Aws::String &awardsKey,
const Aws::String &awardsValue,
const Aws::String &songTitleKey,
const Aws::String &songTitleValue,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Perform a query on a DynamoDB Table and retrieve items.
/*!
\sa queryItems()
\param tableName: The table name.
\param partitionKey: The partition key.
\param partitionValue: The value for the partition key.
\param projectionExpression: The projections expression, which is ignored if empty.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool queryItems(const Aws::String &tableName,
const Aws::String &partitionKey,
const Aws::String &partitionValue,
const Aws::String &projectionExpression,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Scan a DynamoDB table.
/*!
\sa scanTable()
\param tableName: Name for the DynamoDB table.
\param projectionExpression: An optional projection expression, ignored if empty.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool scanTable(const Aws::String &tableName,
const Aws::String &projectionExpression,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Update a DynamoDB table item.
/*!
\sa updateItem()
\param tableName: The table name.
\param partitionKey: The partition key.
\param partitionValue: The value for the partition key.
\param attributeKey: The key for the attribute to be updated.
\param attributeValue: The value for the attribute to be updated.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool updateItem(const Aws::String &tableName,
const Aws::String &partitionKey,
const Aws::String &partitionValue,
const Aws::String &attributeKey,
const Aws::String &attributeValue,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Update a DynamoDB table.
/*!
\sa updateTable()
\param tableName: Name for the DynamoDB table.
\param readCapacity: Provisioned read capacity.
\param writeCapacity: Provisioned write capacity.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool updateTable(const Aws::String &tableName,
long long readCapacity,
long long writeCapacity,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Create a DynamoDB table to be used in sample code scenarios.
/*!
\sa createMoviesDynamoDBTable()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool createMoviesDynamoDBTable(
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Delete the DynamoDB table used for sample code scenarios.
/*!
\sa deleteMoviesDynamoDBTable()
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool deleteMoviesDynamoDBTable(
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Query a newly created DynamoDB table until it is active.
/*!
\sa waitTableActive()
\param waitTableActive: The DynamoDB table's name.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool waitTableActive(const Aws::String &tableName,
const Aws::Client::ClientConfiguration &clientConfiguration);
//! Command line prompt/response utility function.
/*!
\\sa askQuestion()
\param string: A question prompt.
\param test: Test function for response.
\return Aws::String: User's response.
*/
Aws::String askQuestion(const Aws::String &string,
const std::function<bool(
Aws::String)> &test = [](
const Aws::String &) -> bool { return true; });
//! Command line prompt/response utility function for an integer result.
/*!
\sa askQuestionForInt()
\param string: A question prompt.
\return int: User's response.
*/
int askQuestionForInt(const std::string &string);
//! Command line prompt/response utility function for a float result confined to
//! a range.
/*!
\sa askQuestionForFloatRange()
\param string: A question prompt.
\param low: Low inclusive.
\param high: High inclusive.
\return float: User's response.
*/
float
askQuestionForFloatRange(const Aws::String &string, float low, float high);
//! Command line prompt/response utility function for an int result confined to
//! a range.
/*!
\sa askQuestionForIntRange()
\param string: A question prompt.
\param low: Low inclusive.
\param high: High inclusive.
\return int: User's response.
*/
int askQuestionForIntRange(const Aws::String &string, int low,
int high);
//! Utility function to log movie attributes to std::cout.
/*!
\sa printMovieInfo()
\param movieMap: Map of DynamoDB attribute values.
\return void
*/
void printMovieInfo(
const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &movieMap);
} // DynamoDB
} // AwsDoc
#endif //DYNAMODB_EXAMPLES_DYNAMODB_SAMPLES_H
| [
"noreply@github.com"
] | noreply@github.com |
1ececdc81fb0ee00b3cd78906134c6528f5dc70c | bd14ce57871d7a0bb6a32d7329694e2586e16668 | /Source/WebKit/blackberry/Api/BackingStore_p.h | 49992e34dc542a020edfa1c9a8ad69b254faf7dc | [
"BSD-2-Clause"
] | permissive | chriszhu/webkit | 7f6221e3bf14eb2975e4fa91f189ef5524166092 | eeb67b7dda0c55292cef18ead8a2af5d7fd89e63 | refs/heads/master | 2021-01-15T22:46:37.210810 | 2012-03-03T12:34:40 | 2012-03-03T12:34:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,963 | h | /*
* Copyright (C) 2009, 2010, 2011 Research In Motion Limited. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef BackingStore_p_h
#define BackingStore_p_h
#include "BackingStore.h"
#include "RenderQueue.h"
#include "TileIndex.h"
#include "TileIndexHash.h"
#include "Timer.h"
#include <BlackBerryPlatformGraphics.h>
#include <BlackBerryPlatformGuardedPointer.h>
#include <wtf/HashMap.h>
#include <wtf/Vector.h>
#include <pthread.h>
namespace WebCore {
class IntRect;
class TransformationMatrix;
}
namespace BlackBerry {
namespace WebKit {
class BackingStoreTile;
class TileBuffer;
class WebPage;
class BackingStoreClient;
typedef WTF::HashMap<TileIndex, BackingStoreTile*> TileMap;
class BackingStoreGeometry {
public:
BackingStoreGeometry()
: m_numberOfTilesWide(0)
, m_numberOfTilesHigh(0)
{
}
Platform::IntRect backingStoreRect() const;
Platform::IntSize backingStoreSize() const;
int numberOfTilesWide() const { return m_numberOfTilesWide; }
void setNumberOfTilesWide(int numberOfTilesWide) { m_numberOfTilesWide = numberOfTilesWide; }
int numberOfTilesHigh() const { return m_numberOfTilesHigh; }
void setNumberOfTilesHigh(int numberOfTilesHigh) { m_numberOfTilesHigh = numberOfTilesHigh; }
Platform::IntPoint backingStoreOffset() const { return m_backingStoreOffset; }
void setBackingStoreOffset(const Platform::IntPoint& offset) { m_backingStoreOffset = offset; }
BackingStoreTile* tileAt(TileIndex index) const { return m_tileMap.get(index); }
const TileMap& tileMap() const { return m_tileMap; }
void setTileMap(const TileMap& tileMap) { m_tileMap = tileMap; }
private:
int m_numberOfTilesWide;
int m_numberOfTilesHigh;
Platform::IntPoint m_backingStoreOffset;
TileMap m_tileMap;
};
class BackingStoreWindowBufferState {
public:
Platform::IntRectRegion blittedRegion() const { return m_blittedRegion; }
void addBlittedRegion(const Platform::IntRectRegion& region)
{
m_blittedRegion = Platform::IntRectRegion::unionRegions(m_blittedRegion, region);
}
void clearBlittedRegion(const Platform::IntRectRegion& region)
{
m_blittedRegion = Platform::IntRectRegion::subtractRegions(m_blittedRegion, region);
}
void clearBlittedRegion() { m_blittedRegion = Platform::IntRectRegion(); }
bool isRendered(const Platform::IntPoint& scrollPosition, const Platform::IntRectRegion& contents) const
{
return Platform::IntRectRegion::subtractRegions(contents, m_blittedRegion).isEmpty();
}
private:
Platform::IntRectRegion m_blittedRegion;
};
class BackingStorePrivate : public BlackBerry::Platform::GuardedPointerBase {
public:
enum TileMatrixDirection { Horizontal, Vertical };
BackingStorePrivate();
~BackingStorePrivate();
// Returns whether direct rendering is explicitly turned on or is
// required because the surface pool is not large enough to meet
// the minimum number of tiles required to scroll.
bool shouldDirectRenderingToWindow() const;
bool isSuspended() const { return m_suspendBackingStoreUpdates; }
// Suspends all screen updates so that 'blitContents' is disabled.
void suspendScreenAndBackingStoreUpdates();
// Resumes all screen updates so that 'blitContents' is enabled.
void resumeScreenAndBackingStoreUpdates(BackingStore::ResumeUpdateOperation);
// The functions repaint(), slowScroll(), scroll(), scrollingStartedHelper() are
// called from outside WebKit and within WebKit via ChromeClientBlackBerry.
void repaint(const Platform::IntRect& windowRect, bool contentChanged, bool immediate);
void slowScroll(const Platform::IntSize& delta, const Platform::IntRect& windowRect, bool immediate);
void scroll(const Platform::IntSize& delta, const Platform::IntRect& scrollViewRect, const Platform::IntRect& clipRect);
void scrollingStartedHelper(const Platform::IntSize& delta);
bool shouldSuppressNonVisibleRegularRenderJobs() const;
bool shouldPerformRenderJobs() const;
bool shouldPerformRegularRenderJobs() const;
void startRenderTimer();
void stopRenderTimer();
void renderOnTimer(WebCore::Timer<BackingStorePrivate>*);
void renderOnIdle();
bool willFireTimer();
// Set of helper methods for the scrollBackingStore() method.
Platform::IntRect contentsRect() const;
Platform::IntRect expandedContentsRect() const;
Platform::IntRect visibleContentsRect() const;
Platform::IntRect unclippedVisibleContentsRect() const;
bool shouldMoveLeft(const Platform::IntRect&) const;
bool shouldMoveRight(const Platform::IntRect&) const;
bool shouldMoveUp(const Platform::IntRect&) const;
bool shouldMoveDown(const Platform::IntRect&) const;
bool canMoveX(const Platform::IntRect&) const;
bool canMoveY(const Platform::IntRect&) const;
bool canMoveLeft(const Platform::IntRect&) const;
bool canMoveRight(const Platform::IntRect&) const;
bool canMoveUp(const Platform::IntRect&) const;
bool canMoveDown(const Platform::IntRect&) const;
Platform::IntRect backingStoreRectForScroll(int deltaX, int deltaY, const Platform::IntRect&) const;
void setBackingStoreRect(const Platform::IntRect&);
typedef WTF::Vector<TileIndex> TileIndexList;
TileIndexList indexesForBackingStoreRect(const Platform::IntRect&) const;
Platform::IntPoint originOfLastRenderForTile(const TileIndex&, BackingStoreTile*, const Platform::IntRect& backingStoreRect) const;
TileIndex indexOfLastRenderForTile(const TileIndex&, BackingStoreTile*) const;
TileIndex indexOfTile(const Platform::IntPoint& origin, const Platform::IntRect& backingStoreRect) const;
void clearAndUpdateTileOfNotRenderedRegion(const TileIndex&, BackingStoreTile*, const Platform::IntRectRegion&, const Platform::IntRect& backingStoreRect, bool update = true);
bool isCurrentVisibleJob(const TileIndex&, BackingStoreTile*, const Platform::IntRect& backingStoreRect) const;
// Responsible for scrolling the backing store and updating the
// tile matrix geometry.
void scrollBackingStore(int deltaX, int deltaY);
// Render the tiles dirty rect and invalidate the screen.
bool renderDirectToWindow(const Platform::IntRect&);
// Render the tiles dirty rect.
// NOTE: This will not update the screen. To do that you should call
// blitVisibleContents() after this method.
bool render(const Platform::IntRect&);
// Called by the render queue to ensure that the queue is in a
// constant state before performing a render job.
void requestLayoutIfNeeded() const;
// Helper render methods.
bool renderVisibleContents();
bool renderBackingStore();
void blitVisibleContents(bool force = false);
// Assumes the rect to be in window/viewport coordinates.
void copyPreviousContentsToBackSurfaceOfWindow();
void copyPreviousContentsToBackSurfaceOfTile(const Platform::IntRect&, BackingStoreTile*);
void paintDefaultBackground(const Platform::IntRect& contents, const WebCore::TransformationMatrix&, bool flush);
void blitContents(const Platform::IntRect& dstRect, const Platform::IntRect& contents, bool force = false);
void blitOnIdle();
typedef std::pair<TileIndex, Platform::IntRect> TileRect;
Platform::IntRect blitTileRect(TileBuffer*, const TileRect&, const Platform::IntPoint&, const WebCore::TransformationMatrix&, BackingStoreGeometry*);
#if USE(ACCELERATED_COMPOSITING)
void blendCompositingSurface(const Platform::IntRect& dstRect);
void clearCompositingSurface();
bool drawSubLayers();
bool drawLayersOnCommitIfNeeded();
// WebPage will call this when drawing layers to tell us we don't need to
void willDrawLayersOnCommit() { m_needsDrawLayersOnCommit = false; }
#endif
void blitHorizontalScrollbar(const Platform::IntPoint&);
void blitVerticalScrollbar(const Platform::IntPoint&);
// Returns whether the tile index is currently visible or not.
bool isTileVisible(const TileIndex&) const;
bool isTileVisible(const Platform::IntPoint&) const;
// Returns a rect that is the union of all tiles that are visible.
Platform::IntRect visibleTilesRect() const;
// Used to clip to the visible content for instance.
Platform::IntRect tileVisibleContentsRect(const TileIndex&) const;
// Used to clip to the unclipped visible content for instance which includes overscroll.
Platform::IntRect tileUnclippedVisibleContentsRect(const TileIndex&) const;
// Used to clip to the contents for instance.
Platform::IntRect tileContentsRect(const TileIndex&, const Platform::IntRect&) const;
Platform::IntRect tileContentsRect(const TileIndex&, const Platform::IntRect&, BackingStoreGeometry* state) const;
// This is called by WebPage once load is committed to reset the render queue.
void resetRenderQueue();
// This is called by FrameLoaderClient that explicitly paints on first visible layout.
void clearVisibleZoom();
// This is called by WebPage once load is committed to reset all the tiles.
void resetTiles(bool resetBackground);
// This is called by WebPage after load is complete to update all the tiles.
void updateTiles(bool updateVisible, bool immediate);
// This is called during scroll and by the render queue.
void updateTilesForScrollOrNotRenderedRegion(bool checkLoading = true);
// Reset an individual tile.
void resetTile(const TileIndex&, BackingStoreTile*, bool resetBackground);
// Update an individual tile.
void updateTile(const TileIndex&, bool immediate);
void updateTile(const Platform::IntPoint&, bool immediate);
Platform::IntRect mapFromTilesToTransformedContents(const TileRect&) const;
Platform::IntRect mapFromTilesToTransformedContents(const TileRect&, const Platform::IntRect&) const;
typedef WTF::Vector<TileRect> TileRectList;
TileRectList mapFromTransformedContentsToAbsoluteTileBoundaries(const Platform::IntRect&) const;
TileRectList mapFromTransformedContentsToTiles(const Platform::IntRect&) const;
TileRectList mapFromTransformedContentsToTiles(const Platform::IntRect&, BackingStoreGeometry*) const;
void updateTileMatrixIfNeeded();
// Called by WebPagePrivate::notifyTransformedContentsSizeChanged.
void contentsSizeChanged(const Platform::IntSize&);
// Called by WebPagePrivate::notifyTransformedScrollChanged.
void scrollChanged(const Platform::IntPoint&);
// Called by WebpagePrivate::notifyTransformChanged.
void transformChanged();
// Called by WebpagePrivate::actualVisibleSizeChanged.
void actualVisibleSizeChanged(const Platform::IntSize&);
// Called by WebPagePrivate::setScreenRotated.
void orientationChanged();
// Sets the geometry of the tile matrix.
void setGeometryOfTileMatrix(int numberOfTilesWide, int numberOfTilesHigh);
// Create the surfaces of the backing store.
void createSurfaces();
void createVisibleTileBuffer();
// Various calculations of quantities relevant to backing store.
Platform::IntPoint originOfTile(const TileIndex&) const;
Platform::IntPoint originOfTile(const TileIndex&, const Platform::IntRect&) const;
int minimumNumberOfTilesWide() const;
int minimumNumberOfTilesHigh() const;
Platform::IntSize expandedContentsSize() const;
// The tile geometry methods are all static function.
static int tileWidth();
static int tileHeight();
static Platform::IntSize tileSize();
static Platform::IntRect tileRect();
// This takes transformed contents coordinates.
void renderContents(BlackBerry::Platform::Graphics::Buffer*, const Platform::IntPoint& surfaceOffset, const Platform::IntRect& contentsRect) const;
void blitToWindow(const Platform::IntRect& dstRect, const BlackBerry::Platform::Graphics::Buffer* srcBuffer, const Platform::IntRect& srcRect, bool blend, unsigned char globalAlpha);
void checkerWindow(const Platform::IntRect& dstRect, const Platform::IntPoint& contentsOrigin, double contentsScale);
void invalidateWindow();
void invalidateWindow(const Platform::IntRect& dst);
void clearWindow();
void clearWindow(const Platform::IntRect&, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha = 255);
bool isScrollingOrZooming() const;
void setScrollingOrZooming(bool scrollingOrZooming, bool shouldBlit = true);
void lockBackingStore();
void unlockBackingStore();
BackingStoreGeometry* frontState() const;
BackingStoreGeometry* backState() const;
void swapState();
BackingStoreWindowBufferState* windowFrontBufferState() const;
BackingStoreWindowBufferState* windowBackBufferState() const;
static void setCurrentBackingStoreOwner(WebPage* webPage) { BackingStorePrivate::s_currentBackingStoreOwner = webPage; }
static WebPage* currentBackingStoreOwner() { return BackingStorePrivate::s_currentBackingStoreOwner; }
bool isActive() const;
static WebPage* s_currentBackingStoreOwner;
bool m_suspendScreenUpdates;
bool m_suspendBackingStoreUpdates;
bool m_suspendRenderJobs;
bool m_suspendRegularRenderJobs;
bool m_isScrollingOrZooming;
WebPage* m_webPage;
BackingStoreClient* m_client;
OwnPtr<RenderQueue> m_renderQueue;
mutable Platform::IntSize m_previousDelta;
bool m_defersBlit;
bool m_hasBlitJobs;
mutable unsigned m_frontState;
mutable unsigned m_backState;
unsigned m_currentWindowBackBuffer;
mutable BackingStoreWindowBufferState m_windowBufferState[2];
TileMatrixDirection m_preferredTileMatrixDimension;
Platform::IntRect m_visibleTileBufferRect;
// Last resort timer for rendering.
OwnPtr<WebCore::Timer<BackingStorePrivate> > m_renderTimer;
pthread_mutex_t m_mutex;
int m_blitGeneration;
pthread_mutex_t m_blitGenerationLock;
pthread_cond_t m_blitGenerationCond;
struct timespec m_currentBlitEnd;
#if USE(ACCELERATED_COMPOSITING)
mutable bool m_needsDrawLayersOnCommit; // Not thread safe, WebKit thread only
#endif
};
} // namespace WebKit
} // namespace BlackBerry
#endif // BackingStore_p_h
| [
"commit-queue@webkit.org"
] | commit-queue@webkit.org |
6cd918a96cfbf1000a8db32996569936336ebb08 | 3805f3e3b62bce5a804fd5e9438525713dfcd8ec | /比赛.cpp | ad03425ee5face3725e3abdfe580e71e4f30b11b | [] | no_license | lcl0512/lcl_Cpp | 812e991d082a443e515d361f4b326489416100da | 48f30c426e7b6d3af90e38e0d0e4d88bfc745b31 | refs/heads/master | 2020-07-17T09:35:47.780556 | 2019-12-27T13:38:59 | 2019-12-27T13:38:59 | 205,995,425 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,247 | cpp | #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int MAX = 110;
class CHugeInt {
// 在此处补充你的代码
private:
char maxNum[210];
int len;
public:
CHugeInt(char * s){
strcpy(maxNum,s);
int i=0,j=strlen(s)-1;
while(i<j)
{
swap(maxNum[i],maxNum[j]);
i++;
j--;
}
//cout<<"init:"<<maxNum<<endl;
len=strlen(s);
//cout<<"Init success"<<endl;
}
CHugeInt(){
len=0;
}
CHugeInt(int n){
int i=0;
if(n==0)
{
maxNum[i++]='0';
}else{
while(n)
{
maxNum[i++]=n%10+'0';
n=n/10;
}
}
maxNum[i]='\0';
len=i;
//cout<<maxNum<<endl;
}
CHugeInt operator+(CHugeInt & a)
{
//cout<<"hrer"<<endl;
int i=0,j=0;
int t,sum=0;
CHugeInt temps;
strcpy(temps.maxNum,maxNum);
temps.len=len;
//cout<<"before:"<<temps.maxNum<<endl;
//maxNum=new char[strlen(a.maxNum)+1];
//cout<<a.len<<","<<len<<endl;
int flag=0;
while(j<a.len&&i<temps.len)
{
t=a.maxNum[j]-'0';
int te=temps.maxNum[i]-'0';
sum=t+te;
//cout<<t<<"+"<<te<<":"<<sum<<endl;
if(sum>=10)
{
temps.maxNum[i]=sum%10+'0';
//cout<<temps.maxNum[i]<<endl;
temps.maxNum[i+1]=sum/10+temps.maxNum[i+1];
if(i+1>=temps.len)
{
temps.maxNum[i+1]+='0';
}
flag=1;
}else{
//cout<<"sum:"<<sum<<endl;
flag=0;
temps.maxNum[i]=sum+'0';
}
//cout<<temps.maxNum[i]<<endl;
i++,j++;
sum=0;
}
while(j<a.len)
{
if(flag==1)
{
temps.maxNum[i+1]=a.maxNum[j];
i++,j++;
}else{
temps.maxNum[i]=a.maxNum[j];
i++,j++;
}
}
if(i>=len)
{
if(flag==1){
temps.maxNum[i+1]='\0';
temps.len=i+1;
}
else{
temps.maxNum[i]='\0';
temps.len=i;
}
}
return temps;
}
/*operator char *()
{
return maxNum;
}*/
CHugeInt & operator +=(int n)
{
CHugeInt temps(n);
*this=this->operator+(temps);
//cout<<this->maxNum<<endl;
return *this;
}
friend ostream & operator<<(ostream & os,const CHugeInt & s)
{
int i=0,j=s.len-1;
//cout<<"len:"<<s.len<<endl;
//cout<<"输出:"<<s.maxNum<<endl;
for(;j>=i;j--)
os<<s.maxNum[j];
return os;
}
friend CHugeInt operator+(int n,CHugeInt s)
{
CHugeInt temps(n);
s=s+temps;
return s;
}
friend CHugeInt operator+(CHugeInt s,int n)
{
CHugeInt temps(n);
s=s+temps;
return s;
}
CHugeInt & operator++()
{
(*this)+=1;
//cout<<"前置自增后:"<<this->maxNum<<endl;
return *(this);
}
CHugeInt operator++(int n)
{
CHugeInt temps;
strcpy(temps.maxNum,maxNum);
temps.len=len;
this->operator +=(1);
//cout<<temps.maxNum<<endl;
//cout<<"len:"<<temps.len<<endl;
return temps;
}
};
int main()
{
char s[210];
int n;
while (cin >> s >> n) {
CHugeInt a(s);
CHugeInt b(n);
cout << a + b << endl;
cout << n + a << endl;
cout << a + n << endl;
b += n;
cout << ++ b << endl;
cout << b++ << endl;
cout << b << endl;
}
return 0;
}
| [
"2030315248@qq.com"
] | 2030315248@qq.com |
907d39cd69b119238634572761d437371bfc8446 | 430230531191849e288a2ceb911d9fd913c46af7 | /livox_ros_driver/common/rapidjson/encodedstream.h | 656d85ac1f9056e327bf0d391716430a04e6aebe | [
"BSD-3-Clause",
"Zlib",
"BSD-4-Clause-UC",
"LicenseRef-scancode-rsa-md4",
"BSD-4-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"Beerware",
"RSA-MD",
"ISC",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-rsa-1990"
] | permissive | protoCAD/livox_ros_driver | bf8be9fe825f889a28fc5176b66a3f9fedd12805 | 1c514ed0059328820b82447421e026f621dc03a3 | refs/heads/master | 2022-12-10T11:18:01.905597 | 2020-09-20T09:54:21 | 2020-09-20T09:54:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,079 | h | // Tencent is pleased to support the open source community by making RapidJSON
// available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
// rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License
// at
//
// http://opensource.org/licenses/MIT
//
// 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 RAPIDJSON_ENCODEDSTREAM_H_
#define RAPIDJSON_ENCODEDSTREAM_H_
#include "memorystream.h"
#include "stream.h"
#ifdef __GNUC__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Input byte stream wrapper with a statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8,
UTF16LE, UTF16BE, UTF32LE, UTF32BE. \tparam InputByteStream Type of input
byte stream. For example, FileReadStream.
*/
template <typename Encoding, typename InputByteStream>
class EncodedInputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
public:
typedef typename Encoding::Ch Ch;
EncodedInputStream(InputByteStream &is) : is_(is) {
current_ = Encoding::TakeBOM(is_);
}
Ch Peek() const { return current_; }
Ch Take() {
Ch c = current_;
current_ = Encoding::Take(is_);
return c;
}
size_t Tell() const { return is_.Tell(); }
// Not implemented
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch *PutBegin() {
RAPIDJSON_ASSERT(false);
return 0;
}
size_t PutEnd(Ch *) {
RAPIDJSON_ASSERT(false);
return 0;
}
private:
EncodedInputStream(const EncodedInputStream &);
EncodedInputStream &operator=(const EncodedInputStream &);
InputByteStream &is_;
Ch current_;
};
//! Specialized for UTF8 MemoryStream.
template <> class EncodedInputStream<UTF8<>, MemoryStream> {
public:
typedef UTF8<>::Ch Ch;
EncodedInputStream(MemoryStream &is) : is_(is) {
if (static_cast<unsigned char>(is_.Peek()) == 0xEFu)
is_.Take();
if (static_cast<unsigned char>(is_.Peek()) == 0xBBu)
is_.Take();
if (static_cast<unsigned char>(is_.Peek()) == 0xBFu)
is_.Take();
}
Ch Peek() const { return is_.Peek(); }
Ch Take() { return is_.Take(); }
size_t Tell() const { return is_.Tell(); }
// Not implemented
void Put(Ch) {}
void Flush() {}
Ch *PutBegin() { return 0; }
size_t PutEnd(Ch *) { return 0; }
MemoryStream &is_;
private:
EncodedInputStream(const EncodedInputStream &);
EncodedInputStream &operator=(const EncodedInputStream &);
};
//! Output byte stream wrapper with statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8,
UTF16LE, UTF16BE, UTF32LE, UTF32BE. \tparam OutputByteStream Type of input
byte stream. For example, FileWriteStream.
*/
template <typename Encoding, typename OutputByteStream>
class EncodedOutputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
public:
typedef typename Encoding::Ch Ch;
EncodedOutputStream(OutputByteStream &os, bool putBOM = true) : os_(os) {
if (putBOM)
Encoding::PutBOM(os_);
}
void Put(Ch c) { Encoding::Put(os_, c); }
void Flush() { os_.Flush(); }
// Not implemented
Ch Peek() const {
RAPIDJSON_ASSERT(false);
return 0;
}
Ch Take() {
RAPIDJSON_ASSERT(false);
return 0;
}
size_t Tell() const {
RAPIDJSON_ASSERT(false);
return 0;
}
Ch *PutBegin() {
RAPIDJSON_ASSERT(false);
return 0;
}
size_t PutEnd(Ch *) {
RAPIDJSON_ASSERT(false);
return 0;
}
private:
EncodedOutputStream(const EncodedOutputStream &);
EncodedOutputStream &operator=(const EncodedOutputStream &);
OutputByteStream &os_;
};
#define RAPIDJSON_ENCODINGS_FUNC(x) \
UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
//! Input stream wrapper with dynamically bound encoding and automatic encoding
//! detection.
/*!
\tparam CharType Type of character for reading.
\tparam InputByteStream type of input byte stream to be wrapped.
*/
template <typename CharType, typename InputByteStream>
class AutoUTFInputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
public:
typedef CharType Ch;
//! Constructor.
/*!
\param is input stream to be wrapped.
\param type UTF encoding type if it is not detected from the stream.
*/
AutoUTFInputStream(InputByteStream &is, UTFType type = kUTF8)
: is_(&is), type_(type), hasBOM_(false) {
RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
DetectType();
static const TakeFunc f[] = {RAPIDJSON_ENCODINGS_FUNC(Take)};
takeFunc_ = f[type_];
current_ = takeFunc_(*is_);
}
UTFType GetType() const { return type_; }
bool HasBOM() const { return hasBOM_; }
Ch Peek() const { return current_; }
Ch Take() {
Ch c = current_;
current_ = takeFunc_(*is_);
return c;
}
size_t Tell() const { return is_->Tell(); }
// Not implemented
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch *PutBegin() {
RAPIDJSON_ASSERT(false);
return 0;
}
size_t PutEnd(Ch *) {
RAPIDJSON_ASSERT(false);
return 0;
}
private:
AutoUTFInputStream(const AutoUTFInputStream &);
AutoUTFInputStream &operator=(const AutoUTFInputStream &);
// Detect encoding type with BOM or RFC 4627
void DetectType() {
// BOM (Byte Order Mark):
// 00 00 FE FF UTF-32BE
// FF FE 00 00 UTF-32LE
// FE FF UTF-16BE
// FF FE UTF-16LE
// EF BB BF UTF-8
const unsigned char *c =
reinterpret_cast<const unsigned char *>(is_->Peek4());
if (!c)
return;
unsigned bom =
static_cast<unsigned>(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24));
hasBOM_ = false;
if (bom == 0xFFFE0000) {
type_ = kUTF32BE;
hasBOM_ = true;
is_->Take();
is_->Take();
is_->Take();
is_->Take();
} else if (bom == 0x0000FEFF) {
type_ = kUTF32LE;
hasBOM_ = true;
is_->Take();
is_->Take();
is_->Take();
is_->Take();
} else if ((bom & 0xFFFF) == 0xFFFE) {
type_ = kUTF16BE;
hasBOM_ = true;
is_->Take();
is_->Take();
} else if ((bom & 0xFFFF) == 0xFEFF) {
type_ = kUTF16LE;
hasBOM_ = true;
is_->Take();
is_->Take();
} else if ((bom & 0xFFFFFF) == 0xBFBBEF) {
type_ = kUTF8;
hasBOM_ = true;
is_->Take();
is_->Take();
is_->Take();
}
// RFC 4627: Section 3
// "Since the first two characters of a JSON text will always be ASCII
// characters [RFC0020], it is possible to determine whether an octet
// stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
// at the pattern of nulls in the first four octets."
// 00 00 00 xx UTF-32BE
// 00 xx 00 xx UTF-16BE
// xx 00 00 00 UTF-32LE
// xx 00 xx 00 UTF-16LE
// xx xx xx xx UTF-8
if (!hasBOM_) {
int pattern =
(c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0);
switch (pattern) {
case 0x08:
type_ = kUTF32BE;
break;
case 0x0A:
type_ = kUTF16BE;
break;
case 0x01:
type_ = kUTF32LE;
break;
case 0x05:
type_ = kUTF16LE;
break;
case 0x0F:
type_ = kUTF8;
break;
default:
break; // Use type defined by user.
}
}
// Runtime check whether the size of character type is sufficient. It only
// perform checks with assertion.
if (type_ == kUTF16LE || type_ == kUTF16BE)
RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
if (type_ == kUTF32LE || type_ == kUTF32BE)
RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
}
typedef Ch (*TakeFunc)(InputByteStream &is);
InputByteStream *is_;
UTFType type_;
Ch current_;
TakeFunc takeFunc_;
bool hasBOM_;
};
//! Output stream wrapper with dynamically bound encoding and automatic encoding
//! detection.
/*!
\tparam CharType Type of character for writing.
\tparam OutputByteStream type of output byte stream to be wrapped.
*/
template <typename CharType, typename OutputByteStream>
class AutoUTFOutputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
public:
typedef CharType Ch;
//! Constructor.
/*!
\param os output stream to be wrapped.
\param type UTF encoding type.
\param putBOM Whether to write BOM at the beginning of the stream.
*/
AutoUTFOutputStream(OutputByteStream &os, UTFType type, bool putBOM)
: os_(&os), type_(type) {
RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
// Runtime check whether the size of character type is sufficient. It only
// perform checks with assertion.
if (type_ == kUTF16LE || type_ == kUTF16BE)
RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
if (type_ == kUTF32LE || type_ == kUTF32BE)
RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
static const PutFunc f[] = {RAPIDJSON_ENCODINGS_FUNC(Put)};
putFunc_ = f[type_];
if (putBOM)
PutBOM();
}
UTFType GetType() const { return type_; }
void Put(Ch c) { putFunc_(*os_, c); }
void Flush() { os_->Flush(); }
// Not implemented
Ch Peek() const {
RAPIDJSON_ASSERT(false);
return 0;
}
Ch Take() {
RAPIDJSON_ASSERT(false);
return 0;
}
size_t Tell() const {
RAPIDJSON_ASSERT(false);
return 0;
}
Ch *PutBegin() {
RAPIDJSON_ASSERT(false);
return 0;
}
size_t PutEnd(Ch *) {
RAPIDJSON_ASSERT(false);
return 0;
}
private:
AutoUTFOutputStream(const AutoUTFOutputStream &);
AutoUTFOutputStream &operator=(const AutoUTFOutputStream &);
void PutBOM() {
typedef void (*PutBOMFunc)(OutputByteStream &);
static const PutBOMFunc f[] = {RAPIDJSON_ENCODINGS_FUNC(PutBOM)};
f[type_](*os_);
}
typedef void (*PutFunc)(OutputByteStream &, Ch);
OutputByteStream *os_;
UTFType type_;
PutFunc putFunc_;
};
#undef RAPIDJSON_ENCODINGS_FUNC
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#ifdef __GNUC__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_FILESTREAM_H_
| [
"runeg96@hotmail.com"
] | runeg96@hotmail.com |
e2cfff9e7cb5d0442d4dc532a3983cf845dd4955 | a7b78ab632b77d1ed6b7e1fa46c33eda7a523961 | /samples/factorization_machine/train_fm.cc | 72be517523b2e433f5606a182696666d9a22f4e4 | [
"BSD-2-Clause"
] | permissive | frovedis/frovedis | 80b830da4f3374891f3646a2298d71a3f42a1b2d | 875ae298dfa84ee9815f53db5bf7a8b76a379a6f | refs/heads/master | 2023-05-12T20:06:44.165117 | 2023-04-29T08:30:36 | 2023-04-29T08:30:36 | 138,103,263 | 68 | 13 | BSD-2-Clause | 2018-12-20T10:46:53 | 2018-06-21T01:17:51 | C++ | UTF-8 | C++ | false | false | 3,973 | cc | #include <sstream>
#include <boost/program_options.hpp>
#include <frovedis/ml/fm/fm.hpp>
#include <frovedis/matrix/crs_matrix.hpp>
using namespace boost;
using namespace frovedis;
using namespace std;
int main(int argc, char* argv[]) {
use_frovedis use(argc, argv);
// debug option
set_loglevel(TRACE);
using namespace boost::program_options;
vector<size_t> dims;
double init_stdev;
size_t iteration;
double init_learn_rate;
string optimizer_name;
string input_path, label_path, output_path;
vector<double> regulars;
string task;
size_t batch_size_pernode;
bool binary_input;
options_description opt("option");
opt.add_options()
("dim", value<vector<size_t>>(&dims)->multitoken()->zero_tokens()->default_value({1,1,8}, "'1 1 8'"),
"k0 k1 k2: k0=use bias, k1=use 1-way interactions, k2=dim of 2-way interactions")
("help,h", "print help")
("init-stdev", value<double>(&init_stdev)->default_value(0.1, "0.1"),
"stdev of initialization of 2-way factors")
("iter", value<size_t>(&iteration)->default_value(100, "100"), "number of iteration")
("learn-rate", value<double>(&init_learn_rate)->default_value(0.1, "0.1"),
"learning rate for SGD; dafault=0.1")
("method", value<string>(&optimizer_name)->default_value("SGD"),
"learning method in SGD, SGDA, ALS, MCMC")
("input,i", value<string>(&input_path)->required(), "filename for training data, crs matrix format")
("label,l", value<string>(&label_path)->required(), "filename for training label, dvector format")
("output,o", value<string>(&output_path)->required(), "filename for output model")
("regular", value<vector<double>>(®ulars)->multitoken()->default_value(vector<double>{0.,0.,0.}, "'0 0 0'"),
"r0,r1,r2 for SGD or ALS: r0=bias reg., r1=1-way reg., r2=2-way reg.")
("task,t", value<string>(&task)->default_value("r"), "r=regression, c=classification")
("batchsize,s", value<size_t>(&batch_size_pernode)->default_value(5000, "5000"),
"minibatch size per node")
("binary", bool_switch(&binary_input)->default_value(false, "false"),
"use binary input file")
;
variables_map argmap;
store(command_line_parser(argc,argv).options(opt).allow_unregistered().run(), argmap);
if(argmap.count("help")){
cerr << opt << endl;
exit(1);
}
notify(argmap);
if (dims.size() != 3) throw runtime_error("--dim is required to have 3 values.");
bool dim_0 = dims[0];
bool dim_1 = dims[1];
size_t dim_2 = dims[2];
fm::FmOptimizer optimizer;
if (optimizer_name == "SGD") {
optimizer = FmOptimizer::SGD;
} else if (optimizer_name == "SGDA") {
optimizer = FmOptimizer::SGDA;
} else if (optimizer_name == "ALS") {
optimizer = FmOptimizer::ALS;
} else if (optimizer_name == "MCMC") {
optimizer = FmOptimizer::MCMC;
} else {
throw runtime_error("optimizer specified by -method is not supported.");
}
if (regulars.size() != 3) throw runtime_error("--regular is required to have 3 values.");
double regular_0 = regulars[0];
double regular_1 = regulars[1];
double regular_2 = regulars[2];
bool is_regression;
if (task == "r") {
is_regression = true;
} else if (task == "c") {
is_regression = false;
} else {
throw runtime_error("-task is required to be 'r' or 'c'.");
}
crs_matrix<double> nl_data;
if (binary_input) {
nl_data = make_crs_matrix_loadbinary<double>(input_path);
} else {
nl_data = make_crs_matrix_load<double>(input_path);
}
dvector<double> dv_label;
if (binary_input) {
dv_label = make_dvector_loadbinary<double>(label_path);
} else {
dv_label = make_dvector_loadline<double>(label_path);
}
auto model = fm_train(dim_0, dim_1, dim_2,
init_stdev, iteration, init_learn_rate, optimizer,
regular_0, regular_1, regular_2, is_regression,
nl_data, dv_label, batch_size_pernode);
model.save(output_path);
return 0;
}
| [
"t-araki@dc.jp.nec.com"
] | t-araki@dc.jp.nec.com |
87bda1c89e0de8f9d30c9db40486746808216bf6 | 8c30a57405f79028d5ed4503072d28badeb73e48 | /courses/courses/done/17041/uva227.cpp | 13ab2ba23b15abd02776b42bd2e2aa93fa5e68a8 | [] | no_license | wzh1994/Exercises | a266209e5600797a0a352718437a296c45ff9651 | dfaebdec8fa57661ee718ac828af9cfb50ac2c17 | refs/heads/master | 2020-12-30T23:46:55.909370 | 2017-05-26T15:43:40 | 2017-05-26T15:43:40 | 86,593,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | cpp | #include <iostream>
#include <cstring>
using namespace std;
int puzzle(){
int i = 0;
int end = 0;
while (++i){
char a[6][6];
int pos_x=0, pos_y=0;
memset(a, 0, sizeof(a));
for (int x = 1; x < 6; x++){
int skip = 0;
for (int y = 1; y < 6; y++){
a[x][y]=cin.get();
if (a[x][y] == 'Z') {
end = 1;
break;
}
else if (a[x][y] == ' '){
pos_x = x;
pos_y = y;
}
else if (a[x][y] == '\n'){
a[x][y] = ' ';
pos_x = x;
pos_y = y;
skip = 1;
}
}
if (end) break;
char ch;
if (!skip){
do{
ch = cin.get();
} while (ch != '\n');
}
}
if (end) break;
char ch;
int error = 0;
do{
ch = cin.get();
switch (ch){
case 'A':
if (pos_x < 2) error = 1;
else {
a[pos_x][pos_y] = a[pos_x-1][pos_y];
pos_x -= 1;
a[pos_x][pos_y] = ' ';
}
break;
case 'B':
if (pos_x > 4) error = 1;
else {
a[pos_x][pos_y] = a[pos_x+1][pos_y];
pos_x += 1;
a[pos_x][pos_y] = ' ';
}
break;
case 'L':
if (pos_y < 2) error = 1;
else {
a[pos_x][pos_y] = a[pos_x ][pos_y-1];
pos_y -= 1;
a[pos_x][pos_y] = ' ';
}
break;
case 'R':
if (pos_y > 4) error = 1;
else {
a[pos_x][pos_y] = a[pos_x][pos_y + 1];
pos_y += 1;
a[pos_x][pos_y] = ' ';
}
break;
}
if (error) break;
/*cout << endl;
for (int x = 1; x < 6; x++){
for (int y = 1; y < 6; y++){
cout << a[x][y];
}
cout << endl;
}
cout << endl;*/
} while (ch != '0');
if (i > 1) cout << endl;
cout << "Puzzle #" << i << ":" << endl;
if (error) cout << "This puzzle has no final configuration."<<endl;
else {
for (int x = 1; x < 6; x++){
for (int y = 1; y < 5; y++){
cout << a[x][y]<<" ";
}
cout<<a[x][5] << endl;
}
}
do{
ch = cin.get();
} while (ch != '\n');
}
return 0;
} | [
"scse1082@126.com"
] | scse1082@126.com |
c894ed600f30c41c53246cd595f818991fe87664 | 400f2bd233ba997af651c8fa1d6ce08ef557c97a | /core/SCommandEventFactory.cpp | 5828530d13abcca86ea7869674d8a115b31bd59e | [] | no_license | huhuhu1092/test-server | 08878dbef203479cd0879d59caec1fed70f5ad70 | 57e7d09daca19fdf0298df38ee0c7ad6a7b8f317 | refs/heads/master | 2021-01-01T15:45:14.516984 | 2014-09-06T06:25:35 | 2014-09-06T06:25:35 | 406,540 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 154 | cpp | #include "SCommandEventFactory.h"
#include "SType.h"
SCommandEvent* SCommandEventFactory::create(int commandId, unsigned char* data)
{
return NULL;
}
| [
"wei.lu95@gmail.com"
] | wei.lu95@gmail.com |
ac10114df2bfc51453d516b706e90766f5e7fd27 | 6c49f38248b1f08bcb65995a64cc53052192392d | /src/EPlane.cpp | 18478017a038eea8ce8696ee47169c7494946692 | [] | no_license | Bravewtz/WTZ_LQL_Plane_Game | 1f7a8097dfbfa37bd10f70aabd532f8c7b34b464 | 798ac1a67b57060d72f0defd271282024620c0ed | refs/heads/master | 2020-07-27T09:45:07.172328 | 2019-09-17T12:39:06 | 2019-09-17T12:39:06 | 209,049,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,385 | cpp | #pragma once
#include "stdafx.h"
#include "GameObject.h"
#include "EPlane.h"
#include "resource.h"
#include "EPlane1.h"
CImageList CEPlane::m_ImagesUp;
CImageList CEPlane::m_ImagesDown;
CEPlane::CEPlane(int x, int y, int z,int h,int W,int H):CPlane(x,y,h,W,H),attack(z){}
CEPlane::~CEPlane(){}
//CEPlane::CEPlane(){}
void CEPlane::Show(CDC* pMemDC)
{
POSITION pos1, pos2;
for (pos1 = m_ObjList[1].GetHeadPosition(); (pos2 = pos1) != NULL; )
{
CGameObject* pObj = (CGameObject*)m_ObjList[1].GetNext(pos1);
if (!pObj->Draw(pMemDC, FALSE))
{
m_ObjList[1].RemoveAt(pos2);
delete pObj;
}
}
}
BOOL CEPlane::LoadImageUp()
{
return CGameObject::LoadImage(m_ImagesUp, IDB_BITMAP10, RGB(0, 0, 0), 100, 60, 5);
}
BOOL CEPlane::LoadImageDown()
{
return CGameObject::LoadImage(m_ImagesDown, IDB_BITMAP11, RGB(0, 0, 0), 100, 60, 5);
}
void CEPlane::DoFired(CObList* List)
{
}
BOOL CEPlane::Draw(CDC* pDC, BOOL bPause)
{
if (!bPause)
{
update();
move->update();
m_ptPos.y = m_ptPos.y + move->GetVy();
m_ptPos.x = m_ptPos.x + move->GetVx();
}
if (m_ptPos.y > GAME_HEIGHT + ENEMY_HEIGHT)return FALSE;
if (m_ptPos.y < -ENEMY_HEIGHT)return FALSE;
if (m_ptPos.x > GAME_WIDTH + ENEMY_WIDTH)return FALSE;
if (m_ptPos.y < -ENEMY_WIDTH)return FALSE;
//m_ImagesDown.Draw(pDC, 0, m_ptPos, ILD_TRANSPARENT);
return TRUE;
}
| [
"1658794070@qq.com"
] | 1658794070@qq.com |
5d2e2366a8358406c36ff07a4f861dc0721e75d7 | aa8d0b28b5440b9bebebf9f1aa4588663a84cb58 | /Energo/rep/bill/fDemLimit.h | bdb4baecb10cb77a8c44cea255e12b5e773d0466 | [] | no_license | ssivtsov1/energo | a27713e3276bd2dd31bf329097466c60007be0a8 | bdd7ba17fee9840ebf7ee344488d07f99c05fa85 | refs/heads/master | 2020-03-11T12:52:18.781588 | 2018-04-18T05:49:24 | 2018-04-18T05:49:24 | 130,009,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | h | //---------------------------------------------------------------------------
#ifndef fDemLimitH
#define fDemLimitH
#include "Main.h"
#include "ParamsForm.h"
class TfDemandLimit : public TWTDoc
{
public:
TWTDBGrid* DBGrDoc;
TWTQuery* qDocList;
TWTDBGrid* DBGrDocLines;
TWTQuery* qDocLines;
TDateTime mmgg;
// TWTPanel* PTax;
int id_client;
TZPgSqlQuery *ParentDataSet;
TZPgSqlQuery *ZEqpQuery;
__fastcall TfDemandLimit(TComponent* AOwner,TDataSet* ZQAbonList);
/*
void __fastcall TaxDelete(TObject *Sender);
//void __fastcall TaxRebuild(TObject *Sender);
void __fastcall ClientTaxPrint(TObject *Sender);
void __fastcall AllTaxPrint(TObject *Sender);
void __fastcall CancelInsert(TDataSet* DataSet);
void __fastcall PeriodSel(TObject *Sender);
void __fastcall TaxCorManual(TObject *Sender);
void __fastcall AbonAccept (TObject* Sender);
void __fastcall AbonClose(System::TObject* Sender, bool &CanClose);
void __fastcall PrefAccept (TObject* Sender);
*/
void __fastcall ShowData(void);
void __fastcall NewDocInsert(TDataSet* DataSet);
void __fastcall NewStrInsert(TDataSet* DataSet);
void __fastcall LimitIns(TObject *Sender);
void __fastcall AutoFill(TObject *Sender);
void __fastcall NewStrError (TDataSet* DataSet, EDatabaseError* E, TDataAction &Action);
//int abonent;
};
//---------------------------------------------------------------------------
//extern PACKAGE TWTWinDBGrid *WMeterGrid;
#endif
| [
"globalserg@ukr.net"
] | globalserg@ukr.net |
702d4d9cb8a77e666c12a572462a69dac9bc5421 | c9f2ca0490cb6fa3eb2ce0e5f1e5a15870eea2f5 | /Common/MFC/UtilControls/ControlResizer.h | 9573c2f8f1ed7319858359dd1ebe2dab31b9dab2 | [] | no_license | afrozm/projects | 936dbf1e99e27a8ba5399ad5d6c66f450dd032c7 | 82ba1194d6db3a7662956987586375ec657a3a59 | refs/heads/master | 2021-04-18T20:12:45.481202 | 2021-01-06T09:58:23 | 2021-01-06T09:58:23 | 39,421,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,423 | h | #pragma once
#define RSZF_RIGHT_FIXED 1
#define RSZF_BOTTOM_FIXED 2
#define RSZF_SIZEX_FIXED 4
#define RSZF_SIZEY_FIXED 8
#define RSZF_SIZE_FIXED (RSZF_SIZEY_FIXED|RSZF_SIZEX_FIXED)
#define RSZF_LEFT_FIXED 16
#define RSZF_TOP_FIXED 32
#define RSZF_RESIZE_OPPOSITE 64
#define RSZF_RESIZE_UPDATE 128 // Re pait the client area
#define RSZF_NO_RESIZE 256
struct ResizeProp {
int controlID;
UINT uFlags;
int controlRightMargin;
int controlBottomMargin;
bool operator == (const ResizeProp & prop) const {return controlID == prop.controlID;}
};
class CControlResizer
{
public:
CControlResizer(CDialog *pDialog = NULL);
~CControlResizer(void);
void AddControl(int id, UINT uFlags = RSZF_RIGHT_FIXED | RSZF_BOTTOM_FIXED);
void RemoveControl(int id);
void DoReSize();
void DoReSize(int cx, int cy);
void HideControls(int id, bool bHide = true, bool bLeft = true, bool bHorizontally = false);
void ShowControls(int nCmdShow = SW_SHOW);
void operator=(const CControlResizer& objectSrc);
void Append(const CControlResizer& objectSrc);
private:
void DoResize(const ResizeProp &rszProp, const RECT &dialogClientRect);
const ResizeProp* GetControl(int id) const;
int IsLeft(int baseID, int controlIDToCompare, bool bLeft = true, bool bHorizontally = false) const;
bool IsHidden(int iControlID) const;
CDialog *m_pDialog;
CArrayEx<ResizeProp> m_ResizePropArray;
CArray<int> m_ControlsHidden;
int m_iHiddenLen;
};
| [
"afroz_muzammil@yahoo.com"
] | afroz_muzammil@yahoo.com |
a3f83cc6a3dc95477cd930567c340da86c94eaca | 83a42c32bbf5464f2928876c40983bc082e6dba5 | /W4/Practice5-4/Practice5-4/Practice5-4Doc.h | b84cc2692e17289bc81da74e6c8c93e9f53f04e3 | [] | no_license | miny2627/MFC | f721dfd0517be93c6e6a3bac44636f15e65e10e6 | 62e9a0cf9b85cb58b0e78bd267c9d675d9023816 | refs/heads/master | 2022-12-15T07:54:45.720837 | 2020-09-15T09:22:12 | 2020-09-15T09:22:12 | 295,334,218 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 967 | h |
// Practice5-4Doc.h : CPractice54Doc 클래스의 인터페이스
//
#pragma once
class CPractice54Doc : public CDocument
{
protected: // serialization에서만 만들어집니다.
CPractice54Doc();
DECLARE_DYNCREATE(CPractice54Doc)
// 특성입니다.
public:
// 작업입니다.
public:
// 재정의입니다.
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
#ifdef SHARED_HANDLERS
virtual void InitializeSearchContent();
virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds);
#endif // SHARED_HANDLERS
// 구현입니다.
public:
virtual ~CPractice54Doc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 생성된 메시지 맵 함수
protected:
DECLARE_MESSAGE_MAP()
#ifdef SHARED_HANDLERS
// 검색 처리기에 대한 검색 콘텐츠를 설정하는 도우미 함수
void SetSearchContent(const CString& value);
#endif // SHARED_HANDLERS
};
| [
"miny2627@naver.com"
] | miny2627@naver.com |
073ffc338eea7d06073fbf8dfb3f48aafca4cd66 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/e2/99a89be7a85ac3/main.cpp | d87b9da7800851e7a46355138befe95890138e79 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | #include "/Archive2/0d/a5c6abf40c82f9/main.cpp"
int main()
{
for (Session *ss : iter_map_sessions())
{
frob(ss);
}
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
f75d8eebd145d771d676ba16cb7574312c385d01 | e7ecf0b18ba577446145ade664dc5b9c3d1ea269 | /control1/widget.h | 7c9c70125f6bd8b331466d27e3e79e7925a080d1 | [] | no_license | shyheng/QT | edfa821aa118a370cf35d44c3d4bc4a7c664e2a1 | 1e78d90d49668ca816697f86676179873443f58c | refs/heads/main | 2023-02-17T01:15:48.919448 | 2021-01-16T13:53:56 | 2021-01-16T13:53:56 | 324,552,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | h | #ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
QLabel *label;
QLabel *label_pic;
QLabel *label_move;
};
#endif // WIDGET_H
| [
"shy2210278285@aliyun.com"
] | shy2210278285@aliyun.com |
b77610a6e8bde52f5ddf0b472c070dff930f0f08 | 407dd259ebb5f7472ba851eb3cacc4add4a49b1b | /Engine/ZenCore/Export/Graphic/Binding/zcExpGfxRenderPass.h | 1a65f6d4a33767c2a7503e07a2257e1efbd8d318 | [
"MIT"
] | permissive | isoundy000/ZenEngine | 892c319a6e1a1b6245907d397a934571329b3054 | b27a6f8a62b131df2f7337b0438a903c5505298a | refs/heads/master | 2020-04-27T19:52:22.980823 | 2018-11-10T04:14:20 | 2018-11-10T04:14:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,919 | h | #pragma once
namespace zcExp
{
struct ExportInfoGfxRenderpass : public ExportInfoBase
{
zString mzStageName;
zResID mRasterStateID;
zUInt muPassPriority;
const zArrayBase<zenRes::zGfxRenderPass::ConfigColorRT>* mpaConfigRTColor;
const zenRes::zGfxRenderPass::ConfigDepthRT* mpConfigRTDepth;
zenRes::zGfxStateRaster mrStateRaster;
zVec2U16 mvDim;
zVec2S16 mvOrigin;
};
class ExportGfxRenderPass : public zenRes::zExportData
{
zenClassDeclare(ExportGfxRenderPass, zenRes::zExportData)
public:
//virtual bool Serialize( zcExp::Serializer_Base& _Serializer ){return true;}
zString mzStageName;
zResID mBlendStateID;
zResID mDepthStencilStateID;
zResID mRasterStateID;
zResID mViewStateID;
zUInt muPassPriority;
};
class ExporterGfxRenderPass : public ExporterBase
{
zenClassDeclare(ExporterGfxRenderPass, ExporterBase)
public:
typedef zEngineRef<ExportGfxRenderPass> ExportResultRef; //todo use proper ref class
ExporterGfxRenderPass(const ExportResultRef& _rExportOut);
protected:
virtual bool ExportStart();
ExportResultRef mrExport;
};
zResID CreateGfxRenderpass(const zString& _zStageName, zUInt _uPassPriority, const zenRes::zGfxRenderPass::ConfigColorRT& _ConfigRTColor, const zenRes::zGfxRenderPass::ConfigDepthRT& _ConfigRTDepth, zenRes::zGfxStateRaster _rStateRaster, const zVec2U16& _vDim = zVec2U16(0xFFFF, 0xFFFF), const zVec2S16& _vOrigin = zVec2S16(0,0));
zResID CreateGfxRenderpass(const zString& _zStageName, zUInt _uPassPriority, const zArrayBase<zenRes::zGfxRenderPass::ConfigColorRT>& _aConfigRTColor, const zenRes::zGfxRenderPass::ConfigDepthRT& _ConfigRTDepth, zenRes::zGfxStateRaster _rStateRaster, const zVec2U16& _vDim = zVec2U16(0xFFFF, 0xFFFF), const zVec2S16& _vOrigin = zVec2S16(0,0));
}
| [
"ZenEngine3D@gmail.com"
] | ZenEngine3D@gmail.com |
e050e0bf1782af06cf621c963e19e26770d1841e | 968dbbfccad302afb1bd3503c9a9f3a6f3fbec70 | /src/thread.cpp | 4a9e6c46d955500129211ef6c0c329abf2f3c940 | [] | no_license | BojanG99/OS1-Project | 157c2c5fe01173d4f01ed13e868a2b55b1d4ccf8 | 38e0946c6c41b4b073bd71cbfcdf2db9a6863134 | refs/heads/main | 2023-03-04T00:41:58.895206 | 2021-02-18T00:54:33 | 2021-02-18T00:54:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,100 | cpp | /*
* thread.cpp
*
* Created on: Jul 30, 2020
* Author: OS1
*/
#include"thread.h"
#include"PCB.h"
#include<iostream.h>
#include"SCHEDULE.H"
#include"List.h"
extern int onDemand;
int Thread::globalsignal[16]={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
Thread::Thread(StackSize sS,Time timeSlice){
prvi=0;
prviCek=0;
poslednjiCek=0;
poslednji=0;
myPCB=new PCB(sS,timeSlice,this);
for(int i=0;i<16;i++){
first[i]=0;
last[i]=0;
mysignal[i]=1;
}
}
void Thread::start(){
Scheduler::put(myPCB);
}
void Thread::waitToComplete(){
if(myPCB->fleg!=4){
myPCB->put(PCB::running);
// cout<<"Izbacen";
PCB::running->fleg=3;
dispatch();
}
}
ID Thread::getId(){
return myPCB->getId();
}
ID Thread::getRunningId(){
return PCB::getRunningId();
}
Thread* Thread::getThreadById(ID id){
return PCB::allPCBs[id]->myThread;
}
Thread::~Thread(){
delete myPCB;
}
void dispatch(){
asm cli
onDemand=1;
timer();
asm sti
}
void Thread::unblockSignalGlobally(SignalId sig){//otkljucava sve signale globalno i poziva one koji su bili na cekanju
Thread::globalsignal[sig]=1;
for(int i=0;i< PCB::idGive;i++)
if(PCB::allPCBs[i]->myThread->mysignal[sig]==1 ){
if(PCB::allPCBs[i]->myThread->prviCek){
if(PCB::allPCBs[i]->myThread->prvi==0)PCB::allPCBs[i]->myThread->prvi=PCB::allPCBs[i]->myThread->prviCek;
else PCB::allPCBs[i]->myThread->poslednji=PCB::allPCBs[i]->myThread->prviCek;
PCB::allPCBs[i]->myThread->poslednji=PCB::allPCBs[i]->myThread->poslednjiCek;
PCB::allPCBs[i]->myThread->prviCek=0;
PCB::allPCBs[i]->myThread->poslednjiCek=0;
}
}
}
void Thread::signal(SignalId signal){//provjerava da li se moze odraditi signal
if(mysignal[signal]==1 && globalsignal[signal]==1){
struct listSig *s=new listSig(signal);
if(prvi==0){
prvi=s;
}
else{
poslednji->next=s;
}
poslednji=s;
}
else
{
struct listSig *s=new listSig(signal);
if(prviCek==0){
prviCek=s;
}
else{
poslednjiCek->next=s;
}
poslednjiCek=s;
}
}
void Thread::doSignals(){//iyvrsava signale
while(prvi){
int a=prvi->id;
if(a==0){
asm cli
signal(2);
if(myPCB->parent)
myPCB->parent->myThread->signal(1);
PCB::running->fleg=(4);
if(PCB::running->waitFor){//oslobadja sve niti koji su je cekali
List *pom=PCB::running->waitFor->next;
while(PCB::running->waitFor){
PCB::running->waitFor->pcb->fleg=(2);
Scheduler::put(PCB::running->waitFor->pcb);
// cout<<"Ubacen\n";
delete PCB::running->waitFor;
PCB::running->waitFor=pom;
if(pom)pom=pom->next;
}
}
//cout<<"gotovo";
dispatch();
asm sti
}else{
struct sig*tmp=Thread::first[a];
while (tmp){
(*(tmp->sh))();
tmp=tmp->next;
}
}
prvi=prvi->next;
}
//dozvoli promjenu konteksa
}
void Thread::unregisterAllHandlers(SignalId id){//brise sve hendlere za neki signal
struct sig *old=0;
while(first[id]){
old=first[id];
first[id]=first[id]->next;
old->sh=0;
delete old;
}
last[id]=0;
}
void Thread::registerHandler(SignalId signal,SignalHandler handler){//ubacuje handler u listu signala signal
asm cli
int a;
struct sig * novi=new struct sig(signal,handler);
if(first[signal]){
last[signal]->next=novi;
last[signal]=novi;
}else{
first[signal]=last[signal]=novi;
}
asm sti
}
void Thread::swap(SignalId signal,SignalHandler hand1,SignalHandler hand2){//zamjenjuje 2 signala
struct sig*oldh1,*oldh2,*tmp,*ph1,*ph2,*pom;
oldh1=oldh2= tmp=first[signal];
int h1=0,h2=0;
if(hand2==hand1)return;
while(tmp){
if(h1&&h2){
if((ph1==oldh2)){
if(oldh1){
oldh1->next=ph2;
}else first[signal]=ph2;
ph1->next=ph2->next;
ph2->next=ph1;
}
else if(ph2==oldh1){
if(oldh2){
oldh2->next=ph1;
}else first[signal]=ph1;
ph2->next=ph1->next;
ph1->next=ph2;
}
else{
if(oldh1){
oldh1->next=ph2;
}
else first[signal]=ph2;
if(oldh2){
oldh2->next=ph1;
}
else first[signal]=ph1;
pom=ph1->next;
ph1->next=ph2->next;
ph2->next=pom;
if(last[signal]==ph1)last[signal]==ph2;
if(last[signal]==ph2)last[signal]==ph1;
}
break;
}
else{
if(tmp->id==signal){
if(tmp->sh==hand1){
ph1=tmp;
h1=1;
}
if(tmp->sh==hand2){
ph2=tmp;
h2=1;
}
if(h1==0){
oldh1=tmp;
}
if(h1==0){
oldh2=tmp;
}
}
}
tmp=tmp->next;
}
}
void Thread::unblockSignal(SignalId sig){
mysignal[sig]=1;
if(mysignal[sig]==1 && globalsignal[sig]==1){
if(prviCek){
if(prvi==0)prvi=prviCek;
else poslednji=prviCek;
poslednji=poslednjiCek;
prviCek=0;
poslednjiCek=0;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
9ab06097c5eacde21cb2cff933601220ed49ed0c | 92e22ff9edefdf4a909b5ec68d3074ffdff19261 | /LaGuardia-LoBianco_CH2_problem_37.cpp | f80bc776475e69059b50a1dc65b853dff128c11c | [] | no_license | cafeTechne/C-PracticeProblems | 9714535a4c5361a6517accd8a7387185f197b6b4 | 6f6021f8c281e99cabb2231f357305785a1244e7 | refs/heads/master | 2021-04-12T11:50:22.719605 | 2018-04-12T22:29:02 | 2018-04-12T22:29:02 | 126,253,746 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | cpp | // LaGuardia-LoBianco_CH2_problem_37.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
const double OXYGEN = 15.9994;
const double CARBON = 12.011;
const double NITROGEN = 14.00674;
const double SULFUR = 32.066;
const double HYDROGREN = 1.00794;
//Gino N. LaGuardia-LoBianco, 01775469, Chapter 2, Problem # 37
//This program calculates the molecular weight of glycine based on the weights of it's constituent elements.
int main()
{
//declarations
//declared and initialized the variable that will store the output of this program
double glycine;
//statements
//algebraic equation multiplying the contant element weights against the number of each molecule in a molecule of glycine
glycine = ((double(2) * OXYGEN) + ((double(2) * CARBON) + ((double(1) * NITROGEN) + (double(5) * HYDROGEN))));
cout << " The Molecular weight of glycine is " << glycine << ". ";
return 0;
}
| [
"cafetechne@gmail.com"
] | cafetechne@gmail.com |
a94fa5a5de026f502a8ec0b2a2927e3b833c8b11 | 81c5811ced0fde5d7404325ee5ca2890d96d95da | /Eballet_Reset.h | 3e6ef735363acad3cbbdb34ecb394ced4420dbb5 | [] | no_license | Kuroharei398/Real-to-Fantasy | 84a1a6ad77c4d579abcaadb9f7c3f21b716dcebc | 4d5241c98fe8bf27d10a6ce5f41d46a31dad12af | refs/heads/main | 2023-06-14T00:54:24.181852 | 2021-07-15T05:22:30 | 2021-07-15T05:22:30 | 385,816,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | #pragma once
#ifndef DEF_EBALLETRESET_H
#define DEF_EBALLETRESET_H
#define Eb_Max 60
class EballetReset
{
public:
int Edimg;
int ex0[Eb_Max], ex1[Eb_Max], ex2[Eb_Max];
int ey0[Eb_Max], ey1[Eb_Max], ey2[Eb_Max];
int Ebx[Eb_Max];
int Ebradius[Eb_Max];
bool Ebflag[Eb_Max];
bool Ebflag1[Eb_Max];
bool Ebflag2[Eb_Max];
void EballetReset1();
void EballetReset2();
void EballetReset3();
void ResetImage();
void ResetValue();
};
#endif // !DEF_EBALLETRESET_H
| [
"noreply@github.com"
] | noreply@github.com |
d9390f8b3ba34c9d4640815bb8d792136197466b | 35bfc68a6acce4d6947aefa49a82a935dfaf1c49 | /数据结构/图/最短路径/Dijkstra.cpp | 93684cfea835fab1cef0ec6a73c6ede9980b3724 | [] | no_license | PeterSansan/job_prepare | dd2e364bf0be8d94a63efb36e9e5c5bedd35d219 | baed6453a9fe026bdae343525297511aed5f9e01 | refs/heads/master | 2021-06-14T00:55:34.650870 | 2017-04-13T16:04:49 | 2017-04-13T16:04:49 | 83,214,895 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,033 | cpp | /*顺序表示例代码*/
#include<iostream>
#include <fstream>
#include<time.h>
#include<stdlib.h>
#include<math.h>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <cmath>
using namespace std;
/*总结Dijkstra基本思想:
1、把顶点分为已知最短路径和未知最短路径的集合P与Q
2、每次找到离源点最近的一个顶点u,把这个源点归入集合P
3、以该顶点u进行扩展,比较与u有相接的下一个点与源点的最短距离,更新
4、重复2,直到n-1个点都进行这样的操作终止。*/
int main()
{
int e[10][10], dis[10], book[10], i, j, n, m, t1, t2, t3, u, v, min;
int inf = 99999999; //表示无穷大的值
cin >> n >> m;
//初始化
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
if (i == j)
e[i][j] = 0;
else
e[i][j] = inf;
//读入边
for (i = 1; i <= m; i++)
{
cin >> t1 >> t2 >> t3;
e[t1][t2] = t3;
}
//初始化dis数组,这里是1号顶点到其余各个顶点的初始路程
for (i = 1; i <= n; i++)
dis[i] = e[1][i];
//book数组初始化
for (i = 1; i <= n; i++)
book[i] = 0;
book[1] = 1;//起源点加入集合P
//Dijkstra算法核心语句
//分为两个集合,已知最智囊路径的点P,未知最短路径的点Q
for (i = 1; i <= n - 1; i++) //要判断n-1次,即去掉源结点
{
//找到离1号顶点最近的顶点
min = inf;
for (j = 1; j <= n; j++)
{
if (book[j] == 0 && dis[j] < min)
{
min = dis[j];
u = j;
}
}
book[u] = 1;//最近的那个顶点,放入集合P,这句很关键
for (v = 1; v <= n;v++) //判断源点与u点指向所有下个节点的最短距离
{
if (e[u][v] < inf) //如果u点与其他点没有连接则跳过
{
if (dis[v] > dis[u] + e[u][v]) //判断源点到u下一个点的距离是否为最小,更新
dis[v] = dis[u] + e[u][v];
}
}
}
//输出最终的结果
for (i = 1; i <= n; i++)
cout << dis[i]<<" ";
return 0;
}
| [
"1657225860@qq.com"
] | 1657225860@qq.com |
90027e77fe462e7ca75c04d57b44076a3ba3bbd1 | 01e7d572720e4219379158b6d5d397401cb819e9 | /telescope.ino | 7bef4d14cd35fd0ecd7faad8c5199c1f60bd62e4 | [] | no_license | sebsebseb1982/telescope | 4bebdea91d71bc9af3d63fe3df97687439d37607 | b8be6d55a73a1e035f9b42cb95a3b6bc02fd3ffd | refs/heads/master | 2023-08-21T22:48:03.169420 | 2021-09-17T07:48:35 | 2021-09-17T07:48:35 | 398,406,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,871 | ino | #include <SPI.h>
#include <Wire.h>
#include <SoftwareSerial.h>
#include <TinyGPSPlus.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include "BigNumber.h"
// #include "MemoryFree.h"
#include "celestial-calculation.h"
#include "object.h"
#include "object-tracker.h"
#include "nunchuk.h"
#include "stepper.h"
#include "screen.h"
#include "images/moon.h"
#include "images/saturn.h"
#include "images/cluster.h"
#include "images/iss.h"
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
static const int precision = 50;
TinyGPSPlus gps;
Screen currentScreen;
boolean trackingInProgress = false;
Object objects[] = {
{
"Whirpool galaxy",
{
202.46963,
47.19519
}
},
{
"Pleiade cluster",
{
56.87117,
24.10503
}
},
{
"47 TUCANAE, CLST",
{
6.02363,
-72.08128
}
},
{
"BEEHIVE CLUSTER",
{
130.1,
19.98333
}
},
{
"HYADES CLUSTER",
{
66.75,
15.86667
}
},
{
"JEWEL BOX, CLSTR",
{
193.41254,
-60.36161
}
},
{
"M4 CLUSTER",
{
245.89775,
-26.52536
}
},
{
"M12 CLUSTER",
{
251.81042,
-1.94781
}
},
{
"M14 CLUSTER",
{
264.40063,
-3.24594
}
},
{
"M15 CLUSTER",
{
322.49375,
12.16681
}
},
{
"M52 CLUSTER",
{
351.20504,
61.59994
}
},
{
"M68 CLUSTER",
{
189.86675,
-26.74281
}
},
{
"M93 CLUSTER",
{
116.12342,
-23.85483
}
},
{
"M107 CLUSTER",
{
248.13279,
-13.05356
}
},
{
"NGC 3201 CLUSTER",
{
154.40329,
-46.41103
}
},
{
"NGC 4833 CLUSTER",
{
194.89567,
-70.87453
}
},
{
"OMEGA CEN., CLST",
{
201.69142,
-47.47681
}
},
{
"PLEIADES CLUSTER",
{
56.87117,
24.10503
}
},
{
"CAT'S EYE NEBULA",
{
269.63917,
66.63314
}
},
{
"CONE NEBULA",
{
100.24271,
9.89558
}
},
{
"CRESCENT NEBULA",
{
303.02700,
38.35497
}
},
{
"DUMBBELL NEBULA",
{
299.90133,
22.72150
}
},
{
"EAGLE NEBULA",
{
274.70021,
-13.80694
}
},
{
"EIGHT-BURST, NEB",
{
151.75675,
-40.43619
}
},
{
"ESKIMO NEBULA",
{
112.29492,
20.91175
}
},
{
"ETA CARINAE, NEB",
{
161.27513,
-59.86661
}
},
{
"HELIX NEBULA",
{
337.41025,
-20.83686
}
},
{
"HOURGLASS NEBULA",
{
204.89583,
-67.38083
}
},
{
"IC 2944 NEBULA",
{
173.94717,
-63.01936
}
},
{
"LAGOON NEBULA",
{
270.92504,
-24.38
}
},
{
"ORION NEBULA",
{
83.82163,
-5.39081
}
},
{
"OWL NEBULA",
{
168.69875,
55.01914
}
},
{
"RING NEBULA",
{
283.39588,
33.02914
}
},
{
"SATURN NEBULA",
{
316.04513,
-11.36342
}
},
{
"STINGRAY NEBULA",
{
259.08780,
-59.4899
}
},
{
"TARANTULA NEBULA",
{
84.67621,
-69.10064
}
},
{
"TRIFID NEBULA",
{
270.63104,
-22.99944
}
},
{
"VEIL NEBULA",
{
311.42513,
30.71664
}
},
{
"ANDROMEDA GALAXY",
{
10.68471,
41.26892
}
},
{
"BLACK EYE GALAXY",
{
194.18217,
21.68186
}
},
{
"BODE'S GALAXY",
{
148.88813,
69.06533
}
},
{
"CIGAR GALAXY",
{
148.96796,
69.67983
}
},
{
"LARGE MAGELLANIC",
{
80.89433,
-69.75611
}
},
{
"SMALL MAGELLANIC",
{
13.15838,
-72.80028
}
},
{
"SOMBRERO GALAXY",
{
189.99775,
-11.62294
}
},
{
"TRIANGULUM, GLXY",
{
23.46213,
30.65986
}
},
{
"Polaris",
{
37.95454,
89.26411
}
}
};
void setup() {
Serial.begin(115200);
setupMath(precision);
setupNunchuk();
setupGPS();
setupSteppers();
setupScreen();
setupTracker();
}
void loop() {
refreshGPS();
computeControls();
if (isGPSReady() && trackingInProgress) {
track();
}
updateScreen();
// Serial.println(" == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ");
}
| [
"seb@seb.fr"
] | seb@seb.fr |
1ed4083a9b3dfae482e5f9ab507d93e93cb4fc6c | c56012edcb3550317ace8943b01f4b5f46476d16 | /include/allowed_mentions.h | 5ce295dcf3d0b7e4418066643af2872b06964d88 | [
"MIT"
] | permissive | cerww/cpp_discord_api | 8d27dc94f03014a44db975f491d20759547bc8bf | 3989b9e3fdcceb6823fb5df935ef38e3f7cb350e | refs/heads/master | 2021-06-12T11:49:40.180426 | 2021-05-28T10:40:12 | 2021-05-28T10:40:12 | 128,608,135 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,412 | h | #pragma once
#include "snowflake.h"
#include "guild_role.h"
#include "User.h"
#include "modifies_message_json.h"
#include "../common/range-like-stuffs.h"
constexpr int allows_everyone_flag = 1;
constexpr int allows_all_users_flag = 1 << 1;
constexpr int allows_all_roles_flag = 1 << 2;
constexpr int allows_roles_flag = 1 << 3;
constexpr int allows_users_flag = 1 << 4;
struct empty_allowed_mentions{};
template<int flags = 0>
struct allowed_mentions {
static constexpr bool allow_everyone = bool(flags & allows_everyone_flag);
static constexpr bool allow_all_roles = bool(flags & allows_all_roles_flag);
static constexpr bool allow_all_users = bool(flags & allows_all_users_flag);
static constexpr bool allow_some_users = bool(flags & allows_users_flag);
static constexpr bool allow_some_roles = bool(flags & allows_roles_flag);
static_assert(!((allow_all_roles &&allow_some_roles )|| (allow_all_users && allow_some_users)));
using vector_if_has_roles = std::conditional_t<allow_some_roles, std::vector<snowflake>, empty_allowed_mentions>;
using vector_if_has_users = std::conditional_t<allow_some_roles, std::vector<snowflake>, empty_allowed_mentions>;
allowed_mentions() = default;
template<int other_flags>
requires ((flags | other_flags) == flags)
explicit allowed_mentions(allowed_mentions<other_flags> other) {
using other_type = allowed_mentions<other_flags>;
if constexpr(other_type::allow_some_roles && allow_some_roles){
roles_ids = std::move(other.roles_ids);
}
if constexpr(other_type::allow_some_users && allow_some_users){
user_ids = std::move(other.user_ids);
}
}
allowed_mentions<flags | allows_everyone_flag> everyone()requires !allow_everyone{
return allowed_mentions<flags | allows_everyone_flag>(*this);
}
allowed_mentions<flags | allows_all_roles_flag> all_roles()requires !allow_all_roles && !allow_some_roles{
return allowed_mentions<flags | allows_all_roles_flag>(*this);
}
allowed_mentions<flags | allows_all_users_flag> all_users()requires !allow_all_users && !allow_some_users{
return allowed_mentions<flags | allows_all_users_flag>(*this);
}
template<typename... T>
allowed_mentions<flags | allows_roles_flag> add_roles(T&&... roles)
requires !allow_all_roles && !allow_some_roles && (std::is_base_of_v<guild_role, std::remove_cvref_t<T>>&& ...)
{
auto ret = allowed_mentions<flags | allows_roles_flag>(*this);
ret.roles_ids.reserve(sizeof...(T));
((ret.roles_ids.push_back(roles.id())), ...);
return ret;
}
template<typename... T>
allowed_mentions<flags | allows_users_flag> add_users(T&&... users)
requires !allow_all_users && !allow_some_users && ((std::is_base_of_v<user, std::remove_cvref_t<T>>) && ...) {
auto ret = allowed_mentions<flags | allows_users_flag>(*this);
ret.user_ids.reserve(sizeof...(T));
((ret.user_ids.push_back(users.id())), ...);
return ret;
}
template<typename... T>
allowed_mentions<flags | allows_roles_flag> add_roles(T&&... roles)
requires !allow_all_roles && !allow_some_roles && ((std::is_same_v<snowflake, std::remove_cvref_t<T>>) && ...) {
auto ret = allowed_mentions<flags | allows_roles_flag>(*this);
ret.roles_ids.reserve(sizeof...(T));
((ret.roles_ids.push_back(roles)), ...);
return ret;
}
template<typename... T>
allowed_mentions<flags | allows_users_flag> add_users(T&&... users)
requires !allow_all_users && !allow_some_users && ((std::is_same_v<snowflake, std::remove_cvref_t<T>>) && ...) {
auto ret = allowed_mentions<flags | allows_users_flag>(*this);
ret.user_ids.reserve(sizeof...(T));
((ret.user_ids.push_back(users)), ...);
return ret;
}
template<typename T>
allowed_mentions<flags | allows_users_flag>& add_roles(T&& roles)
requires !allow_all_roles && !allow_some_roles && is_range_of_v<T, guild_role> {
auto ret = allowed_mentions<flags | allows_users_flag>(*this);
for (const guild_role& usera : roles) {
ret.roles_ids.push_back(usera.id());
}
return *this;
}
template<typename T>
allowed_mentions<flags | allows_users_flag>& add_roles(T&& roles)
requires !allow_all_roles && !allow_some_roles && is_range_of_v<T, snowflake> {
auto ret = allowed_mentions<flags | allows_users_flag>(*this);
for (snowflake usera : roles) {
ret.roles_ids.push_back(usera);
}
return *this;
}
template<typename T>
allowed_mentions<flags | allows_users_flag>& add_users(T&& users)
requires !allow_all_users && !allow_some_users && is_range_of_v<T, user> {
auto ret = allowed_mentions<flags | allows_users_flag>(*this);
//ret.users = users | ranges::to<std::vector<user>>();
for (const user& a : users) {
ret.user_ids.push_back(a.id());
}
return ret;
}
template<typename T>
allowed_mentions<flags | allows_users_flag>& add_users(T&& users)
requires !allow_all_users && !allow_some_users && is_range_of_v<T, snowflake> {
auto ret = allowed_mentions<flags | allows_users_flag>(*this);
//ret.users = users | ranges::to<std::vector<user>>();
for (snowflake a : users) {
ret.user_ids.push_back(a);
}
return ret;
}
//already have the flag
template<typename... T>
allowed_mentions<flags>& add_roles(T&&... roles)
requires !allow_all_roles && allow_some_roles && (std::is_base_of_v<guild_role, std::remove_cvref_t<T>>&& ...) {
((roles_ids.push_back(roles.id())), ...);
return *this;
}
template<typename... T>
allowed_mentions<flags>& add_roles(T&&... roles)
requires !allow_all_roles && allow_some_roles && ((std::is_same_v<snowflake, std::remove_cvref_t<T>>) && ...)
{
((roles_ids.push_back(roles)), ...);
return *this;
}
template<typename... T>
allowed_mentions<flags>& add_users(T&&... users)
requires !allow_all_users && allow_some_users && ((std::is_base_of_v<snowflake, std::remove_cvref_t<T>>) && ...) {
((user_ids.push_back(users)), ...);
return *this;
}
template<typename... T>
allowed_mentions<flags>& add_users(T&&... users)
requires !allow_all_users && allow_some_users && ((std::is_same_v<user, std::remove_cvref_t<T>>) && ...) {
((user_ids.push_back(users.id())), ...);
return *this;
}
template<typename T>
allowed_mentions<flags>& add_users(T&& users)
requires !allow_all_users && allow_some_users && is_range_of_v<T,user> {
for(const auto& usera:users) {
user_ids.push_back(usera.id());
}
return *this;
}
template<typename T>
allowed_mentions<flags>& add_roles(T&& roles)
requires !allow_all_roles && allow_some_roles && is_range_of_v<T, guild_role> {
for (const guild_role& role : roles) {
roles_ids.push_back(role.id());
}
return *this;
}
template<typename T>
allowed_mentions<flags>& add_users(T&& users)
requires !allow_all_users && allow_some_users&& is_range_of_v<T, snowflake> {
for (snowflake usera : users) {
user_ids.push_back(usera);
}
return *this;
}
template<typename T>
allowed_mentions<flags>& add_roles(T&& roles)
requires !allow_all_roles && allow_some_roles&& is_range_of_v<T, snowflake> {
for (snowflake role_id: roles) {
roles_ids.push_back(role_id);
}
return *this;
}
//[[no_unique_address]]
vector_if_has_roles roles_ids = {};
//[[no_unique_address]]
vector_if_has_users user_ids = {};
void modify_message_json(nlohmann::json& json)const;;
};
//user/role, has flag/doesnt have flag, snowflake/not_snowflake, variadic/not variadic=>16 ;-;
static_assert(std::is_base_of_v<user, user>);
//static inline const allowed_mentions<0> disable_mentions{};
struct disable_mentions_t{
static void modify_message_json(nlohmann::json& json) {
json["allowed_mentions"]["parse"] = nlohmann::json::array();
}
} inline constexpr disable_mentions;
static_assert(message_modifier<disable_mentions_t>);
template<int flags>
inline void to_json(nlohmann::json& json, const allowed_mentions<flags>& stuff) {
json["parse"] = nlohmann::json::array_t();
if constexpr(stuff.allow_everyone){
json["parse"].push_back("everyone");
}
if constexpr (stuff.allow_all_roles){
json["parse"].push_back("roles");
}
if constexpr (stuff.allow_all_users) {
json["parse"].push_back("users");
}
if constexpr(stuff.allow_some_roles){
json["roles"] = stuff.roles_ids;
}
if constexpr (stuff.allow_some_users) {
json["users"] = stuff.user_ids;
}
}
template<int flags>
void allowed_mentions<flags>::modify_message_json(nlohmann::json& json) const{
json["allowed_mentions"] = *this;
}
//conditions:
//allow_users == true => user_ids.size == 0
//allow_roles == true => role_ids.size == 0
//
//
//
//
struct allowed_mentions1{
bool everyone = false;
bool allow_users = false;
bool allow_roles = false;
std::vector<snowflake> role_ids;
std::vector<snowflake> user_ids;
void modify_message_json(nlohmann::json& json)const;
};
//static const allowed_mentions1 disable_mentions{};
inline void to_json(nlohmann::json& json, const allowed_mentions1& stuff) {
json["parse"] = nlohmann::json::array_t();
if (stuff.everyone) {
json["parse"].push_back("everyone");
}
if (stuff.allow_users) {
json["parse"].push_back("users");
} else {
if (!stuff.user_ids.empty()) {
json["users"] = stuff.user_ids;
}
}
if (stuff.allow_roles) {
json["parse"].push_back("roles");
} else {
if (!stuff.role_ids.empty()) {
json["roles"] = stuff.role_ids;
}
}
}
inline void allowed_mentions1::modify_message_json(nlohmann::json& json) const {
json["allowed_mentions"] = *this;
}
struct allowed_mentions2 {
bool everyone = false;
std::variant<bool, std::vector<snowflake>> roles;
std::variant<bool, std::vector<snowflake>> users;
void modify_message_json(nlohmann::json& j) {
auto& allowed_mentions_json = j["allowed_mentions"];
auto& parse = allowed_mentions_json["parse"] = nlohmann::json::array();
if(everyone) {
parse.push_back("everyone");
}
if (std::holds_alternative<bool>(roles)) {
if(std::get<bool>(roles)) {
parse.push_back("roles");
}
}else if(std::holds_alternative<std::vector<snowflake>>(roles)){
allowed_mentions_json["roles"] = std::get<std::vector<snowflake>>(roles);
}
if (std::holds_alternative<bool>(users)) {
if (std::get<bool>(users)) {
parse.push_back("users");
}
}
else if (std::holds_alternative<std::vector<snowflake>>(users)) {
allowed_mentions_json["users"] = std::get<std::vector<snowflake>>(users);
}
}
};
| [
"calebtran1@hotmail.com"
] | calebtran1@hotmail.com |
8691fe9a5886325dfd0c196d3af75ce8a21868f3 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5686275109552128_1/C++/Alextrovert/B.cpp | c5b9391a9668ec72ea4313a57cebe82ccc249359 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,955 | cpp | #ifdef ONLINE_JUDGE
#define DEBUG 0
#define NDEBUG
#else
#define DEBUG 1
#endif
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <vector>
using namespace std;
#define Rep(i,N) for(int i= 0 , _##i=(N); i< _##i; ++i) /* 0 ==> N-1 */
#define For(i,L,H) for(int i=(L), _##i=(H); i<=_##i; ++i) /* L ==> H */
#define Rev(i,N) for(int i=(N); --i>= 0; ) /* N-1 ==> 0 */
#define Dwn(i,H,L) for(int i=(H), _##i=(L); i>=_##i; --i) /* H ==> L */
#define All(a) (a).begin(), (a).end()
#define Sz(a) int((a).size())
#define Mem(a,b) memset((a),(b),sizeof(a))
#define Fill(a,b) fill((a),(a)+sizeof(a)/sizeof((a)[0]),(b))
#define Fill2(a,b) fill(&(a)[0][0],&(a)[0][0]+sizeof(a)/sizeof((a)[0][0]),(b))
#define ToStr(i) static_cast<ostringstream*>(&(ostringstream()<<(i)))->str()
#define ToInt(s) ({ int i; istringstream SS(s); if (!(SS >> i)) i = 0; i; })
#define Rng(x,a,b) ({ (x) >= (a) && (x) <= (b); })
#define Min(a,b) ({ (a) < (b) ? (a) : (b); })
#define Max(a,b) ({ (a) > (b) ? (a) : (b); })
#define Defl(a,b) ({ (a) > (b) ? (a) = (b) : a; })
#define Infl(a,b) ({ (a) < (b) ? (a) = (b) : a; })
#define Rd(x...) ({ RD , x; }) /* Rd(a,b, ...) is equivalent to cin>>a>>b>> ... */
#define Ru(x...) ({ RU , x; }) /* Only reads whitespace-separated unsigned ints */
#define Pr(x...) ({ if (DEBUG) { cout << "Debug["; DB, x, "]\n"; } })
#define Db(x...) ({ if (DEBUG) { cout << "Debug["; DB, #x, ":", x, "]\n"; } })
#define Open(I,O) ({ if (*I) freopen(I,"r",stdin); if (*O) freopen(O,"w",stdout); })
#define Unsync() ({ ios_base::sync_with_stdio(false); cin.tie(0); })
#define pb push_back
#define mp make_pair
#define x first
#define y second
#ifndef _WIN32
#define getchar getchar_unlocked
#define fgetc fgetc_unlocked
#define fgets fgets_unlocked
#endif
template<class T> inline void ruint(T & a) {
while ((a = getchar() - '0') < 0);
for (register char c; (c = getchar() - '0') >= 0; )
a = (a << 3) + (a << 1) + c;
}
struct Reader { template<class T> Reader& operator ,
(T & v) { cin >> v; return *this; } } RD;
struct ReaderU { template<class T> ReaderU& operator ,
(T & v) { ruint(v); return *this; } } RU;
struct Debugger { template<class T> Debugger& operator ,
(const T & v) { cout << " " << v << flush; return *this; } } DB;
struct classcomp { template<class T> bool operator ()
(const T & a, const T & b) const { return a > b; } };
/* Print range [lo, hi) with iterators. e.g. Dbrng(A, A + N) */
template<class T> void Dbrng(T lo, T hi, string note = "", int w = 0) {
if (DEBUG) {
cout << "Debug[ ";
if (!note.empty()) cout << setw(3) << note << " : ";
for (; lo != hi; ++lo) cout << setw(w) << *lo << " ";
cout << "]" << endl;
}
}
typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
const int INF = 0x3F3F3F3F;
/********************************** END OF TEMPLATE *********************************/
int T, D, P[1005];
int main() {
if (DEBUG) Open("B-large.in", "B-large.out");
scanf("%d", &T);
for (int test = 1; test <= T; test++) {
scanf("%d", &D);
for (int i = 0; i < D; i++) scanf("%d", P + i);
sort(P, P + D, greater<int>());
int ans = 1000000000;
for (int sz = 1; sz <= 1000; sz++) {
int cost = 0;
for (int i = 0; i < D; i++) {
if (P[i] <= sz) goto done;
cost += (P[i] / sz) - 1;
cost += (P[i] % sz) > 0;
}
done: ans = min(ans, sz + cost);
}
printf("Case #%d: %d\n", test, ans);
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
1864c7936626eb752f79eb41160507c19aaa863b | b71a961209aec8199418218eb4b40d0c55cd9f84 | /BitWise/singlenum3repeat.cpp | c224c0e7afb03e489856efac27d85791bbc9bbb8 | [] | no_license | prady91/CPP-Practice | b4ffc994043c79cdee4e85a8e9fee5b00f0ee575 | e80366395fe50c9aa08bafcf057bb0cd6257b0c0 | refs/heads/master | 2020-12-25T21:44:22.172930 | 2016-09-29T04:48:25 | 2016-09-29T04:48:25 | 68,346,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//All the numbers are reapated 3 times except for 1 number which is unique, find it
int singleNumber(vector<int>& nums) {
int sum,i,l;
l = nums.size();
int ones=0,twos=0,common=0;
//ones keep track of the numbers which are encountered first time
//twos keep track of the nums which are encountered second time
//we achieve this by twos|(ones&nums[i])
//for discarding the numbers which are obtained 3rd time, we find the
//common bits btn "ones" & "twos" and take negation which gives
//0's in the common bits position, now & this common wiht ones and twos
//to remove the 3rd encountered number
for(i=0;i<l;i++){
twos |= (ones&nums[i]);
ones ^= nums[i];
common = (ones&twos);
twos &= ~(common);
ones &= ~(common);
}
return ones;
}
int main(){
int tmparr[] = {1,1,1,4,3,3,3};
vector<int> inp(tmparr,tmparr+ sizeof(tmparr)/sizeof(tmparr[0]));
int res = singleNumber(inp);
int i;
cout<<res<<endl;
} | [
"pradyumnareddy09@gmail.com"
] | pradyumnareddy09@gmail.com |
6441c0994479f0ee1236dbcf263c1e270e9f656e | eb6f8317c6c361e05df91ae16fd66ecf3a3a8b01 | /leetcode/p9/p9/main.cpp | 37c046c5fe6e109ea758ae07520877d9080a7854 | [] | no_license | Joey-Liu/online-judge-old-version | b00a12ec2da0053c461e914433ccb6760f7e8c50 | c452ecee203c20e2856faa8ef876ad855e6c8957 | refs/heads/master | 2020-03-16T00:53:56.668165 | 2018-10-28T02:54:28 | 2018-10-28T02:54:28 | 132,428,000 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
class Solution {
public:
bool isPalindrome(int x)
{
if (x < 0)
return false;
long long res = 0;
int tmpx = x;
while (x != 0)
{
int tail = x % 10;
res = res * 10 + tail;
x /= 10;
if (res > INT_MAX || res < INT_MIN)
return false;
}
return ((int)res == tmpx);
}
}; | [
"joey_liucoder@163.com"
] | joey_liucoder@163.com |
d58bffb90d92b98150d169f8c9ab50bc3ff00ba8 | ede5e60f433432d52f2e076c231a5c2ccec21773 | /Project1/Project1/Source.cpp | 3a2bcca8a016a19d0043689cb17d353b3198c086 | [] | no_license | sebastianbocul/Space-Arcade-Game | c84822062e370c961a27aa5e129c2669bb446b0e | 50e3ecc14463cb498e22461569914c59d1d7ad82 | refs/heads/master | 2021-06-10T04:49:50.996561 | 2017-01-28T11:28:14 | 2017-01-28T11:28:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,730 | cpp | #include <allegro5\allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5\allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include "objects.h"
#include <allegro5\allegro_audio.h>
#include <allegro5\allegro_acodec.h>
//GLOBALNE
int WIDTH = 1200;
int HEIGHT = 600;
int imp = 0;
int zycia = 0;
int NUM_BULLETS;
int NUM_COMETS ;
enum KEYS { UP, DOWN, LEFT, RIGHT, SPACE };
bool keys[5] = { false,false,false,false,false };
int r[] = { 196,196,196,196,196,196 }, g[] = { 119,119,119,119,119,119 }, b[] = { 89,89,89,89,89,89 }; // colors of pressed buttons
int color[] = { 255, 240, 110 };
ALLEGRO_SAMPLE *song = NULL;
ALLEGRO_SAMPLE_INSTANCE *songinstance = NULL;
//Prototypy
void InitShip(SpaceShip &statek);
void DrawShip(SpaceShip &statek);
void MoveShipUp(SpaceShip &statek);
void MoveShipDown(SpaceShip &statek);
void MoveShipLeft(SpaceShip &statek);
void MoveShipRight(SpaceShip &statek);
void InitBullet(Bullet bullet[], int size);
void DrawBullet(Bullet bullet[], int size);
void FireBullet(Bullet bullet[], int size, SpaceShip &statek);
void UpdateBullet(Bullet bullet[], int size);
void CollideBulet(Bullet bullet[], int Bsize, Comet comets[], int cSize, SpaceShip &statek);
void InitComet(Comet comets[], int size);
void DrawComet(Comet comets[], int size);
void StartComet(Comet comets[], int size);
void UpdateComet(Comet comets[], int size);
void CollideComet(Comet comets[], int cSize, SpaceShip &statek);
void color_press(int *r, int *g, int *b, int selection, int max);
int main(void)
{
//prymitywne zmienne;
bool done = false;
bool redraw = true;
const int FPS = 60;
bool isGameOver = false;
bool menu_done = false;
//zmienne obiektowe
SpaceShip statek;
Bullet *bullets = new Bullet[100000];
Comet *comets = new Comet[100000];
//zmienne allegro
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_FONT *font18 = NULL;
//inicjalizacja funkcji
al_init();
al_init_image_addon();
if (!al_init()) //inicjalizacja allegro
{
return -1;
}
display = al_create_display(WIDTH, HEIGHT);
if (!display)
{
return -1;
}
al_init_primitives_addon();
al_install_keyboard();
al_init_font_addon();
al_init_ttf_addon();
al_install_audio();
al_init_acodec_addon();
event_queue = al_create_event_queue();
timer = al_create_timer(1.0 / FPS);
srand(time(NULL));
al_reserve_samples(10);
song = al_load_sample("song.ogg");
songinstance = al_create_sample_instance(song);
al_set_sample_instance_playmode(songinstance, ALLEGRO_PLAYMODE_LOOP);
al_attach_sample_instance_to_mixer(songinstance, al_get_default_mixer());
font18 = al_load_font("arial.ttf", 18, 0);
/////////////////
main_menu:
InitShip(statek);
InitBullet(bullets, 100000);
InitComet(comets, 100000);
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_register_event_source(event_queue, al_get_display_event_source(display));
al_start_timer(timer);
for(int i=0;i<5;i++)
keys[i] = false;
menu_done = false;
ALLEGRO_BITMAP *cursor = al_load_bitmap("grafika/Cursor_small.png");
ALLEGRO_FONT *menu_item = al_load_ttf_font("arial.ttf", 18, 0);
//ALLEGRO_BITMAP *dup = al_load_bitmap("dup.png");
ALLEGRO_BITMAP * dup = al_load_bitmap("background.jpg");
int cord_cursor_x = (WIDTH / 2) - 120;
int cord_cursor_y = ((HEIGHT / 2) - 4) + 30;
while (!menu_done)
{
ALLEGRO_EVENT menu_ev;
al_wait_for_event(event_queue, &menu_ev);
//al_draw_bitmap(dup, 0, 0, 0);
if (menu_ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch (menu_ev.keyboard.keycode)
{
case ALLEGRO_KEY_UP:
if (cord_cursor_y > ((HEIGHT / 2) - 4) -90)
cord_cursor_y -= 30;
if (cord_cursor_y == ((HEIGHT / 2) - 4) + 0) cord_cursor_y= ((HEIGHT / 2) - 4) -30;
break;
case ALLEGRO_KEY_DOWN:
if (cord_cursor_y < ((HEIGHT / 2) - 4) + 60)
cord_cursor_y += 30;
if (cord_cursor_y == ((HEIGHT / 2) - 4) + 0) cord_cursor_y= ((HEIGHT / 2) - 4)+ 30;
break;
case ALLEGRO_KEY_ENTER:
if (cord_cursor_y == ((HEIGHT / 2) - 4) + 30)
{
// start game
menu_done = true;
done = false;
isGameOver = false;
NUM_BULLETS = 1;
NUM_COMETS = 4;
}
else if (cord_cursor_y == ((HEIGHT / 2) - 4) + 60)
{
menu_done = true;
done = true;
}
else if (cord_cursor_y == ((HEIGHT / 2) - 4) -30)
{
if (HEIGHT != 600)
{
WIDTH = 1200;
HEIGHT = 600;
al_destroy_display(display);
display = al_create_display(WIDTH, HEIGHT);
if (!display)
{
return -1;
}
cord_cursor_y = ((HEIGHT / 2) - 4) - 30;
}
}
else if (cord_cursor_y == ((HEIGHT / 2) - 4) - 60)
{
if (HEIGHT != 450)
{
WIDTH = 1200;
HEIGHT = 450;
al_destroy_display(display);
display = al_create_display(WIDTH, HEIGHT);
if (!display)
{
return -1;
}
cord_cursor_y = ((HEIGHT / 2) - 4) - 60;
}
}
else if (cord_cursor_y == ((HEIGHT / 2) - 4) - 90)
{
if (HEIGHT != 300)
{
WIDTH = 1200;
HEIGHT = 300;
al_destroy_display(display);
display = al_create_display(WIDTH, HEIGHT);
if (!display)
{
return -1;
}
cord_cursor_y = ((HEIGHT / 2) - 4) - 90;
}
}
break;
case ALLEGRO_KEY_ESCAPE:
{
menu_done = true;
done = true;
break;
}
}
}
else if (menu_ev.type == ALLEGRO_EVENT_TIMER)
{
if (cord_cursor_y == ((HEIGHT / 2) - 4) - 90)
color_press(r, g, b, 2 , 5);
if (cord_cursor_y == ((HEIGHT / 2) - 4) - 60)
color_press(r, g, b, 3, 5);
if (cord_cursor_y == ((HEIGHT / 2) - 4) - 30)
color_press(r, g, b, 4, 5);
if (cord_cursor_y == ((HEIGHT / 2) - 4) + 30)
color_press(r, g, b, 0, 5);
if (cord_cursor_y == ((HEIGHT / 2) - 4) + 60)
color_press(r, g, b, 1, 5);
// rendering
al_draw_text(menu_item, al_map_rgb(r[2], g[2], b[2]), WIDTH / 2, (HEIGHT / 2) - 90, ALLEGRO_ALIGN_CENTRE, "1200x300");
al_draw_text(menu_item, al_map_rgb(r[3], g[3], b[3]), WIDTH / 2, (HEIGHT / 2) - 60, ALLEGRO_ALIGN_CENTRE, "1200x450");
al_draw_text(menu_item, al_map_rgb(r[4], g[4], b[4]), WIDTH / 2, (HEIGHT / 2) - 30, ALLEGRO_ALIGN_CENTRE, "1200x600");
al_draw_text(menu_item, al_map_rgb(r[0], g[0], b[0]), WIDTH / 2, (HEIGHT / 2) + 30, ALLEGRO_ALIGN_CENTRE, "START GAME");
al_draw_text(menu_item, al_map_rgb(r[1], g[1], b[1]), WIDTH / 2, (HEIGHT / 2) + 60, ALLEGRO_ALIGN_CENTRE, "EXIT");
al_draw_bitmap(cursor, cord_cursor_x, cord_cursor_y, 0);
al_flip_display();
al_clear_to_color(al_map_rgb(0, 0, 0));
}
}
// destroying objects
al_destroy_font(menu_item);
al_destroy_bitmap(cursor);
// al_destroy_event_queue(event_queue);
///////////////////////////////////////////
while (!done)
{
al_play_sample_instance(songinstance);
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_TIMER)
{
redraw = true;
if (keys[UP]) MoveShipUp(statek);
if (keys[DOWN]) MoveShipDown(statek);
if (keys[LEFT]) MoveShipLeft(statek);
if (keys[RIGHT]) MoveShipRight(statek);
if (!isGameOver)
{
al_play_sample_instance(songinstance);
UpdateBullet(bullets, NUM_BULLETS);
StartComet(comets, NUM_COMETS);
UpdateComet(comets, NUM_COMETS);
CollideBulet(bullets, NUM_BULLETS, comets, NUM_COMETS, statek);
CollideComet(comets, NUM_COMETS, statek);
if (statek.lives <= 0)
isGameOver = true;
}
}
else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
{
done = true;
}
else if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch (ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
{
done = true;
break;
}
case ALLEGRO_KEY_UP:
{
keys[UP] = true;
break;
}
case ALLEGRO_KEY_DOWN:
{
keys[DOWN] = true;
break;
}
case ALLEGRO_KEY_LEFT:
{
keys[LEFT] = true;
break;
}
case ALLEGRO_KEY_RIGHT:
{
keys[RIGHT] = true;
break;
}
case ALLEGRO_KEY_SPACE:
{
keys[SPACE] = true;
FireBullet(bullets, NUM_BULLETS, statek);
break;
}
}
}
else if (ev.type == ALLEGRO_EVENT_KEY_UP)
{
switch (ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
{
done = false;
break;
}
case ALLEGRO_KEY_UP:
{
keys[UP] = false;
break;
}
case ALLEGRO_KEY_DOWN:
{
keys[DOWN] = false;
break;
}
case ALLEGRO_KEY_LEFT:
{
keys[LEFT] = false;
break;
}
case ALLEGRO_KEY_RIGHT:
{
keys[RIGHT] = false;
break;
}
case ALLEGRO_KEY_SPACE:
{
keys[SPACE] = false;
break;
}
}
}
if (redraw&& al_is_event_queue_empty(event_queue))
{
redraw = false;
if (!isGameOver)
{
DrawShip(statek);
DrawComet(comets, NUM_COMETS);
al_flip_display();
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_bitmap(dup, 0, 0, 0);
DrawBullet(bullets, NUM_BULLETS);;
al_draw_textf(font18, al_map_rgb(255, 0, 0), 5, 5, 0, "Lives:%i Score:%i", statek.lives, statek.score);
}
else
{
al_draw_bitmap(dup, 0, 0, 0);
al_draw_textf(font18, al_map_rgb(0, 255, 0), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "GAME OVER SCORE: %i", statek.score);
al_flip_display();
al_rest(3);
al_clear_to_color(al_map_rgb(0, 0, 0));
al_stop_sample_instance(songinstance);
isGameOver = false;
goto main_menu;
}
}
}
//al_draw_bitmap(dup, 50, 50, 0);
al_destroy_display(display); //usuwa okienko
al_destroy_sample(song);
al_destroy_sample_instance(songinstance);
al_destroy_bitmap(dup);
delete[] bullets;
delete[] comets;
}
void InitShip(SpaceShip &statek)
{
statek.x = 20;
statek.y = HEIGHT / 2;
statek.ID = PLAYER;
statek.lives = 3;
statek.speed = 7;
statek.boundx = 14;
statek.boundy = 14;
statek.score = 0;
}
void DrawShip(SpaceShip &statek)
{
ALLEGRO_BITMAP *statekimg = al_load_bitmap("grafika/statek.png");
//al_draw_filled_triangle(statek.x - 12, statek.y - 17, statek.x + 12, statek.y, statek.x - 12, statek.y + 17, al_map_rgb(0, 255, 0));
al_draw_bitmap(statekimg, statek.x - 17, statek.y - 17, 0);
}
void MoveShipUp(SpaceShip &statek)
{
statek.y -= statek.speed;
if (statek.y < 0) statek.y = 0;
}
void MoveShipDown(SpaceShip &statek)
{
statek.y += statek.speed;
if (statek.y > HEIGHT) statek.y = HEIGHT;
}
void MoveShipLeft(SpaceShip &statek)
{
statek.x -= statek.speed;
if (statek.x < 0) statek.x = 0;
}
void MoveShipRight(SpaceShip &statek)
{
statek.x += statek.speed;
if (statek.x > 300) statek.x = 300;
}
void InitBullet(Bullet bullet[], int size)
{
for (int i = 0; i < size; i++)
{
bullet[i].ID = BULLET;
bullet[i].speed = 10;
bullet[i].live = false;
}
}
void DrawBullet(Bullet bullet[], int size)
{
for (int i = 0; i < size; i++)
{
if (bullet[i].live)
al_draw_filled_circle(bullet[i].x, bullet[i].y, 2, al_map_rgb(255, 255, 255));
}
}
void FireBullet(Bullet bullet[], int size, SpaceShip &statek)
{
for (int i = 0; i < size; i++)
{
if (!bullet[i].live)
{
bullet[i].x = statek.x + 23;
bullet[i].y = statek.y+6;
bullet[i].live = true;
break;
}
}
}
void UpdateBullet(Bullet bullet[], int size)
{
for (int i = 0; i < size; i++)
{
if (bullet[i].live)
{
bullet[i].x += bullet[i].speed;
if (bullet[i].x > WIDTH)
bullet[i].live = false;
}
}
}
void CollideBulet(Bullet bullet[], int bSize, Comet comets[], int cSize, SpaceShip &statek)
{
for (int i = 0; i < bSize; i++)
{
if (bullet[i].live)
{
for (int j = 0; j < cSize; j++)
{
if (comets[j].live)
{
if (bullet[i].x > (comets[j].x - comets[j].boundx+25) &&
bullet[i].x < (comets[j].x + comets[j].boundx) &&
bullet[i].y>(comets[j].y - comets[j].boundy) &&
bullet[i].y < (comets[j].y + comets[j].boundy))
{
bullet[i].live = false;
comets[j].live = false;
statek.score++;
imp++;
//zycia++;
if (statek.score % 10 == 0)
{
//zycia = 0;
statek.lives++;
}
if (imp == 3)
{
NUM_BULLETS = NUM_BULLETS + 1;
NUM_COMETS = NUM_COMETS + 3;
imp = 0;
// statek.lives++;
//Bullet *bullets = new Bullet[NUM_BULLETS];
//Comet *comets = new Comet[NUM_COMETS];
//InitBullet(bullets, NUM_BULLETS);
//InitComet(comets, NUM_COMETS);
}
}
}
}
}
}
}
void InitComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
comets[i].ID = ENEMY;
comets[i].live = false;
comets[i].speed = 5;
comets[i].boundx = 23;
comets[i].boundy = 28;
}
}
void DrawComet(Comet comets[], int size)
{
ALLEGRO_BITMAP * kometa1 = al_load_bitmap("grafika/kometa1.png");
// ALLEGRO_BITMAP * kometa2 = al_load_bitmap("grafika/kometa2.png");
// ALLEGRO_BITMAP * kometa3 = al_load_bitmap("grafika/kometa3.png");
for (int i = 0; i < size; i++)
{
if (comets[i].live)
{
/*if(rand() % 3 ==0) al_draw_bitmap(kometa1, comets[i].x, comets[i].y-23, 0);
else if (rand() % 3 == 1) al_draw_bitmap(kometa2, comets[i].x, comets[i].y - 23, 0);
else if (rand() % 3 == 2) al_draw_bitmap(kometa3, comets[i].x, comets[i].y - 23, 0);*/
al_draw_bitmap(kometa1, comets[i].x, comets[i].y - 23, 0);
//al_draw_filled_circle(comets[i].x, comets[i].y, 20, al_map_rgb(255, 0, 0));
}
}
}
void StartComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
if (!comets[i].live)
{
if (rand() % 500 == 0)
{
comets[i].live = true;
comets[i].x = WIDTH;
comets[i].y = 30 + rand() % (HEIGHT - 60);
break;
}
}
}
}
void UpdateComet(Comet comets[], int size)
{
for (int i = 0; i < size; i++)
{
if (comets[i].live)
{
comets[i].x -= comets[i].speed;
//if (comets[i].x < 0) comets[i].live = false;
}
}
}
void CollideComet(Comet comets[], int cSize, SpaceShip &statek)
{
for (int i = 0; i < cSize; i++)
{
if (comets[i].live)
{
if (comets[i].x - comets[i].boundx < statek.x + statek.boundx - 30 &&
comets[i].x + comets[i].boundx > statek.x - statek.boundx &&
comets[i].y - comets[i].boundy < statek.y + statek.boundy &&
comets[i].y + comets[i].boundy > statek.y + statek.boundy)
{
statek.lives--;
comets[i].live = false;
}
else if (comets[i].x < 0)
{
statek.lives--;
comets[i].live = false;
}
}
}
}
void color_press(int *r, int *g, int *b, int selection, int max)
{
for (int i = 0; i < max; ++i)
{
r[i] = color[0]; g[i] = color[1]; b[i] = color[2];
}
r[selection] = 255; g[selection] = 120; b[selection] = 0;
}
| [
"seba23495@gmail.com"
] | seba23495@gmail.com |
1d6e01d6b00c357fd013406ce071b744b6aa9abc | 52767515c87f99525fdbe74a4b86e6b322bf38c0 | /OperatingSystem_Shell.cpp | bac7116e6f4634ebf9d23d54ddf549af92589502 | [] | no_license | 6guojun/C_Datastructures_Algorithms | 3e73628c625b6f83ac94fe94823a00a8bb0fa952 | d123c8437ab806f9eb4eaac5a728c3ae33b3b881 | refs/heads/master | 2021-02-15T10:05:30.571195 | 2018-12-15T06:40:03 | 2018-12-15T06:40:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,446 | cpp | #include<iostream>
#include<dirent.h>
#include<stdlib.h>
#include<string>
using namespace std;
void listCommand(){
cout << "List of Command: " << endl;
cout << "1. dir" << endl;
cout << "2. createProcess" << endl;
cout << "3. readBat" << endl;
}
int dir(){
DIR *dir;
struct dirent *ent;
cout<<"List of file name: "<<endl;
int n_file=0;
if ((dir = opendir ("C:/Users/USER/")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
n_file++;
cout<<n_file;
cout<<"\t"<<ent->d_name<<endl;
}
closedir (dir);
cout<<"\t\t\t\tTotal: "<<n_file<<" file(s)"<<endl;
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}
void createProcess(){
}
void readBat(){
}
void controlCmd(string str){
if(str == "dir") dir();
else if(str == "createProcess") createProcess();
else if(str == "reatBat") readBat();
else cout << str << "is not recognized as an internal command, operable program or batch file." << endl;
}
int main(int argc,char *argv[]){
string cmd;
cout << "\t\tWelcome to My_Basic_Shell !!!" << endl;
cout << "\t\t\tCreated by DMT" << endl;
cout << " _____________________________________________" << endl;
listCommand();
cout << "_________________" << endl;
cout<<"Your Command : "<<endl;
getline(std::cin,cmd);
fflush(stdin);
cout << "_________________" << endl;
controlCmd(cmd);
}
| [
"damminhtienchl@gmail.com"
] | damminhtienchl@gmail.com |
bb0cfcae1f0cb2727ba00a7f6fc485a1cffbbb27 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/compiler-rt/lib/msan/lit_tests/keep-going-dso.cc | 6d006756a110f6cba551ab9f32826e6aad1fa4ea | [
"MIT",
"NCSA"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 1,341 | cc | // RUN: %clangxx_msan -m64 -O0 %s -o %t && not %t >%t.out 2>&1
// FileCheck --check-prefix=CHECK-KEEP-GOING %s <%t.out
// RUN: %clangxx_msan -m64 -O0 %s -o %t && MSAN_OPTIONS=keep_going=0 not %t >%t.out 2>&1
// FileCheck %s <%t.out
// RUN: %clangxx_msan -m64 -O0 %s -o %t && MSAN_OPTIONS=keep_going=1 not %t >%t.out 2>&1
// FileCheck --check-prefix=CHECK-KEEP-GOING %s <%t.out
// RUN: %clangxx_msan -m64 -mllvm -msan-keep-going=1 -O0 %s -o %t && not %t >%t.out 2>&1
// FileCheck --check-prefix=CHECK-KEEP-GOING %s <%t.out
// RUN: %clangxx_msan -m64 -mllvm -msan-keep-going=1 -O0 %s -o %t && MSAN_OPTIONS=keep_going=0 not %t >%t.out 2>&1
// FileCheck %s <%t.out
// RUN: %clangxx_msan -m64 -mllvm -msan-keep-going=1 -O0 %s -o %t && MSAN_OPTIONS=keep_going=1 not %t >%t.out 2>&1
// FileCheck --check-prefix=CHECK-KEEP-GOING %s <%t.out
// Test how -mllvm -msan-keep-going and MSAN_OPTIONS=keep_going affect reports
// from interceptors.
// -mllvm -msan-keep-going provides the default value of keep_going flag, but is
// always overwritten by MSAN_OPTIONS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char *volatile x = (char*)malloc(5 * sizeof(char));
x[4] = 0;
if (strlen(x) < 3)
exit(0);
fprintf(stderr, "Done\n");
// CHECK-NOT: Done
// CHECK-KEEP-GOING: Done
return 0;
}
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
cc7b906f7bf9af4c97252280cf4623cb087acb2f | d303f2ef67f354d0d4a7579aad798bc735d91f53 | /ConsoleApplication1/Material.h | a5f352d5de428cb552eb8c7e13c3382dd04538a5 | [] | no_license | clatterrr/RayTracingPractice | f9e55d30452d5d69279775e0d9925c5759edb65a | 225078d957e6f3246368ae29b82056cdc8555750 | refs/heads/master | 2022-11-26T17:18:00.729143 | 2020-08-05T13:06:13 | 2020-08-05T13:06:13 | 285,287,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,298 | h | #ifndef MATERIAL_H
#define MATERIAL_H
#include "Rtweekend.h"
#include "Hittable.h"
#include "Texture.h"
struct hit_record;
class material {
public:
virtual color emitted(double u, double v, const point3& p) const {
return color(0, 0, 0);
}
virtual bool scatter(
const Ray& r_in, const hit_record& rec, color& attenuation, Ray& scattered
) const = 0;
};
class lambertian :public material
{
public:
lambertian(const color& a) : albedo(make_shared<solid_color>(a)) {}
lambertian(shared_ptr<texture> a) : albedo(a) {}
virtual bool scatter(
const Ray& r_in, const hit_record& rec, color& attenuation, Ray& scattered
) const override {
vec3 scatter_direction = rec.normal + random_unit_vector();
scattered = Ray(rec.p, scatter_direction, r_in.time());
attenuation = albedo->value(rec.u, rec.v, rec.p);
return true;
}
public:
shared_ptr<texture> albedo;
};
class metal : public material
{
public:
metal(const color& a, double f) :albedo(a), fuzz(f < 1 ? f : 1) {}
virtual bool scatter(
const Ray& r_in, const hit_record& rec, color& attenuation, Ray& scattered
) const override {
vec3 reflected = reflect(unit_vector(r_in.direction()), rec.normal);
scattered = Ray(rec.p, reflected + fuzz*random_in_unit_sphere());
attenuation = albedo;
return (dot(scattered.direction(), rec.normal) > 0);
}
public:
color albedo;
double fuzz;
};
class dielectric :public material
{
public:
dielectric(double ri):ref_idx(ri){}
virtual bool scatter(
const Ray& r_in, const hit_record& rec, color& attenuation, Ray& scattered
) const override {
attenuation = color(1.0, 1.0, 1.0);
double etai_over_etat = rec.front_face ? (1.0 / ref_idx) : ref_idx;
vec3 unit_direction = unit_vector(r_in.direction());
double cos_theta = fmin(dot(-unit_direction, rec.normal), 1.0);
double sin_theta = sqrt(1.0 - cos_theta * cos_theta);
if (etai_over_etat * sin_theta > 1.0)
{
vec3 reflected = reflect(unit_direction, rec.normal);
scattered = Ray(rec.p, reflected);
return true;
}
double reflect_prob = schlick(cos_theta, etai_over_etat);
if (random_double() < reflect_prob)
{
vec3 reflected = reflect(unit_direction, rec.normal);
scattered = Ray(rec.p, reflected);
return true;
}
vec3 refracted = refract(unit_direction, rec.normal, etai_over_etat);
scattered = Ray(rec.p, refracted);
return true;
}
double ref_idx;
};
class diffuse_light : public material {
public:
diffuse_light(shared_ptr<texture> a) : emit(a) {}
diffuse_light(color c) : emit(make_shared<solid_color>(c)) {}
virtual bool scatter(
const Ray& r_in, const hit_record& rec, color& attenuation, Ray& scattered
) const override {
return false;
}
virtual color emitted(double u, double v, const point3& p) const override {
return emit->value(u, v, p);
}
public:
shared_ptr<texture> emit;
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
f9a011839d2570050ad2c1ac25de60c6b9bb50eb | d162e580d3a58ba0a56dcd27481fe96ca204372b | /experiments/LSM_303_driver/Adafruit_LSM303_U.cpp | c66d22fc12bfca17f8446e6d553f2e658c827fc0 | [] | no_license | zachbellay/ODAF | ed347b64f43f0aca97815f3645ff2a44d2b08dce | 08bb857530132724b8ecbb8801ac7696c124f6ad | refs/heads/master | 2021-06-10T02:24:46.559929 | 2021-03-31T07:08:35 | 2021-03-31T07:08:35 | 131,802,004 | 0 | 0 | null | 2020-09-20T22:53:46 | 2018-05-02T05:23:40 | C++ | UTF-8 | C++ | false | false | 20,463 | cpp | /***************************************************************************
This is a library for the LSM303 Accelerometer and magnentometer/compass
Designed specifically to work with the Adafruit LSM303DLHC Breakout
These displays use I2C to communicate, 2 pins are required to interface.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <i2c_t3.h> //Edited JB
#include <limits.h>
#include "Adafruit_LSM303_U.h"
/* enabling this #define will enable the debug print blocks
#define LSM303_DEBUG
*/
static float _lsm303Accel_MG_LSB = 0.001F; // 1, 2, 4 or 12 mg per lsb
static float _lsm303Mag_Gauss_LSB_XY = 1100.0F; // Varies with gain
static float _lsm303Mag_Gauss_LSB_Z = 980.0F; // Varies with gain
/***************************************************************************
ACCELEROMETER
***************************************************************************/
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
/**************************************************************************/
/*!
@brief Abstract away platform differences in Arduino wire library
*/
/**************************************************************************/
void Adafruit_LSM303_Accel_Unified::write8(byte address, byte reg, byte value)
{
Wire.beginTransmission(address);
#if ARDUINO >= 100
Wire.write((uint8_t)reg);
Wire.write((uint8_t)value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}
/**************************************************************************/
/*!
@brief Abstract away platform differences in Arduino wire library
*/
/**************************************************************************/
byte Adafruit_LSM303_Accel_Unified::read8(byte address, byte reg)
{
byte value;
Wire.beginTransmission(address);
#if ARDUINO >= 100
Wire.write((uint8_t)reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(address, (byte)1);
#if ARDUINO >= 100
value = Wire.read();
#else
value = Wire.receive();
#endif
Wire.endTransmission();
return value;
}
/**************************************************************************/
/*!
@brief Reads the raw data from the sensor
*/
/**************************************************************************/
void Adafruit_LSM303_Accel_Unified::read()
{
// Read the accelerometer
Wire.beginTransmission((byte)LSM303_ADDRESS_ACCEL);
#if ARDUINO >= 100
Wire.write(LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80);
#else
Wire.send(LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80);
#endif
Wire.endTransmission();
Wire.requestFrom((byte)LSM303_ADDRESS_ACCEL, (byte)6);
// Wait around until enough data is available
while (Wire.available() < 6);
#if ARDUINO >= 100
uint8_t xlo = Wire.read();
uint8_t xhi = Wire.read();
uint8_t ylo = Wire.read();
uint8_t yhi = Wire.read();
uint8_t zlo = Wire.read();
uint8_t zhi = Wire.read();
#else
uint8_t xlo = Wire.receive();
uint8_t xhi = Wire.receive();
uint8_t ylo = Wire.receive();
uint8_t yhi = Wire.receive();
uint8_t zlo = Wire.receive();
uint8_t zhi = Wire.receive();
#endif
// Shift values to create properly formed integer (low byte first)
raw.x = (int16_t)(xlo | (xhi << 8)) >> 4;
raw.y = (int16_t)(ylo | (yhi << 8)) >> 4;
raw.z = (int16_t)(zlo | (zhi << 8)) >> 4;
}
/***************************************************************************
CONSTRUCTOR
***************************************************************************/
/**************************************************************************/
/*!
@brief Instantiates a new Adafruit_LSM303 class
*/
/**************************************************************************/
Adafruit_LSM303_Accel_Unified::Adafruit_LSM303_Accel_Unified(int32_t sensorID) {
_sensorID = sensorID;
// Clear the raw accel data
raw.x = 0;
raw.y = 0;
raw.z = 0;
}
/***************************************************************************
PUBLIC FUNCTIONS
***************************************************************************/
/**************************************************************************/
/*!
@brief Setups the HW
*/
/**************************************************************************/
bool Adafruit_LSM303_Accel_Unified::begin()
{
// Enable I2C
//Wire.begin();
Wire.begin(I2C_MASTER, LSM303_ADDRESS_ACCEL, I2C_PINS_37_38, I2C_PULLUP_INT, I2C_RATE_400); //Edited JB
// Enable the accelerometer (100Hz)
write8(LSM303_ADDRESS_ACCEL, LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0x57);
// LSM303DLHC has no WHOAMI register so read CTRL_REG1_A back to check
// if we are connected or not
uint8_t reg1_a = read8(LSM303_ADDRESS_ACCEL, LSM303_REGISTER_ACCEL_CTRL_REG1_A);
if (reg1_a != 0x57)
{
return false;
}
return true;
}
/**************************************************************************/
/*!
@brief Gets the most recent sensor event
*/
/**************************************************************************/
bool Adafruit_LSM303_Accel_Unified::getEvent(sensors_event_t *event) {
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
/* Read new data */
read();
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_ACCELEROMETER;
event->timestamp = millis();
event->acceleration.x = (float)raw.x * _lsm303Accel_MG_LSB * SENSORS_GRAVITY_STANDARD;
event->acceleration.y = (float)raw.y * _lsm303Accel_MG_LSB * SENSORS_GRAVITY_STANDARD;
event->acceleration.z = (float)raw.z * _lsm303Accel_MG_LSB * SENSORS_GRAVITY_STANDARD;
return true;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data
*/
/**************************************************************************/
void Adafruit_LSM303_Accel_Unified::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy (sensor->name, "LSM303", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name)- 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_ACCELEROMETER;
sensor->min_delay = 0;
sensor->max_value = 0.0F; // TBD
sensor->min_value = 0.0F; // TBD
sensor->resolution = 0.0F; // TBD
}
/***************************************************************************
MAGNETOMETER
***************************************************************************/
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
/**************************************************************************/
/*!
@brief Abstract away platform differences in Arduino wire library
*/
/**************************************************************************/
void Adafruit_LSM303_Mag_Unified::write8(byte address, byte reg, byte value)
{
Wire1.beginTransmission(address);
#if ARDUINO >= 100
Wire1.write((uint8_t)reg);
Wire1.write((uint8_t)value);
#else
Wire1.send(reg);
Wire1.send(value);
#endif
Wire1.endTransmission();
}
/**************************************************************************/
/*!
@brief Abstract away platform differences in Arduino wire library
*/
/**************************************************************************/
byte Adafruit_LSM303_Mag_Unified::read8(byte address, byte reg)
{
byte value;
Wire1.beginTransmission(address);
#if ARDUINO >= 100
Wire1.write((uint8_t)reg);
#else
Wire1.send(reg);
#endif
Wire1.endTransmission();
Wire1.requestFrom(address, (byte)1);
#if ARDUINO >= 100
value = Wire1.read();
#else
value = Wire1.receive();
#endif
Wire1.endTransmission();
return value;
}
/**************************************************************************/
/*!
@brief Reads the raw data from the sensor
*/
/**************************************************************************/
void Adafruit_LSM303_Mag_Unified::read()
{
// Read the magnetometer
Wire1.beginTransmission((byte)LSM303_ADDRESS_MAG);
#if ARDUINO >= 100
Wire1.write(LSM303_REGISTER_MAG_OUT_X_H_M);
#else
Wire1.send(LSM303_REGISTER_MAG_OUT_X_H_M);
#endif
Wire1.endTransmission();
Wire1.requestFrom((byte)LSM303_ADDRESS_MAG, (byte)6);
// Wait around until enough data is available
while (Wire1.available() < 6);
// Note high before low (different than accel)
#if ARDUINO >= 100
uint8_t xhi = Wire1.read();
uint8_t xlo = Wire1.read();
uint8_t zhi = Wire1.read();
uint8_t zlo = Wire1.read();
uint8_t yhi = Wire1.read();
uint8_t ylo = Wire1.read();
#else
uint8_t xhi = Wire1.receive();
uint8_t xlo = Wire1.receive();
uint8_t zhi = Wire1.receive();
uint8_t zlo = Wire1.receive();
uint8_t yhi = Wire1.receive();
uint8_t ylo = Wire1.receive();
#endif
// Shift values to create properly formed integer (low byte first)
raw.x = (int16_t)(xlo | ((int16_t)xhi << 8));
raw.y = (int16_t)(ylo | ((int16_t)yhi << 8));
raw.z = (int16_t)(zlo | ((int16_t)zhi << 8));
}
/***************************************************************************
CONSTRUCTOR
***************************************************************************/
/**************************************************************************/
/*!
@brief Instantiates a new Adafruit_LSM303 class
*/
/**************************************************************************/
Adafruit_LSM303_Mag_Unified::Adafruit_LSM303_Mag_Unified(int32_t sensorID) {
_sensorID = sensorID;
autoRangeEnabled = false;
// Clear the raw mag data
raw.x = 0;
raw.y = 0;
raw.z = 0;
}
/***************************************************************************
PUBLIC FUNCTIONS
***************************************************************************/
/**************************************************************************/
/*!
@brief Setups the HW
*/
/**************************************************************************/
bool Adafruit_LSM303_Mag_Unified::begin()
{
// Enable I2C
//Wire.begin();
Wire1.begin(I2C_MASTER, LSM303_ADDRESS_MAG, I2C_PINS_37_38, I2C_PULLUP_INT, I2C_RATE_400); //Edited JB
// Enable the magnetometer
write8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_MR_REG_M, 0x00);
// LSM303DLHC has no WHOAMI register so read CRA_REG_M to check
// the default value (0b00010000/0x10)
uint8_t reg1_a = read8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_CRA_REG_M);
if (reg1_a != 0x10)
{
return false;
}
// Set the gain to a known level
setMagGain(LSM303_MAGGAIN_1_3);
return true;
}
/**************************************************************************/
/*!
@brief Enables or disables auto-ranging
*/
/**************************************************************************/
void Adafruit_LSM303_Mag_Unified::enableAutoRange(bool enabled)
{
autoRangeEnabled = enabled;
}
/**************************************************************************/
/*!
@brief Sets the magnetometer's gain
*/
/**************************************************************************/
void Adafruit_LSM303_Mag_Unified::setMagGain(lsm303MagGain gain)
{
write8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_CRB_REG_M, (byte)gain);
magGain = gain;
switch(gain)
{
case LSM303_MAGGAIN_1_3:
_lsm303Mag_Gauss_LSB_XY = 1100;
_lsm303Mag_Gauss_LSB_Z = 980;
break;
case LSM303_MAGGAIN_1_9:
_lsm303Mag_Gauss_LSB_XY = 855;
_lsm303Mag_Gauss_LSB_Z = 760;
break;
case LSM303_MAGGAIN_2_5:
_lsm303Mag_Gauss_LSB_XY = 670;
_lsm303Mag_Gauss_LSB_Z = 600;
break;
case LSM303_MAGGAIN_4_0:
_lsm303Mag_Gauss_LSB_XY = 450;
_lsm303Mag_Gauss_LSB_Z = 400;
break;
case LSM303_MAGGAIN_4_7:
_lsm303Mag_Gauss_LSB_XY = 400;
_lsm303Mag_Gauss_LSB_Z = 355;
break;
case LSM303_MAGGAIN_5_6:
_lsm303Mag_Gauss_LSB_XY = 330;
_lsm303Mag_Gauss_LSB_Z = 295;
break;
case LSM303_MAGGAIN_8_1:
_lsm303Mag_Gauss_LSB_XY = 230;
_lsm303Mag_Gauss_LSB_Z = 205;
break;
}
}
/**************************************************************************/
/*!
@brief Sets the magnetometer's update rate
*/
/**************************************************************************/
void Adafruit_LSM303_Mag_Unified::setMagRate(lsm303MagRate rate)
{
byte reg_m = ((byte)rate & 0x07) << 2;
write8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_CRA_REG_M, reg_m);
}
/**************************************************************************/
/*!
@brief Gets the most recent sensor event
*/
/**************************************************************************/
bool Adafruit_LSM303_Mag_Unified::getEvent(sensors_event_t *event) {
bool readingValid = false;
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
while(!readingValid)
{
uint8_t reg_mg = read8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_SR_REG_Mg);
if (!(reg_mg & 0x1)) {
return false;
}
/* Read new data */
read();
/* Make sure the sensor isn't saturating if auto-ranging is enabled */
if (!autoRangeEnabled)
{
readingValid = true;
}
else
{
#ifdef LSM303_DEBUG
Serial.print(raw.x); Serial.print(" ");
Serial.print(raw.y); Serial.print(" ");
Serial.print(raw.z); Serial.println(" ");
#endif
/* Check if the sensor is saturating or not */
if ( (raw.x >= 2040) | (raw.x <= -2040) |
(raw.y >= 2040) | (raw.y <= -2040) |
(raw.z >= 2040) | (raw.z <= -2040) )
{
/* Saturating .... increase the range if we can */
switch(magGain)
{
case LSM303_MAGGAIN_5_6:
setMagGain(LSM303_MAGGAIN_8_1);
readingValid = false;
#ifdef LSM303_DEBUG
Serial.println("Changing range to +/- 8.1");
#endif
break;
case LSM303_MAGGAIN_4_7:
setMagGain(LSM303_MAGGAIN_5_6);
readingValid = false;
#ifdef LSM303_DEBUG
Serial.println("Changing range to +/- 5.6");
#endif
break;
case LSM303_MAGGAIN_4_0:
setMagGain(LSM303_MAGGAIN_4_7);
readingValid = false;
#ifdef LSM303_DEBUG
Serial.println("Changing range to +/- 4.7");
#endif
break;
case LSM303_MAGGAIN_2_5:
setMagGain(LSM303_MAGGAIN_4_0);
readingValid = false;
#ifdef LSM303_DEBUG
Serial.println("Changing range to +/- 4.0");
#endif
break;
case LSM303_MAGGAIN_1_9:
setMagGain(LSM303_MAGGAIN_2_5);
readingValid = false;
#ifdef LSM303_DEBUG
Serial.println("Changing range to +/- 2.5");
#endif
break;
case LSM303_MAGGAIN_1_3:
setMagGain(LSM303_MAGGAIN_1_9);
readingValid = false;
#ifdef LSM303_DEBUG
Serial.println("Changing range to +/- 1.9");
#endif
break;
default:
readingValid = true;
break;
}
}
else
{
/* All values are withing range */
readingValid = true;
}
}
}
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_MAGNETIC_FIELD;
event->timestamp = millis();
event->magnetic.x = (float)raw.x / _lsm303Mag_Gauss_LSB_XY * SENSORS_GAUSS_TO_MICROTESLA;
event->magnetic.y = (float)raw.y / _lsm303Mag_Gauss_LSB_XY * SENSORS_GAUSS_TO_MICROTESLA;
event->magnetic.z = (float)raw.z / _lsm303Mag_Gauss_LSB_Z * SENSORS_GAUSS_TO_MICROTESLA;
return true;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data
*/
/**************************************************************************/
void Adafruit_LSM303_Mag_Unified::getSensor(sensor_t *sensor) {
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy (sensor->name, "LSM303", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name)- 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_MAGNETIC_FIELD;
sensor->min_delay = 0;
sensor->max_value = 0.0F; // TBD
sensor->min_value = 0.0F; // TBD
sensor->resolution = 0.0F; // TBD
}
/* --- The code below is no longer maintained and provided solely for */
/* --- compatibility reasons! */
/***************************************************************************
DEPRECATED (NON UNIFIED) DRIVER (Adafruit_LSM303.c/h)
***************************************************************************/
/***************************************************************************
CONSTRUCTOR
***************************************************************************/
bool Adafruit_LSM303::begin()
{
//Wire.begin();
Wire.begin(I2C_MASTER, 0x00, I2C_PINS_37_38, I2C_PULLUP_INT, I2C_RATE_400); //Edited JB
//Not sure about which address this should be
// Enable the accelerometer
write8(LSM303_ADDRESS_ACCEL, LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0x27);
// Enable the magnetometer
write8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_MR_REG_M, 0x00);
return true;
}
/***************************************************************************
PUBLIC FUNCTIONS
***************************************************************************/
void Adafruit_LSM303::read()
{
// Read the accelerometer
Wire.beginTransmission((byte)LSM303_ADDRESS_ACCEL);
Wire.write(LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80);
Wire.endTransmission();
Wire.requestFrom((byte)LSM303_ADDRESS_ACCEL, (byte)6);
// Wait around until enough data is available
while (Wire.available() < 6);
uint8_t xlo = Wire.read();
uint8_t xhi = Wire.read();
uint8_t ylo = Wire.read();
uint8_t yhi = Wire.read();
uint8_t zlo = Wire.read();
uint8_t zhi = Wire.read();
// Shift values to create properly formed integer (low byte first)
accelData.x = (int16_t)((uint16_t)xlo | ((uint16_t)xhi << 8)) >> 4;
accelData.y = (int16_t)((uint16_t)ylo | ((uint16_t)yhi << 8)) >> 4;
accelData.z = (int16_t)((uint16_t)zlo | ((uint16_t)zhi << 8)) >> 4;
// Read the magnetometer
Wire.beginTransmission((byte)LSM303_ADDRESS_MAG);
Wire.write(LSM303_REGISTER_MAG_OUT_X_H_M);
Wire.endTransmission();
Wire.requestFrom((byte)LSM303_ADDRESS_MAG, (byte)6);
// Wait around until enough data is available
while (Wire.available() < 6);
// Note high before low (different than accel)
xhi = Wire.read();
xlo = Wire.read();
zhi = Wire.read();
zlo = Wire.read();
yhi = Wire.read();
ylo = Wire.read();
// Shift values to create properly formed integer (low byte first)
magData.x = (int16_t)((uint16_t)xlo | ((uint16_t)xhi << 8));
magData.y = (int16_t)((uint16_t)ylo | ((uint16_t)yhi << 8));
magData.z = (int16_t)((uint16_t)zlo | ((uint16_t)zhi << 8));
}
void Adafruit_LSM303::setMagGain(lsm303MagGain gain)
{
write8(LSM303_ADDRESS_MAG, LSM303_REGISTER_MAG_CRB_REG_M, (byte)gain);
}
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
void Adafruit_LSM303::write8(byte address, byte reg, byte value)
{
Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
Wire.endTransmission();
}
byte Adafruit_LSM303::read8(byte address, byte reg)
{
byte value;
Wire.beginTransmission(address);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(address, (byte)1);
value = Wire.read();
Wire.endTransmission();
return value;
}
| [
"zbellay@Zachs-MacBook-Air.local"
] | zbellay@Zachs-MacBook-Air.local |
dbaaee3803d78e96aa33b634ad062d347a8a5360 | 72f2992a3659ff746ba5ce65362acbe85a918df9 | /apps-src/apps/external/chromium/net/base/network_delegate_impl.h | c86514025cb54cff9153ba69a26d5d1797ff60d9 | [
"BSD-2-Clause"
] | permissive | chongtianfeiyu/Rose | 4742f06ee9ecd55f9717ac6378084ccf8bb02a15 | 412175b57265ba2cda1e33dd2047a5a989246747 | refs/heads/main | 2023-05-23T14:03:08.095087 | 2021-06-19T13:23:58 | 2021-06-19T14:00:25 | 391,238,554 | 0 | 1 | BSD-2-Clause | 2021-07-31T02:39:25 | 2021-07-31T02:39:24 | null | UTF-8 | C++ | false | false | 3,177 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_BASE_NETWORK_DELEGATE_IMPL_H_
#define NET_BASE_NETWORK_DELEGATE_IMPL_H_
#include <stdint.h>
#include <set>
#include "base/optional.h"
#include "base/strings/string16.h"
#include "net/base/completion_once_callback.h"
#include "net/base/net_export.h"
#include "net/base/network_delegate.h"
// #include "net/cookies/canonical_cookie.h"
#include "net/proxy_resolution/proxy_retry_info.h"
class GURL;
namespace url {
class Origin;
}
namespace net {
class CookieOptions;
class HttpRequestHeaders;
class HttpResponseHeaders;
class URLRequest;
class NET_EXPORT NetworkDelegateImpl : public NetworkDelegate {
public:
~NetworkDelegateImpl() override {}
private:
int OnBeforeURLRequest(URLRequest* request,
CompletionOnceCallback callback,
GURL* new_url) override;
int OnBeforeStartTransaction(URLRequest* request,
CompletionOnceCallback callback,
HttpRequestHeaders* headers) override;
int OnHeadersReceived(
URLRequest* request,
CompletionOnceCallback callback,
const HttpResponseHeaders* original_response_headers,
scoped_refptr<HttpResponseHeaders>* override_response_headers,
const IPEndPoint& endpoint,
base::Optional<GURL>* preserve_fragment_on_redirect_url) override;
void OnBeforeRedirect(URLRequest* request, const GURL& new_location) override;
void OnResponseStarted(URLRequest* request, int net_error) override;
void OnCompleted(URLRequest* request, bool started, int net_error) override;
void OnURLRequestDestroyed(URLRequest* request) override;
void OnPACScriptError(int line_number, const base::string16& error) override;
/*
bool OnCanGetCookies(const URLRequest& request,
bool allowed_from_caller) override;
bool OnCanSetCookie(const URLRequest& request,
const net::CanonicalCookie& cookie,
CookieOptions* options,
bool allowed_from_caller) override;
bool OnForcePrivacyMode(
const GURL& url,
const SiteForCookies& site_for_cookies,
const base::Optional<url::Origin>& top_frame_origin) const override;
*/
bool OnCancelURLRequestWithPolicyViolatingReferrerHeader(
const URLRequest& request,
const GURL& target_url,
const GURL& referrer_url) const override;
bool OnCanQueueReportingReport(const url::Origin& origin) const override;
void OnCanSendReportingReports(std::set<url::Origin> origins,
base::OnceCallback<void(std::set<url::Origin>)>
result_callback) const override;
bool OnCanSetReportingClient(const url::Origin& origin,
const GURL& endpoint) const override;
bool OnCanUseReportingClient(const url::Origin& origin,
const GURL& endpoint) const override;
};
} // namespace net
#endif // NET_BASE_NETWORK_DELEGATE_IMPL_H_
| [
"service@leagor.com"
] | service@leagor.com |
ab1a709c05d9fdb6b998f2cee5afe2ae95653f33 | 6c800b3c0a39defa5f5605f60688dc82ac164416 | /Candle.cpp | e692e9c87e937877327bedd37eff797221eb86c7 | [] | no_license | ralstonba/COC_CandleShrine | d352b3fc677f11900f75b20380b89202ddedd0ae | 23020207cb3d1153eaed829e20679b5e69cfa330 | refs/heads/master | 2020-05-27T11:30:24.494639 | 2019-05-25T23:08:47 | 2019-05-25T23:08:47 | 188,601,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | cpp | /*
* Candle object source
* Brendan Ralston, 5/25/19
*/
#include "Arduino.h"
#include "Candle.h"
Candle::Candle(byte pin){
pinMode(pin, OUTPUT);
_pin = pin;
_state = true;
}
Candle::Candle(){}
void Candle::on(){
_state = false;
digitalWrite(_pin, _state);
}
void Candle::off(){
_state = true;
digitalWrite(_pin, _state);
}
void Candle::toggle(){
_state = !_state;
digitalWrite(_pin, _state);
}
bool Candle::isLit(){
return !_state;
}
| [
"ralston.brendan@me.com"
] | ralston.brendan@me.com |
ace179bdff002024e579b3aaf7298601d1cab52d | e402d6ed8df8651cb3f441860d09c874faddb6e9 | /src/Vector2d.h | 8c588d4baefa1c566af00ac56a53a627582b4a48 | [] | no_license | ErikWallstrom/Client_Test | 87bdc8e9fd9e985870b8118ef2b7405b3304e41a | 0de01a608f850f6171ca5e6a9e3d6d806587bc6d | refs/heads/master | 2016-08-12T23:39:52.957087 | 2016-02-07T21:56:26 | 2016-02-07T21:56:26 | 50,063,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | h | #ifndef VECTOR2D_H
#define VECTOR2D_H
class Vector2d
{
private:
double x;
double y;
public:
Vector2d(double x, double y);
~Vector2d();
void print();
Vector2d operator+(Vector2d vec);
void operator+=(Vector2d vec);
Vector2d operator-(Vector2d vec);
void operator-=(Vector2d vec);
Vector2d operator*(double count);
void operator*=(double count);
Vector2d operator/(double count);
void operator/=(double count);
//bool operator==(Vector2d vec);
Vector2d normalize();
void set_x(double x);
void set_y(double y);
double get_x();
double get_y();
double get_length();
};
#endif
| [
"erik.wallstrom@live.com"
] | erik.wallstrom@live.com |
edb6ce416eea337bea4d0e207e716c3adad04552 | bc2e69ff89262b5abc534322857014adb51391d4 | /PROJECT.ino | 3deb41acdfa26b8f5607ab45a02251897248803c | [] | no_license | hazynatulasrori/Project-Arduino | 25875cf0bf5c7a7b3b119898348927027b4e43c8 | ac9d1f205cd776b8a090f3d959f2cee90b64c988 | refs/heads/master | 2022-12-05T16:07:18.108048 | 2020-08-24T13:04:07 | 2020-08-24T13:04:07 | 286,357,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | ino |
#include <SoftwareSerial.h>
#include <DFPlayer_Mini_Mp3.h>
void setup() {
SoftwareSerial mySerial(12, 13);
Serial.begin (9600);
mySerial.begin (9600);
mp3_set_serial (mySerial);
delay(10);
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,INPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
pinMode(7,INPUT);
pinMode(8,INPUT);
pinMode(9,INPUT);
pinMode(10,INPUT);
digitalWrite(2,HIGH);
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(7,HIGH);
digitalWrite(8,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
void loop() {
if(digitalRead(2)==LOW)
{
}
else if(digitalRead(3)==LOW)
{
}
else if(digitalRead(4)==LOW)
{
}
}
| [
"noreply@github.com"
] | noreply@github.com |
32dcf216ae7ef36a84cafdb8462ba024c7fb4798 | 4e3fa94daadcf38d8516df1e9716dfaea79ac30b | /ExcelSheetColumnTitle.cpp | cdf9e4687ea7aaf5c34e2f89a7ea899ea1c37a00 | [] | no_license | witwolf/leetcode | 8aa20ce5ebb474907a510e24e7839bc6a0cf9cdf | d4088c7bce050cec2b5cb69fe4a3bf3b957b9866 | refs/heads/master | 2021-01-02T09:08:37.569214 | 2017-09-25T01:47:46 | 2017-09-25T01:47:46 | 25,668,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 637 | cpp | //
// ExcelSheetColumnTitle.cpp
// leetcode
//
// Created by witwolf on 4/30/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
string convertToTitle(int n) {
string s;
while(n){
n -= 1;
s.push_back(n % 26 + 'A');
n = n / 26;
}
reverse(s.begin(), s.end());
return s;
}
};
int main(int argc,char **argv){
Solution s;
for(int i = 1 ; i <= 28 * 26 ; ++i){
cout << i << ":" << s.convertToTitle(i) << endl;
}
} | [
"yingxiang.hong@horizon-robotics.com"
] | yingxiang.hong@horizon-robotics.com |
0553c3d6a904224573764330f17d08b2659b50aa | 4d12369aff139e70a96d679de6c20a3f9000450f | /lib/fitsdk/fit_segment_lap_mesg_listener.hpp | 6f215a1c838c2692d78cc3fd3b869e3da3d6234c | [] | no_license | whz20024117/Cycling_Fit_Analyzer | dca655669992b1b4f79add649d9690a342172cae | 7bc597574ef9c0f85be01312da09bafbd03c5f67 | refs/heads/master | 2023-01-05T12:41:24.996491 | 2020-10-29T19:23:19 | 2020-10-29T19:23:19 | 306,160,096 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | hpp | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Garmin Canada Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2020 Garmin Canada Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 21.40Release
// Tag = production/akw/21.40.00-0-g813c158
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_SEGMENT_LAP_MESG_LISTENER_HPP)
#define FIT_SEGMENT_LAP_MESG_LISTENER_HPP
#include "fit_segment_lap_mesg.hpp"
namespace fit
{
class SegmentLapMesgListener
{
public:
virtual ~SegmentLapMesgListener() {}
virtual void OnMesg(SegmentLapMesg& mesg) = 0;
};
} // namespace fit
#endif // !defined(FIT_SEGMENT_LAP_MESG_LISTENER_HPP)
| [
"whz20024117@gmail.com"
] | whz20024117@gmail.com |
99b3dd89fcf17ab3ac48c13a0168f3680f1da82b | 31030f9c260a2befb67b85350f0a6adde5163f14 | /src/clientversion.h | 0d86d4e64d0472f852b5ed7c34f479d7ddac9660 | [
"MIT"
] | permissive | shahripal/e-BlockCoin-Silver | 05322d716be0eb63b2d7a814abb20d7e2cd3c7c9 | 0f0522fce9c9fb2b8432bdbe13c7cf71263dce4b | refs/heads/master | 2020-04-11T02:23:45.562050 | 2018-11-05T09:29:07 | 2018-11-05T09:29:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,049 | h | // Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2017-2018 The eBlockCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CLIENTVERSION_H
#define BITCOIN_CLIENTVERSION_H
#if defined(HAVE_CONFIG_H)
#include "config/eblockcoin-config.h"
#endif //HAVE_CONFIG_H
// Check that required client information is defined
#if !defined(CLIENT_VERSION_MAJOR) || !defined(CLIENT_VERSION_MINOR) || !defined(CLIENT_VERSION_REVISION) || !defined(CLIENT_VERSION_BUILD) || !defined(CLIENT_VERSION_IS_RELEASE) || !defined(COPYRIGHT_YEAR)
#error Client version information missing: version is not defined by eblockcoin-config.h or in any other way
#endif
/**
* Converts the parameter X to a string after macro replacement on X has been performed.
* Don't merge these into one macro!
*/
#define STRINGIZE(X) DO_STRINGIZE(X)
#define DO_STRINGIZE(X) #X
//! Copyright string used in Windows .rc files
#define COPYRIGHT_STR "2009-" STRINGIZE(COPYRIGHT_YEAR) " The Bitcoin Core Developers, 2014-" STRINGIZE(COPYRIGHT_YEAR) " The Dash Core Developers, 2015-" STRINGIZE(COPYRIGHT_YEAR) " The eBlockCoin Core Developers"
/**
* eblockcoind-res.rc includes this file, but it cannot cope with real c++ code.
* WINDRES_PREPROC is defined to indicate that its pre-processor is running.
* Anything other than a define should be guarded below.
*/
#if !defined(WINDRES_PREPROC)
#include <string>
#include <vector>
static const int CLIENT_VERSION =
1000000 * CLIENT_VERSION_MAJOR ///
+ 10000 * CLIENT_VERSION_MINOR ///
+ 100 * CLIENT_VERSION_REVISION ///
+ 1 * CLIENT_VERSION_BUILD;
extern const std::string CLIENT_NAME;
extern const std::string CLIENT_BUILD;
extern const std::string CLIENT_DATE;
std::string FormatFullVersion();
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
#endif // WINDRES_PREPROC
#endif // BITCOIN_CLIENTVERSION_H
| [
"44762973+eblockcoin7@users.noreply.github.com"
] | 44762973+eblockcoin7@users.noreply.github.com |
95fd691d50ec24dabff3082ef35d8ef0270ca281 | 0e952027484dbec9c00fb15a5aa111925ddb19c4 | /controlWithJacobian/Stepper_Initial.ino | 6b1d183df0dd4ba5564629a1667b91e469186378 | [] | no_license | mahmoudelmohtady/new_mohtady | f3dd0da0248bdc86f3dd86e3efc9c853cf910c1b | 242659014a04b1d9032db6a43f1962a9bed70311 | refs/heads/master | 2021-01-22T06:27:48.631321 | 2017-02-12T23:06:17 | 2017-02-12T23:06:17 | 81,762,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 645 | ino | void Stepper_Initial() {
/*
//---------------------------------------------------------------------------------------
//*********************************Set absolute travel distance**************************
stepperA.moveTo(((L1 / 11.25) * DS) / (2 * pi))); // Set required absolute travel of Motor A
stepperB.moveTo(((L1 / 11.25) * DS) / (2 * pi))); // Set required absolute travel of Motor B
stepperC.moveTo(((L1 / 11.25) * DS) / (2 * pi))); // Set required absolute travel of Motor C
delay(10); // Wait 10 milli-seconds before moving the Steppers
*/
}
| [
"mahmoud"
] | mahmoud |
fd30b74adfd3302ad0a645bdc7deec4a20a41127 | 6ea6691636a1a5072f12efe0aad9d778d32f126c | /OGLplus_build/implement/oglplus/shapes/torus.ipp | fcbf9405550f5d81b18032f0aa51a4055b54178c | [
"BSL-1.0"
] | permissive | pm990320/OpenGLLearning | 6c63234da5f00193bf3799ee4b97b16bd14cdc6b | d4f83a047dbfe816631d59ea1115176514d9fad6 | refs/heads/master | 2021-01-10T06:21:34.592102 | 2014-07-04T10:42:52 | 2014-07-04T10:42:52 | 54,271,323 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,721 | ipp | /**
* @file oglplus/shapes/torus.ipp
* @brief Implementation of shapes::Torus
*
* @author Matus Chochlik
*
* Copyright 2010-2013 Matus Chochlik. 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)
*/
namespace oglplus {
namespace shapes {
OGLPLUS_LIB_FUNC
Torus::IndexArray Torus::Indices(void) const
{
const unsigned n = _rings * (2 * (_sections + 1) + 1);
assert((1<<(sizeof(GLushort)*8)) - 1 >= n);
//
IndexArray indices(n);
unsigned k = 0;
unsigned offs = 0;
// the triangle strips
for(unsigned r=0; r!=(_rings); ++r)
{
for(unsigned s=0; s!=(_sections+1); ++s)
{
indices[k++] = offs + s;
indices[k++] = offs + s + (_sections+1);
}
indices[k++] = n;
offs += _sections + 1;
}
assert(k == indices.size());
//
// return the indices
return indices;
}
OGLPLUS_LIB_FUNC
Torus::IndexArray Torus::IndicesWithAdjacency(void) const
{
const unsigned m = _rings*(_sections + 1);
const unsigned n = _rings*(4 * (_sections + 1) + 1);
assert((1<<(sizeof(GLushort)*8)) - 1 >= n);
//
IndexArray indices(n);
unsigned k = 0;
unsigned offs = 0;
for(unsigned r=0; r!=(_rings); ++r)
{
indices[k++] = offs;
indices[k++] = offs + (2*_sections);
indices[k++] = offs + (_sections+1);
for(unsigned s=0; s!=_sections; ++s)
{
indices[k++] = (offs + m-(_sections+1))%m + s+1;
indices[k++] = offs + s + 1;
indices[k++] = (offs + 2*(_sections+1)) % m + s;
indices[k++] = offs + (_sections+1) + s + 1;
}
indices[k++] = offs + 1;
indices[k++] = n;
offs += _sections + 1;
}
assert(k == indices.size());
//
// return the indices
return indices;
}
OGLPLUS_LIB_FUNC
DrawingInstructions Torus::Instructions(void) const
{
auto instructions = this->MakeInstructions();
const GLuint n = _rings * (2 * (_sections + 1) + 1);
DrawOperation operation;
operation.method = DrawOperation::Method::DrawElements;
operation.mode = PrimitiveType::TriangleStrip;
operation.first = GLuint(0);
operation.count = n;
operation.restart_index = n;
operation.phase = 0;
this->AddInstruction(instructions, operation);
return instructions;
}
OGLPLUS_LIB_FUNC
DrawingInstructions Torus::InstructionsWithAdjacency(void) const
{
auto instructions = this->MakeInstructions();
const unsigned n = _rings*(4 * (_sections + 1) + 1);
DrawOperation operation;
operation.method = DrawOperation::Method::DrawElements;
operation.mode = PrimitiveType::TriangleStripAdjacency;
operation.first = GLuint(0);
operation.count = n;
operation.restart_index = n;
operation.phase = 0;
this->AddInstruction(instructions, operation);
return instructions;
}
} // shapes
} // oglplus
| [
"patmenlove@gmail.com"
] | patmenlove@gmail.com |
9b6ee777c7fd8ea8e261c31c967b562405adb247 | 102be9b531fc0cad28bb1f938f1858292c0397f4 | /src/wcs/esp32/FB_TCP_Client.h | d58122e2c5be601d7b109c72a017cb36c283ec52 | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | sanchirganzorig/Firebase-ESP-Client | 76b98a580d9bdfb7383a5eefdbc2037ab63863dc | 3076fc6abb70986645ebb9a0c83eac60d3319986 | refs/heads/main | 2023-09-04T15:01:59.062093 | 2021-11-23T14:55:50 | 2021-11-23T14:55:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,232 | h | /**
* Firebase TCP Client v1.1.15
*
* Created November 20, 2001
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the HTTPClient for Arduino.
* Port to ESP32 by Evandro Luis Copercini (2017),
* changed fingerprints to CA verification.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef FB_TCP_Client_H
#define FB_TCP_Client_H
#ifdef ESP32
#include <Arduino.h>
#include <WiFiClient.h>
#include <FS.h>
#include <SPIFFS.h>
#include <SD.h>
#include <ETH.h>
#include "FirebaseFS.h"
#include <WiFiClientSecure.h>
#if defined(FIREBASE_USE_PSRAM)
#define FIREBASEJSON_USE_PSRAM
#endif
#include "./json/FirebaseJson.h"
#if __has_include(<FireBase32.h>)
#error Prohibited!
#endif
#if __has_include(<esp_idf_version.h>)
#include <esp_idf_version.h>
#endif
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if defined DEFAULT_FLASH_FS
#define FLASH_FS DEFAULT_FLASH_FS
#endif
#if defined DEFAULT_SD_FS
#define SD_FS DEFAULT_SD_FS
#endif
#define FORMAT_FLASH FORMAT_FLASH_IF_MOUNT_FAILED
#include "wcs/HTTPCode.h"
static const char esp_idf_branch_str[] PROGMEM = "release/v";
struct fb_esp_sd_config_info_t
{
int sck = -1;
int miso = -1;
int mosi = -1;
int ss = -1;
const char *sd_mmc_mountpoint = "";
bool sd_mmc_mode1bit = false;
bool sd_mmc_format_if_mount_failed = false;
};
//The derived class to fix the memory leaks issue
//https://github.com/espressif/arduino-esp32/issues/5480
class FB_WCS : public WiFiClientSecure
{
public:
FB_WCS(){};
~FB_WCS(){};
int _connect(const char *host, uint16_t port, unsigned long timeout)
{
_timeout = timeout;
if (connect(host, port) == 0)
{
if (_CA_cert != NULL)
mbedtls_x509_crt_free(&sslclient->ca_cert);
return 0;
}
_connected = true;
return 1;
}
};
class FB_TCP_Client
{
friend class FirebaseData;
friend class FB_RTDB;
friend class FB_CM;
friend class UtilsClass;
public:
FB_TCP_Client();
~FB_TCP_Client();
/**
* Initialization of new http connection.
* \param host - Host name without protocols.
* \param port - Server's port.
* \return True as default.
* If no certificate string provided, use (const char*)NULL to CAcert param
*/
bool begin(const char *host, uint16_t port);
/**
* Check the http connection status.
* \return True if connected.
*/
bool connected();
/**
* Establish TCP connection when required and send data.
* \param data - The data to send.
* \param len - The length of data to send.
*
* \return TCP status code, Return zero if new TCP connection and data sent.
*/
int send(const char *data, size_t len = 0);
/**
* Get the WiFi client pointer.
* \return WiFi client pointer.
*/
WiFiClient *stream(void);
/**
* Set insecure mode
*/
void setInsecure();
void stop();
bool connect(void);
void setCACert(const char *caCert);
void setCACertFile(const char *caCertFile, uint8_t storageType, struct fb_esp_sd_config_info_t sd_config);
private:
std::unique_ptr<FB_WCS> _wcs = std::unique_ptr<FB_WCS>(new FB_WCS());
MBSTRING _host;
uint16_t _port = 0;
//lwIP socket connection and ssl handshake timeout
unsigned long timeout = 10 * 1000;
MBSTRING _CAFile;
uint8_t _CAFileStoreageType = 0;
int _certType = -1;
bool _clockReady = false;
void release();
};
#endif /* ESP32 */
#endif /* FB_TCP_Client_H */
| [
"k_suwatchai@hotmail.com"
] | k_suwatchai@hotmail.com |
dbe50ea233844d6909427022f4a6291c13459390 | 7f90f00214221b7f3f4893202fb9996475a12453 | /src/chainparamsbase.h | 50cfc241ba927213acbee2bd8097e26ff2628932 | [
"MIT"
] | permissive | ezehy/adzcoin | 04f394e053a0e21fd4587f8f544539e33d58273a | a6a1e6cd144142350f7df30bdecc86c7157ef9a0 | refs/heads/master | 2020-03-28T14:34:10.892435 | 2018-10-11T12:08:45 | 2018-10-11T12:08:45 | 148,500,077 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | h | // Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CHAINPARAMSBASE_H
#define BITCOIN_CHAINPARAMSBASE_H
#include <string>
#include <vector>
/**
* CBaseChainParams defines the base parameters (shared between adzcoin-cli and adzcoind)
* of a given instance of the Adzcoin system.
*/
class CBaseChainParams
{
public:
/** BIP70 chain name strings (main, test or regtest) */
static const std::string MAIN;
static const std::string TESTNET;
static const std::string REGTEST;
const std::string& DataDir() const { return strDataDir; }
int RPCPort() const { return nRPCPort; }
protected:
CBaseChainParams() {}
int nRPCPort;
std::string strDataDir;
};
/**
* Append the help messages for the chainparams options to the
* parameter string.
*/
void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp=true);
/**
* Return the currently selected parameters. This won't change after app
* startup, except for unit tests.
*/
const CBaseChainParams& BaseParams();
CBaseChainParams& BaseParams(const std::string& chain);
/** Sets the params returned by Params() to those for the given network. */
void SelectBaseParams(const std::string& chain);
/**
* Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
* @return CBaseChainParams::MAX_NETWORK_TYPES if an invalid combination is given. CBaseChainParams::MAIN by default.
*/
std::string ChainNameFromCommandLine();
/**
* Return true if SelectBaseParamsFromCommandLine() has been called to select
* a network.
*/
bool AreBaseParamsConfigured();
#endif // BITCOIN_CHAINPARAMSBASE_H
| [
"noreply@github.com"
] | noreply@github.com |
79226c31da22687d610774ebf2864669d8211792 | 86d4e5dd50cd5eac55819f89dd29ba346724868e | /QGSS2/LINE.cpp | 45650551ddb96d527bf42032cf6ae69101f902dc | [] | no_license | ppkhang285/C-Codes | e074b1a184c975499d013e47eaceb371ee5dfa80 | 341a4e83a16a791f5fe2e4cc46c2a27107b59cfd | refs/heads/master | 2023-01-12T13:44:45.694680 | 2020-11-14T08:12:43 | 2020-11-14T08:12:43 | 294,895,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | #include <bits/stdc++.h>
#define task "LINE"
#define REP(i,a,b) for(int i = a; i<=b;++i)
using namespace std;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
map<iii, int> m;
int n;
int main(){
freopen(task".inp","r",stdin);
freopen(task".out","w",stdout);
cin>>n;
int res = 0;
REP(i,1,n){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
int d = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1);
int u = x2 - x1;
int v = y2 - y1;
//cout<<d<<" "<<u<<" "<<v<<"\n";
res += m[iii(d, ii(-v,u))] + m[iii(d, ii(v,-u))];
m[iii(d, ii(u,v))]++;
}
cout<<res;
return 0;
}
| [
"ppkhang285@gmail.com"
] | ppkhang285@gmail.com |
4a500689c02b585eb9f4f6195155fcfe5f19fee4 | 43b02ae78c60d27927a93347ba6e53aa06ffe30d | /test/com/facebook/buck/android/testdata/android_project/native/xdsodce/top.cpp | 4bb6b687a216ad91827e94dc0f7daec3c40e74a7 | [
"Apache-2.0"
] | permissive | bocon13/buck | 75e7b6bb2cba9976d2f836e22a6980ae12966ff1 | bb08f203569a2527a78b6471d016479d52783f3e | refs/heads/master | 2021-01-18T08:33:02.435393 | 2017-12-20T22:23:17 | 2017-12-20T22:30:51 | 55,684,269 | 0 | 1 | Apache-2.0 | 2017-12-20T22:30:52 | 2016-04-07T10:05:28 | Java | UTF-8 | C++ | false | false | 157 | cpp | #include "top.h"
#include "mid.h"
#include "bot.h"
int unused(int) {
return 1;
}
int JNI_OnLoad(int a, int b) {
return midFromTop(a) + botFromTop(b);
} | [
"facebook-github-bot-1-bot@fb.com"
] | facebook-github-bot-1-bot@fb.com |
e5f1047c77db4f367e66180d3e4f424e5a5fe205 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /ccc/include/alibabacloud/ccc/model/GetHistoricalCampaignReportRequest.h | 169c13e7f28b5a2a3f56af3ae2d7633756929cd9 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,557 | h | /*
* Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_CCC_MODEL_GETHISTORICALCAMPAIGNREPORTREQUEST_H_
#define ALIBABACLOUD_CCC_MODEL_GETHISTORICALCAMPAIGNREPORTREQUEST_H_
#include <alibabacloud/ccc/CCCExport.h>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace CCC {
namespace Model {
class ALIBABACLOUD_CCC_EXPORT GetHistoricalCampaignReportRequest : public RpcServiceRequest {
public:
GetHistoricalCampaignReportRequest();
~GetHistoricalCampaignReportRequest();
std::string getCampaignId() const;
void setCampaignId(const std::string &campaignId);
std::string getInstanceId() const;
void setInstanceId(const std::string &instanceId);
private:
std::string campaignId_;
std::string instanceId_;
};
} // namespace Model
} // namespace CCC
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_CCC_MODEL_GETHISTORICALCAMPAIGNREPORTREQUEST_H_
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
7b06e9bcd2e6f4bf419847c31633ba3cf43dd8aa | b533cc85d6de35b0e6a9664dce6b31e6945531a1 | /Anaface/AnafaceUI.cpp | d892eab4a15b4fd86976d3f76c06c4e87470b62d | [] | no_license | TrecApps/AnaGame | efa90d4af51aea14fd0ecd834341193cb1c36cbc | 23b349a2f4afa64d6410e47a3c5e56c99c136d57 | refs/heads/master | 2022-08-11T17:30:07.756655 | 2021-07-03T15:55:56 | 2021-07-03T15:55:56 | 142,814,475 | 0 | 2 | null | 2021-06-23T03:10:11 | 2018-07-30T02:25:01 | C++ | UTF-8 | C++ | false | false | 24,724 | cpp |
#include "AnafaceUI.h"
/**
* Method: AnafaceUI::GetType
* Purpose: Returns a String Representation of the object type
* Parameters: void
* Returns: TString - representation of the object type
*/
TString AnafaceUI::GetType()
{
return TString(L"AnafaceUI;") + TControl::GetType();
}
/*
* Method: AnaFaceUI::AnafaceUI
* Purpose: Constructor
* Parameters: TrecPointer<DrawingBoard> rt - the render target to use
* TrecPointer <TArray<styleTable>> ta - the styles for Anaface
* HWND win - the window handle to use
* Returns void
*/
AnafaceUI::AnafaceUI(TrecPointer<DrawingBoard>rt, TrecPointer <TArray<styleTable>> ta, HWND win):TControl(rt,ta), bar(rt, ta)
{
winHandle = win;
tabHeight = unknownTab = 0;
tabShow = 1;
tabHeight = 30;
}
/*
* Method: AnafaceUI::~AnafaceUI
* Purpose: Destructor
* Parameters: void
* Returns: void
*/
AnafaceUI::~AnafaceUI()
{
}
/**
* Method: AnafaceUI::TookTab
* Purpose: Allows TControls with Tab Bars to take in a tab
* Parameters: TrecPointer<Tab> tab - the tab to take
* Returns: bool - whether the tab was taken in
*/
bool AnafaceUI::TookTab(TrecPointer<Tab> tab)
{
ThreadLock();
if (bar.AddTab(tab))
return true;
for (UINT Rust = 0; Rust < bar.GetContentSize(); Rust++)
{
auto curTab = bar.GetCurrentTab();
if (curTab.Get() && curTab->GetContent().Get())
{
if (curTab->GetContent()->TookTab(tab))
{
ThreadRelease();
return true;
}
}
}
ThreadRelease();
return false;
}
/*
* Method: AnafaceUI::switchView
* Purpose: Switches the view towards the specified Content
* Parameters: UINT x - the index of the control to use
* Returns: bool - whether the operation is successful
*/
bool AnafaceUI::switchView(UINT x)
{
ThreadLock();
if (x < bar.GetContentSize())
{
try
{
auto tab = bar.GetTabAt(x);
currentContent = tab->GetContent();
ThreadRelease();
return true;
}
catch (...)
{
currentContent.Nullify();
}
}
ThreadRelease();
return false;
}
/**
* Method: AnafaceUI::SwitchChildControl
* Purpose: Allows a child control to insert another control between it and THIS control (usually a scroller control)
* Parameters: TrecPointerSoft<TControl> curControl - the Control making the call (used to help parent control identify which child to replace)
* TrecPointer<TControl> newControl - the Control to replace it with
* Returns: void
*/
void AnafaceUI::SwitchChildControl(TrecPointerSoft<TControl> curControl, TrecPointer<TControl> newControl)
{
ThreadLock();
for (UINT Rust = 0; Rust < bar.GetContentSize(); Rust++)
{
auto tab = bar.GetTabAt(Rust);
if (!tab.Get())
continue;
auto tabCont = tab->GetContent();
if (!tabCont.Get() || (tabCont->GetContentType() != TabContentType::tct_control))
continue;
TrecPointer<TControl> c = dynamic_cast<TabControlContent*>(tabCont.Get())->GetControl();
if (curControl.Get() == c.Get())
{
dynamic_cast<TabControlContent*>(tabCont.Get())->SetControl(newControl);
break;
}
}
ThreadRelease();
}
/*
* Method: AnafaceUI::OnRButtonUp
* Purpose: Allows Control to catch the RightmessageState::mouse button release event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*/
void AnafaceUI::OnRButtonUp(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
ThreadLock();
if (currentContent.Get())
currentContent->OnRButtonUp(nFlags, point, mOut, eventAr);
ThreadRelease();
}
/*
* Method: AnafaceUI::OnLButtonDown
* Purpose: Allows the AnafaceUI to catch when a tab is
* Parameters: UINT nFlags - flags provided by MFC
* CPoint point - the point of the click
* messageOutput * mOut - the result of the click (was it in the control?)
* TDataArray<EventID_Cred>& eventAr - events and their handlers documented by the control
* TDataArray<TControl*>& clickedControl - allows the control to report that this is a contestant for clicks
* Returns: void
*/
void AnafaceUI::OnLButtonDown(UINT nFlags, TPoint point, messageOutput * mOut, TDataArray<EventID_Cred>& eventAr, TDataArray<TControl*>& clickedControl)
{
ThreadLock();
if (isContained(point, location))
{
clickedControl.push_back(this);
bar.OnLButtonDown(nFlags, point, mOut, eventAr, clickedControl);
if (currentContent.Get())
currentContent->OnLButtonDown(nFlags, point, mOut, eventAr, clickedControl);
}
ThreadRelease();
}
/*
* Method: AnafaceUI::OnRButtonDown
* Purpose: Allows Control to catch the RightmessageState::mouse button down event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* TDataArray<TControl*>& clickedControls - list of controls that exprienced the on Button Down Event to alert when the button is released
* Returns: void
*/
void AnafaceUI::OnRButtonDown(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr, TDataArray<TControl*>& clickedButtons)
{
ThreadLock();
if (isContained(point, location))
{
if (currentContent.Get())
{
currentContent->OnRButtonDown(nFlags, point, mOut, eventAr, clickedButtons);
}
clickedButtons.push_back(this);
}
ThreadRelease();
}
/*
* Method: AnafaceUI::OnMouseMove
* Purpose: Allows Controls to catch themessageState::mouse Move event and deduce if the cursor has hovered over it
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* TDataArray<TControl*>& clickedControls - list of controls that exprienced the on Button Down Event to alert when the button is released
* Returns: void
*/
void AnafaceUI::OnMouseMove(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr, TDataArray<TControl*>& hoverControls)
{
ThreadLock();
if (isContained(point, location))
{
hoverControls.push_back(this);
bar.OnMouseMove(nFlags, point, mOut, eventAr, hoverControls);
if (currentContent.Get())
{
currentContent->OnMouseMove(nFlags, point, mOut, eventAr, hoverControls);
}
}
ThreadRelease();
}
/*
* Method: AnafaceUI::OnLButtonDblClk
* Purpose: Allows control to catch the DOuble Click event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*/
void AnafaceUI::OnLButtonDblClk(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
ThreadLock();
if (isContained(point, location))
{
bar.OnLButtonDblClk(nFlags, point, mOut, eventAr);
if (currentContent.Get())
currentContent->OnLButtonDblClk(nFlags, point, mOut, eventAr);
}
ThreadRelease();
}
/*
* Method: AnafaceUI::OnLButtonUp
* Purpose: Allows control to catch the Left Button Up event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*/
void AnafaceUI::OnLButtonUp(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
ThreadLock();
if (isContained(point, location))
{
bar.OnLButtonUp(nFlags, point, mOut, eventAr);
auto curTab = bar.GetCurrentTab();
if (curTab.Get())
currentContent = curTab->GetContent();
if (currentContent.Get())
currentContent->OnLButtonUp(nFlags, point, mOut, eventAr);
}
ThreadRelease();
}
/*
* Method: AnafaceUI::OnChar
* Purpose: Allows Controls to repond to character input
* Parameters: bool fromChar - can be called either from on Key Down or OnChar
* UINT nChar - The ID of the character that was pressed
* UINT nRepCnt - how many times the character was processed for this event
* UINT nFlags - flags provided by MFC's Message system, not used
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*/
bool AnafaceUI::OnChar(bool fromChar, UINT nChar, UINT nRepCnt, UINT nFlags, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
ThreadLock();
bool ret = currentContent.Get() ? currentContent->OnChar(fromChar, nChar, nRepCnt, nFlags, mOut, eventAr) : false;
ThreadRelease();
return ret;
}
/*
* Method: AnafaceUI::onCreate
* Purpose: Sets up the switching control with AnafaceUI specific attributes
* Parameters: RECT container - the location the control will be stored
* Returns: bool
*/
bool AnafaceUI::onCreate(D2D1_RECT_F container, TrecPointer<TWindowEngine> d3d)
{
ThreadLock();
windowEngine = d3d;
TControl::onCreate(container,d3d);
D2D1_RECT_F r;
TrecPointer<TString> valpoint = attributes.retrieveEntry(L"|TabsPresent");
if (valpoint.Get())
{
if (!valpoint->Compare(L"False"))
this->tabShow = 0;
else if (!valpoint->Compare(L"Bottom"))
this->tabShow = 2;
}
valpoint = attributes.retrieveEntry(TString(L"|TabHeight"));
if (valpoint.Get())
{
int v = 0;
if (!valpoint->ConvertToInt(v))
this->tabHeight = v;
}// End of valpoint if statement for "TabHeight" and code for creating tabs
D2D1_RECT_F tabsLoc = container;
switch (tabShow)
{
case 1:
container.top += tabHeight;
tabsLoc.bottom = container.top;
bar.onCreate(tabsLoc, d3d);
break;
case 2:
container.bottom -= tabHeight;
tabsLoc.top = container.bottom;
bar.onCreate(tabsLoc, d3d);
}
for (int c = 0; c < children.Count(); c++)
{
auto tc = children.ElementAt(c);
if (!tc.Get())
continue;
TrecSubPointer<TabContent, TabControlContent> controlCont = TrecPointerKey::GetNewTrecSubPointer<TabContent, TabControlContent>();
controlCont->SetControl(tc);
tc->onCreate(container, d3d);
TString tabText = tc->GetID();
if (!tabText.GetSize())
tabText.Format(L"Unknown %d", unknownTab++);
TrecPointer<Tab> tab = bar.AddTab(tabText);
TrecPointer<TabContent> cContent = TrecPointerKey::GetTrecPointerFromSub<TabContent, TabControlContent>(controlCont);
tab->SetContent(cContent);
if (!c)
currentContent = cContent;
}
ThreadRelease();
return false;
}
/*
* Method: AnafaceUI::addControl
* Purpose: Adds a new control to the list of child controls
* Parameters: TrecPointer<TControl> control - the control to add
* TString tabName - the name to give the tab
* Returns: int - the index of the control (-1 if failed)
*/
int AnafaceUI::addControl(TrecPointer<TabContent> control, TString tabName)
{
ThreadLock();
if (control.Get() && control->HasContent())
{
if (control->GetContentType() == TabContentType::tct_control)
{
auto newControl = dynamic_cast<TabControlContent*>(control.Get())->GetControl();
for (UINT c = 0; c < children.Count(); c++)
{
if (newControl.Get() == children.ElementAt(c).Get())
{
currentContent = control;
ThreadRelease();
return c;
}
}
children.Add(newControl);
newControl->setParent(GetParentReference());
}
control->Resize(CalculateClientSpace());
currentContent = control;
auto tab = bar.AddTab(tabName);
tab->SetContent(control);
int ret = bar.GetContentSize();;
ThreadRelease();
return ret;
}
ThreadRelease();
return -1;
}
/*
* Method: AnafaceUI::onDraw
* Purpose: Draws the control and any tabs present
* Parameters: void
* Returns: void
*/
void AnafaceUI::onDraw(TObject* obj)
{
ThreadLock();
//TControl::onDraw();
if (!isActive)
{
ThreadRelease();
return;
}
if (mState == messageState::mouseLClick)
{
if (content3.Get())
content3->onDraw(location);
else if (content1.Get())
content1->onDraw(location);
if (border3.Get())
border3->onDraw(location);
else if (border1.Get())
border1->onDraw(location);
if (text3.Get())
text3->onDraw(location, obj);
else if (text1.Get())
text1->onDraw(location, obj);
}
else if (mState == messageState::mouseHover)
{
if (content2.Get())
content2->onDraw(location);
else if (content1.Get())
content1->onDraw(location);
if (border2.Get())
border2->onDraw(location);
else if (border1.Get())
border1->onDraw(location);
if (text2.Get())
text2->onDraw(location, obj);
else if (text1.Get())
text1->onDraw(location, obj);
}
else
{
if (content1.Get())
content1->onDraw(location);
if (border1.Get())
border1->onDraw(location);
if (text1.Get())
text1->onDraw(location, obj);
}
/*
if (vScroll)
vScroll->updateDraw();
if (hScroll)
hScroll->updateDraw();
*/
if (tabShow)
bar.onDraw(obj);
if (currentContent.Get())
currentContent->Draw(obj);
ThreadRelease();
}
/*
* Method: AnafaceUI::GetChildAt
* Purpose: Retrieves the child control at the given location
* Parameters: UINT c - the index of the control to look for
* Returns: TrecPointer<TControl> - the control at the given index
*/
TrecPointer<TControl> AnafaceUI::GetChildAt(UINT c)
{
ThreadLock();
auto ret = (c < children.Count()) ? children.ElementAt(c) : TrecPointer<TControl>();
ThreadRelease();
return ret;
}
/*
* Method: AnafaceUI::GetCurrentChild
* Purpose: Retrieves the currently active body control
* Parameters: void
* Returns: TrecPointer<TControl> - the current control active
*/
TrecPointer<TabContent> AnafaceUI::GetCurrentChild()
{
ThreadLock();
auto ret = currentContent;
ThreadRelease();
return ret;
}
/*
* Method: AnafaceUI::GetAnaGameType
* Purpose: Enables system to report whether the object is in fact an AnafaceUI
* Parameters: void
* Returns: UCHAR* - the AnaGame representation of the AnafaceUI
*/
UCHAR * AnafaceUI::GetAnaGameType()
{
return nullptr;
}
/*
* Method: AnafaceUI::GetControlArea
* Purpose: Retrieves the location of the main body control (tabs might reduce the actual size)
* Parameters: void
* Returns: RECT - the location of the main body area
*/
D2D1_RECT_F AnafaceUI::GetControlArea()
{
D2D1_RECT_F returnable = location;
returnable.top += tabHeight;
return returnable;
}
/**
* Method: AnafaceUI::Resize
* Purpose: Resizes the control upon the window being resized
* Parameters: D2D1_RECT_F& r - the new location for the control
* Returns: void
*/
void AnafaceUI::Resize(D2D1_RECT_F& r)
{
TControl::Resize(r);
auto clientRect = CalculateClientSpace();
for (UINT Rust = 0; Rust < bar.GetContentSize(); Rust++)
{
auto tab = bar.GetTabAt(Rust);
if (tab.Get() && tab->GetContent().Get())
tab->GetContent()->Resize(clientRect);
}
updateComponentLocation();
}
D2D1_RECT_F AnafaceUI::CalculateClientSpace()
{
auto ret = location;
switch (tabShow)
{
case 1:
ret.top += tabHeight;
break;
case 2:
ret.bottom -= tabHeight;
}
return ret;
}
/**
* Method: TabControlContent::TabControlContent
* Purpose: Default Constructor
* Parameters: void
* Returns: new TabContent object
*/
TabControlContent::TabControlContent()
{
}
/**
* Method: TabControlContent::~TabControlContent
* Purpose: Destructor
* Parameters: void
* Returns: void
*/
TabControlContent::~TabControlContent()
{
}
/**
* Method: TabControlContent::Resize
* Purpose: Calls Resize on the underlying content object
* Parameters: const D2D1_RECT_F& loc - the new location the content is expected to occupy
* Returns: void
*
* Attributes: override
*/
void TabControlContent::Resize(const D2D1_RECT_F& loc)
{
auto tLoc = loc;
if (control.Get())
control->Resize(tLoc);
}
/**
* Method: TabControlContent::GetContentType
* Purpose: Returns the Content Type, allowing users of this object to cast it into the right sub-type and take it from there
* Parameters: void
* Returns: TabContentType - the type of content this is expected to yield
*
* Attributes: override
*/
TabContentType TabControlContent::GetContentType()
{
return TabContentType::tct_control;
}
bool TabControlContent::TookTab(TrecPointer<Tab> tab)
{
if(!tab.Get() || !this->control.Get())
return false;
return control->TookTab(tab);
}
/*
* Method: TabControlContent::OnRButtonUp
* Purpose: Allows Control to catch the RightmessageState::mouse button release event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*
* Attributes: override; message
*/
void TabControlContent::OnRButtonUp(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
if (control.Get())
control->OnRButtonUp(nFlags, point, mOut, eventAr);
}
/*
* Method: TabControlContent::OnLButtonDown
* Purpose: Allows Control to catch the LeftmessageState::mouse Button Down event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* TDataArray<TControl*>& clickedControls - list of controls that exprienced the on Button Down Event to alert when the button is released
* Returns: void
*
* Attributes: override; message
*/
void TabControlContent::OnLButtonDown(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr, TDataArray<TControl*>& clickedButtons)
{
if (control.Get())
control->OnLButtonDown(nFlags, point, mOut, eventAr, clickedButtons);
}
/*
* Method: TabControlContent::OnRButtonDown
* Purpose: Allows Control to catch the RightmessageState::mouse button down event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* TDataArray<TControl*>& clickedControls - list of controls that exprienced the on Button Down Event to alert when the button is released
* Returns: void
*
* Attributes: override; message
*/
void TabControlContent::OnRButtonDown(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr, TDataArray<TControl*>& clickedControls)
{
if (control.Get())
control->OnRButtonDown(nFlags, point, mOut, eventAr, clickedControls);
}
/*
* Method: TabControlContent::OnMouseMove
* Purpose: Allows Controls to catch themessageState::mouse Move event and deduce if the cursor has hovered over it
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* TDataArray<TControl*>& clickedControls - list of controls that exprienced the on Button Down Event to alert when the button is released
* Returns: void
*
* Attributes: override; message
*/
void TabControlContent::OnMouseMove(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr, TDataArray<TControl*>& hoverControls)
{
if (control.Get())
control->OnMouseMove(nFlags, point, mOut, eventAr, hoverControls);
}
/**
* Method: TabControlContent::OnMouseLeave
* Purpose: Allows Controls to catch themessageState::mouse Move event and deduce if the cursor has hovered over it
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* TDataArray<TControl*>& clickedControls - list of controls that exprienced the on Button Down Event to alert when the button is released
* Returns: bool - whether the leave occured
*
* Attributes: override; message
*/
bool TabControlContent::OnMouseLeave(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
if (control.Get())
return control->OnMouseLeave(nFlags, point, mOut, eventAr);
return false;
}
/**
* Method: TabControlContent::OnLButtonDblClk
* Purpose: Allows control to catch the DOuble Click event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*
* Attributes: override; message
*/
void TabControlContent::OnLButtonDblClk(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
if (control.Get())
control->OnLButtonDblClk(nFlags, point, mOut, eventAr);
}
/*
* Method: TabControlContent::OnLButtonUp
* Purpose: Allows control to catch the Left Button Up event and act accordingly
* Parameters: UINT nFlags - flags provided by MFC's Message system, not used
* TPoint point - the point on screen where the event occured
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*
* Attributes: override; message
*/
void TabControlContent::OnLButtonUp(UINT nFlags, TPoint point, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
if (control.Get())
control->OnLButtonUp(nFlags, point, mOut, eventAr);
}
/*
* Method: TabControlContent::OnChar
* Purpose: Allows Controls to repond to character input
* Parameters: bool fromChar - can be called either from on Key Down or OnChar
* UINT nChar - The ID of the character that was pressed
* UINT nRepCnt - how many times the character was processed for this event
* UINT nFlags - flags provided by MFC's Message system, not used
* messageOutput* mOut - allows controls to keep track of whether ohter controls have caught the event
* TDataArray<EventID_Cred>& eventAr - allows Controls to add whatever Event Handler they have been assigned
* Returns: void
*
* Attributes: override; message
*/
bool TabControlContent::OnChar(bool fromChar, UINT nChar, UINT nRepCnt, UINT nFlags, messageOutput* mOut, TDataArray<EventID_Cred>& eventAr)
{
if (control.Get())
control->OnChar(fromChar, nChar, nRepCnt, nFlags, mOut, eventAr);
return false;
}
/**
* Method: TabControlContent::SetControl
* Purpose: Sets up the Control to hold
* Parameters: TrecPointer<TControl> control - the control to hold
* Returns: void
*/
void TabControlContent::SetControl(TrecPointer<TControl> control)
{
this->control = control;
}
/**
* Method: TabControlContent:GetControl
* Purpose: Retrieves the underlying Control
* Parameters: void
* Returns: TrecPointer<TControl> - the control this object holds
*/
TrecPointer<TControl> TabControlContent::GetControl()
{
return control;
}
bool TabControlContent::HasContent()
{
return control.Get() != nullptr;
}
void TabControlContent::Draw(TObject* obj)
{
if (control.Get())
control->onDraw(obj);
}
| [
"jljacko@outlook.com"
] | jljacko@outlook.com |
e475bbfbf202d5c5ecf5e5cb1baff149918715d8 | 0057005bb64e68fe58c5ca0e40e7112bd23badef | /Sim_path_tracking/src/main_lane.cpp | 81c4d95530a8fcfa79b53d495d3e466d57e09f18 | [] | no_license | jiohLee/selfcar_2020_ws | e4b3c68d16c978499dc2ec55800384ddb94d0663 | 0cb2044edb20d65b72f7560a2c6d22d51b95640d | refs/heads/master | 2023-03-06T16:02:19.431646 | 2021-02-23T04:45:27 | 2021-02-23T04:45:27 | 341,431,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,834 | cpp | #include "Sim_path_tracking_only_lane.cpp"
#include <ros/ros.h>
#include <sensor_msgs/PointCloud.h>
#include <nav_msgs/Odometry.h>
#include <nav_msgs/Path.h>
#include <tf/transform_broadcaster.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main(int argc, char **argv)
{
ros::init(argc, argv, "Sim_path_tracking");
ros::NodeHandle node_("~");
PurePursuit controller;
ros::AsyncSpinner spinner(2); // Use multi threads
spinner.start();
ros::waitForShutdown();
return 0;
/*
while(ros::ok())
{
try
{
tf_listener.transformPose("novatel", ros::Time(0) , map_path_pose, "map" ,odom_path_pose);
}
catch(tf::TransformException &ex)
{
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
}
}
*/
// ros::Subscriber sim_sub = node_.subscribe("/sim_test/VehicleTlm", 1, sim_callback); //vel, heading sub
// ros::Subscriber gps_sub = node_.subscribe("/gps_utm_odom", 1, gps_callback);
// ros::Subscriber local_path = node_.subscribe("/Local_path", 1,local_path_callback); // waypoint sub
// ros::Publisher sim_pub = node_.advertise<sim_test::VehicleCmd>("/sim_test/VehicleCmd", 1); //control pub
// sim_test::VehicleCmd sim_cmd;
// sim_cmd.accel_cmd=1; // 0~4
// sim_cmd.steer_cmd=0; //-450 ~450
// node_.getParam("/Sim_global_path/sim", Simulator_mode); //get param
// ros::Rate loop_rate(50);
/*
while(ros::ok())
{
if(Simulator_mode==1)
{
sim_pub.publish(sim_cmd);
}
else
{
}
ros::spinOnce();
loop_rate.sleep();
}
return 0;
*/
}
| [
"jiosiro@gmail.com"
] | jiosiro@gmail.com |
4750b2a93535c73f39ec57e02c7e6f4b28b42f7a | dda0ba3c3a78cb4f8aae81de498a4cf511bce2eb | /WannaTry/EZCrypt/EZHybrid.h | 61e33f08c64d2c713161b04b3c9c57dbc100f4ae | [] | no_license | symanli/MP21930_Example | d26e4f70239ad440f67c77e22e43f832282bbe12 | 947e52117b76c9544fa6ca09a5e16d8bba46b06d | refs/heads/master | 2023-03-15T11:46:05.322067 | 2020-02-14T13:25:26 | 2020-02-14T13:25:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | h | #pragma once
#include "EZRSA.h"
#include "EZAES.h"
#define EZH_SRCBUFFERSIZE 0x10000
#define EZH_IOBUFFERSIZE 0x100000
#define EZH_SUFFIX_CIPHER _T(".WNCRY")
#define EZH_SUFFIX_TEMP _T(".WNCRYT")
#define EZH_MAGIC "WANACRY!"
#define EZH_ENCRYPT 4
class EZHybrid
{
PEZRSA m_pEncRSA;
PEZRSA m_pDecRSA;
PUCHAR m_InBuffer;
PUCHAR m_OutBuffer;
public:
EZHybrid();
~EZHybrid();
BOOL GenKey();
BOOL ImportPublicKey(PUCHAR, ULONG);
BOOL ImportPrivateKey(PUCHAR, ULONG);
BOOL ImportPublicKey(LPCTSTR);
BOOL ImportPrivateKey(LPCTSTR);
BOOL Encrypt(LPCTSTR);
BOOL Decrypt(LPCTSTR);
};
typedef EZHybrid* PEZHybrid; | [
"49492695+jtlai0921@users.noreply.github.com"
] | 49492695+jtlai0921@users.noreply.github.com |
427bf154b46ad1f04a600eafa4e04db5adf0e2a5 | 00ba6a9f14906a73fe1921c17c39f541492783a8 | /yblib/include/ybSD_Semi.hh | 70119c5f93fd0915a6a628c5af60d2daaee0c93a | [] | no_license | yiyuqianyuan/geant4 | f2fa81ce7f332962c24abe31ab07fef2e6b7e9ae | d10d3d1d02ca760826fb0f1c4d26958c58416764 | refs/heads/master | 2021-01-21T06:39:36.369234 | 2017-02-27T06:45:41 | 2017-02-27T06:45:41 | 83,268,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,436 | hh | #ifndef ybSD_Semi_H
#define ybSD_Semi_H 1
//===================C++==================//
#include <stdio.h>
#include <cmath>
//=================GEANT4=================//
#include "globals.hh"
#include "G4EventManager.hh"
#include "G4VSensitiveDetector.hh"
#include "G4HCofThisEvent.hh"
#include "G4SystemOfUnits.hh"
#include "G4Step.hh"
#include "G4ThreeVector.hh"
#include "G4SDManager.hh"
#include "G4ios.hh"
#include "G4Track.hh"
#include "G4TransportationManager.hh"
#include "G4Navigator.hh"
#include "Randomize.hh"
//===================yb===================//
#include "G4DigiManager.hh"
#include "ybDataHit.hh"
#include "ybDataDigi.hh"
#include "ybDM_Amplifier.hh"
class ybSD_Semi : public G4VSensitiveDetector
{
public:
enum Geometry{kGeoBox,kGeoTube};
enum ResoType{kNull,kReso,kNoise};
public:
ybSD_Semi(G4String name,int numx,G4double widx,int numy,G4double widy);
ybSD_Semi(G4String name,G4double rin,G4double rout, G4double angle, int cirnum, int linenum);
~ybSD_Semi();
inline void SetResolution(double reso) {fResolutionType=kReso;fResolution=reso;};
inline void SetResolution(double fano,G4double gap,G4double noise)
{fResolutionType=kNoise;fFano=fano;fEnergyGap=gap;fNoise=noise;};
inline void SetTimeGate(G4double time) {fTimeGate=time;}
inline void SetTimeInterval(G4double time) {fTimeInterval=time;}
inline void SetThreshold(G4double energy) {fThreshold=energy;}
void Initialize(G4HCofThisEvent*);
G4bool ProcessHits(G4Step*, G4TouchableHistory*);
void EndOfEvent(G4HCofThisEvent*);
private:
void CreatSignal();
G4double MinTime();
void OutputHitsData();
void OutputDigiData();
private:
enum Geometry fShape;
enum ResoType fResolutionType;
//for Box
int fNum_X;
int fNum_Y;
G4double fWidth_X;
G4double fWidth_Y;
//for Tube
G4double fRin;
G4double fRout;
G4double fAngle;
int fCirnum;
int fLinenum;
int fTotNum;
int fHCID;
int fDCID;
G4double fTimeInterval;
G4double fTimeGate;
G4double fThreshold;
double fResolution;
double fFano;
G4double fEnergyGap;
double fNoise;
G4double fDeltaE;
G4double fGlobaltime;
ybDM_Amplifier *pDM_Amplifier;
G4String fDMname;
G4String fDCname;
typedef multimap<G4double,G4double,less<G4double> > ybSignalMap;
ybSignalMap *fHitsMap;
ybSignalMap *fOutputMap;
G4DigiManager *pDigiMan;
ybDataHitsCollection* pHitsCollection;
ybDataDigiCollection* pDigiCollection;
ybDataHit *pNewHit;
ybDataDigi *pNewDigi;
};
#endif
| [
"yb@hep.pku.edu.cn"
] | yb@hep.pku.edu.cn |
8c93bfa2b338fc0b4a04453c799ee106beb456c1 | 613a0d6d32522f8b5118fb7cfcd8a541bdc32db0 | /BinaryToDecimal/arrayStackType.h | 46a76a8a422b73c92a7315bc4270708a88bcaec5 | [] | no_license | UpToEleven1102/BinaryToDecimal | 1f51745cc1037f0bc344b9c6c3906e3d1e8b45c1 | 8f44024d483b1745cb3340cab124f06f745b891c | refs/heads/master | 2021-07-14T14:11:00.676183 | 2017-10-18T14:59:18 | 2017-10-18T14:59:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,220 | h | #pragma once
#ifndef H_StackType
#define H_StackType
#include <iostream>
#include <cassert>
using namespace std;
const int MAX_STACK_SIZE = 10;
template <class Type>
class arrayStackType : public StackADT<Type> {
public:
//constructor
arrayStackType();
arrayStackType(const arrayStackType<Type>& otherStack);
~arrayStackType();
void initializeStack();
void resetStack();
void push(const Type& newItem);
void pop();
Type top() const;
bool isEmptyStack() const;
bool isFullStack() const;
//const arrayStackType<Type> &operator= (const ArrayStackType<Type>& otherStack);
protected:
Type *list;
int stackTop;
private:
void copyStack(const arrayStackType<Type>& otherStack);
};
template<class Type>
void arrayStackType<Type>::initializeStack() {
stackTop = 0;
}
template <class Type>
arrayStackType<Type>::arrayStackType()
{
list = new Type[MAX_STACK_SIZE];
stackTop = 0;
}
template <class Type>
arrayStackType<Type>::arrayStackType(const arrayStackType<Type>& otherStack)
{
list = new Type[MAX_STACK_SIZE];
copyStack(otherStack);
}
template <class Type>
void arrayStackType<Type>::copyStack(const arrayStackType<Type>& otherStack)
{
stackTop = otherStack.stackTop;
for (int i = 0; i < stackTop; i++)
list[i] = otherStack.list[i];
}
template <class Type>
bool arrayStackType<Type>::isEmptyStack() const {
return (stackTop == 0);
}
template <class Type>
bool arrayStackType<Type> ::isFullStack() const {
return (stackTop == MAX_STACK_SIZE);
}
template <class Type>
void arrayStackType<Type>::push(const Type& newItem) {
if (!isFullStack()) {
list[stackTop] = newItem;
stackTop++;
}
else
cout << "The stack is full" << endl;
}
template <class Type>
void arrayStackType<Type>::pop() {
if (!isEmptyStack())
{
stackTop--;
}
else
{
cout << "The stack is empty" << endl;
}
}
template <class Type>
Type arrayStackType<Type>::top() const {
if (!isEmptyStack())
return list[stackTop - 1];
else
{
cout << "Error: The stack is empty" << endl;
exit(EXIT_FAILURE);
}
}
template <class Type>
void arrayStackType<Type>::resetStack() {
stackTop = 0;
}
template <class Type>
arrayStackType<Type>::~arrayStackType() {
delete[] list;
}
#endif // !H_StackType
| [
"quyhuyen.vu@hotmail.com"
] | quyhuyen.vu@hotmail.com |
f275479380ee01222f6497825fd19f142133953b | 6247adecabef0b770697716900ebb0b2b4468a98 | /src/jnc_ct/jnc_ct_TypeMgr/jnc_ct_ArrayType.cpp | 649f425fcc5f09e20cf1efc939db11dec3222c58 | [
"MIT"
] | permissive | Watch-Later/jancy | d6dbdcb2d8c8abeed95b25df8e9a7048fc27ea53 | df693ef8072aeb4280d771a7d146041978ffce1f | refs/heads/master | 2023-08-16T04:00:49.345491 | 2021-10-19T02:24:39 | 2021-10-19T06:40:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,586 | cpp | //..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_ArrayType.h"
#include "jnc_ct_Module.h"
#include "jnc_rt_GcHeap.h"
namespace jnc {
namespace ct {
//..............................................................................
ArrayType::ArrayType() {
m_typeKind = TypeKind_Array;
m_flags = TypeFlag_StructRet;
m_elementType = NULL;
m_rootType = NULL;
m_elementCount = -1;
m_getDynamicSizeFunction = NULL;
m_parentUnit = NULL;
m_parentNamespace = NULL;
}
Type*
ArrayType::getRootType() {
if (!m_rootType)
m_rootType = m_elementType->getTypeKind() == TypeKind_Array ?
((ArrayType*)m_elementType)->getRootType() :
m_elementType;
return m_rootType;
}
void
ArrayType::prepareTypeString() {
TypeStringTuple* tuple = getTypeStringTuple();
tuple->m_typeStringPrefix = getRootType()->getTypeString();
tuple->m_typeStringSuffix = createDimensionString();
}
void
ArrayType::prepareDoxyLinkedText() {
TypeStringTuple* tuple = getTypeStringTuple();
tuple->m_doxyLinkedTextPrefix = getRootType()->getDoxyLinkedTextPrefix();
tuple->m_doxyLinkedTextSuffix = createDimensionString();
}
sl::String
ArrayType::createDimensionString() {
sl::String string;
if (m_elementCount == -1)
string = "[]";
else
string.format("[%d]", m_elementCount);
Type* elementType = m_elementType;
while (elementType->getTypeKind() == TypeKind_Array) {
ArrayType* arrayType = (ArrayType*)elementType;
string.appendFormat(" [%d]", arrayType->m_elementCount);
elementType = arrayType->m_elementType;
}
return string;
}
bool
ArrayType::ensureDynamicLayout(
StructType* dynamicStruct,
Field* dynamicField
) {
bool result;
if (m_flags & ModuleItemFlag_LayoutReady)
return true;
result = calcLayoutImpl(dynamicStruct, dynamicField);
if (!result)
return false;
m_flags |= ModuleItemFlag_LayoutReady;
return true;
}
bool
ArrayType::calcLayoutImpl(
StructType* dynamicStruct,
Field* dynamicField
) {
bool result = m_elementType->ensureLayout();
if (!result)
return false;
if (m_elementType->getTypeKind() == TypeKind_Class ||
m_elementType->getFlags() & TypeFlag_Dynamic) {
err::setFormatStringError("'%s' cannot be an element of an array", m_elementType->getTypeString().sz());
return false;
}
// ensure update
m_rootType = NULL;
if (m_typeStringTuple) {
AXL_MEM_DELETE(m_typeStringTuple);
m_typeStringTuple = NULL;
}
uint_t rootTypeFlags = getRootType()->getFlags();
if (rootTypeFlags & TypeFlag_Pod)
m_flags |= TypeFlag_Pod;
else if (rootTypeFlags & TypeFlag_GcRoot)
m_flags |= TypeFlag_GcRoot;
m_alignment = m_elementType->getAlignment();
// calculate size
if (!m_elementCountInitializer.isEmpty()) {
ASSERT(m_parentUnit && m_parentNamespace);
Unit* prevUnit = m_module->m_unitMgr.setCurrentUnit(m_parentUnit);
m_module->m_namespaceMgr.openNamespace(m_parentNamespace);
int64_t value = 0;
if (!dynamicStruct) {
result = m_module->m_operatorMgr.parseConstIntegerExpression(m_elementCountInitializer, &value);
m_module->m_namespaceMgr.closeNamespace();
m_module->m_unitMgr.setCurrentUnit(prevUnit);
if (!result)
return false;
} else {
// try parsing it as a const-integer expression first...
m_module->enterTryCompile();
result = m_module->m_operatorMgr.parseConstIntegerExpression(m_elementCountInitializer, &value);
m_module->leaveTryCompile();
m_module->m_namespaceMgr.closeNamespace();
m_module->m_unitMgr.setCurrentUnit(prevUnit);
if (!result) { // nope, create a runtime function...
sl::String qualifiedName = sl::formatString(
"%s.%s.getDynamicSize",
dynamicStruct->getQualifiedName().sz(),
dynamicField->getName().sz()
);
Type* returnType = m_module->m_typeMgr.getPrimitiveType(TypeKind_SizeT);
FunctionType* type = m_module->m_typeMgr.getFunctionType(returnType, NULL, 0);
m_getDynamicSizeFunction = m_module->m_functionMgr.createInternalFunction<GetDynamicSizeFunction>(
qualifiedName,
type
);
m_getDynamicSizeFunction->m_arrayType = this;
m_getDynamicSizeFunction->m_storageKind = StorageKind_Member;
m_getDynamicSizeFunction->convertToMemberMethod(dynamicStruct);
m_module->markForCompile(m_getDynamicSizeFunction);
m_flags |= TypeFlag_Dynamic;
m_elementCount = 0;
m_size = 0;
return true;
}
}
if (value <= 0) {
err::setFormatStringError("invalid array size '%lld'\n", value);
lex::pushSrcPosError(
m_parentUnit->getFilePath(),
m_elementCountInitializer.getHead()->m_pos
);
return false;
}
#if (JNC_PTR_SIZE == 4)
if (value >= (uint32_t) -1) {
err::setFormatStringError("array size '%lld' is too big\n", value);
lex::pushSrcPosError(
m_parentUnit->getFilePath(),
m_elementCountInitializer.getHead()->m_pos
);
return false;
}
#endif
m_elementCount = (size_t)value;
}
m_size = m_elementType->getSize() * m_elementCount;
if (m_size > TypeSizeLimit_StackAllocSize)
m_flags |= TypeFlag_NoStack;
return true;
}
sl::String
ArrayType::getValueString(
const void* p0,
const char* formatSpec
) {
if (m_flags & TypeFlag_Dynamic) {
AXL_TODO("format dynamic arrays")
return "{ dynamic-array }";
}
const char* p = (char*)p0;
if (m_elementType->getTypeKind() == TypeKind_Char) {
const char* null = (const char*)memchr(p, 0, m_elementCount);
sl::String string(p, null ? null - p : m_elementCount);
return formatSpec ? sl::formatString(formatSpec, string.sz()) : string;
}
if (!m_elementCount)
return "{}";
sl::String string = "{ " + m_elementType->getValueString(p);
for (size_t i = 1; i < m_elementCount; i++) {
p += m_elementType->getSize();
string += ", ";
string += m_elementType->getValueString(p, formatSpec);
}
string += " }";
return string;
}
void
ArrayType::markGcRoots(
const void* p,
rt::GcHeap* gcHeap
) {
ASSERT(m_flags & TypeFlag_GcRoot);
gcHeap->addRootArray(p, m_elementType, m_elementCount);
}
void
ArrayType::prepareLlvmDiType() {
m_llvmDiType = m_module->m_llvmDiBuilder.createArrayType(this);
}
bool
ArrayType::compileGetDynamicSizeFunction(Function* function) {
ASSERT(function == m_getDynamicSizeFunction);
bool result;
Unit* parentUnit = function->getParentUnit();
if (parentUnit)
m_module->m_unitMgr.setCurrentUnit(parentUnit);
m_module->m_namespaceMgr.openNamespace(function->getParentNamespace());
m_module->m_functionMgr.internalPrologue(function);
m_module->m_functionMgr.createThisValue();
Value resultValue;
result = m_module->m_operatorMgr.parseExpression(m_elementCountInitializer, &resultValue);
if (!result)
return false;
size_t size = m_elementType->getSize();
if (size != 1) {
Value sizeValue(size, m_module->m_typeMgr.getPrimitiveType(TypeKind_SizeT));
result = m_module->m_operatorMgr.binaryOperator(
BinOpKind_Mul,
&resultValue,
sizeValue
);
if (!result)
return false;
}
result = m_module->m_controlFlowMgr.ret(resultValue);
if (!result)
return false;
m_module->m_functionMgr.internalEpilogue();
m_module->m_namespaceMgr.closeNamespace();
return true;
}
//..............................................................................
} // namespace ct
} // namespace jnc
| [
"vovkos@gmail.com"
] | vovkos@gmail.com |
f34828d1d358fc042975632ab33905ece6b3f000 | e7f77b94ffcd3b5476f04ba012bcc68f0cd29191 | /Result.h | 191dd2523e1cc936af3107c2c2c5dfbad11e5c00 | [] | no_license | RathanakSreang/APongGame | a475dcd54419a9a2f69316b612e8b965d992007a | 7295c45edcd48745a99cc3b399109be9c738c464 | refs/heads/master | 2021-01-23T05:04:13.455768 | 2017-03-27T00:01:37 | 2017-03-27T00:01:37 | 86,273,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,511 | h | #ifndef RESULT_H
#define RESULT_H
#include"Money.h"
class Result
{
private:
int Num1[15];
bool all;
bool take,Ret,win;
int sce;
int ReX,ReY;
int first;
int RexFin,ReyFin;
bool skipdo;
//int over;
public:
void SetSce(int c){sce=c;}
int GetSce(){return sce;}
Result(){
all=false;
sce=0;
ReX=0;ReY=0;
first=0;
//over=0;
RexFin=0;ReyFin=0;
skipdo=false;
take=false;Ret=false;win=false;
for(int i=0;i<15;i++)
Num1[i]=0;}
bool GetAll(){return all;}
void SetAll(bool a){all=a;}
bool ShowResult(Money obj[],int Num,Apong Ap);
bool ReturnMoney(Money obj[],int Num,Apong Ap);
bool TakeMoney(Money obj[],int Num,Apong Ap);
bool WinMoney(Money obj[],int Num,Apong Ap);
void PlaceRecieve(int n,Money obj[],Apong Ap);
void GiveMoney(int xG,int yG,int xR,int yR,Money obj[],Apong Ap);
};
bool Result::ShowResult(Money obj[],int Num,Apong Ap)
{
if(TakeMoney(obj,Num,Ap))
{
take=true;
}
if(take==true)
if(ReturnMoney(obj,Num,Ap))
{
Ret=true;
}
if(Ret==true)
{
if(WinMoney(obj,Num,Ap))
{
win=true;
}
}
if(win==true)
{
take=false;
Ret=false;
win=false;
sce=0;
return true;
}
return false;
}
void Result::GiveMoney(int xG,int yG,int xR,int yR,Money obj[],Apong Ap)
{int i=0,j=0,st=0;
int x,y;
x=xG;y=yG;
for(;;)
{
if(xR<xG)
{x=x-15;
if(x<=xR){i=3;x=xR;}
}
else if(xR>xG)
{x=x+15;
if(x>=xR){i=3;x=xR;}
}
if(yR<yG)
{y=y-10;
if(y<=yR){j=3;y=yR;}
}
else if(yR>yG)
{y=y+10;
if(y>=yR){j=3;y=yR;}
}
if(i==3&&j==3)break;
Refresh(obj,Ap);
if((x>154&&x<638)&&(y>251&&y<480))
{
if((xR==XMoney1||xR==XMoney2||xR==XMoney3||xR==XMoney4||xR==XMoney8||xR==XMoney9)&&(yR==YMoney1234||yR==YMoney89))
set_display(x,y,pic1,screen,&threeMon[KindMon(Money::kind,Money::MonType)]);
else
set_display(x,y,pic3,screen,&twoMon[KindMon(Money::kind,Money::MonType)]);
}
else set_display(x,y,pic2,screen,&oneMon[KindMon(Money::kind,Money::MonType)]);
SDL_Flip( screen );
// SDL_Delay(5);
}
}
void Result::PlaceRecieve(int n,Money obj[],Apong Ap)
{
if(n==1)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney1,YMoney1234,obj,Ap);//computer to 1
else if(n==2)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney2,YMoney1234,obj,Ap);//computer to 2
else if(n==3)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney3,YMoney1234,obj,Ap);//computer to 3
else if(n==4)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney4,YMoney1234,obj,Ap);//computer to 4
else if(n==5)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney5,YMoney567,obj,Ap);//computer to 5
else if(n==6)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney6,YMoney567,obj,Ap);//computer to 6
else if(n==7)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney7,YMoney567,obj,Ap);//computer to 7
else if(n==8)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney8,YMoney89,obj,Ap);//computer to 8
else if(n==9)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney9,YMoney89,obj,Ap);//computer to 9
else if(n==10)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney10,YMoney101112,obj,Ap);//computer to 10
else if(n==11)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney11,YMoney101112,obj,Ap);//computer to 11
else if(n==12)GiveMoney(XMoneyComputer,YMoneyComputer,XMoney12,YMoney101112,obj,Ap);//computer to 12
else if(n==13)GiveMoney(XMoney1,YMoney1234,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==14)GiveMoney(XMoney2,YMoney1234,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==15)GiveMoney(XMoney3,YMoney1234,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==16)GiveMoney(XMoney4,YMoney1234,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==17)GiveMoney(XMoney5,YMoney567,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==18)GiveMoney(XMoney6,YMoney567,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==19)GiveMoney(XMoney7,YMoney567,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==20)GiveMoney(XMoney8,YMoney89,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==21)GiveMoney(XMoney9,YMoney89,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==22)GiveMoney(XMoney10,YMoney101112,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==23)GiveMoney(XMoney11,YMoney101112,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==24)GiveMoney(XMoney12,YMoney101112,XMoneyComputer,YMoneyComputer,obj,Ap);
else if(n==25)GiveMoney(XMoney1,YMoney1234,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==26)GiveMoney(XMoney2,YMoney1234,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==27)GiveMoney(XMoney3,YMoney1234,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==28)GiveMoney(XMoney4,YMoney1234,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==29)GiveMoney(XMoney5,YMoney567,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==30)GiveMoney(XMoney6,YMoney567,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==31)GiveMoney(XMoney7,YMoney567,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==32)GiveMoney(XMoney8,YMoney89,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==33)GiveMoney(XMoney9,YMoney89,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==34)GiveMoney(XMoney10,YMoney101112,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==35)GiveMoney(XMoney11,YMoney101112,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==36)GiveMoney(XMoney12,YMoney101112,XMoneyPlay1,YMoneyPlay12,obj,Ap);
else if(n==37)GiveMoney(XMoney1,YMoney1234,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==38)GiveMoney(XMoney2,YMoney1234,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==39)GiveMoney(XMoney3,YMoney1234,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==40)GiveMoney(XMoney4,YMoney1234,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==41)GiveMoney(XMoney5,YMoney567,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==42)GiveMoney(XMoney6,YMoney567,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==43)GiveMoney(XMoney7,YMoney567,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==44)GiveMoney(XMoney8,YMoney89,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==45)GiveMoney(XMoney9,YMoney89,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==46)GiveMoney(XMoney10,YMoney101112,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==47)GiveMoney(XMoney11,YMoney101112,XMoneyPlay2,YMoneyPlay12,obj,Ap);
else if(n==48)GiveMoney(XMoney12,YMoney101112,XMoneyPlay2,YMoneyPlay12,obj,Ap);
}
bool Result::ReturnMoney(Money obj[],int Num,Apong Ap)
{int i,tem;
if(sce==0)
{ if(obj[11].GetMon()>=Money::kind)
Num1[11]=obj[11].GetMon()+obj[11].GetMon();
if(obj[12].GetMon()>=Money::kind)
Num1[12]=obj[12].GetMon()+obj[12].GetMon()*4;
if(obj[13].GetMon()>=Money::kind)
Num1[13]=obj[13].GetMon()+obj[13].GetMon()*2;
if(obj[3].GetMon()>=Money::kind)
Num1[3]=obj[3].GetMon()+obj[3].GetMon()*4;
if(obj[7].GetMon()>=Money::kind)
Num1[7]=obj[7].GetMon()+obj[7].GetMon()*2;
if(obj[4].GetMon()>=Money::kind)
Num1[4]=obj[4].GetMon()+obj[4].GetMon()*4;
if(obj[8].GetMon()>=Money::kind)
Num1[8]=obj[8].GetMon()+obj[8].GetMon()*2;
if(obj[10].GetMon()>=Money::kind)
Num1[10]=obj[10].GetMon()+obj[10].GetMon();
if(obj[5].GetMon()>=Money::kind)
Num1[5]=obj[5].GetMon()+obj[5].GetMon()*4;
if(obj[9].GetMon()>=Money::kind)
Num1[9]=obj[9].GetMon()+obj[9].GetMon()*2;
if(obj[6].GetMon()>=Money::kind)
Num1[6]=obj[6].GetMon()+obj[6].GetMon()*4;
if(obj[14].GetMon()>=Money::kind)
Num1[14]=obj[14].GetMon()+obj[14].GetMon()*4;
}
sce=1;//set econd time
if(Num==1)
{
if(obj[11].GetMon()>0&&obj[11].GetMon()<Num1[11])
{
obj[11].SetNum(obj[11].GetMon()+Money::kind);
{
PlaceRecieve(9,obj,Ap);
}
}
if(obj[12].GetMon()>0&&obj[12].GetMon()<Num1[12])
{
obj[12].SetNum(obj[12].GetMon()+Money::kind);
{
PlaceRecieve(10,obj,Ap);
}
}
if(obj[13].GetMon()>0&&obj[13].GetMon()<Num1[13])
{
obj[13].SetNum(obj[13].GetMon()+Money::kind);
{
PlaceRecieve(11,obj,Ap);
}
}
}
else if(Num==2)
{
if(obj[11].GetMon()>0&&obj[11].GetMon()<Num1[11])
{
//tem=obj[11].GetMon();
obj[11].SetNum(obj[11].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(9,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[3].GetMon()>0&&obj[3].GetMon()<Num1[3])
{
//tem=obj[3].GetMon()*4;
obj[3].SetNum(obj[3].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(1,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[7].GetMon()>0&&obj[7].GetMon()<Num1[7])
{
//tem=obj[7].GetMon()*2;
obj[7].SetNum(obj[7].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(5,obj,Ap);
//SDL_Delay(5);
}
}
}
else if(Num==3)
{
if(obj[11].GetMon()>0&&obj[11].GetMon()<Num1[11])
{
//tem=obj[11].GetMon();
obj[11].SetNum(obj[11].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(9,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[4].GetMon()>0&&obj[4].GetMon()<Num1[4])
{
//tem=obj[4].GetMon()*4;
obj[4].SetNum(obj[4].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(2,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[7].GetMon()>0&&obj[7].GetMon()<Num1[7])
{
//tem=obj[7].GetMon()*2;
obj[7].SetNum(obj[7].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(5,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[8].GetMon()>0&&obj[8].GetMon()<Num1[8])
{
//tem=obj[8].GetMon()*2;
obj[8].SetNum(obj[8].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(6,obj,Ap);
//SDL_Delay(5);
}
}
}
else if(Num==4)
{
if(obj[10].GetMon()>0&&obj[10].GetMon()<Num1[10])
{
//tem=obj[10].GetMon();
obj[10].SetNum(obj[10].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(8,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[5].GetMon()>0&&obj[5].GetMon()<Num1[5])
{
//tem=obj[5].GetMon()*4;
obj[5].SetNum(obj[5].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(3,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[8].GetMon()>0&&obj[8].GetMon()<Num1[8])
{
//tem=obj[8].GetMon()*2;
obj[8].SetNum(obj[8].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(6,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[9].GetMon()>0&&obj[9].GetMon()<Num1[9])
{
//tem=obj[9].GetMon()*2;
obj[9].SetNum(obj[9].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(7,obj,Ap);
//SDL_Delay(5);
}
}
}
else if(Num==5)
{
if(obj[10].GetMon()>0&&obj[10].GetMon()<Num1[10])
{
//tem=obj[10].GetMon();
obj[10].SetNum(obj[10].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(8,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[6].GetMon()>0&&obj[6].GetMon()<Num1[6])
{
//tem=obj[6].GetMon()*4;
obj[6].SetNum(obj[6].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(4,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[9].GetMon()>0&&obj[9].GetMon()<Num1[9])
{
//tem=obj[9].GetMon()*2;
obj[9].SetNum(obj[9].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(7,obj,Ap);
//SDL_Delay(5);
}
}
}
else if(Num==6)
{
if(obj[10].GetMon()>0&&obj[10].GetMon()<Num1[10])
{
//tem=obj[10].GetMon();
obj[10].SetNum(obj[10].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(8,obj,Ap);
//SDL_Delay(5);
}
}
if(obj[14].GetMon()>0&&obj[14].GetMon()<Num1[14])
{
//tem=obj[14].GetMon()*4;
obj[14].SetNum(obj[14].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(12,obj,Ap);
// SDL_Delay(5);
}
}
if(obj[13].GetMon()>0&&obj[13].GetMon()<Num1[13])
{
//tem=obj[13].GetMon()*2;
obj[13].SetNum(obj[13].GetMon()+Money::kind);
//for(i=0;i<tem;i=i+Money::kind)
{
PlaceRecieve(11,obj,Ap);
// SDL_Delay(5);
}
}}
if(Num==1)
{
if(Num1[11]<=obj[11].GetMon()&&Num1[13]<=obj[13].GetMon()&&Num1[12]<=obj[12].GetMon())
all=true;
}
else if(Num==2)
{
if(Num1[11]<=obj[11].GetMon()&&Num1[3]<=obj[3].GetMon()&&Num1[7]<=obj[7].GetMon())all=true;
}
else if(Num==3)
{
if(Num1[11]<=obj[11].GetMon()&&Num1[4]<=obj[4].GetMon()&&Num1[7]<=obj[7].GetMon()&&Num1[8]<=obj[8].GetMon())all=true;
}
else if(Num==4)
{
if(Num1[10]<=obj[10].GetMon()&&Num1[5]<=obj[5].GetMon()&&Num1[8]<=obj[8].GetMon()&&Num1[9]<=obj[9].GetMon())all=true;
}
else if(Num==5)
{
if(Num1[10]<=obj[10].GetMon()&&Num1[6]<=obj[6].GetMon()&&Num1[9]<=obj[9].GetMon())all=true;
}
else if(Num==6)
{
if(Num1[10]<=obj[10].GetMon()&&Num1[14]<=obj[14].GetMon()&&Num1[13]<=obj[13].GetMon())all=true;
}
// SDL_Delay(5);
if(all==true)
{
for(int i=0;i<15;i++)Num1[i]=0;
all=false;
return true;
}
else if(all==false)
return false;
}
bool Result::TakeMoney(Money obj[],int Num,Apong Ap)
{int i;
if(Num!=1)
{
if(obj[12].GetMon()>=Money::kind)
{obj[12].SetNum(obj[12].GetMon()-Money::kind);
PlaceRecieve(22,obj,Ap);
}
}
if(Num!=2)
{
if(obj[3].GetMon()>=Money::kind)
{
obj[3].SetNum(obj[3].GetMon()-Money::kind);
PlaceRecieve(13,obj,Ap);
}
}
if(Num!=3)
{
if(obj[4].GetMon()>=Money::kind)
{
obj[4].SetNum(obj[4].GetMon()-Money::kind);
PlaceRecieve(14,obj,Ap);
}
}
if(Num!=4)
{
if(obj[5].GetMon()>=Money::kind)
{
obj[5].SetNum(obj[5].GetMon()-Money::kind);
PlaceRecieve(15,obj,Ap);
}
}
if(Num!=5)
{
if(obj[6].GetMon()>=Money::kind)
{
obj[6].SetNum(obj[6].GetMon()-Money::kind);
PlaceRecieve(16,obj,Ap);
}
}
if(Num!=6)
{
if(obj[14].GetMon()>=Money::kind)
{
obj[14].SetNum(obj[14].GetMon()-Money::kind);
PlaceRecieve(24,obj,Ap);
}
}
if(Num>3)
{
if(obj[7].GetMon()>=Money::kind)
{
obj[7].SetNum(obj[7].GetMon()-Money::kind);
PlaceRecieve(17,obj,Ap);
}
if(obj[11].GetMon()>=Money::kind)
{
obj[11].SetNum(obj[11].GetMon()-Money::kind);
PlaceRecieve(21,obj,Ap);
}
if(Num<6)
{
if(obj[13].GetMon()>=Money::kind)
{
obj[13].SetNum(obj[13].GetMon()-Money::kind);
PlaceRecieve(23,obj,Ap);
}
}
if(Num>4)
{
if(obj[8].GetMon()>=Money::kind)
{
obj[8].SetNum(obj[8].GetMon()-Money::kind);
PlaceRecieve(18,obj,Ap);
}
}
if(Num>5)
{
if(obj[9].GetMon()>=Money::kind)
{
obj[9].SetNum(obj[9].GetMon()-Money::kind);
PlaceRecieve(19,obj,Ap);
}
}
}
if(Num<4)
{
if(obj[9].GetMon()>=Money::kind)
{
obj[9].SetNum(obj[9].GetMon()-Money::kind);
PlaceRecieve(19,obj,Ap);
}
if(obj[10].GetMon()>0)
{
obj[10].SetNum(obj[10].GetMon()-Money::kind);
PlaceRecieve(20,obj,Ap);
}
if(Num>1)
{
if(obj[13].GetMon()>=Money::kind)
{
obj[13].SetNum(obj[13].GetMon()-Money::kind);
PlaceRecieve(23,obj,Ap);
}
}
if(Num<3)
{
if(obj[8].GetMon()>=Money::kind)
{
obj[8].SetNum(obj[8].GetMon()-Money::kind);
PlaceRecieve(18,obj,Ap);
}
}
if(Num<2)
{
if(obj[7].GetMon()>=Money::kind)
{
obj[7].SetNum(obj[7].GetMon()-Money::kind);
PlaceRecieve(17,obj,Ap);
}
}
}
//SDL_Delay(5);
if(Num==1)
{
if(obj[3].GetMon()==0&&obj[4].GetMon()==0&&obj[5].GetMon()==0&&obj[6].GetMon()==0&&obj[7].GetMon()==0&&obj[8].GetMon()==0&&obj[9].GetMon()==0&&obj[10].GetMon()==0&&obj[14].GetMon()==0)
{
return true;
}
}
else if(Num==2)
{
if(obj[12].GetMon()==0&&obj[4].GetMon()==0&&obj[5].GetMon()==0&&obj[6].GetMon()==0&&obj[13].GetMon()==0&&obj[8].GetMon()==0&&obj[9].GetMon()==0&&obj[10].GetMon()==0&&obj[14].GetMon()==0)
{
return true;
}
}
else if(Num==3)
{
if(obj[3].GetMon()==0&&obj[5].GetMon()==0&&obj[6].GetMon()==0&&obj[12].GetMon()==0&&obj[13].GetMon()==0&&obj[9].GetMon()==0&&obj[10].GetMon()==0&&obj[14].GetMon()==0)
{
return true;
}
}
else if(Num==4)
{
if(obj[3].GetMon()==0&&obj[4].GetMon()==0&&obj[11].GetMon()==0&&obj[6].GetMon()==0&&obj[7].GetMon()==0&&obj[12].GetMon()==0&&obj[13].GetMon()==0&&obj[10].GetMon()==0&&obj[14].GetMon()==0)
{
return true;
}
}
else if(Num==5)
{
if(obj[3].GetMon()==0&&obj[4].GetMon()==0&&obj[5].GetMon()==0&&obj[11].GetMon()==0&&obj[7].GetMon()==0&&obj[8].GetMon()==0&&obj[12].GetMon()==0&&obj[13].GetMon()==0&&obj[14].GetMon()==0)
{
return true;
}
}
else if(Num==6)
{
if(obj[3].GetMon()==0&&obj[4].GetMon()==0&&obj[5].GetMon()==0&&obj[6].GetMon()==0&&obj[7].GetMon()==0&&obj[8].GetMon()==0&&obj[9].GetMon()==0&&obj[11].GetMon()==0&&obj[12].GetMon()==0)
{
return true;
}
}
return false;
}
bool Result::WinMoney(Money obj[],int Num,Apong Ap)
{
int i;
if(Num==1)
{
if(obj[11].GetMon()>=Money::kind)
{
if(obj[11].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(33,obj,Ap);
}
else if(obj[11].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(45,obj,Ap);
}
obj[11].SetNum(obj[11].GetMon()-Money::kind);
if(obj[11].GetMon()<Money::kind)obj[11].SetLocat(0);
}
if(obj[12].GetMon()>=Money::kind)
{
if(obj[12].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(34,obj,Ap);
}
else if(obj[12].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(46,obj,Ap);
}
obj[12].SetNum(obj[12].GetMon()-Money::kind);
if(obj[12].GetMon()<Money::kind)obj[12].SetLocat(0);
}
if(obj[13].GetMon()>=Money::kind)
{
if(obj[13].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(35,obj,Ap);
}
else if(obj[13].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(47,obj,Ap);
}
obj[13].SetNum(obj[13].GetMon()-Money::kind);
if(obj[13].GetMon()<Money::kind)obj[13].SetLocat(0);
}
}
else if(Num==2)
{
if(obj[11].GetMon()>=Money::kind)
{
if(obj[11].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(33,obj,Ap);
}
else if(obj[11].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(45,obj,Ap);
}
obj[11].SetNum(obj[11].GetMon()-Money::kind);
if(obj[11].GetMon()<Money::kind)obj[11].SetLocat(0);
}
if(obj[3].GetMon()>=Money::kind)
{
if(obj[3].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(25,obj,Ap);
}
else if(obj[3].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(37,obj,Ap);
}
obj[3].SetNum(obj[3].GetMon()-Money::kind);
if(obj[3].GetMon()<Money::kind)obj[3].SetLocat(0);
}
if(obj[7].GetMon()>=Money::kind)
{
if(obj[7].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(29,obj,Ap);
}
else if(obj[7].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(41,obj,Ap);
}
obj[7].SetNum(obj[7].GetMon()-Money::kind);
if(obj[7].GetMon()<Money::kind)obj[7].SetLocat(0);
}
}
else if(Num==3)
{
if(obj[11].GetMon()>=Money::kind)
{
if(obj[11].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(33,obj,Ap);
}
else if(obj[11].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(45,obj,Ap);
}
obj[11].SetNum(obj[11].GetMon()-Money::kind);
if(obj[11].GetMon()<Money::kind)obj[11].SetLocat(0);
}
if(obj[4].GetMon()>=Money::kind)
{
if(obj[4].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(26,obj,Ap);
}
else if(obj[4].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(38,obj,Ap);
}
obj[4].SetNum(obj[4].GetMon()-Money::kind);
if(obj[4].GetMon()<Money::kind)obj[4].SetLocat(0);
}
if(obj[7].GetMon()>=Money::kind)
{
if(obj[7].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(29,obj,Ap);
}
else if(obj[7].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(41,obj,Ap);
}
obj[7].SetNum(obj[7].GetMon()-Money::kind);
if(obj[7].GetMon()<Money::kind)obj[7].SetLocat(0);
}
if(obj[8].GetMon()>=Money::kind)
{
if(obj[8].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(30,obj,Ap);
}
else if(obj[8].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(42,obj,Ap);
}
obj[8].SetNum(obj[8].GetMon()-Money::kind);
if(obj[8].GetMon()<Money::kind)obj[8].SetLocat(0);
}
}
else if(Num==4)
{
if(obj[10].GetMon()>=Money::kind)
{
if(obj[10].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(32,obj,Ap);
}
else if(obj[10].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(44,obj,Ap);
}
obj[10].SetNum(obj[10].GetMon()-Money::kind);
if(obj[10].GetMon()<Money::kind)obj[10].SetLocat(0);
}
if(obj[5].GetMon()>=Money::kind)
{
if(obj[5].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(27,obj,Ap);
}
else if(obj[5].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(39,obj,Ap);
}
obj[5].SetNum(obj[5].GetMon()-Money::kind);
if(obj[5].GetMon()<Money::kind)obj[5].SetLocat(0);
}
if(obj[8].GetMon()>=Money::kind)
{
if(obj[8].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(30,obj,Ap);
}
else if(obj[8].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(42,obj,Ap);
}
obj[8].SetNum(obj[8].GetMon()-Money::kind);
if(obj[8].GetMon()<Money::kind)obj[8].SetLocat(0);
}
if(obj[9].GetMon()>=Money::kind)
{
if(obj[9].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(31,obj,Ap);
}
else if(obj[9].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(43,obj,Ap);
}
obj[9].SetNum(obj[9].GetMon()-Money::kind);
if(obj[9].GetMon()<Money::kind)obj[9].SetLocat(0);
}
}
else if(Num==5)
{
if(obj[10].GetMon()>=Money::kind)
{
if(obj[10].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(32,obj,Ap);
}
else if(obj[10].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(44,obj,Ap);
}
obj[10].SetNum(obj[10].GetMon()-Money::kind);
if(obj[10].GetMon()<Money::kind)obj[10].SetLocat(0);
}
if(obj[6].GetMon()>=Money::kind)
{
if(obj[6].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(28,obj,Ap);
}
else if(obj[6].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(40,obj,Ap);
}
obj[6].SetNum(obj[6].GetMon()-Money::kind);
if(obj[6].GetMon()<Money::kind)obj[6].SetLocat(0);
}
if(obj[9].GetMon()>=Money::kind)
{
if(obj[9].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(31,obj,Ap);
}
else if(obj[9].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(43,obj,Ap);
}
obj[9].SetNum(obj[9].GetMon()-Money::kind);
if(obj[9].GetMon()<Money::kind)obj[9].SetLocat(0);
}
}
else if(Num==6)
{
if(obj[10].GetMon()>=Money::kind)
{
if(obj[10].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(32,obj,Ap);
}
else if(obj[10].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(44,obj,Ap);
}
obj[10].SetNum(obj[10].GetMon()-Money::kind);
if(obj[10].GetMon()<Money::kind)obj[10].SetLocat(0);
}
if(obj[14].GetMon()>=Money::kind)
{
if(obj[14].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(36,obj,Ap);
}
else if(obj[14].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(48,obj,Ap);
}
obj[14].SetNum(obj[14].GetMon()-Money::kind);
if(obj[14].GetMon()<Money::kind)obj[14].SetLocat(0);
}
if(obj[13].GetMon()>=Money::kind)
{
if(obj[13].GetLocat()==1)
{
obj[1].SetNum(obj[1].GetMon()+Money::kind);
PlaceRecieve(35,obj,Ap);
}
else if(obj[13].GetLocat()==2)
{
obj[2].SetNum(obj[2].GetMon()+Money::kind);
PlaceRecieve(47,obj,Ap);
}
obj[13].SetNum(obj[13].GetMon()-Money::kind);
if(obj[13].GetMon()<Money::kind)obj[13].SetLocat(0);
}}
// SDL_Delay(5);
for(int l=3;l<15;l++)
if(obj[l].GetMon()>=Money::kind)
return false;
return true;
}
#endif
| [
"sreangrathanak@yahoo.com"
] | sreangrathanak@yahoo.com |
3eb8ccf87075f3e564c8b4aa26fe8559ea9fb92d | cfa955080fae0b3b8674ae339fbec99a9cd0fc6d | /week-4/day-3/MyApp/MyApp_Lib/Apple.h | d327a47b13c6f736da37f931b342bd6672acc9f3 | [] | no_license | green-fox-academy/Csano97 | bfd77f3adb85a584537a54ad0242bee658c7b381 | 09abc43750c4029b1492a9727f186fb51863f815 | refs/heads/master | 2020-06-09T23:31:01.583756 | 2019-09-19T12:29:56 | 2019-09-19T12:29:56 | 193,527,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 201 | h | #ifndef APPLES_APPLE_H
#define APPLES_APPLE_H
#include <string>
#include <vector>
class Apples
{
public:
std::string getApple();
int sum(std::vector<int> apples);
};
#endif //APPLES_APPLE_H
| [
"csano.kornel@gmail.com"
] | csano.kornel@gmail.com |
fa0c216f5b77980ba0d28dab4e77e564a60c32fe | f0568a303cb42ab03a52aca5d3962e449dd3790f | /Week06/task1.cpp | 83ce12d851192857040a26411d9f2bb6d3d4e4b4 | [] | no_license | kiretooo/Up-2016-2017 | 4b7596ef418445e855bd42a04097101afccf96ba | 7c9f868945b56c7726a35f41604a8a2ea779729d | refs/heads/master | 2021-01-12T15:27:03.188170 | 2017-03-19T20:47:07 | 2017-03-19T20:47:07 | 71,786,849 | 0 | 0 | null | 2016-10-25T17:50:50 | 2016-10-24T12:32:14 | null | UTF-8 | C++ | false | false | 534 | cpp | // task1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
char a, b;
cout << "n = ";
cin >> n;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
int counterA, counterB;
cout << "\nResult: " << endl;
for (int i = 1; i <= n - 1; i++)
{
counterA = i;
counterB = n - i;
while (counterA > 0)
{
cout << a;
counterA--;
}
while (counterB > 0)
{
cout << b;
counterB--;
}
cout << '\n';
}
return 0;
}
| [
"kirilmironov@abv.bg"
] | kirilmironov@abv.bg |
0dcab7871ee38f5f0fcd54d0acd87aeee93b2819 | 78386ccc57f2f7408a468b830f22133232f22b19 | /sources/world/physics/physics_static_rigid_body_component.h | 81bca9c3166fbe77c3ba544210ce166ef8bc47ef | [
"MIT"
] | permissive | suVrik/hooker.galore | 298a438398fa2aa96536390dbf94ac6c4e8a4c4a | 616e2692d7afab24b70bfb6aa14ad780eb7c451d | refs/heads/master | 2021-06-11T19:09:57.369637 | 2021-06-05T13:46:13 | 2021-06-05T13:46:13 | 190,454,769 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 209 | h | #pragma once
namespace hg {
/** `PhysicsStaticRigidBodyComponent` marks entity as static rigid body. */
class PhysicsStaticRigidBodyComponent final {
private:
bool m_dummy = false;
};
} // namespace hg
| [
"suvri4@gmail.com"
] | suvri4@gmail.com |
8070a83c458c66c19412aeca6366ef91574fd23f | b12a2a973090ca6a034ebbf5aed8e574caecaaed | /src/Text.cpp | 586d288fab1c0adf53fbca7a5df9d8e08b1bef4b | [
"MIT"
] | permissive | fluffels/crispy-carnival | a5d2a73b1da490ec97e30cf22fc63def24cf2fe1 | 13f4200e3558f6aeaa6d234863c2816eaf7e6c2d | refs/heads/master | 2022-12-15T23:04:51.300298 | 2020-09-14T16:02:56 | 2020-09-14T16:02:56 | 266,358,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,090 | cpp | #pragma warning(disable: 4267)
#include "Mesh.h"
#include "Text.h"
#include "stb_easy_font.h"
const float SIZE_X = 0;
const float SIZE_Y = 0;
const uint32_t VERTICES_PER_QUAD = 4;
static VulkanPipeline pipeline;
static Mesh mesh;
void createIndexBuffer(
Vulkan& vk,
Mesh& mesh
) {
uint32_t data[6];
auto count = sizeof(data) / sizeof(uint32_t);
auto size = sizeof(uint32_t) * count;
data[0] = 0;
data[1] = 1;
data[2] = 2;
data[3] = 2;
data[4] = 3;
data[5] = 0;
createIndexBuffer(
vk.device, vk.memories, vk.queueFamily, (uint32_t)size, mesh.iBuff
);
void *dst = mapMemory(vk.device, mesh.iBuff.handle, mesh.iBuff.memory);
memcpy(dst, data, size);
unMapMemory(vk.device, mesh.iBuff.memory);
}
void createVertexBuffer(
Vulkan& vk,
uint8_t* buffer,
uint32_t quadCount,
VulkanPipeline& pipeline,
Mesh& mesh
) {
auto count = quadCount * VERTICES_PER_QUAD;
auto stride = pipeline.inputBinding.stride;
auto size = count * stride;
float* data = (float*)malloc(size);
float* vertex = data;
for (uint32_t idx = 0; idx < quadCount * VERTICES_PER_QUAD; idx++) {
// NOTE(jan): vertex positions
for (int i = 0; i < 3; i++) {
*vertex++ = *((float*)buffer);
// NOTE(jan): each coord is stored as a 32 bit float
buffer += 4;
}
// NOTE(jan): vertex colours
for (int i = 0; i < 4; i++) {
*vertex++ = ((uint8_t)*buffer++) / 255.f;
}
}
createVertexBuffer(
vk.device, vk.memories, vk.queueFamily, size, mesh.vBuff
);
void *dst = mapMemory(vk.device, mesh.vBuff.handle, mesh.vBuff.memory);
memcpy(dst, data, size);
unMapMemory(vk.device, mesh.vBuff.memory);
mesh.idxCount = count;
free(data);
}
void
recordTextCommandBuffers(Vulkan& vk, vector<VkCommandBuffer>& cmds, char* text) {
char buffer[99999];
auto quadCount = stb_easy_font_print(
SIZE_X, SIZE_Y, text, NULL, buffer, sizeof(buffer)
);
initVKPipeline(vk, "text", pipeline);
createVertexBuffer(vk, (uint8_t*)buffer, quadCount, pipeline, mesh);
createIndexBuffer(vk, mesh);
uint32_t framebufferCount = vk.swap.images.size();
cmds.resize(framebufferCount);
createCommandBuffers(vk.device, vk.cmdPoolTransient, framebufferCount, cmds);
VkDeviceSize offsets[] = {0};
for (size_t swapIdx = 0; swapIdx < framebufferCount; swapIdx++) {
auto& cmd = cmds[swapIdx];
beginFrameCommandBuffer(cmd);
VkRenderPassBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
beginInfo.clearValueCount = 0;
beginInfo.pClearValues = nullptr;
beginInfo.framebuffer = vk.swap.framebuffers[swapIdx];
beginInfo.renderArea.extent = vk.swap.extent;
beginInfo.renderArea.offset = {0, 0};
beginInfo.renderPass = vk.renderPassNoClear;
vkCmdBeginRenderPass(cmd, &beginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.handle);
vkCmdBindIndexBuffer(cmd, mesh.iBuff.handle, 0, VK_INDEX_TYPE_UINT32);
vkCmdBindVertexBuffers(cmd, 0, 1, &mesh.vBuff.handle, offsets);
for (size_t quadIdx = 0; quadIdx < quadCount; quadIdx++) {
vkCmdDrawIndexed(cmd, 6, 1, 0, quadIdx * VERTICES_PER_QUAD, 0);
}
vkCmdEndRenderPass(cmd);
checkSuccess(vkEndCommandBuffer(cmd));
}
}
void resetTextCommandBuffers(Vulkan& vk, vector<VkCommandBuffer>& cmds) {
vkFreeCommandBuffers(
vk.device,
vk.cmdPoolTransient,
cmds.size(),
cmds.data()
);
vkFreeMemory(vk.device, mesh.iBuff.memory, nullptr);
vkDestroyBufferView(vk.device, mesh.iBuff.view, nullptr);
vkDestroyBuffer(vk.device, mesh.iBuff.handle, nullptr);
vkFreeMemory(vk.device, mesh.vBuff.memory, nullptr);
vkDestroyBufferView(vk.device, mesh.vBuff.view, nullptr);
vkDestroyBuffer(vk.device, mesh.vBuff.handle, nullptr);
}
| [
"jcwkroeze@pm.me"
] | jcwkroeze@pm.me |
5c539c916977c5cc887795d489e45bb521f1e03e | bce031e32e68970ff72debd120900221bdd734f8 | /chap6-dfs1/c6-p2-aKnightJourney.cpp | 1bf2fb301ff93796cd151fda1f89363c4b21c194 | [] | no_license | chrisdenado/suanfa-jichu | a999b1b6eb471cde998e6a907aa8f6bbec0b0c03 | 51b0d862fdf7a55c151d7c1e83c621a68615f5cc | refs/heads/master | 2020-04-07T08:24:38.952600 | 2018-12-27T09:53:40 | 2018-12-27T09:53:40 | 158,212,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//POJ2488: A Knight's Journey
struct chass
{
int x, y;
chass() {}
chass(int xx, int yy):x(xx), y(yy) {}
};
bool dfs(int cur_id, int x, int y, int p, int q, vector<chass> &path, vector<vector<int>> &visited)
{
if(cur_id == p*q) return true;
if( x<0 || x>=p || y<0 || y>=q ) return false;
if( visited[x][y] ) return false;
path.push_back(chass(x, y));
visited[x][y]=1;
if( dfs(cur_id+1, x-1, y-2, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x+1, y-2, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x-2, y-1, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x+2, y-1, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x-2, y+1, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x+2, y+1, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x-1, y+2, p, q, path, visited) ) return true;
if( dfs(cur_id+1, x+1, y+2, p, q, path, visited) ) return true;
visited[x][y]=0;
path.pop_back();
return false;
}
int main()
{
int t;
cin>>t;
for(int i=1; i<=t; i++)
{
int p, q;
cin>>p>>q;
vector<vector<int>> visited(p, vector<int>(q,0));
vector<chass> path;
cout<<"Scenario #"<<i<<":"<<endl;
if( dfs(0, 0, 0, p, q, path, visited) )
{
string res;
for(int i=0; i<path.size(); i++)
{
res += path[i].y + 'A';
res += path[i].x + '1';
}
cout<<res<<endl;
}
else cout<<"impossible"<<endl;
cout<<endl;
}
return 0;
}
| [
"18792658993@163.com"
] | 18792658993@163.com |
74e9a5972e7beb2e47a9351a245702914bf30364 | 54a324e0d956fcbabf12f5aea6c5b051592a310c | /Ved/Ved.cpp | 8d56acf8ed7c7ab178e3e5e17d36646f432b4c49 | [] | no_license | gmestanley/Ved | 3e5090e4c81fdca982fd71d912e62f35e1b21095 | d085ff3284cba4a6ed7af9bdf2ace7ac794cdb17 | refs/heads/master | 2023-02-19T09:33:30.793799 | 2021-01-06T23:09:26 | 2021-01-06T23:09:26 | 327,448,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,809 | cpp | // Ved.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "Ved.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_VED, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_VED));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_VED));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_VED);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
} | [
"agsproductionsnew@outlook.com"
] | agsproductionsnew@outlook.com |
c3774ac59e254244bb3ec6cb6a90f2ad62d3895c | 36e5c06883c0288dc48e3978ca9deaf6d6a9bffc | /src/cmdline/Error.cpp | 6696f7bf7be8fd3148478186dcb695d13ee970dc | [
"MIT"
] | permissive | cwbaker/forge | 46271bc05311ce64b09e2c6e2311f51a124761c2 | 18b7ec97769354b28189d390474bd22473537f49 | refs/heads/main | 2022-11-19T17:13:46.367043 | 2022-11-11T07:23:23 | 2022-11-11T07:23:23 | 3,674,381 | 14 | 2 | MIT | 2022-09-07T04:20:33 | 2012-03-09T20:16:16 | C++ | UTF-8 | C++ | false | false | 302 | cpp | //
// Error.cpp
// Copyright (c) Charles Baker. All rights reserved.
//
#include "Error.hpp"
using namespace sweet::cmdline;
/**
// Constructor.
//
// @param error
// The number that uniquely identifies this Error.
*/
Error::Error( int error )
: sweet::error::Error( error )
{
}
| [
"charles.baker@sweetsoftware.co.nz"
] | charles.baker@sweetsoftware.co.nz |
f65cac9f94189e05d22def7579c11cf06f126bab | d002ed401cba924074e021d22347b84334a02b0f | /export/windows/obj/src/openfl/errors/RangeError.cpp | 5db377e4c8505248c258a7e6028d6a951b9995d6 | [] | no_license | IADenner/LD47 | 63f6beda87424ba7e0e129848ee190c1eb1da54d | 340856f1d77983da0e7f331b467609c45587f5d1 | refs/heads/master | 2022-12-29T13:01:46.789276 | 2020-10-05T22:04:42 | 2020-10-05T22:04:42 | 301,550,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 3,063 | cpp | // Generated by Haxe 4.1.2
#include <hxcpp.h>
#ifndef INCLUDED_openfl_errors_Error
#include <openfl/errors/Error.h>
#endif
#ifndef INCLUDED_openfl_errors_RangeError
#include <openfl/errors/RangeError.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_bc09bde916c21592_11_new,"openfl.errors.RangeError","new",0xae8f9562,"openfl.errors.RangeError.new","openfl/errors/RangeError.hx",11,0xfc04662e)
namespace openfl{
namespace errors{
void RangeError_obj::__construct(::String __o_message){
::String message = __o_message;
if (::hx::IsNull(__o_message)) message = HX_("",00,00,00,00);
HX_STACKFRAME(&_hx_pos_bc09bde916c21592_11_new)
HXLINE( 12) super::__construct(message,0);
HXLINE( 14) this->name = HX_("RangeError",eb,ac,85,3c);
}
Dynamic RangeError_obj::__CreateEmpty() { return new RangeError_obj; }
void *RangeError_obj::_hx_vtable = 0;
Dynamic RangeError_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< RangeError_obj > _hx_result = new RangeError_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool RangeError_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x3495c9c5) {
return inClassId==(int)0x00000001 || inClassId==(int)0x3495c9c5;
} else {
return inClassId==(int)0x5467b8e6;
}
}
::hx::ObjectPtr< RangeError_obj > RangeError_obj::__new(::String __o_message) {
::hx::ObjectPtr< RangeError_obj > __this = new RangeError_obj();
__this->__construct(__o_message);
return __this;
}
::hx::ObjectPtr< RangeError_obj > RangeError_obj::__alloc(::hx::Ctx *_hx_ctx,::String __o_message) {
RangeError_obj *__this = (RangeError_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(RangeError_obj), true, "openfl.errors.RangeError"));
*(void **)__this = RangeError_obj::_hx_vtable;
__this->__construct(__o_message);
return __this;
}
RangeError_obj::RangeError_obj()
{
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *RangeError_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *RangeError_obj_sStaticStorageInfo = 0;
#endif
::hx::Class RangeError_obj::__mClass;
void RangeError_obj::__register()
{
RangeError_obj _hx_dummy;
RangeError_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.errors.RangeError",70,fc,c4,66);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< RangeError_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = RangeError_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = RangeError_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace errors
| [
"theiadstudios@gmail.com"
] | theiadstudios@gmail.com |
aa6658a8c55d049aa5669bfc15672b884b3b8699 | 53127ee1473d4cb2d2f8c77bb0394e9ff71e3c5a | /Classes/Scene/GameMain/PlayStage1.cpp | 376a5d495ef85d495e84b5123bad28ede30fe979 | [] | no_license | nanathia/ElementalMaster_luna | 984450de966955f2859b8013ddb00b2e74c784d5 | 0fdbe2b805533848df6c1f75368af0174e260dbf | refs/heads/master | 2016-08-04T15:43:53.129880 | 2014-08-27T05:07:01 | 2014-08-27T05:07:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 985 | cpp | #include "PlayStage1.h"
#include "PlayStage1State.h"
#include "GameMain.h"
#include "TextureManager.h"
namespace stage1{
PlayStage1::PlayStage1(GameMain* user):
PlayStateChild(user),
m_state(0),
m_bgSprite(0){
m_state = new State(this);
cocos2d::Size winSize = cocos2d::Director::getInstance()->getWinSize();
m_bgSprite = gGameMain->getTexMan()->createSprite(GameMain::texName_StageBGI, gGameMain,
cocos2d::Rect(winSize.width/2, winSize.height/2,
winSize.width, winSize.height));
}
PlayStage1::~PlayStage1(){
delete m_state;
m_state = 0;
m_bgSprite->removeFromParentAndCleanup(true);
m_bgSprite = 0;
}
PlayStateChild* PlayStage1::update(float deltaTime){
PlayStateChild* next = this;
m_state->update(deltaTime);
return next;
}
} | [
"tpmk95217@gmail.com"
] | tpmk95217@gmail.com |
f981100fd33e871a81220914f786790c326c3b8f | 827405b8f9a56632db9f78ea6709efb137738b9d | /CodingWebsites/LeetCode/CPP/Volume5/438.cpp | 3c40e36e7276ef1a71409a1b544632b344a96d11 | [] | no_license | MingzhenY/code-warehouse | 2ae037a671f952201cf9ca13992e58718d11a704 | d87f0baa6529f76e41a448b8056e1f7ca0ab3fe7 | refs/heads/master | 2020-03-17T14:59:30.425939 | 2019-02-10T17:12:36 | 2019-02-10T17:12:36 | 133,694,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,599 | cpp | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <list>
#include <cmath>
#include <map>
#include <set>
#include <stack>
using namespace std;
class Solution {
int NS,NP;
int KP,KPP;
map<char,int> CountS;
map<char,int> CountP;
void Add(char ch){
int c = ++CountS[ch];
NS += c == 1;
KP += c == CountP[ch];
KPP += c == CountP[ch] + 1;
}
void Remove(char ch){
int c = --CountS[ch];
NS -= c == 0;
KP -= c == CountP[ch] - 1;
KPP -= c == CountP[ch];
}
bool isValid(){
return KP == NP && KPP == 0;
}
public:
vector<int> findAnagrams(string s, string p) {
NP = 0;
for(auto ch : p){
NP += !CountP[ch]++;
}
NS = KP = KPP = 0;
int L = 0, R = 0, N = s.length();
vector<int> ret;
while(L < N){
if(isValid()){
ret.push_back(L);
Remove(s[L++]);
}
else{
if(KPP > 0){
//too much letters, L++, --R
Remove(s[L++]);
Remove(s[--R]);
}
else{
//not Enough letters, R++
if(R < N)
Add(s[R++]);
else
break;
}
}
}
return ret;
}
void Test(){
}
};
int main(){
Solution S;
S.Test();
return 0;
}
| [
"mingzhenyan@yahoo.com"
] | mingzhenyan@yahoo.com |
83aabaea46db19f9424b121262e92fb774ce778d | e3e1892aa9824dccb9b09cc7861d5a4d2f4da0be | /P1a/List.h | f5366ba1322b513237cf7b90671a5a885d91f22d | [] | no_license | exp111/ADHS | 29880aff9712fed955fdc0dadeb64bd64f415479 | 54e704cebd384babdabd679ba9f02507d48fc1f1 | refs/heads/master | 2020-03-09T11:58:59.152624 | 2018-07-18T18:08:30 | 2018-07-18T18:08:30 | 128,774,393 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,975 | h | #ifndef _LIST_H
#define _LIST_H
#include "Node.h"
#include <string>
#include <iostream>
class List
{
/*
Die Klasse List dient zur Verwaltung von Knoten (Node). Mit Hilfe der Klasse List
kann ein Stapel oder Warteschlange realisiert werden.
*/
private:
struct form { std::string start = "<< "; std::string zwischen = ", "; std::string ende = " >>\n"; } _form;
Node * head, * tail; // Zeiger auf Kopf- und End-Element
int _size; // Länge der Kette
bool temp; // normalerweise false; ist true, wenn es sich um eine temoräre Liste handelt
// die innerhalb der überladenen Operatoren angelegt wird
public:
List();
~List();
void InsertFront(int key); // Einfügen eines Knotens am Anfang
void InsertBack(int key); // Einfügen eines Knotesn am Ende
bool getFront(int & key); // Entnehmen eines Knoten am Anfang
bool getBack(int & key); // Entnehmen eines Knoten am Ende
Node* searchFirst(int key);
bool del(int key); // löschen eines Knotens [key]
bool search(int key); // Suchen eines Knoten
bool swap(int key1, int key2); // Knoten in der Liste vertauschen
int size(void); // Größe der Lise (Anzahl der Knoten)
bool test(void); // Überprüfen der Zeigerstruktur der Liste
void format(const std::string & start, const std::string & zwischen, const std::string & ende); // Mit der format-Methode kann die Ausgabe gesteuert werden: operator <<
List & operator = (const List & _List); // Zuweisungsoperator definieren
List & operator = (const List * _List); // Zuweisungsoperator definieren
List & operator + (const List & List_Append); // Listen zusammenführen zu einer Liste
List & operator + (const List * List_Append); // Listen zusammenführen zu einer Liste
friend std::ostream & operator << (std::ostream & stream, List const & Liste); // Ausgabeoperator überladen
friend std::ostream & operator << (std::ostream & stream, List const * Liste); // Ausgabeoperator überladen
};
#endif | [
"theexp111@gmail.com"
] | theexp111@gmail.com |
1493d2f582facf9f70062aedea7cb500acd4d575 | e8661c02f83efeba2023c7aad9cdc48131d54f24 | /At Stumholmen/libraries/SdFat-master/examples/dataLogger/dataLogger.ino | bf61faa82e2452a5c832a95c52a289f883a34b57 | [] | no_license | simonpoulding/ERIKS_brain | 00b7c446516deb24a1bd59122ece3805e3d31d7e | e885a4cc130ba3997c95bc1e3432dd8029b35176 | refs/heads/master | 2020-12-30T15:54:33.579193 | 2017-05-13T15:18:43 | 2017-05-13T15:18:43 | 91,182,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,935 | ino | /*
* Simple data logger.
*/
#include <SPI.h>
#include <SdFat.h>
// SD chip select pin.
const uint8_t chipSelect = 5;
// Interval between data records in milliseconds.
// The interval must be greater than the maximum SD write latency plus the
// time to acquire and write data to the SD to avoid overrun errors.
// Run the bench example to check the quality of your SD card.
const uint32_t SAMPLE_INTERVAL_MS = 200;
// Log file base name. Must be six characters or less.
#define FILE_BASE_NAME "Data"
//------------------------------------------------------------------------------
// File system object.
SdFat sd;
// Log file.
SdFile file;
// Time in micros for next data record.
uint32_t logTime;
//==============================================================================
// User functions. Edit writeHeader() and logData() for your requirements.
const uint8_t ANALOG_COUNT = 4;
//------------------------------------------------------------------------------
// Write data header.
void writeHeader() {
file.print(F("micros"));
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.print(F(",adc"));
file.print(i, DEC);
}
file.println();
}
//------------------------------------------------------------------------------
// Log a data record.
void logData() {
uint16_t data[ANALOG_COUNT];
// Read all channels to avoid SD write latency between readings.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
data[i] = analogRead(i);
}
// Write data to file. Start with log time in micros.
file.print(logTime);
// Write ADC data to CSV record.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.write(',');
file.print(data[i]);
}
file.println();
}
//==============================================================================
// Error messages stored in flash.
#define error(msg) sd.errorHalt(F(msg))
//------------------------------------------------------------------------------
void setup() {
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[13] = FILE_BASE_NAME "00.csv";
Serial.begin(9600);
while (!Serial) {} // wait for Leonardo
delay(1000);
Serial.println(F("Type any character to start"));
while (!Serial.available()) {}
// Initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
// breadboards. use SPI_FULL_SPEED for better performance.
if (!sd.begin(chipSelect, SPI_FULL_SPEED)) {
sd.initErrorHalt();
}
// Find an unused file name.
if (BASE_NAME_SIZE > 6) {
error("FILE_BASE_NAME too long");
}
while (sd.exists(fileName)) {
if (fileName[BASE_NAME_SIZE + 1] != '9') {
fileName[BASE_NAME_SIZE + 1]++;
} else if (fileName[BASE_NAME_SIZE] != '9') {
fileName[BASE_NAME_SIZE + 1] = '0';
fileName[BASE_NAME_SIZE]++;
} else {
error("Can't create file name");
}
}
if (!file.open(fileName, O_CREAT | O_WRITE | O_EXCL)) {
error("file.open");
}
do {
delay(10);
} while (Serial.read() >= 0);
Serial.print(F("Logging to: "));
Serial.println(fileName);
Serial.println(F("Type any character to stop"));
// Write data header.
writeHeader();
// Start on a multiple of the sample interval.
logTime = micros()/(1000UL*SAMPLE_INTERVAL_MS) + 1;
logTime *= 1000UL*SAMPLE_INTERVAL_MS;
}
//------------------------------------------------------------------------------
void loop() {
// Time for next record.
logTime += 1000UL*SAMPLE_INTERVAL_MS;
// Wait for log time.
int32_t diff;
do {
diff = micros() - logTime;
} while (diff < 0);
// Check for data rate too high.
if (diff > 10) {
error("Missed data record");
}
logData();
// Force data to SD and update the directory entry to avoid data loss.
if (!file.sync() || file.getWriteError()) {
error("write error");
}
if (Serial.available()) {
// Close file and stop.
file.close();
Serial.println(F("Done"));
while(1) {}
}
} | [
"simon.poulding@gmail.com"
] | simon.poulding@gmail.com |
1badf9323b6c4028cc2097a393fcbb262e64241c | 248c3b2ff56dce06feb554f1e851e6c785918dba | /include/syntax/Token.h | ff3d70bea57bf9584f2c20befe31d363bddd51ba | [] | no_license | CASC-Lang/CAScript-Native | d6a44e334c29c767277cae83e05daa64dcce8285 | 299c759521e2d58bac0c0c421f7a95df19435b6b | refs/heads/main | 2023-07-18T08:25:39.759110 | 2021-08-22T05:10:01 | 2021-08-22T05:10:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | h | //
// Created by ChAoS-UnItY on 8/10/2021.
//
#ifndef COLLAGE_CPP_TOKEN_H
#define COLLAGE_CPP_TOKEN_H
#include <utility>
#include <iterator>
#include <iostream>
#include <magic_enum.hpp>
#include "TokenType.h"
#include "SyntaxNode.h"
namespace cascript::syntax {
struct Token : public SyntaxNode {
Token(TokenType type, char literal) : type(type), literal(1, literal) {}
Token(TokenType type, std::string literal) : type(type), literal(std::move(literal)) {}
TokenType type;
std::string literal;
SyntaxType syntax_type() const final {
return SyntaxType::Token;
};
std::vector<SyntaxNode*> children() final {
return std::vector<SyntaxNode*> {};
};
};
inline std::ostream &operator<<(std::ostream &os, const Token &token) {
os << "<syntax_type:" << magic_enum::enum_name(token.type) << "/literal:" << token.literal << ">";
return os;
}
}
#endif //COLLAGE_CPP_TOKEN_H
| [
"43753315+KyleLin921021@users.noreply.github.com"
] | 43753315+KyleLin921021@users.noreply.github.com |
6beee2ab41243c4e3556d0b70f673cb7f234c5cc | 8b7fdf5100ebd616eb5ac9f2b14d1c8d6c4c0d8e | /frameworks/core/components/test/unittest/flex/render_magic_layout_test.cpp | 0fe98116eb639a9ce33ec73f0d6068d5708d6e17 | [
"Apache-2.0"
] | permissive | openharmony-sig-ci/ace_ace_engine | 13f2728bce323b67ac94a34d2e9c0a941227c402 | 05ebe2d6d2674777f5dc64fd735088dcf1a42cd9 | refs/heads/master | 2023-07-25T02:26:10.854405 | 2021-09-10T01:48:59 | 2021-09-10T01:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,902 | cpp | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "base/log/log.h"
#include "base/utils/utils.h"
#include "core/components/test/unittest/flex/flex_test_utils.h"
#include "core/components/test/unittest/mock/mock_render_common.h"
#include "core/components/text/text_component.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Ace {
namespace {
constexpr double SMALL_BOX = 100.0;
constexpr double MEDIUM_BOX = 200.0;
constexpr double LARGE_BOX = 300.0;
constexpr double RECT_WIDTH = 1080.0;
constexpr double RECT_HEIGHT = 2244.0;
} // namespace
class RenderMagicLayoutTest : public testing::Test {
public:
static void SetUpTestCase()
{
GTEST_LOG_(INFO) << "RenderMagicLayoutTest SetUpTestCase";
}
static void TearDownTestCase()
{
GTEST_LOG_(INFO) << "RenderMagicLayoutTest TearDownTestCase";
}
void SetUp() {}
void TearDown() {}
};
/**
* @tc.name: FlexWeight001
* @tc.desc: Verify the row component with 1 weight child works fine.
* @tc.type: FUNC
* @tc.require: AR000F2BCC
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight001, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_START);
row->Attach(mockContext);
root->AddChild(row);
RefPtr<RenderBox> firstBox = FlexTestUtils::CreateWeightedBox(1, SMALL_BOX, SMALL_BOX);
firstBox->Attach(mockContext);
row->AddChild(firstBox);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstBox->GetPosition().IsZero());
EXPECT_TRUE(firstBox->GetLayoutSize() == Size(RECT_WIDTH, SMALL_BOX));
EXPECT_TRUE(row->GetLayoutSize() == Size(RECT_WIDTH, SMALL_BOX));
}
/**
* @tc.name: FlexWeight002
* @tc.desc: Verify the row component with 3 same weight child works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAS
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight002, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_START);
row->Attach(mockContext);
root->AddChild(row);
RefPtr<RenderBox> firstBox = FlexTestUtils::CreateWeightedBox(1, SMALL_BOX);
firstBox->Attach(mockContext);
row->AddChild(firstBox);
RefPtr<RenderBox> secondBox = FlexTestUtils::CreateWeightedBox(2, SMALL_BOX);
secondBox->Attach(mockContext);
row->AddChild(secondBox);
RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateWeightedBox(3, SMALL_BOX);
thirdBox->Attach(mockContext);
row->AddChild(thirdBox);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstBox->GetPosition().IsZero());
EXPECT_TRUE(secondBox->GetPosition() == Offset(180, 0.0));
EXPECT_TRUE(thirdBox->GetPosition() == Offset(540, 0.0));
EXPECT_TRUE(firstBox->GetLayoutSize() == Size(180.0, SMALL_BOX));
EXPECT_TRUE(secondBox->GetLayoutSize() == Size(360.0, SMALL_BOX));
EXPECT_TRUE(thirdBox->GetLayoutSize() == Size(540.0, SMALL_BOX));
EXPECT_TRUE(row->GetLayoutSize() == Size(RECT_WIDTH, SMALL_BOX));
}
/**
* @tc.name: FlexWeight003
* @tc.desc: Verify the column component with 3 same weight child works fine.
* @tc.type: FUNC
* @tc.require: AR000F2BCC
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight003, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::COLUMN, FlexAlign::FLEX_START, FlexAlign::CENTER);
row->Attach(mockContext);
root->AddChild(row);
RefPtr<RenderBox> firstBox = FlexTestUtils::CreateWeightedBox(1, SMALL_BOX, SMALL_BOX);
firstBox->Attach(mockContext);
row->AddChild(firstBox);
RefPtr<RenderBox> secondBox = FlexTestUtils::CreateWeightedBox(2, MEDIUM_BOX, MEDIUM_BOX);
secondBox->Attach(mockContext);
row->AddChild(secondBox);
RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateWeightedBox(3, LARGE_BOX, LARGE_BOX);
thirdBox->Attach(mockContext);
row->AddChild(thirdBox);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstBox->GetPosition() == Offset(100, 0));
EXPECT_TRUE(secondBox->GetPosition() == Offset(50, 374.0));
EXPECT_TRUE(thirdBox->GetPosition() == Offset(0, 1122.0));
EXPECT_TRUE(firstBox->GetLayoutSize() == Size(SMALL_BOX, 374.0));
EXPECT_TRUE(secondBox->GetLayoutSize() == Size(MEDIUM_BOX, 748.0));
EXPECT_TRUE(thirdBox->GetLayoutSize() == Size(LARGE_BOX, 1122.0));
EXPECT_TRUE(row->GetLayoutSize() == Size(LARGE_BOX, RECT_HEIGHT));
}
/**
* @tc.name: FlexWeight004
* @tc.desc: Verify the row component with 3 different weight and aspect ratio children works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAI
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight004, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_START);
row->Attach(mockContext);
root->AddChild(row);
auto firstItem = FlexTestUtils::CreateMagicNode(2, 1, 1, LayoutParam(Size(), Size()), mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, 2, 1, LayoutParam(Size(), Size()), mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(0.5, 3, 1, LayoutParam(Size(), Size()), mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition().IsZero());
EXPECT_TRUE(secondItem->GetPosition() == Offset(180, 0.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(540, 0.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(180.0, 90));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(360.0, 360));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(540.0, 1080));
EXPECT_TRUE(row->GetLayoutSize() == Size(RECT_WIDTH, 1080));
}
/**
* @tc.name: FlexWeight005
* @tc.desc: Verify the column component with 3 different weight and aspect ratio children works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAR
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight005, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> column =
FlexTestUtils::CreateRenderFlex(FlexDirection::COLUMN, FlexAlign::FLEX_START, FlexAlign::CENTER);
column->Attach(mockContext);
root->AddChild(column);
auto firstItem = FlexTestUtils::CreateMagicNode(2, 1, 1, LayoutParam(Size(), Size()), mockContext);
firstItem->Attach(mockContext);
column->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, 2, 1, LayoutParam(Size(), Size()), mockContext);
secondItem->Attach(mockContext);
column->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(0.5, 3, 1, LayoutParam(Size(), Size()), mockContext);
thirdItem->Attach(mockContext);
column->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(0.0, 374.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(93.5, 1122.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(748, 374.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(748.0, 748.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(561.0, 1122));
EXPECT_TRUE(column->GetLayoutSize() == Size(748.0, 2244.0));
}
/**
* @tc.name: FlexWeight006
* @tc.desc: Verify the row component with 3 different weight and constraint children works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAJ
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight006, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_END);
row->Attach(mockContext);
root->AddChild(row);
LayoutParam constraint = LayoutParam(Size(1500.0, 500.0), Size(500.0, 100.0));
auto firstItem = FlexTestUtils::CreateMagicNode(1, 1, 1, constraint, mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, 2, 1, constraint, mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(1, 3, 3, constraint, mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 500.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(0.0, 500.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(0, 0.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(1080.0, 500));
EXPECT_TRUE(row->GetLayoutSize() == Size(1080.0, 500.0));
}
/**
* @tc.name: FlexWeight007
* @tc.desc: Verify the column component with 3 different weight and displayIndex children works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAK
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight007, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> column =
FlexTestUtils::CreateRenderFlex(FlexDirection::COLUMN, FlexAlign::FLEX_START, FlexAlign::FLEX_END);
column->Attach(mockContext);
root->AddChild(column);
LayoutParam constraint = LayoutParam(Size(150.0, 1200.0), Size(50.0, 500.0));
auto firstItem = FlexTestUtils::CreateMagicNode(0, 1, 3, constraint, mockContext);
firstItem->Attach(mockContext);
column->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, 2, 2, constraint, mockContext);
secondItem->Attach(mockContext);
column->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(0, 3, 1, constraint, mockContext);
thirdItem->Attach(mockContext);
column->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(50.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(0.0, 748.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(150.0, 1948.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(100.0, 748.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(150.0, 1200.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(column->GetLayoutSize() == Size(150.0, 2244.0));
}
/**
* @tc.name: FlexWeight008
* @tc.desc: Verify the row component in weight and stretch works fine.
* @tc.type: FUNC
* @tc.require: AR000F7J2H
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight008, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-stretch.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::STRETCH);
row->Attach(mockContext);
root->AddChild(row);
LayoutParam constraint = LayoutParam(Size(1500.0, 500.0), Size(500.0, 100.0));
auto firstItem = FlexTestUtils::CreateMagicNode(1, 5, 3, constraint, mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, 2, 1, constraint, mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(1, 3, 3, constraint, mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(675.0, 0.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(675, 0.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(675, 500.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(500.0, 500.0));
EXPECT_TRUE(row->GetLayoutSize() == Size(1080.0, 500.0));
}
/**
* @tc.name: FlexWeight009
* @tc.desc: Verify the column component with 3 different weight and stretch-mode works fine.
* @tc.type: FUNC
* @tc.require: AR000F7JGL
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight009, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, column are set as start-stretch.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::COLUMN, FlexAlign::FLEX_START, FlexAlign::STRETCH);
row->Attach(mockContext);
root->AddChild(row);
LayoutParam constraint = LayoutParam(Size(1500.0, 500.0), Size(500.0, 100.0));
auto firstItem = FlexTestUtils::CreateMagicNode(1, 1, 3, constraint, mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, 2, 1, constraint, mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(1, 3, 3, constraint, mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(0.0, 374.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(0, 874.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(500, 374.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(500.0, 500.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(500.0, 500));
EXPECT_TRUE(row->GetLayoutSize() == Size(500.0, 2244.0));
}
/**
* @tc.name: FlexWeight010
* @tc.desc: Verify the row component with illegal weight works fine.
* @tc.type: FUNC
* @tc.require: AR000F7JGL
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, FlexWeight010, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-stretch.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::STRETCH);
row->Attach(mockContext);
root->AddChild(row);
LayoutParam constraint = LayoutParam(Size(1500.0, 500.0), Size(500.0, 100.0));
auto firstItem = FlexTestUtils::CreateMagicNode(1, 0, 3, constraint, mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(1, -1, 1, constraint, mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(1, 3, 3, constraint, mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(500.0, 0.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(500, 0.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(500, 500.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(500.0, 500));
EXPECT_TRUE(row->GetLayoutSize() == Size(1080.0, 500.0));
}
/**
* @tc.name: DisplayIndexTest001
* @tc.desc: Verify the row component with 3 constrainted and displayIndex children with no aspect-ratio works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAI
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, DisplayIndexTest001, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_START);
row->Attach(mockContext);
root->AddChild(row);
LayoutParam constraint = LayoutParam(Size(1000.0, 1000.0), Size(500.0, 500.0));
auto firstItem = FlexTestUtils::CreateMagicNode(0, 0, 3, constraint, mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(0, 0, 2, constraint, mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(0, 0, 1, constraint, mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(500.0, 0.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(1000, 0.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(500.0, 500.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(500.0, 500.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(row->GetLayoutSize() == Size(1080.0, 500.0));
}
/**
* @tc.name: DisplayIndexTest002
* @tc.desc: Verify the row component with 3 constrainted and displayIndex children with aspect-ratio works fine.
* @tc.type: FUNC
* @tc.require: AR000F3BAS
* @tc.author: yangfan
*/
HWTEST_F(RenderMagicLayoutTest, DisplayIndexTest002, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the RenderNode tree, row are set as start-start.
*/
auto mockContext = MockRenderCommon::GetMockContext();
RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot();
RefPtr<RenderFlex> row =
FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::STRETCH);
row->Attach(mockContext);
root->AddChild(row);
LayoutParam constraint = LayoutParam(Size(1000.0, 1000.0), Size(500.0, 500.0));
auto firstItem = FlexTestUtils::CreateMagicNode(2, 0, 3, constraint, mockContext);
firstItem->Attach(mockContext);
row->AddChild(firstItem);
auto secondItem = FlexTestUtils::CreateMagicNode(2, 0, 2, constraint, mockContext);
secondItem->Attach(mockContext);
row->AddChild(secondItem);
auto thirdItem = FlexTestUtils::CreateMagicNode(1.5, 0, 1, constraint, mockContext);
thirdItem->Attach(mockContext);
row->AddChild(thirdItem);
/**
* @tc.steps: step2. call PerformLayout interface
* @tc.expected: step2. the positions of three boxes are set correctly
*/
root->PerformLayout();
EXPECT_TRUE(firstItem->GetPosition() == Offset(0.0, 0.0));
EXPECT_TRUE(secondItem->GetPosition() == Offset(1000.0, 0.0));
EXPECT_TRUE(thirdItem->GetPosition() == Offset(1000, 0.0));
EXPECT_TRUE(firstItem->GetLayoutSize() == Size(1000.0, 500.0));
EXPECT_TRUE(secondItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(thirdItem->GetLayoutSize() == Size(0.0, 0.0));
EXPECT_TRUE(row->GetLayoutSize() == Size(1080.0, 500.0));
}
} // namespace OHOS::Ace | [
"mamingshuai1@huawei.com"
] | mamingshuai1@huawei.com |
b3396c32290fbad69442b1969398b7a1f890e99c | 713f1df3ae1c1823127d3005996a69331baa0aa9 | /UnrealPyEmbed/Source/UnrealPyEmbed_Python/Public/IUnrealPyEmbed_PythonModule.h | 8259186dba4c15bfe97f58b40311f474640d370d | [
"MIT"
] | permissive | nzavagli/UnrealPy | 4fca710fb3a149bfe49f0d23e47ea2de6d4f49e7 | 5cc10fb49c2809ed76b34474e2a00c411e4617d1 | refs/heads/master | 2021-01-17T22:29:30.708990 | 2015-12-01T07:24:25 | 2015-12-01T07:24:25 | 47,168,375 | 0 | 0 | null | 2015-12-01T05:44:51 | 2015-12-01T05:44:51 | null | UTF-8 | C++ | false | false | 390 | h |
#pragma once
#include "ModuleManager.h"
class IUnrealPyEmbed_PythonModule : public IModuleInterface
{
public:
static inline IUnrealPyEmbed_PythonModule& Get()
{
return FModuleManager::LoadModuleChecked< IUnrealPyEmbed_PythonModule >( "UnrealPyEmbed_Python" );
}
static inline bool IsAvailable()
{
return FModuleManager::Get().IsModuleLoaded( "UnrealPyEmbed_Python" );
}
};
| [
"tobias@mollstam.com"
] | tobias@mollstam.com |
b1ed78cea98353dfe49d14c821ee59cfc12d7ccc | 4dc3536eedd35ce7fdfe5c60a37bb75b53a219d4 | /lib/ntldd.cpp | ccd541da30c7756b102d14fb5603927d0caf9d15 | [] | no_license | rtzbyte/c-utils | 352e5503148684d7613f1c50ea4571bb2be232ca | 7eb40f88dd51dd798e2742e5556a9dfb3f7a5fa4 | refs/heads/master | 2022-12-03T20:43:13.739653 | 2020-08-24T23:30:18 | 2020-08-24T23:30:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
WINAPI
WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
try {
Application->Initialize();
Application->Title = "ntldd";
Application->Run();
} catch(Exception& exception) {
Application->ShowException(&exception);
} catch(...) {
try {
throw Exception("");
} catch(Exception& exception) {
Application->ShowException(&exception);
}
}
return 0;
}
//---------------------------------------------------------------------------
| [
"roman.l.senn@gmail.com"
] | roman.l.senn@gmail.com |
18a5ed02587f6c98b11dd10f5ca4c4510375d1d3 | 3438e8c139a5833836a91140af412311aebf9e86 | /components/autofill/core/browser/autofill_manager_unittest.cc | 76d8e853b03fa5c0d503e64c92e5c92c15e9802d | [
"BSD-3-Clause"
] | permissive | Exstream-OpenSource/Chromium | 345b4336b2fbc1d5609ac5a67dbf361812b84f54 | 718ca933938a85c6d5548c5fad97ea7ca1128751 | refs/heads/master | 2022-12-21T20:07:40.786370 | 2016-10-18T04:53:43 | 2016-10-18T04:53:43 | 71,210,435 | 0 | 2 | BSD-3-Clause | 2022-12-18T12:14:22 | 2016-10-18T04:58:13 | null | UTF-8 | C++ | false | false | 212,223 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/core/browser/autofill_manager.h"
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <vector>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/format_macros.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_vector.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/autocomplete_history_manager.h"
#include "components/autofill/core/browser/autofill_download_manager.h"
#include "components/autofill/core/browser/autofill_experiments.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/credit_card.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/popup_item_ids.h"
#include "components/autofill/core/browser/test_autofill_client.h"
#include "components/autofill/core/browser/test_autofill_driver.h"
#include "components/autofill/core/browser/test_autofill_external_delegate.h"
#include "components/autofill/core/browser/validation.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/autofill/core/common/autofill_pref_names.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/autofill/core/common/autofill_util.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/prefs/pref_service.h"
#include "components/rappor/test_rappor_service.h"
#include "components/variations/variations_associated_data.h"
#include "grit/components_strings.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/rect.h"
#include "url/gurl.h"
using base::ASCIIToUTF16;
using base::UTF8ToUTF16;
using testing::_;
using testing::AtLeast;
using testing::SaveArg;
namespace autofill {
namespace {
const int kDefaultPageID = 137;
class MockAutofillClient : public TestAutofillClient {
public:
MockAutofillClient() {}
~MockAutofillClient() override {}
MOCK_METHOD2(ConfirmSaveCreditCardLocally,
void(const CreditCard& card, const base::Closure& callback));
MOCK_METHOD0(ShouldShowSigninPromo, bool());
private:
DISALLOW_COPY_AND_ASSIGN(MockAutofillClient);
};
class TestPaymentsClient : public payments::PaymentsClient {
public:
TestPaymentsClient(net::URLRequestContextGetter* context_getter,
payments::PaymentsClientDelegate* delegate)
: PaymentsClient(context_getter, delegate), delegate_(delegate) {}
~TestPaymentsClient() override {}
void GetUploadDetails(const std::vector<AutofillProfile>& addresses,
const std::string& app_locale) override {
delegate_->OnDidGetUploadDetails(
app_locale == "en-US" ? AutofillClient::SUCCESS
: AutofillClient::PERMANENT_FAILURE,
ASCIIToUTF16("this is a context token"),
std::unique_ptr<base::DictionaryValue>(nullptr));
}
void UploadCard(const payments::PaymentsClient::UploadRequestDetails&
request_details) override {
delegate_->OnDidUploadCard(AutofillClient::SUCCESS);
}
private:
payments::PaymentsClientDelegate* const delegate_;
DISALLOW_COPY_AND_ASSIGN(TestPaymentsClient);
};
class TestPersonalDataManager : public PersonalDataManager {
public:
TestPersonalDataManager()
: PersonalDataManager("en-US"),
num_times_save_imported_profile_called_(0) {
CreateTestAutofillProfiles(&web_profiles_);
CreateTestCreditCards(&local_credit_cards_);
}
using PersonalDataManager::set_database;
using PersonalDataManager::SetPrefService;
int num_times_save_imported_profile_called() {
return num_times_save_imported_profile_called_;
}
std::string SaveImportedProfile(const AutofillProfile& profile) override {
num_times_save_imported_profile_called_++;
AutofillProfile* imported_profile = new AutofillProfile(profile);
AddProfile(imported_profile);
return profile.guid();
}
AutofillProfile* GetProfileWithGUID(const char* guid) {
for (AutofillProfile* profile : GetProfiles()) {
if (!profile->guid().compare(guid))
return profile;
}
return NULL;
}
CreditCard* GetCreditCardWithGUID(const char* guid) {
for (CreditCard* card : GetCreditCards()) {
if (!card->guid().compare(guid))
return card;
}
return NULL;
}
void AddProfile(AutofillProfile* profile) {
profile->set_modification_date(base::Time::Now());
web_profiles_.push_back(profile);
}
void AddCreditCard(CreditCard* credit_card) {
credit_card->set_modification_date(base::Time::Now());
local_credit_cards_.push_back(credit_card);
}
void RecordUseOf(const AutofillDataModel& data_model) override {
CreditCard* credit_card = GetCreditCardWithGUID(data_model.guid().c_str());
if (credit_card)
credit_card->RecordAndLogUse();
AutofillProfile* profile = GetProfileWithGUID(data_model.guid().c_str());
if (profile)
profile->RecordAndLogUse();
}
void RemoveByGUID(const std::string& guid) override {
CreditCard* credit_card = GetCreditCardWithGUID(guid.c_str());
if (credit_card) {
local_credit_cards_.erase(
std::find(local_credit_cards_.begin(), local_credit_cards_.end(),
credit_card));
}
AutofillProfile* profile = GetProfileWithGUID(guid.c_str());
if (profile) {
web_profiles_.erase(
std::find(web_profiles_.begin(), web_profiles_.end(), profile));
}
}
void ClearAutofillProfiles() {
web_profiles_.clear();
}
void ClearCreditCards() {
local_credit_cards_.clear();
}
// Create Elvis card with whitespace in the credit card number.
void CreateTestCreditCardWithWhitespace() {
ClearCreditCards();
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Elvis Presley",
"4234 5678 9012 3456", // Visa
"04", "2999");
credit_card->set_guid("00000000-0000-0000-0000-000000000008");
local_credit_cards_.push_back(credit_card);
}
// Create Elvis card with separator characters in the credit card number.
void CreateTestCreditCardWithSeparators() {
ClearCreditCards();
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Elvis Presley",
"4234-5678-9012-3456", // Visa
"04", "2999");
credit_card->set_guid("00000000-0000-0000-0000-000000000009");
local_credit_cards_.push_back(credit_card);
}
void CreateTestCreditCardsYearAndMonth(const char* year, const char* month) {
ClearCreditCards();
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Miku Hatsune",
"4234567890654321", // Visa
month, year);
credit_card->set_guid("00000000-0000-0000-0000-000000000007");
local_credit_cards_.push_back(credit_card);
}
void CreateTestExpiredCreditCard() {
ClearCreditCards();
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Homer Simpson",
"4234567890654321", // Visa
"05", "2000");
credit_card->set_guid("00000000-0000-0000-0000-000000000009");
local_credit_cards_.push_back(credit_card);
}
private:
void CreateTestAutofillProfiles(ScopedVector<AutofillProfile>* profiles) {
AutofillProfile* profile = new AutofillProfile;
test::SetProfileInfo(profile, "Elvis", "Aaron",
"Presley", "theking@gmail.com", "RCA",
"3734 Elvis Presley Blvd.", "Apt. 10",
"Memphis", "Tennessee", "38116", "US",
"12345678901");
profile->set_guid("00000000-0000-0000-0000-000000000001");
profiles->push_back(profile);
profile = new AutofillProfile;
test::SetProfileInfo(profile, "Charles", "Hardin",
"Holley", "buddy@gmail.com", "Decca",
"123 Apple St.", "unit 6", "Lubbock",
"Texas", "79401", "US", "23456789012");
profile->set_guid("00000000-0000-0000-0000-000000000002");
profiles->push_back(profile);
profile = new AutofillProfile;
test::SetProfileInfo(
profile, "", "", "", "", "", "", "", "", "", "", "", "");
profile->set_guid("00000000-0000-0000-0000-000000000003");
profiles->push_back(profile);
}
void CreateTestCreditCards(ScopedVector<CreditCard>* credit_cards) {
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Elvis Presley",
"4234567890123456", // Visa
"04", "2999");
credit_card->set_guid("00000000-0000-0000-0000-000000000004");
credit_card->set_use_count(10);
credit_card->set_use_date(base::Time::Now() - base::TimeDelta::FromDays(5));
credit_cards->push_back(credit_card);
credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Buddy Holly",
"5187654321098765", // Mastercard
"10", "2998");
credit_card->set_guid("00000000-0000-0000-0000-000000000005");
credit_card->set_use_count(5);
credit_card->set_use_date(base::Time::Now() - base::TimeDelta::FromDays(4));
credit_cards->push_back(credit_card);
credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "", "", "", "");
credit_card->set_guid("00000000-0000-0000-0000-000000000006");
credit_cards->push_back(credit_card);
}
size_t num_times_save_imported_profile_called_;
DISALLOW_COPY_AND_ASSIGN(TestPersonalDataManager);
};
class TestAutofillDownloadManager : public AutofillDownloadManager {
public:
TestAutofillDownloadManager(AutofillDriver* driver,
AutofillDownloadManager::Observer* observer)
: AutofillDownloadManager(driver, observer) {}
bool StartQueryRequest(const std::vector<FormStructure*>& forms) override {
last_queried_forms_ = forms;
return true;
}
// Verify that the last queried forms equal |expected_forms|.
void VerifyLastQueriedForms(const std::vector<FormData>& expected_forms) {
ASSERT_EQ(expected_forms.size(), last_queried_forms_.size());
for (size_t i = 0; i < expected_forms.size(); ++i) {
EXPECT_EQ(*last_queried_forms_[i], expected_forms[i]);
}
}
private:
std::vector<FormStructure*> last_queried_forms_;
DISALLOW_COPY_AND_ASSIGN(TestAutofillDownloadManager);
};
void ExpectFilledField(const char* expected_label,
const char* expected_name,
const char* expected_value,
const char* expected_form_control_type,
const FormFieldData& field) {
SCOPED_TRACE(expected_label);
EXPECT_EQ(UTF8ToUTF16(expected_label), field.label);
EXPECT_EQ(UTF8ToUTF16(expected_name), field.name);
EXPECT_EQ(UTF8ToUTF16(expected_value), field.value);
EXPECT_EQ(expected_form_control_type, field.form_control_type);
}
// Verifies that the |filled_form| has been filled with the given data.
// Verifies address fields if |has_address_fields| is true, and verifies
// credit card fields if |has_credit_card_fields| is true. Verifies both if both
// are true. |use_month_type| is used for credit card input month type.
void ExpectFilledForm(int page_id,
const FormData& filled_form,
int expected_page_id,
const char* first,
const char* middle,
const char* last,
const char* address1,
const char* address2,
const char* city,
const char* state,
const char* postal_code,
const char* country,
const char* phone,
const char* email,
const char* name_on_card,
const char* card_number,
const char* expiration_month,
const char* expiration_year,
bool has_address_fields,
bool has_credit_card_fields,
bool use_month_type) {
// The number of fields in the address and credit card forms created above.
const size_t kAddressFormSize = 11;
const size_t kCreditCardFormSize = use_month_type ? 4 : 5;
EXPECT_EQ(expected_page_id, page_id);
EXPECT_EQ(ASCIIToUTF16("MyForm"), filled_form.name);
if (has_credit_card_fields) {
EXPECT_EQ(GURL("https://myform.com/form.html"), filled_form.origin);
EXPECT_EQ(GURL("https://myform.com/submit.html"), filled_form.action);
} else {
EXPECT_EQ(GURL("http://myform.com/form.html"), filled_form.origin);
EXPECT_EQ(GURL("http://myform.com/submit.html"), filled_form.action);
}
size_t form_size = 0;
if (has_address_fields)
form_size += kAddressFormSize;
if (has_credit_card_fields)
form_size += kCreditCardFormSize;
ASSERT_EQ(form_size, filled_form.fields.size());
if (has_address_fields) {
ExpectFilledField("First Name", "firstname", first, "text",
filled_form.fields[0]);
ExpectFilledField("Middle Name", "middlename", middle, "text",
filled_form.fields[1]);
ExpectFilledField("Last Name", "lastname", last, "text",
filled_form.fields[2]);
ExpectFilledField("Address Line 1", "addr1", address1, "text",
filled_form.fields[3]);
ExpectFilledField("Address Line 2", "addr2", address2, "text",
filled_form.fields[4]);
ExpectFilledField("City", "city", city, "text",
filled_form.fields[5]);
ExpectFilledField("State", "state", state, "text",
filled_form.fields[6]);
ExpectFilledField("Postal Code", "zipcode", postal_code, "text",
filled_form.fields[7]);
ExpectFilledField("Country", "country", country, "text",
filled_form.fields[8]);
ExpectFilledField("Phone Number", "phonenumber", phone, "tel",
filled_form.fields[9]);
ExpectFilledField("Email", "email", email, "email",
filled_form.fields[10]);
}
if (has_credit_card_fields) {
size_t offset = has_address_fields? kAddressFormSize : 0;
ExpectFilledField("Name on Card", "nameoncard", name_on_card, "text",
filled_form.fields[offset + 0]);
ExpectFilledField("Card Number", "cardnumber", card_number, "text",
filled_form.fields[offset + 1]);
if (use_month_type) {
std::string exp_year = expiration_year;
std::string exp_month = expiration_month;
std::string date;
if (!exp_year.empty() && !exp_month.empty())
date = exp_year + "-" + exp_month;
ExpectFilledField("Expiration Date", "ccmonth", date.c_str(), "month",
filled_form.fields[offset + 2]);
} else {
ExpectFilledField("Expiration Date", "ccmonth", expiration_month, "text",
filled_form.fields[offset + 2]);
ExpectFilledField("", "ccyear", expiration_year, "text",
filled_form.fields[offset + 3]);
}
}
}
void ExpectFilledAddressFormElvis(int page_id,
const FormData& filled_form,
int expected_page_id,
bool has_credit_card_fields) {
ExpectFilledForm(page_id, filled_form, expected_page_id, "Elvis", "Aaron",
"Presley", "3734 Elvis Presley Blvd.", "Apt. 10", "Memphis",
"Tennessee", "38116", "United States", "12345678901",
"theking@gmail.com", "", "", "", "", true,
has_credit_card_fields, false);
}
void ExpectFilledCreditCardFormElvis(int page_id,
const FormData& filled_form,
int expected_page_id,
bool has_address_fields) {
ExpectFilledForm(page_id, filled_form, expected_page_id, "", "", "", "", "",
"", "", "", "", "", "", "Elvis Presley", "4234567890123456",
"04", "2999", has_address_fields, true, false);
}
void ExpectFilledCreditCardYearMonthWithYearMonth(int page_id,
const FormData& filled_form,
int expected_page_id,
bool has_address_fields,
const char* year,
const char* month) {
ExpectFilledForm(page_id, filled_form, expected_page_id, "", "", "", "", "",
"", "", "", "", "", "", "Miku Hatsune", "4234567890654321",
month, year, has_address_fields, true, true);
}
class MockAutocompleteHistoryManager : public AutocompleteHistoryManager {
public:
MockAutocompleteHistoryManager(AutofillDriver* driver, AutofillClient* client)
: AutocompleteHistoryManager(driver, client) {}
MOCK_METHOD4(OnGetAutocompleteSuggestions, void(
int query_id,
const base::string16& name,
const base::string16& prefix,
const std::string& form_control_type));
MOCK_METHOD1(OnWillSubmitForm, void(const FormData& form));
private:
DISALLOW_COPY_AND_ASSIGN(MockAutocompleteHistoryManager);
};
class MockAutofillDriver : public TestAutofillDriver {
public:
MockAutofillDriver() : is_off_the_record_(false) {}
// Mock methods to enable testability.
MOCK_METHOD3(SendFormDataToRenderer, void(int query_id,
RendererFormDataAction action,
const FormData& data));
void SetIsOffTheRecord(bool is_off_the_record) {
is_off_the_record_ = is_off_the_record;
}
bool IsOffTheRecord() const override { return is_off_the_record_; }
private:
bool is_off_the_record_;
DISALLOW_COPY_AND_ASSIGN(MockAutofillDriver);
};
class TestAutofillManager : public AutofillManager {
public:
TestAutofillManager(AutofillDriver* driver,
AutofillClient* client,
TestPersonalDataManager* personal_data)
: AutofillManager(driver, client, personal_data),
personal_data_(personal_data),
autofill_enabled_(true),
credit_card_upload_enabled_(false),
credit_card_was_uploaded_(false),
expected_observed_submission_(true) {
set_payments_client(
new TestPaymentsClient(driver->GetURLRequestContext(), this));
}
~TestAutofillManager() override {}
bool IsAutofillEnabled() const override { return autofill_enabled_; }
void set_autofill_enabled(bool autofill_enabled) {
autofill_enabled_ = autofill_enabled;
}
bool IsCreditCardUploadEnabled() override {
return credit_card_upload_enabled_;
}
void set_credit_card_upload_enabled(bool credit_card_upload_enabled) {
credit_card_upload_enabled_ = credit_card_upload_enabled;
}
bool credit_card_was_uploaded() { return credit_card_was_uploaded_; }
void set_expected_submitted_field_types(
const std::vector<ServerFieldTypeSet>& expected_types) {
expected_submitted_field_types_ = expected_types;
}
void set_expected_observed_submission(bool expected) {
expected_observed_submission_ = expected;
}
void UploadFormDataAsyncCallback(const FormStructure* submitted_form,
const base::TimeTicks& load_time,
const base::TimeTicks& interaction_time,
const base::TimeTicks& submission_time,
bool observed_submission) override {
run_loop_->Quit();
EXPECT_EQ(expected_observed_submission_, observed_submission);
// If we have expected field types set, make sure they match.
if (!expected_submitted_field_types_.empty()) {
ASSERT_EQ(expected_submitted_field_types_.size(),
submitted_form->field_count());
for (size_t i = 0; i < expected_submitted_field_types_.size(); ++i) {
SCOPED_TRACE(
base::StringPrintf(
"Field %d with value %s", static_cast<int>(i),
base::UTF16ToUTF8(submitted_form->field(i)->value).c_str()));
const ServerFieldTypeSet& possible_types =
submitted_form->field(i)->possible_types();
EXPECT_EQ(expected_submitted_field_types_[i].size(),
possible_types.size());
for (ServerFieldTypeSet::const_iterator it =
expected_submitted_field_types_[i].begin();
it != expected_submitted_field_types_[i].end(); ++it) {
EXPECT_TRUE(possible_types.count(*it))
<< "Expected type: " << AutofillType(*it).ToString();
}
}
}
AutofillManager::UploadFormDataAsyncCallback(
submitted_form, load_time, interaction_time, submission_time,
observed_submission);
}
// Resets the run loop so that it can wait for an asynchronous form
// submission to complete.
void ResetRunLoop() { run_loop_.reset(new base::RunLoop()); }
// Wait for the asynchronous calls within StartUploadProcess() to complete.
void WaitForAsyncUploadProcess() { run_loop_->Run(); }
void UploadFormData(const FormStructure& submitted_form,
bool observed_submission) override {
submitted_form_signature_ = submitted_form.FormSignatureAsStr();
}
const std::string GetSubmittedFormSignature() {
return submitted_form_signature_;
}
AutofillProfile* GetProfileWithGUID(const char* guid) {
return personal_data_->GetProfileWithGUID(guid);
}
CreditCard* GetCreditCardWithGUID(const char* guid) {
return personal_data_->GetCreditCardWithGUID(guid);
}
void AddProfile(AutofillProfile* profile) {
personal_data_->AddProfile(profile);
}
void AddCreditCard(CreditCard* credit_card) {
personal_data_->AddCreditCard(credit_card);
}
int GetPackedCreditCardID(int credit_card_id) {
std::string credit_card_guid =
base::StringPrintf("00000000-0000-0000-0000-%012d", credit_card_id);
return MakeFrontendID(credit_card_guid, std::string());
}
void AddSeenForm(FormStructure* form) {
form_structures()->push_back(form);
}
void ClearFormStructures() {
form_structures()->clear();
}
private:
void OnDidUploadCard(AutofillClient::PaymentsRpcResult result) override {
credit_card_was_uploaded_ = true;
};
// Weak reference.
TestPersonalDataManager* personal_data_;
bool autofill_enabled_;
bool credit_card_upload_enabled_;
bool credit_card_was_uploaded_;
bool expected_observed_submission_;
std::unique_ptr<base::RunLoop> run_loop_;
std::string submitted_form_signature_;
std::vector<ServerFieldTypeSet> expected_submitted_field_types_;
DISALLOW_COPY_AND_ASSIGN(TestAutofillManager);
};
class TestAutofillExternalDelegate : public AutofillExternalDelegate {
public:
explicit TestAutofillExternalDelegate(AutofillManager* autofill_manager,
AutofillDriver* autofill_driver)
: AutofillExternalDelegate(autofill_manager, autofill_driver),
on_query_seen_(false),
on_suggestions_returned_seen_(false) {}
~TestAutofillExternalDelegate() override {}
void OnQuery(int query_id,
const FormData& form,
const FormFieldData& field,
const gfx::RectF& bounds) override {
on_query_seen_ = true;
on_suggestions_returned_seen_ = false;
}
void OnSuggestionsReturned(
int query_id,
const std::vector<Suggestion>& suggestions) override {
on_suggestions_returned_seen_ = true;
query_id_ = query_id;
suggestions_ = suggestions;
}
void CheckSuggestions(int expected_page_id,
size_t expected_num_suggestions,
const Suggestion expected_suggestions[]) {
// Ensure that these results are from the most recent query.
EXPECT_TRUE(on_suggestions_returned_seen_);
EXPECT_EQ(expected_page_id, query_id_);
ASSERT_EQ(expected_num_suggestions, suggestions_.size());
for (size_t i = 0; i < expected_num_suggestions; ++i) {
SCOPED_TRACE(base::StringPrintf("i: %" PRIuS, i));
EXPECT_EQ(expected_suggestions[i].value, suggestions_[i].value);
EXPECT_EQ(expected_suggestions[i].label, suggestions_[i].label);
EXPECT_EQ(expected_suggestions[i].icon, suggestions_[i].icon);
EXPECT_EQ(expected_suggestions[i].frontend_id,
suggestions_[i].frontend_id);
}
}
// Wrappers around the above GetSuggestions call that take a hardcoded number
// of expected results so callsites are cleaner.
void CheckSuggestions(int expected_page_id,
const Suggestion& suggestion0) {
std::vector<Suggestion> suggestion_vector;
suggestion_vector.push_back(suggestion0);
CheckSuggestions(expected_page_id, 1, &suggestion_vector[0]);
}
void CheckSuggestions(int expected_page_id,
const Suggestion& suggestion0,
const Suggestion& suggestion1) {
std::vector<Suggestion> suggestion_vector;
suggestion_vector.push_back(suggestion0);
suggestion_vector.push_back(suggestion1);
CheckSuggestions(expected_page_id, 2, &suggestion_vector[0]);
}
void CheckSuggestions(int expected_page_id,
const Suggestion& suggestion0,
const Suggestion& suggestion1,
const Suggestion& suggestion2) {
std::vector<Suggestion> suggestion_vector;
suggestion_vector.push_back(suggestion0);
suggestion_vector.push_back(suggestion1);
suggestion_vector.push_back(suggestion2);
CheckSuggestions(expected_page_id, 3, &suggestion_vector[0]);
}
// Check that the autofill suggestions were sent, and that they match a page
// but contain no results.
void CheckNoSuggestions(int expected_page_id) {
CheckSuggestions(expected_page_id, 0, nullptr);
}
// Check that the autofill suggestions were sent, and that they match a page
// and contain a specific number of suggestions.
void CheckSuggestionCount(int expected_page_id,
size_t expected_num_suggestions) {
// Ensure that these results are from the most recent query.
EXPECT_TRUE(on_suggestions_returned_seen_);
EXPECT_EQ(expected_page_id, query_id_);
ASSERT_EQ(expected_num_suggestions, suggestions_.size());
}
bool on_query_seen() const {
return on_query_seen_;
}
bool on_suggestions_returned_seen() const {
return on_suggestions_returned_seen_;
}
private:
// Records if OnQuery has been called yet.
bool on_query_seen_;
// Records if OnSuggestionsReturned has been called after the most recent
// call to OnQuery.
bool on_suggestions_returned_seen_;
// The query id of the most recent Autofill query.
int query_id_;
// The results returned by the most recent Autofill query.
std::vector<Suggestion> suggestions_;
DISALLOW_COPY_AND_ASSIGN(TestAutofillExternalDelegate);
};
} // namespace
class AutofillManagerTest : public testing::Test {
public:
AutofillManagerTest() : field_trial_list_(nullptr) {}
void SetUp() override {
autofill_client_.SetPrefs(test::PrefServiceForTesting());
personal_data_.set_database(autofill_client_.GetDatabase());
personal_data_.SetPrefService(autofill_client_.GetPrefs());
autofill_driver_.reset(new MockAutofillDriver());
request_context_ = new net::TestURLRequestContextGetter(
base::ThreadTaskRunnerHandle::Get());
autofill_driver_->SetURLRequestContext(request_context_.get());
autofill_manager_.reset(new TestAutofillManager(
autofill_driver_.get(), &autofill_client_, &personal_data_));
download_manager_ = new TestAutofillDownloadManager(
autofill_driver_.get(), autofill_manager_.get());
// AutofillManager takes ownership of |download_manager_|.
autofill_manager_->set_download_manager(download_manager_);
external_delegate_.reset(new TestAutofillExternalDelegate(
autofill_manager_.get(),
autofill_driver_.get()));
autofill_manager_->SetExternalDelegate(external_delegate_.get());
// Clear all the things.
variations::testing::ClearAllVariationParams();
}
void TearDown() override {
// Order of destruction is important as AutofillManager relies on
// PersonalDataManager to be around when it gets destroyed.
autofill_manager_.reset();
autofill_driver_.reset();
// Remove the AutofillWebDataService so TestPersonalDataManager does not
// need to care about removing self as an observer in destruction.
personal_data_.set_database(scoped_refptr<AutofillWebDataService>(NULL));
personal_data_.SetPrefService(NULL);
request_context_ = nullptr;
}
void EnableCreditCardSigninPromoFeatureWithLimit(int impression_limit) {
const std::string kTrialName = "MyTrial";
const std::string kGroupName = "Group1";
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::CreateFieldTrial(kTrialName, kGroupName));
std::map<std::string, std::string> params;
params[kCreditCardSigninPromoImpressionLimitParamKey] =
base::IntToString(impression_limit);
ASSERT_TRUE(
variations::AssociateVariationParams(kTrialName, kGroupName, params));
// Enable the feature.
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->RegisterFieldTrialOverride(
kAutofillCreditCardSigninPromo.name,
base::FeatureList::OVERRIDE_ENABLE_FEATURE, trial.get());
scoped_feature_list_.InitWithFeatureList(std::move(feature_list));
// Double-checking our params made it.
std::map<std::string, std::string> actualParams;
EXPECT_TRUE(variations::GetVariationParamsByFeature(
kAutofillCreditCardSigninPromo, &actualParams));
EXPECT_EQ(params, actualParams);
}
void GetAutofillSuggestions(int query_id,
const FormData& form,
const FormFieldData& field) {
autofill_manager_->OnQueryFormFieldAutofill(query_id, form, field,
gfx::RectF());
}
void GetAutofillSuggestions(const FormData& form,
const FormFieldData& field) {
GetAutofillSuggestions(kDefaultPageID, form, field);
}
void AutocompleteSuggestionsReturned(
const std::vector<base::string16>& result) {
autofill_manager_->autocomplete_history_manager_->SendSuggestions(&result);
}
void FormsSeen(const std::vector<FormData>& forms) {
autofill_manager_->OnFormsSeen(forms, base::TimeTicks());
}
void FormSubmitted(const FormData& form) {
autofill_manager_->ResetRunLoop();
if (autofill_manager_->OnWillSubmitForm(form, base::TimeTicks::Now()))
autofill_manager_->WaitForAsyncUploadProcess();
autofill_manager_->OnFormSubmitted(form);
}
void FillAutofillFormData(int query_id,
const FormData& form,
const FormFieldData& field,
int unique_id) {
autofill_manager_->FillOrPreviewForm(
AutofillDriver::FORM_DATA_ACTION_FILL, query_id, form, field,
unique_id);
}
// Calls |autofill_manager_->OnFillAutofillFormData()| with the specified
// input parameters after setting up the expectation that the mock driver's
// |SendFormDataToRenderer()| method will be called and saving the parameters
// of that call into the |response_query_id| and |response_data| output
// parameters.
void FillAutofillFormDataAndSaveResults(int input_query_id,
const FormData& input_form,
const FormFieldData& input_field,
int unique_id,
int* response_query_id,
FormData* response_data) {
EXPECT_CALL(*autofill_driver_, SendFormDataToRenderer(_, _, _)).
WillOnce((DoAll(testing::SaveArg<0>(response_query_id),
testing::SaveArg<2>(response_data))));
FillAutofillFormData(input_query_id, input_form, input_field, unique_id);
}
int MakeFrontendID(const std::string& cc_sid,
const std::string& profile_sid) const {
return autofill_manager_->MakeFrontendID(cc_sid, profile_sid);
}
bool WillFillCreditCardNumber(const FormData& form,
const FormFieldData& field) {
return autofill_manager_->WillFillCreditCardNumber(form, field);
}
// Populates |form| with data corresponding to a simple credit card form.
// Note that this actually appends fields to the form data, which can be
// useful for building up more complex test forms.
void CreateTestCreditCardFormData(FormData* form,
bool is_https,
bool use_month_type) {
form->name = ASCIIToUTF16("MyForm");
if (is_https) {
form->origin = GURL("https://myform.com/form.html");
form->action = GURL("https://myform.com/submit.html");
} else {
form->origin = GURL("http://myform.com/form.html");
form->action = GURL("http://myform.com/submit.html");
}
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
form->fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
form->fields.push_back(field);
if (use_month_type) {
test::CreateTestFormField(
"Expiration Date", "ccmonth", "", "month", &field);
form->fields.push_back(field);
} else {
test::CreateTestFormField("Expiration Date", "ccmonth", "", "text",
&field);
form->fields.push_back(field);
test::CreateTestFormField("", "ccyear", "", "text", &field);
form->fields.push_back(field);
}
test::CreateTestFormField("CVC", "cvc", "", "text", &field);
form->fields.push_back(field);
}
// Fills the fields in |form| with test data.
void ManuallyFillAddressForm(const char* first_name,
const char* last_name,
const char* zip_code,
const char* country,
FormData* form) {
for (FormFieldData& field : form->fields) {
if (base::EqualsASCII(field.name, "firstname"))
field.value = ASCIIToUTF16(first_name);
else if (base::EqualsASCII(field.name, "lastname"))
field.value = ASCIIToUTF16(last_name);
else if (base::EqualsASCII(field.name, "addr1"))
field.value = ASCIIToUTF16("123 Maple");
else if (base::EqualsASCII(field.name, "city"))
field.value = ASCIIToUTF16("Dallas");
else if (base::EqualsASCII(field.name, "state"))
field.value = ASCIIToUTF16("Texas");
else if (base::EqualsASCII(field.name, "zipcode"))
field.value = ASCIIToUTF16(zip_code);
else if (base::EqualsASCII(field.name, "country"))
field.value = ASCIIToUTF16(country);
}
}
// Tests if credit card data gets saved.
void TestSaveCreditCards(bool is_https) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, is_https, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Edit the data, and submit.
form.fields[1].value = ASCIIToUTF16("4111111111111111");
form.fields[2].value = ASCIIToUTF16("11");
form.fields[3].value = ASCIIToUTF16("2017");
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(form);
}
void PrepareForRealPanResponse(FormData* form, CreditCard* card) {
// This line silences the warning from PaymentsClient about matching sync
// and Payments server types.
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
"sync-url", "https://google.com");
CreateTestCreditCardFormData(form, true, false);
FormsSeen(std::vector<FormData>(1, *form));
*card = CreditCard(CreditCard::MASKED_SERVER_CARD, "a123");
test::SetCreditCardInfo(card, "John Dillinger", "1881" /* Visa */, "01",
"2017");
card->SetTypeForMaskedCard(kVisaCard);
EXPECT_CALL(*autofill_driver_, SendFormDataToRenderer(_, _, _))
.Times(AtLeast(1));
autofill_manager_->FillOrPreviewCreditCardForm(
AutofillDriver::FORM_DATA_ACTION_FILL, kDefaultPageID, *form,
form->fields[0], *card);
}
// Convenience method for using and retrieving a mock autocomplete history
// manager.
MockAutocompleteHistoryManager* RecreateMockAutocompleteHistoryManager() {
MockAutocompleteHistoryManager* manager = new
MockAutocompleteHistoryManager(autofill_driver_.get(),
autofill_manager_->client());
autofill_manager_->autocomplete_history_manager_.reset(manager);
return manager;
}
// Convenience method to cast the FullCardRequest into a CardUnmaskDelegate.
CardUnmaskDelegate* full_card_unmask_delegate() {
DCHECK(autofill_manager_->full_card_request_);
return static_cast<CardUnmaskDelegate*>(
autofill_manager_->full_card_request_.get());
}
protected:
base::MessageLoop message_loop_;
MockAutofillClient autofill_client_;
std::unique_ptr<MockAutofillDriver> autofill_driver_;
std::unique_ptr<TestAutofillManager> autofill_manager_;
std::unique_ptr<TestAutofillExternalDelegate> external_delegate_;
scoped_refptr<net::TestURLRequestContextGetter> request_context_;
TestPaymentsClient* payments_client_;
TestAutofillDownloadManager* download_manager_;
TestPersonalDataManager personal_data_;
base::FieldTrialList field_trial_list_;
base::test::ScopedFeatureList scoped_feature_list_;
};
class TestFormStructure : public FormStructure {
public:
explicit TestFormStructure(const FormData& form)
: FormStructure(form) {}
~TestFormStructure() override {}
void SetFieldTypes(const std::vector<ServerFieldType>& heuristic_types,
const std::vector<ServerFieldType>& server_types) {
ASSERT_EQ(field_count(), heuristic_types.size());
ASSERT_EQ(field_count(), server_types.size());
for (size_t i = 0; i < field_count(); ++i) {
AutofillField* form_field = field(i);
ASSERT_TRUE(form_field);
form_field->set_heuristic_type(heuristic_types[i]);
form_field->set_server_type(server_types[i]);
}
UpdateAutofillCount();
}
private:
DISALLOW_COPY_AND_ASSIGN(TestFormStructure);
};
// Test that calling OnFormsSeen with an empty set of forms (such as when
// reloading a page or when the renderer processes a set of forms but detects
// no changes) does not load the forms again.
TEST_F(AutofillManagerTest, OnFormsSeen_Empty) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
base::HistogramTester histogram_tester;
FormsSeen(forms);
histogram_tester.ExpectUniqueSample(
"Autofill.UserHappiness", 0 /* FORMS_LOADED */, 1);
// No more forms, metric is not logged.
forms.clear();
FormsSeen(forms);
histogram_tester.ExpectUniqueSample(
"Autofill.UserHappiness", 0 /* FORMS_LOADED */, 1);
}
// Test that calling OnFormsSeen consecutively with a different set of forms
// will query for each separately.
TEST_F(AutofillManagerTest, OnFormsSeen_DifferentFormStructures) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
base::HistogramTester histogram_tester;
FormsSeen(forms);
histogram_tester.ExpectUniqueSample("Autofill.UserHappiness",
0 /* FORMS_LOADED */, 1);
download_manager_->VerifyLastQueriedForms(forms);
// Different form structure.
FormData form2;
form2.name = ASCIIToUTF16("MyForm");
form2.origin = GURL("https://myform.com/form.html");
form2.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
form2.fields.push_back(field);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
form2.fields.push_back(field);
test::CreateTestFormField("Email", "email", "", "text", &field);
form2.fields.push_back(field);
forms.clear();
forms.push_back(form2);
FormsSeen(forms);
histogram_tester.ExpectUniqueSample("Autofill.UserHappiness",
0 /* FORMS_LOADED */, 2);
download_manager_->VerifyLastQueriedForms(forms);
}
// Test that no autofill suggestions are returned for a field with an
// unrecognized autocomplete attribute.
TEST_F(AutofillManagerTest, GetProfileSuggestions_UnrecognizedAttribute) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
// Set a valid autocomplete attribute for the first name.
test::CreateTestFormField("First name", "firstname", "", "text", &field);
field.autocomplete_attribute = "given-name";
form.fields.push_back(field);
// Set no autocomplete attribute for the middle name.
test::CreateTestFormField("Middle name", "middle", "", "text", &field);
field.autocomplete_attribute = "";
form.fields.push_back(field);
// Set an unrecognized autocomplete attribute for the last name.
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
field.autocomplete_attribute = "unrecognized";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Ensure that autocomplete manager is not called for suggestions either.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0);
// Suggestions should be returned for the first two fields.
GetAutofillSuggestions(form, form.fields[0]);
external_delegate_->CheckSuggestionCount(kDefaultPageID, 2);
GetAutofillSuggestions(form, form.fields[1]);
external_delegate_->CheckSuggestionCount(kDefaultPageID, 2);
// No suggestions should not be provided for the third field because of its
// unrecognized autocomplete attribute.
GetAutofillSuggestions(form, form.fields[2]);
external_delegate_->CheckNoSuggestions(kDefaultPageID);
}
// Test that no suggestions are returned when there are less than three fields
// and none of them have an autocomplete attribute.
TEST_F(AutofillManagerTest, GetProfileSuggestions_SmallFormNoAutocomplete) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Ensure that autocomplete manager is called for both fields.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(2);
GetAutofillSuggestions(form, form.fields[0]);
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
GetAutofillSuggestions(form, form.fields[1]);
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that for form with two fields with one that has an autocomplete
// attribute, suggestions are only made for the one that has the attribute.
TEST_F(AutofillManagerTest,
GetProfileSuggestions_SmallFormWithOneAutocomplete) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
field.autocomplete_attribute = "given-name";
form.fields.push_back(field);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
field.autocomplete_attribute = "";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Check that suggestions are made for the field that has the autocomplete
// attribute.
GetAutofillSuggestions(form, form.fields[0]);
external_delegate_->CheckSuggestions(kDefaultPageID,
Suggestion("Charles", "", "", 1),
Suggestion("Elvis", "", "", 2));
// Check that there are no suggestions for the field without the autocomplete
// attribute.
GetAutofillSuggestions(form, form.fields[1]);
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that for a form with two fields with autocomplete attributes,
// suggestions are made for both fields.
TEST_F(AutofillManagerTest,
GetProfileSuggestions_SmallFormWithTwoAutocomplete) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
field.autocomplete_attribute = "given-name";
form.fields.push_back(field);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
field.autocomplete_attribute = "family-name";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
GetAutofillSuggestions(form, form.fields[0]);
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Charles", "Charles Hardin Holley", "", 1),
Suggestion("Elvis", "Elvis Aaron Presley", "", 2));
GetAutofillSuggestions(form, form.fields[1]);
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Holley", "Charles Hardin Holley", "", 1),
Suggestion("Presley", "Elvis Aaron Presley", "", 2));
}
// Test that we return all address profile suggestions when all form fields are
// empty.
TEST_F(AutofillManagerTest, GetProfileSuggestions_EmptyValue) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate. Inferred
// labels include full first relevant field, which in this case is the
// address line 1.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Charles", "123 Apple St.", "", 1),
Suggestion("Elvis", "3734 Elvis Presley Blvd.", "", 2));
}
// Test that we return only matching address profile suggestions when the
// selected form field has been partially filled out.
TEST_F(AutofillManagerTest, GetProfileSuggestions_MatchCharacter) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "E", "text", &field);
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("Elvis", "3734 Elvis Presley Blvd.", "", 1));
}
// Tests that we return address profile suggestions values when the section
// is already autofilled, and that we merge identical values.
TEST_F(AutofillManagerTest,
GetProfileSuggestions_AlreadyAutofilledMergeValues) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// First name is already autofilled which will make the section appear as
// "already autofilled".
form.fields[0].is_autofilled = true;
// Two profiles have the same last name, and the third shares the same first
// letter for last name.
AutofillProfile* profile1 = new AutofillProfile;
profile1->set_guid("00000000-0000-0000-0000-000000000103");
profile1->SetInfo(AutofillType(NAME_FIRST), ASCIIToUTF16("Robin"), "en-US");
profile1->SetInfo(AutofillType(NAME_LAST), ASCIIToUTF16("Grimes"), "en-US");
profile1->SetInfo(AutofillType(ADDRESS_HOME_LINE1),
ASCIIToUTF16("1234 Smith Blvd."), "en-US");
autofill_manager_->AddProfile(profile1);
AutofillProfile* profile2 = new AutofillProfile;
profile2->set_guid("00000000-0000-0000-0000-000000000124");
profile2->SetInfo(AutofillType(NAME_FIRST), ASCIIToUTF16("Carl"), "en-US");
profile2->SetInfo(AutofillType(NAME_LAST), ASCIIToUTF16("Grimes"), "en-US");
profile2->SetInfo(AutofillType(ADDRESS_HOME_LINE1),
ASCIIToUTF16("1234 Smith Blvd."), "en-US");
autofill_manager_->AddProfile(profile2);
AutofillProfile* profile3 = new AutofillProfile;
profile3->set_guid("00000000-0000-0000-0000-000000000126");
profile3->SetInfo(AutofillType(NAME_FIRST), ASCIIToUTF16("Aaron"), "en-US");
profile3->SetInfo(AutofillType(NAME_LAST), ASCIIToUTF16("Googler"), "en-US");
profile3->SetInfo(AutofillType(ADDRESS_HOME_LINE1),
ASCIIToUTF16("1600 Amphitheater pkwy"), "en-US");
autofill_manager_->AddProfile(profile3);
FormFieldData field;
test::CreateTestFormField("Last Name", "lastname", "G", "text", &field);
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate. No labels,
// with duplicate values "Grimes" merged.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Googler", "" /* no label */, "", 1),
Suggestion("Grimes", "" /* no label */, "", 2));
}
// Tests that we return address profile suggestions values when the section
// is already autofilled, and that they have no label.
TEST_F(AutofillManagerTest, GetProfileSuggestions_AlreadyAutofilledNoLabels) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// First name is already autofilled which will make the section appear as
// "already autofilled".
form.fields[0].is_autofilled = true;
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "E", "text", &field);
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate. No labels.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("Elvis", "" /* no label */, "", 1));
}
// Test that we return no suggestions when the form has no relevant fields.
TEST_F(AutofillManagerTest, GetProfileSuggestions_UnknownFields) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("Username", "username", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("Password", "password", "", "password", &field);
form.fields.push_back(field);
test::CreateTestFormField("Quest", "quest", "", "quest", &field);
form.fields.push_back(field);
test::CreateTestFormField("Color", "color", "", "text", &field);
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
GetAutofillSuggestions(form, field);
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that we cull duplicate profile suggestions.
TEST_F(AutofillManagerTest, GetProfileSuggestions_WithDuplicates) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Add a duplicate profile.
AutofillProfile* duplicate_profile =
new AutofillProfile(
*(autofill_manager_->GetProfileWithGUID(
"00000000-0000-0000-0000-000000000001")));
autofill_manager_->AddProfile(duplicate_profile);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Charles", "123 Apple St.", "", 1),
Suggestion("Elvis", "3734 Elvis Presley Blvd.", "", 2));
}
// Test that we return no suggestions when autofill is disabled.
TEST_F(AutofillManagerTest, GetProfileSuggestions_AutofillDisabledByUser) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Disable Autofill.
autofill_manager_->set_autofill_enabled(false);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that we return all credit card profile suggestions when all form fields
// are empty.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_EmptyValue) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[1];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)),
Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"8765",
"10/98", kMasterCard,
autofill_manager_->GetPackedCreditCardID(5)));
}
// Test that we return all credit card profile suggestions when the triggering
// field has whitespace in it.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_Whitespace) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[1];
field.value = ASCIIToUTF16(" ");
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)),
Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"8765",
"10/98", kMasterCard,
autofill_manager_->GetPackedCreditCardID(5)));
}
// Test that we return all credit card profile suggestions when the triggering
// field has stop characters in it, which should be removed.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_StopCharsOnly) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[1];
field.value = ASCIIToUTF16("____-____-____-____");
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)),
Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"8765",
"10/98", kMasterCard,
autofill_manager_->GetPackedCreditCardID(5)));
}
// Test that we return all credit card profile suggestions when the triggering
// field has stop characters in it and some input.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_StopCharsWithInput) {
// Add a credit card with particular numbers that we will attempt to recall.
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "John Smith",
"5255667890123123", // Mastercard
"08", "2017");
credit_card->set_guid("00000000-0000-0000-0000-000000000007");
autofill_manager_->AddCreditCard(credit_card);
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[1];
field.value = ASCIIToUTF16("5255-66__-____-____");
GetAutofillSuggestions(form, field);
// Test that we sent the right value to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"3123",
"08/17", kMasterCard,
autofill_manager_->GetPackedCreditCardID(7)));
}
// Test that we return only matching credit card profile suggestions when the
// selected form field has been partially filled out.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_MatchCharacter) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Card Number", "cardnumber", "78", "text", &field);
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)));
}
// Test that we return credit card profile suggestions when the selected form
// field is not the credit card number field.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_NonCCNumber) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
#if defined(OS_ANDROID)
static const char* kVisaSuggestion =
"Visa\xC2\xA0\xE2\x8B\xAF"
"3456";
static const char* kMcSuggestion =
"MasterCard\xC2\xA0\xE2\x8B\xAF"
"8765";
#else
static const char* kVisaSuggestion = "*3456";
static const char* kMcSuggestion = "*8765";
#endif
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("Elvis Presley", kVisaSuggestion, kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)),
Suggestion("Buddy Holly", kMcSuggestion, kMasterCard,
autofill_manager_->GetPackedCreditCardID(5)));
}
// Test that we return a warning explaining that credit card profile suggestions
// are unavailable when the page and the form target URL are not secure.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_NonHTTPS) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, false, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion(
l10n_util::GetStringUTF8(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION),
"", "", -1));
// Clear the test credit cards and try again -- we shouldn't return a warning.
personal_data_.ClearCreditCards();
GetAutofillSuggestions(form, field);
// Autocomplete suggestions are queried, but not Autofill.
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that we return a warning explaining that credit card profile suggestions
// are unavailable when the page is secure, but the form target URL is not
// secure.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_TargetURLNonHTTPS) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, /* is_https= */ true, false);
// However we set the action (target URL) to be HTTP after all.
form.action = GURL("http://myform.com/submit.html");
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion(l10n_util::GetStringUTF8(
IDS_AUTOFILL_WARNING_INSECURE_CONNECTION),
"", "", -1));
// Clear the test credit cards and try again -- we shouldn't return a warning.
personal_data_.ClearCreditCards();
GetAutofillSuggestions(form, field);
// Autocomplete suggestions are queried, but not Autofill.
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that we return all credit card suggestions in the case that two cards
// have the same obfuscated number.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_RepeatedObfuscatedNumber) {
// Add a credit card with the same obfuscated number as Elvis's.
// |credit_card| will be owned by the mock PersonalDataManager.
CreditCard* credit_card = new CreditCard;
test::SetCreditCardInfo(credit_card, "Elvis Presley",
"5231567890123456", // Mastercard
"05", "2999");
credit_card->set_guid("00000000-0000-0000-0000-000000000007");
credit_card->set_use_date(base::Time::Now() - base::TimeDelta::FromDays(15));
autofill_manager_->AddCreditCard(credit_card);
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[1];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)),
Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"8765",
"10/98", kMasterCard,
autofill_manager_->GetPackedCreditCardID(5)),
Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"3456",
"05/99", kMasterCard,
autofill_manager_->GetPackedCreditCardID(7)));
}
// Test that we return profile and credit card suggestions for combined forms.
TEST_F(AutofillManagerTest, GetAddressAndCreditCardSuggestions) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right address suggestions to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Charles", "123 Apple St.", "", 1),
Suggestion("Elvis", "3734 Elvis Presley Blvd.", "", 2));
const int kPageID2 = 2;
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
GetAutofillSuggestions(kPageID2, form, field);
// Test that we sent the credit card suggestions to the external delegate.
external_delegate_->CheckSuggestions(
kPageID2, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)),
Suggestion("MasterCard\xC2\xA0\xE2\x8B\xAF"
"8765",
"10/98", kMasterCard,
autofill_manager_->GetPackedCreditCardID(5)));
}
// Test that for non-https forms with both address and credit card fields, we
// only return address suggestions. Instead of credit card suggestions, we
// should return a warning explaining that credit card profile suggestions are
// unavailable when the form is not https.
TEST_F(AutofillManagerTest, GetAddressAndCreditCardSuggestionsNonHttps) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
CreateTestCreditCardFormData(&form, false, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right suggestions to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Charles", "123 Apple St.", "", 1),
Suggestion("Elvis", "3734 Elvis Presley Blvd.", "", 2));
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
const int kPageID2 = 2;
GetAutofillSuggestions(kPageID2, form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kPageID2,
Suggestion(
l10n_util::GetStringUTF8(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION),
"", "", -1));
// Clear the test credit cards and try again -- we shouldn't return a warning.
personal_data_.ClearCreditCards();
GetAutofillSuggestions(form, field);
external_delegate_->CheckNoSuggestions(kDefaultPageID);
}
// Test that we return autocomplete-like suggestions when trying to autofill
// already filled forms.
TEST_F(AutofillManagerTest, GetFieldSuggestionsWhenFormIsAutofilled) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Mark one of the fields as filled.
form.fields[2].is_autofilled = true;
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(kDefaultPageID,
Suggestion("Charles", "", "", 1),
Suggestion("Elvis", "", "", 2));
}
// Test that nothing breaks when there are autocomplete suggestions but no
// autofill suggestions.
TEST_F(AutofillManagerTest, GetFieldSuggestionsForAutocompleteOnly) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
FormFieldData field;
test::CreateTestFormField("Some Field", "somefield", "", "text", &field);
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
GetAutofillSuggestions(form, field);
// Add some Autocomplete suggestions.
// This triggers the combined message send.
std::vector<base::string16> suggestions;
suggestions.push_back(ASCIIToUTF16("one"));
suggestions.push_back(ASCIIToUTF16("two"));
AutocompleteSuggestionsReturned(suggestions);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("one", "", "", 0),
Suggestion("two", "", "", 0));
}
// Test that we do not return duplicate values drawn from multiple profiles when
// filling an already filled field.
TEST_F(AutofillManagerTest, GetFieldSuggestionsWithDuplicateValues) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// |profile| will be owned by the mock PersonalDataManager.
AutofillProfile* profile = new AutofillProfile;
test::SetProfileInfo(
profile, "Elvis", "", "", "", "", "", "", "", "", "", "", "");
profile->set_guid("00000000-0000-0000-0000-000000000101");
autofill_manager_->AddProfile(profile);
FormFieldData& field = form.fields[0];
field.is_autofilled = true;
field.value = ASCIIToUTF16("Elvis");
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("Elvis", "", "", 1));
}
TEST_F(AutofillManagerTest, GetProfileSuggestions_FancyPhone) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
AutofillProfile* profile = new AutofillProfile;
profile->set_guid("00000000-0000-0000-0000-000000000103");
profile->SetInfo(AutofillType(NAME_FULL), ASCIIToUTF16("Natty Bumppo"),
"en-US");
profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
ASCIIToUTF16("1800PRAIRIE"));
autofill_manager_->AddProfile(profile);
const FormFieldData& field = form.fields[9];
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate. Inferred
// labels include the most private field of those that would be filled.
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("18007724743", "Natty Bumppo", "", 1), // 1800PRAIRIE
Suggestion("23456789012", "123 Apple St.", "", 2),
Suggestion("12345678901", "3734 Elvis Presley Blvd.", "", 3));
}
TEST_F(AutofillManagerTest, GetProfileSuggestions_ForPhonePrefixOrSuffix) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
struct {
const char* const label;
const char* const name;
size_t max_length;
const char* const autocomplete_attribute;
} test_fields[] = {{"country code", "country_code", 1, "tel-country-code"},
{"area code", "area_code", 3, "tel-area-code"},
{"phone", "phone_prefix", 3, "tel-local-prefix"},
{"-", "phone_suffix", 4, "tel-local-suffix"},
{"Phone Extension", "ext", 5, "tel-extension"}};
FormFieldData field;
for (size_t i = 0; i < arraysize(test_fields); ++i) {
test::CreateTestFormField(
test_fields[i].label, test_fields[i].name, "", "text", &field);
field.max_length = test_fields[i].max_length;
field.autocomplete_attribute = std::string();
form.fields.push_back(field);
}
std::vector<FormData> forms(1, form);
FormsSeen(forms);
AutofillProfile* profile = new AutofillProfile;
profile->set_guid("00000000-0000-0000-0000-000000000104");
profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("1800FLOWERS"));
personal_data_.ClearAutofillProfiles();
autofill_manager_->AddProfile(profile);
const FormFieldData& phone_prefix = form.fields[2];
GetAutofillSuggestions(form, phone_prefix);
// Test that we sent the right prefix values to the external delegate.
external_delegate_->CheckSuggestions(kDefaultPageID,
Suggestion("356", "1800FLOWERS", "", 1));
const FormFieldData& phone_suffix = form.fields[3];
GetAutofillSuggestions(form, phone_suffix);
// Test that we sent the right suffix values to the external delegate.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("9377", "1800FLOWERS", "", 1));
}
// Test that we correctly fill an address form.
TEST_F(AutofillManagerTest, FillAddressForm) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000001";
AutofillProfile* profile = autofill_manager_->GetProfileWithGUID(guid);
ASSERT_TRUE(profile);
EXPECT_EQ(1U, profile->use_count());
EXPECT_NE(base::Time(), profile->use_date());
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
EXPECT_EQ(2U, profile->use_count());
EXPECT_NE(base::Time(), profile->use_date());
}
TEST_F(AutofillManagerTest, WillFillCreditCardNumber) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData* number_field = nullptr;
FormFieldData* name_field = nullptr;
FormFieldData* month_field = nullptr;
for (size_t i = 0; i < form.fields.size(); ++i) {
if (form.fields[i].name == ASCIIToUTF16("cardnumber"))
number_field = &form.fields[i];
else if (form.fields[i].name == ASCIIToUTF16("nameoncard"))
name_field = &form.fields[i];
else if (form.fields[i].name == ASCIIToUTF16("ccmonth"))
month_field = &form.fields[i];
}
// Empty form - whole form is Autofilled.
EXPECT_TRUE(WillFillCreditCardNumber(form, *number_field));
EXPECT_TRUE(WillFillCreditCardNumber(form, *name_field));
// If the user has entered a value, it won't be overridden.
number_field->value = ASCIIToUTF16("gibberish");
EXPECT_TRUE(WillFillCreditCardNumber(form, *number_field));
EXPECT_FALSE(WillFillCreditCardNumber(form, *name_field));
// But if that value is removed, it will be Autofilled.
number_field->value.clear();
EXPECT_TRUE(WillFillCreditCardNumber(form, *name_field));
// When part of the section is Autofilled, only fill the initiating field.
month_field->is_autofilled = true;
EXPECT_FALSE(WillFillCreditCardNumber(form, *name_field));
EXPECT_TRUE(WillFillCreditCardNumber(form, *number_field));
}
// Test that we correctly fill a credit card form.
TEST_F(AutofillManagerTest, FillCreditCardForm_Simple) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000004";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardFormElvis(
response_page_id, response_data, kDefaultPageID, false);
}
// Test that whitespace is stripped from the credit card number.
TEST_F(AutofillManagerTest, FillCreditCardForm_StripCardNumberWhitespace) {
// Same as the SetUp(), but generate Elvis card with whitespace in credit
// card number.
personal_data_.CreateTestCreditCardWithWhitespace();
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000008";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardFormElvis(response_page_id, response_data,
kDefaultPageID, false);
}
// Test that separator characters are stripped from the credit card number.
TEST_F(AutofillManagerTest, FillCreditCardForm_StripCardNumberSeparators) {
// Same as the SetUp(), but generate Elvis card with separator characters in
// credit card number.
personal_data_.CreateTestCreditCardWithSeparators();
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000009";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardFormElvis(response_page_id, response_data,
kDefaultPageID, false);
}
// Test that we correctly fill a credit card form with month input type.
// 1. year empty, month empty
TEST_F(AutofillManagerTest, FillCreditCardForm_NoYearNoMonth) {
// Same as the SetUp(), but generate 4 credit cards with year month
// combination.
personal_data_.CreateTestCreditCardsYearAndMonth("", "");
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, true);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000007";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
kDefaultPageID, false, "", "");
}
// Test that we correctly fill a credit card form with month input type.
// 2. year empty, month non-empty
TEST_F(AutofillManagerTest, FillCreditCardForm_NoYearMonth) {
// Same as the SetUp(), but generate 4 credit cards with year month
// combination.
personal_data_.CreateTestCreditCardsYearAndMonth("", "04");
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, true);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000007";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
kDefaultPageID, false, "", "04");
}
// Test that we correctly fill a credit card form with month input type.
// 3. year non-empty, month empty
TEST_F(AutofillManagerTest, FillCreditCardForm_YearNoMonth) {
// Same as the SetUp(), but generate 4 credit cards with year month
// combination.
personal_data_.CreateTestCreditCardsYearAndMonth("2999", "");
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, true);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000007";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardYearMonthWithYearMonth(
response_page_id, response_data, kDefaultPageID, false, "2999", "");
}
// Test that we correctly fill a credit card form with month input type.
// 4. year non-empty, month empty
TEST_F(AutofillManagerTest, FillCreditCardForm_YearMonth) {
// Same as the SetUp(), but generate 4 credit cards with year month
// combination.
personal_data_.ClearCreditCards();
personal_data_.CreateTestCreditCardsYearAndMonth("2999", "04");
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, true);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000007";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledCreditCardYearMonthWithYearMonth(
response_page_id, response_data, kDefaultPageID, false, "2999", "04");
}
// Test that we correctly fill a credit card form with first and last cardholder
// name.
TEST_F(AutofillManagerTest, FillCreditCardForm_SplitName) {
// Set up our form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("Last Name", "cardlastname", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("CVC", "cvc", "", "text", &field);
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000004";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
ExpectFilledField("Card Name", "cardname", "Elvis", "text",
response_data.fields[0]);
ExpectFilledField("Last Name", "cardlastname", "Presley", "text",
response_data.fields[1]);
ExpectFilledField("Card Number", "cardnumber", "4234567890123456", "text",
response_data.fields[2]);
}
// Test that we correctly fill a combined address and credit card form.
TEST_F(AutofillManagerTest, FillAddressAndCreditCardForm) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// First fill the address data.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
{
SCOPED_TRACE("Address");
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data,
kDefaultPageID, true);
}
// Now fill the credit card data.
const int kPageID2 = 2;
const char guid2[] = "00000000-0000-0000-0000-000000000004";
response_page_id = 0;
{
FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(),
MakeFrontendID(guid2, std::string()),
&response_page_id, &response_data);
SCOPED_TRACE("Credit card");
ExpectFilledCreditCardFormElvis(
response_page_id, response_data, kPageID2, true);
}
}
// Test that a field with an unrecognized autocomplete attribute is not filled.
TEST_F(AutofillManagerTest, FillAddressForm_UnrecognizedAttribute) {
FormData address_form;
address_form.name = ASCIIToUTF16("MyForm");
address_form.origin = GURL("https://myform.com/form.html");
address_form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
// Set a valid autocomplete attribute for the first name.
test::CreateTestFormField("First name", "firstname", "", "text", &field);
field.autocomplete_attribute = "given-name";
address_form.fields.push_back(field);
// Set no autocomplete attribute for the middle name.
test::CreateTestFormField("Middle name", "middle", "", "text", &field);
field.autocomplete_attribute = "";
address_form.fields.push_back(field);
// Set an unrecognized autocomplete attribute for the last name.
test::CreateTestFormField("Last name", "lastname", "", "text", &field);
field.autocomplete_attribute = "unrecognized";
address_form.fields.push_back(field);
std::vector<FormData> address_forms(1, address_form);
FormsSeen(address_forms);
// Fill the address form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(
kDefaultPageID, address_form, address_form.fields[0],
MakeFrontendID(std::string(), guid), &response_page_id, &response_data);
// The fist and middle names should be filled.
ExpectFilledField("First name", "firstname", "Elvis", "text",
response_data.fields[0]);
ExpectFilledField("Middle name", "middle", "Aaron", "text",
response_data.fields[1]);
// The last name should not be filled.
ExpectFilledField("Last name", "lastname", "", "text",
response_data.fields[2]);
}
// Test that non credit card related fields with the autocomplete attribute set
// to off are not filled on desktop.
TEST_F(AutofillManagerTest, FillAddressForm_AutocompleteOff) {
FormData address_form;
address_form.name = ASCIIToUTF16("MyForm");
address_form.origin = GURL("https://myform.com/form.html");
address_form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First name", "firstname", "", "text", &field);
address_form.fields.push_back(field);
test::CreateTestFormField("Middle name", "middle", "", "text", &field);
field.should_autocomplete = false;
address_form.fields.push_back(field);
test::CreateTestFormField("Last name", "lastname", "", "text", &field);
field.should_autocomplete = true;
address_form.fields.push_back(field);
test::CreateTestFormField("Address Line 1", "addr1", "", "text", &field);
field.should_autocomplete = false;
address_form.fields.push_back(field);
std::vector<FormData> address_forms(1, address_form);
FormsSeen(address_forms);
// Fill the address form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(
kDefaultPageID, address_form, address_form.fields[0],
MakeFrontendID(std::string(), guid), &response_page_id, &response_data);
// The fist name should be filled.
ExpectFilledField("First name", "firstname", "Elvis", "text",
response_data.fields[0]);
// The middle name should not be filled on desktop.
if (IsDesktopPlatform()) {
ExpectFilledField("Middle name", "middle", "", "text",
response_data.fields[1]);
} else {
ExpectFilledField("Middle name", "middle", "Aaron", "text",
response_data.fields[1]);
}
// The last name should be filled.
ExpectFilledField("Last name", "lastname", "Presley", "text",
response_data.fields[2]);
// The address line 1 should not be filled on desktop.
if (IsDesktopPlatform()) {
ExpectFilledField("Address Line 1", "addr1", "", "text",
response_data.fields[3]);
} else {
ExpectFilledField("Address Line 1", "addr1", "3734 Elvis Presley Blvd.",
"text", response_data.fields[3]);
}
}
// Test that a field with a value equal to it's placeholder attribute is filled.
TEST_F(AutofillManagerTest, FillAddressForm_PlaceholderEqualsValue) {
FormData address_form;
address_form.name = ASCIIToUTF16("MyForm");
address_form.origin = GURL("https://myform.com/form.html");
address_form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
// Set the same placeholder and value for each field.
test::CreateTestFormField("First name", "firstname", "", "text", &field);
field.placeholder = ASCIIToUTF16("First Name");
field.value = ASCIIToUTF16("First Name");
address_form.fields.push_back(field);
test::CreateTestFormField("Middle name", "middle", "", "text", &field);
field.placeholder = ASCIIToUTF16("Middle Name");
field.value = ASCIIToUTF16("Middle Name");
address_form.fields.push_back(field);
test::CreateTestFormField("Last name", "lastname", "", "text", &field);
field.placeholder = ASCIIToUTF16("Last Name");
field.value = ASCIIToUTF16("Last Name");
address_form.fields.push_back(field);
std::vector<FormData> address_forms(1, address_form);
FormsSeen(address_forms);
// Fill the address form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(
kDefaultPageID, address_form, address_form.fields[0],
MakeFrontendID(std::string(), guid), &response_page_id, &response_data);
// All the fields should be filled.
ExpectFilledField("First name", "firstname", "Elvis", "text",
response_data.fields[0]);
ExpectFilledField("Middle name", "middle", "Aaron", "text",
response_data.fields[1]);
ExpectFilledField("Last name", "lastname", "Presley", "text",
response_data.fields[2]);
}
// Test that a credit card field with an unrecognized autocomplete attribute
// gets filled.
TEST_F(AutofillManagerTest, FillCreditCardForm_UnrecognizedAttribute) {
// Set up the form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
// Set a valid autocomplete attribute on the card name.
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
field.autocomplete_attribute = "cc-name";
form.fields.push_back(field);
// Set no autocomplete attribute on the card number.
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
field.autocomplete_attribute = "";
form.fields.push_back(field);
// Set an unrecognized autocomplete attribute on the expiration month.
test::CreateTestFormField("Expiration Date", "ccmonth", "", "text", &field);
field.autocomplete_attribute = "unrecognized";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000004";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
// The credit card name and number should be filled.
ExpectFilledField("Name on Card", "nameoncard", "Elvis Presley", "text",
response_data.fields[0]);
ExpectFilledField("Card Number", "cardnumber", "4234567890123456", "text",
response_data.fields[1]);
// The expiration month should be filled.
ExpectFilledField("Expiration Date", "ccmonth", "04/2999", "text",
response_data.fields[2]);
}
// Test that credit card fields are filled even if they have the autocomplete
// attribute set to off.
TEST_F(AutofillManagerTest, FillCreditCardForm_AutocompleteOff) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
// Set the autocomplete=off on all fields.
for (FormFieldData field : form.fields)
field.should_autocomplete = false;
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000004";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
// All fields should be filled.
ExpectFilledCreditCardFormElvis(response_page_id, response_data,
kDefaultPageID, false);
}
// Test that selecting an expired credit card fills everything except the
// expiration date.
TEST_F(AutofillManagerTest, FillCreditCardForm_ExpiredCard) {
personal_data_.CreateTestExpiredCreditCard();
// Set up the form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
// Create a credit card form.
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
field.autocomplete_attribute = "cc-name";
form.fields.push_back(field);
std::vector<const char*> kCreditCardTypes = {"Visa", "Master Card", "AmEx",
"discover"};
test::CreateTestSelectField("Card Type", "cardtype", "", kCreditCardTypes,
kCreditCardTypes, 4, &field);
field.autocomplete_attribute = "cc-type";
form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
field.autocomplete_attribute = "cc-number";
form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
field.autocomplete_attribute = "cc-exp-month";
form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
field.autocomplete_attribute = "cc-exp-year";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const char guid[] = "00000000-0000-0000-0000-000000000009";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(guid, std::string()),
&response_page_id, &response_data);
// The credit card name, type and number should be filled.
ExpectFilledField("Name on Card", "nameoncard", "Homer Simpson", "text",
response_data.fields[0]);
ExpectFilledField("Card Type", "cardtype", "Visa", "select-one",
response_data.fields[1]);
ExpectFilledField("Card Number", "cardnumber", "4234567890654321", "text",
response_data.fields[2]);
// The expiration month and year should not be filled.
ExpectFilledField("Expiration Month", "ccmonth", "", "text",
response_data.fields[3]);
ExpectFilledField("Expiration Year", "ccyear", "", "text",
response_data.fields[4]);
}
// Test that non-focusable field is ignored while inferring boundaries between
// sections: http://crbug.com/231160
TEST_F(AutofillManagerTest, FillFormWithNonFocusableFields) {
// Create a form with both focusable and non-focusable fields.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("", "lastname", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("", "email", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("Phone Number", "phonenumber", "", "tel", &field);
form.fields.push_back(field);
test::CreateTestFormField("", "email_", "", "text", &field);
field.is_focusable = false;
form.fields.push_back(field);
test::CreateTestFormField("Country", "country", "", "text", &field);
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the form
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
// The whole form should be filled as all the fields belong to the same
// logical section.
ASSERT_EQ(6U, response_data.fields.size());
ExpectFilledField("First Name", "firstname", "Elvis", "text",
response_data.fields[0]);
ExpectFilledField("", "lastname", "Presley", "text",
response_data.fields[1]);
ExpectFilledField("", "email", "theking@gmail.com", "text",
response_data.fields[2]);
ExpectFilledField("Phone Number", "phonenumber", "12345678901", "tel",
response_data.fields[3]);
ExpectFilledField("", "email_", "theking@gmail.com", "text",
response_data.fields[4]);
ExpectFilledField("Country", "country", "United States", "text",
response_data.fields[5]);
}
// Test that we correctly fill a form that has multiple logical sections, e.g.
// both a billing and a shipping address.
TEST_F(AutofillManagerTest, FillFormWithMultipleSections) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
const size_t kAddressFormSize = form.fields.size();
test::CreateTestAddressFormData(&form);
for (size_t i = kAddressFormSize; i < form.fields.size(); ++i) {
// Make sure the fields have distinct names.
form.fields[i].name = form.fields[i].name + ASCIIToUTF16("_");
}
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the first section.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
{
SCOPED_TRACE("Address 1");
// The second address section should be empty.
ASSERT_EQ(response_data.fields.size(), 2*kAddressFormSize);
for (size_t i = kAddressFormSize; i < form.fields.size(); ++i) {
EXPECT_EQ(base::string16(), response_data.fields[i].value);
}
// The first address section should be filled with Elvis's data.
response_data.fields.resize(kAddressFormSize);
ExpectFilledAddressFormElvis(response_page_id, response_data,
kDefaultPageID, false);
}
// Fill the second section, with the initiating field somewhere in the middle
// of the section.
const int kPageID2 = 2;
const char guid2[] = "00000000-0000-0000-0000-000000000001";
ASSERT_LT(9U, kAddressFormSize);
response_page_id = 0;
FillAutofillFormDataAndSaveResults(
kPageID2, form, form.fields[kAddressFormSize + 9],
MakeFrontendID(std::string(), guid2), &response_page_id, &response_data);
{
SCOPED_TRACE("Address 2");
ASSERT_EQ(response_data.fields.size(), form.fields.size());
// The first address section should be empty.
ASSERT_EQ(response_data.fields.size(), 2*kAddressFormSize);
for (size_t i = 0; i < kAddressFormSize; ++i) {
EXPECT_EQ(base::string16(), response_data.fields[i].value);
}
// The second address section should be filled with Elvis's data.
FormData secondSection = response_data;
secondSection.fields.erase(secondSection.fields.begin(),
secondSection.fields.begin() + kAddressFormSize);
for (size_t i = 0; i < kAddressFormSize; ++i) {
// Restore the expected field names.
base::string16 name = secondSection.fields[i].name;
base::string16 original_name = name.substr(0, name.size() - 1);
secondSection.fields[i].name = original_name;
}
ExpectFilledAddressFormElvis(response_page_id, secondSection, kPageID2,
false);
}
}
// Test that we correctly fill a form that has author-specified sections, which
// might not match our expected section breakdown.
TEST_F(AutofillManagerTest, FillFormWithAuthorSpecifiedSections) {
// Create a form with a billing section and an unnamed section, interleaved.
// The billing section includes both address and credit card fields.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("", "country", "", "text", &field);
field.autocomplete_attribute = "section-billing country";
form.fields.push_back(field);
test::CreateTestFormField("", "firstname", "", "text", &field);
field.autocomplete_attribute = "given-name";
form.fields.push_back(field);
test::CreateTestFormField("", "lastname", "", "text", &field);
field.autocomplete_attribute = "family-name";
form.fields.push_back(field);
test::CreateTestFormField("", "address", "", "text", &field);
field.autocomplete_attribute = "section-billing address-line1";
form.fields.push_back(field);
test::CreateTestFormField("", "city", "", "text", &field);
field.autocomplete_attribute = "section-billing locality";
form.fields.push_back(field);
test::CreateTestFormField("", "state", "", "text", &field);
field.autocomplete_attribute = "section-billing region";
form.fields.push_back(field);
test::CreateTestFormField("", "zip", "", "text", &field);
field.autocomplete_attribute = "section-billing postal-code";
form.fields.push_back(field);
test::CreateTestFormField("", "ccname", "", "text", &field);
field.autocomplete_attribute = "section-billing cc-name";
form.fields.push_back(field);
test::CreateTestFormField("", "ccnumber", "", "text", &field);
field.autocomplete_attribute = "section-billing cc-number";
form.fields.push_back(field);
test::CreateTestFormField("", "ccexp", "", "text", &field);
field.autocomplete_attribute = "section-billing cc-exp";
form.fields.push_back(field);
test::CreateTestFormField("", "email", "", "text", &field);
field.autocomplete_attribute = "email";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the unnamed section.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[1],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
{
SCOPED_TRACE("Unnamed section");
EXPECT_EQ(kDefaultPageID, response_page_id);
EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
ASSERT_EQ(11U, response_data.fields.size());
ExpectFilledField("", "country", "", "text", response_data.fields[0]);
ExpectFilledField("", "firstname", "Elvis", "text",
response_data.fields[1]);
ExpectFilledField("", "lastname", "Presley", "text",
response_data.fields[2]);
ExpectFilledField("", "address", "", "text", response_data.fields[3]);
ExpectFilledField("", "city", "", "text", response_data.fields[4]);
ExpectFilledField("", "state", "", "text", response_data.fields[5]);
ExpectFilledField("", "zip", "", "text", response_data.fields[6]);
ExpectFilledField("", "ccname", "", "text", response_data.fields[7]);
ExpectFilledField("", "ccnumber", "", "text", response_data.fields[8]);
ExpectFilledField("", "ccexp", "", "text", response_data.fields[9]);
ExpectFilledField("", "email", "theking@gmail.com", "text",
response_data.fields[10]);
}
// Fill the address portion of the billing section.
const int kPageID2 = 2;
const char guid2[] = "00000000-0000-0000-0000-000000000001";
response_page_id = 0;
FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields[0],
MakeFrontendID(std::string(), guid2),
&response_page_id, &response_data);
{
SCOPED_TRACE("Billing address");
EXPECT_EQ(kPageID2, response_page_id);
EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
ASSERT_EQ(11U, response_data.fields.size());
ExpectFilledField("", "country", "US", "text",
response_data.fields[0]);
ExpectFilledField("", "firstname", "", "text", response_data.fields[1]);
ExpectFilledField("", "lastname", "", "text", response_data.fields[2]);
ExpectFilledField("", "address", "3734 Elvis Presley Blvd.", "text",
response_data.fields[3]);
ExpectFilledField("", "city", "Memphis", "text", response_data.fields[4]);
ExpectFilledField("", "state", "Tennessee", "text",
response_data.fields[5]);
ExpectFilledField("", "zip", "38116", "text", response_data.fields[6]);
ExpectFilledField("", "ccname", "", "text", response_data.fields[7]);
ExpectFilledField("", "ccnumber", "", "text", response_data.fields[8]);
ExpectFilledField("", "ccexp", "", "text", response_data.fields[9]);
ExpectFilledField("", "email", "", "text", response_data.fields[10]);
}
// Fill the credit card portion of the billing section.
const int kPageID3 = 3;
const char guid3[] = "00000000-0000-0000-0000-000000000004";
response_page_id = 0;
FillAutofillFormDataAndSaveResults(
kPageID3, form, form.fields[form.fields.size() - 2],
MakeFrontendID(guid3, std::string()), &response_page_id, &response_data);
{
SCOPED_TRACE("Credit card");
EXPECT_EQ(kPageID3, response_page_id);
EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
ASSERT_EQ(11U, response_data.fields.size());
ExpectFilledField("", "country", "", "text", response_data.fields[0]);
ExpectFilledField("", "firstname", "", "text", response_data.fields[1]);
ExpectFilledField("", "lastname", "", "text", response_data.fields[2]);
ExpectFilledField("", "address", "", "text", response_data.fields[3]);
ExpectFilledField("", "city", "", "text", response_data.fields[4]);
ExpectFilledField("", "state", "", "text", response_data.fields[5]);
ExpectFilledField("", "zip", "", "text", response_data.fields[6]);
ExpectFilledField("", "ccname", "Elvis Presley", "text",
response_data.fields[7]);
ExpectFilledField("", "ccnumber", "4234567890123456", "text",
response_data.fields[8]);
ExpectFilledField("", "ccexp", "04/2999", "text", response_data.fields[9]);
ExpectFilledField("", "email", "", "text", response_data.fields[10]);
}
}
// Test that we correctly fill a form that has a single logical section with
// multiple email address fields.
TEST_F(AutofillManagerTest, FillFormWithMultipleEmails) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
FormFieldData field;
test::CreateTestFormField("Confirm email", "email2", "", "text", &field);
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
// The second email address should be filled.
EXPECT_EQ(ASCIIToUTF16("theking@gmail.com"),
response_data.fields.back().value);
// The remainder of the form should be filled as usual.
response_data.fields.pop_back();
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
}
// Test that we correctly fill a previously auto-filled form.
TEST_F(AutofillManagerTest, FillAutofilledForm) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
// Mark one of the address fields as autofilled.
form.fields[4].is_autofilled = true;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// First fill the address data.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
{
SCOPED_TRACE("Address");
ExpectFilledForm(response_page_id, response_data, kDefaultPageID, "Elvis",
"", "", "", "", "", "", "", "", "", "", "", "", "", "",
true, true, false);
}
// Now fill the credit card data.
const int kPageID2 = 2;
const char guid2[] = "00000000-0000-0000-0000-000000000004";
response_page_id = 0;
FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(),
MakeFrontendID(guid2, std::string()),
&response_page_id, &response_data);
{
SCOPED_TRACE("Credit card 1");
ExpectFilledCreditCardFormElvis(
response_page_id, response_data, kPageID2, true);
}
// Now set the credit card fields to also be auto-filled, and try again to
// fill the credit card data
for (std::vector<FormFieldData>::iterator iter = form.fields.begin();
iter != form.fields.end();
++iter) {
iter->is_autofilled = true;
}
const int kPageID3 = 3;
response_page_id = 0;
FillAutofillFormDataAndSaveResults(
kPageID3, form, form.fields[form.fields.size() - 2],
MakeFrontendID(guid2, std::string()), &response_page_id, &response_data);
{
SCOPED_TRACE("Credit card 2");
ExpectFilledForm(response_page_id, response_data, kPageID3, "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "2999", true, true,
false);
}
}
// Test that we correctly fill a phone number split across multiple fields.
TEST_F(AutofillManagerTest, FillPhoneNumber) {
// In one form, rely on the maxlength attribute to imply US phone number
// parts. In the other form, rely on the autocompletetype attribute.
FormData form_with_us_number_max_length;
form_with_us_number_max_length.name = ASCIIToUTF16("MyMaxlengthPhoneForm");
form_with_us_number_max_length.origin =
GURL("http://myform.com/phone_form.html");
form_with_us_number_max_length.action =
GURL("http://myform.com/phone_submit.html");
FormData form_with_autocompletetype = form_with_us_number_max_length;
form_with_autocompletetype.name = ASCIIToUTF16("MyAutocompletetypePhoneForm");
struct {
const char* label;
const char* name;
size_t max_length;
const char* autocomplete_attribute;
} test_fields[] = {
{ "country code", "country_code", 1, "tel-country-code" },
{ "area code", "area_code", 3, "tel-area-code" },
{ "phone", "phone_prefix", 3, "tel-local-prefix" },
{ "-", "phone_suffix", 4, "tel-local-suffix" },
{ "Phone Extension", "ext", 3, "tel-extension" }
};
FormFieldData field;
const size_t default_max_length = field.max_length;
for (size_t i = 0; i < arraysize(test_fields); ++i) {
test::CreateTestFormField(
test_fields[i].label, test_fields[i].name, "", "text", &field);
field.max_length = test_fields[i].max_length;
field.autocomplete_attribute = std::string();
form_with_us_number_max_length.fields.push_back(field);
field.max_length = default_max_length;
field.autocomplete_attribute = test_fields[i].autocomplete_attribute;
form_with_autocompletetype.fields.push_back(field);
}
std::vector<FormData> forms;
forms.push_back(form_with_us_number_max_length);
forms.push_back(form_with_autocompletetype);
FormsSeen(forms);
// We should be able to fill prefix and suffix fields for US numbers.
AutofillProfile* work_profile = autofill_manager_->GetProfileWithGUID(
"00000000-0000-0000-0000-000000000002");
ASSERT_TRUE(work_profile != NULL);
work_profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
ASCIIToUTF16("16505554567"));
std::string guid(work_profile->guid());
int page_id = 1;
int response_page_id = 0;
FormData response_data1;
FillAutofillFormDataAndSaveResults(
page_id, form_with_us_number_max_length,
*form_with_us_number_max_length.fields.begin(),
MakeFrontendID(std::string(), guid), &response_page_id, &response_data1);
EXPECT_EQ(1, response_page_id);
ASSERT_EQ(5U, response_data1.fields.size());
EXPECT_EQ(ASCIIToUTF16("1"), response_data1.fields[0].value);
EXPECT_EQ(ASCIIToUTF16("650"), response_data1.fields[1].value);
EXPECT_EQ(ASCIIToUTF16("555"), response_data1.fields[2].value);
EXPECT_EQ(ASCIIToUTF16("4567"), response_data1.fields[3].value);
EXPECT_EQ(base::string16(), response_data1.fields[4].value);
page_id = 2;
response_page_id = 0;
FormData response_data2;
FillAutofillFormDataAndSaveResults(page_id, form_with_autocompletetype,
*form_with_autocompletetype.fields.begin(),
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data2);
EXPECT_EQ(2, response_page_id);
ASSERT_EQ(5U, response_data2.fields.size());
EXPECT_EQ(ASCIIToUTF16("1"), response_data2.fields[0].value);
EXPECT_EQ(ASCIIToUTF16("650"), response_data2.fields[1].value);
EXPECT_EQ(ASCIIToUTF16("555"), response_data2.fields[2].value);
EXPECT_EQ(ASCIIToUTF16("4567"), response_data2.fields[3].value);
EXPECT_EQ(base::string16(), response_data2.fields[4].value);
// We should not be able to fill international numbers correctly in a form
// containing fields with US max_length. However, the field should fill with
// the number of digits equal to the max length specified, starting from the
// right.
work_profile->SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("GB"));
work_profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
ASCIIToUTF16("447700954321"));
page_id = 3;
response_page_id = 0;
FormData response_data3;
FillAutofillFormDataAndSaveResults(
page_id, form_with_us_number_max_length,
*form_with_us_number_max_length.fields.begin(),
MakeFrontendID(std::string(), guid), &response_page_id, &response_data3);
EXPECT_EQ(3, response_page_id);
ASSERT_EQ(5U, response_data3.fields.size());
EXPECT_EQ(ASCIIToUTF16("4"), response_data3.fields[0].value);
EXPECT_EQ(ASCIIToUTF16("700"), response_data3.fields[1].value);
EXPECT_EQ(ASCIIToUTF16("321"), response_data3.fields[2].value);
EXPECT_EQ(ASCIIToUTF16("4321"), response_data3.fields[3].value);
EXPECT_EQ(base::string16(), response_data3.fields[4].value);
page_id = 4;
response_page_id = 0;
FormData response_data4;
FillAutofillFormDataAndSaveResults(page_id, form_with_autocompletetype,
*form_with_autocompletetype.fields.begin(),
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data4);
EXPECT_EQ(4, response_page_id);
ASSERT_EQ(5U, response_data4.fields.size());
EXPECT_EQ(ASCIIToUTF16("44"), response_data4.fields[0].value);
EXPECT_EQ(ASCIIToUTF16("7700"), response_data4.fields[1].value);
EXPECT_EQ(ASCIIToUTF16("954321"), response_data4.fields[2].value);
EXPECT_EQ(ASCIIToUTF16("954321"), response_data4.fields[3].value);
EXPECT_EQ(base::string16(), response_data4.fields[4].value);
}
// Test that we can still fill a form when a field has been removed from it.
TEST_F(AutofillManagerTest, FormChangesRemoveField) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
// Add a field -- we'll remove it again later.
FormFieldData field;
test::CreateTestFormField("Some", "field", "", "text", &field);
form.fields.insert(form.fields.begin() + 3, field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Now, after the call to |FormsSeen|, we remove the field before filling.
form.fields.erase(form.fields.begin() + 3);
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
}
// Test that we can still fill a form when a field has been added to it.
TEST_F(AutofillManagerTest, FormChangesAddField) {
// The offset of the phone field in the address form.
const int kPhoneFieldOffset = 9;
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
// Remove the phone field -- we'll add it back later.
std::vector<FormFieldData>::iterator pos =
form.fields.begin() + kPhoneFieldOffset;
FormFieldData field = *pos;
pos = form.fields.erase(pos);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Now, after the call to |FormsSeen|, we restore the field before filling.
form.fields.insert(pos, field);
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
}
// Test that we are able to save form data when forms are submitted.
TEST_F(AutofillManagerTest, FormSubmitted) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
// Simulate form submission. We should call into the PDM to try to save the
// filled data.
FormSubmitted(response_data);
EXPECT_EQ(1, personal_data_.num_times_save_imported_profile_called());
}
// Test that we are not saving form data when only the WillSubmitForm event is
// sent.
TEST_F(AutofillManagerTest, FormWillSubmitDoesNotSaveData) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
// Simulate OnWillSubmitForm(). We should *not* be calling into the PDM at
// this point (since the form was not submitted). Does not call
// OnFormSubmitted.
autofill_manager_->ResetRunLoop();
autofill_manager_->OnWillSubmitForm(response_data, base::TimeTicks::Now());
autofill_manager_->WaitForAsyncUploadProcess();
EXPECT_EQ(0, personal_data_.num_times_save_imported_profile_called());
}
// Test that when Autocomplete is enabled and Autofill is disabled, form
// submissions are still received by AutocompleteHistoryManager.
TEST_F(AutofillManagerTest, FormSubmittedAutocompleteEnabled) {
TestAutofillClient client;
autofill_manager_.reset(
new TestAutofillManager(autofill_driver_.get(), &client, NULL));
autofill_manager_->set_autofill_enabled(false);
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnWillSubmitForm(_));
FormSubmitted(form);
}
// Test that when Autofill is disabled, Autocomplete suggestions are still
// queried.
TEST_F(AutofillManagerTest, AutocompleteSuggestions_SomeWhenAutofillDisabled) {
TestAutofillClient client;
autofill_manager_.reset(
new TestAutofillManager(autofill_driver_.get(), &client, NULL));
autofill_manager_->set_autofill_enabled(false);
autofill_manager_->SetExternalDelegate(external_delegate_.get());
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
// Expect Autocomplete manager to be called for suggestions.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _));
GetAutofillSuggestions(form, field);
}
// Test that when Autofill is disabled and the field should not autocomplete,
// autocomplete is not queried for suggestions.
TEST_F(AutofillManagerTest,
AutocompleteSuggestions_AutofillDisabledAndFieldShouldNotAutocomplete) {
TestAutofillClient client;
autofill_manager_.reset(
new TestAutofillManager(autofill_driver_.get(), &client, NULL));
autofill_manager_->set_autofill_enabled(false);
autofill_manager_->SetExternalDelegate(external_delegate_.get());
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field = form.fields[0];
field.should_autocomplete = false;
// Autocomplete manager is not called for suggestions.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0);
GetAutofillSuggestions(form, field);
}
// Test that we do not query for Autocomplete suggestions when there are
// Autofill suggestions available.
TEST_F(AutofillManagerTest, AutocompleteSuggestions_NoneWhenAutofillPresent) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
// Autocomplete manager is not called for suggestions.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0);
GetAutofillSuggestions(form, field);
// Test that we sent the right values to the external delegate. Inferred
// labels include full first relevant field, which in this case is the
// address line 1.
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Charles", "123 Apple St.", "", 1),
Suggestion("Elvis", "3734 Elvis Presley Blvd.", "", 2));
}
// Test that we query for Autocomplete suggestions when there are no Autofill
// suggestions available.
TEST_F(AutofillManagerTest, AutocompleteSuggestions_SomeWhenAutofillEmpty) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// No suggestions matching "donkey".
FormFieldData field;
test::CreateTestFormField("Email", "email", "donkey", "email", &field);
// Autocomplete manager is called for suggestions because Autofill is empty.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _));
GetAutofillSuggestions(form, field);
}
// Test that when Autofill is disabled and the field is a credit card name
// field,
// autocomplete is queried for suggestions.
TEST_F(AutofillManagerTest,
AutocompleteSuggestions_CreditCardNameFieldShouldAutocomplete) {
TestAutofillClient client;
autofill_manager_.reset(
new TestAutofillManager(autofill_driver_.get(), &client, NULL));
autofill_manager_->set_autofill_enabled(false);
autofill_manager_->SetExternalDelegate(external_delegate_.get());
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, false, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// The first field is "Name on card", which should autocomplete.
FormFieldData field = form.fields[0];
field.should_autocomplete = true;
// Autocomplete manager is not called for suggestions.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _));
GetAutofillSuggestions(form, field);
}
// Test that when Autofill is disabled and the field is a credit card number
// field, autocomplete is not queried for suggestions.
TEST_F(AutofillManagerTest,
AutocompleteSuggestions_CreditCardNumberShouldNotAutocomplete) {
TestAutofillClient client;
autofill_manager_.reset(
new TestAutofillManager(autofill_driver_.get(), &client, NULL));
autofill_manager_->set_autofill_enabled(false);
autofill_manager_->SetExternalDelegate(external_delegate_.get());
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, false, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// The second field is "Card Number", which should not autocomplete.
FormFieldData field = form.fields[1];
field.should_autocomplete = true;
// Autocomplete manager is not called for suggestions.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0);
GetAutofillSuggestions(form, field);
}
// Test that we do not query for Autocomplete suggestions when there are no
// Autofill suggestions available, and that the field should not autocomplete.
TEST_F(
AutofillManagerTest,
AutocompleteSuggestions_NoneWhenAutofillEmptyFieldShouldNotAutocomplete) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// No suggestions matching "donkey".
FormFieldData field;
field.should_autocomplete = false;
test::CreateTestFormField("Email", "email", "donkey", "email", &field);
// Autocomplete manager is not called for suggestions.
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0);
GetAutofillSuggestions(form, field);
}
TEST_F(AutofillManagerTest, AutocompleteOffRespectedForAutocomplete) {
TestAutofillClient client;
autofill_manager_.reset(
new TestAutofillManager(autofill_driver_.get(), &client, NULL));
autofill_manager_->set_autofill_enabled(false);
autofill_manager_->SetExternalDelegate(external_delegate_.get());
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0);
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData* field = &form.fields[0];
field->should_autocomplete = false;
GetAutofillSuggestions(form, *field);
}
// Test that OnLoadedServerPredictions can obtain the FormStructure with the
// signature of the queried form and apply type predictions.
TEST_F(AutofillManagerTest, OnLoadedServerPredictions) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
// Simulate having seen this form on page load.
// |form_structure| will be owned by |autofill_manager_|.
TestFormStructure* form_structure = new TestFormStructure(form);
form_structure->DetermineHeuristicTypes();
autofill_manager_->AddSeenForm(form_structure);
// Similarly, a second form.
FormData form2;
form2.name = ASCIIToUTF16("MyForm");
form2.origin = GURL("http://myform.com/form.html");
form2.action = GURL("http://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
form2.fields.push_back(field);
test::CreateTestFormField("Middle Name", "middlename", "", "text", &field);
form2.fields.push_back(field);
test::CreateTestFormField("Postal Code", "zipcode", "", "text", &field);
form2.fields.push_back(field);
TestFormStructure* form_structure2 = new TestFormStructure(form2);
form_structure2->DetermineHeuristicTypes();
autofill_manager_->AddSeenForm(form_structure2);
AutofillQueryResponseContents response;
response.add_field()->set_autofill_type(3);
for (int i = 0; i < 7; ++i) {
response.add_field()->set_autofill_type(0);
}
response.add_field()->set_autofill_type(3);
response.add_field()->set_autofill_type(2);
response.add_field()->set_autofill_type(61);
response.add_field()->set_autofill_type(5);
response.add_field()->set_autofill_type(4);
response.add_field()->set_autofill_type(35);
std::string response_string;
ASSERT_TRUE(response.SerializeToString(&response_string));
std::vector<std::string> signatures;
signatures.push_back(form_structure->FormSignatureAsStr());
signatures.push_back(form_structure2->FormSignatureAsStr());
base::HistogramTester histogram_tester;
autofill_manager_->OnLoadedServerPredictions(response_string, signatures);
// Verify that FormStructure::ParseQueryResponse was called (here and below).
histogram_tester.ExpectBucketCount("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_RESPONSE_RECEIVED,
1);
histogram_tester.ExpectBucketCount("Autofill.ServerQueryResponse",
AutofillMetrics::QUERY_RESPONSE_PARSED,
1);
// We expect the server type to have been applied to the first field of the
// first form.
EXPECT_EQ(NAME_FIRST, form_structure->field(0)->Type().GetStorableType());
// We expect the server types to have been applied to the second form.
EXPECT_EQ(NAME_LAST, form_structure2->field(0)->Type().GetStorableType());
EXPECT_EQ(NAME_MIDDLE, form_structure2->field(1)->Type().GetStorableType());
EXPECT_EQ(ADDRESS_HOME_ZIP,
form_structure2->field(2)->Type().GetStorableType());
}
// Test that OnLoadedServerPredictions does not call ParseQueryResponse if the
// AutofillManager has been reset between the time the query was sent and the
// response received.
TEST_F(AutofillManagerTest, OnLoadedServerPredictions_ResetManager) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
// Simulate having seen this form on page load.
// |form_structure| will be owned by |autofill_manager_|.
TestFormStructure* form_structure = new TestFormStructure(form);
form_structure->DetermineHeuristicTypes();
autofill_manager_->AddSeenForm(form_structure);
AutofillQueryResponseContents response;
response.add_field()->set_autofill_type(3);
for (int i = 0; i < 7; ++i) {
response.add_field()->set_autofill_type(0);
}
response.add_field()->set_autofill_type(3);
response.add_field()->set_autofill_type(2);
response.add_field()->set_autofill_type(61);
std::string response_string;
ASSERT_TRUE(response.SerializeToString(&response_string));
std::vector<std::string> signatures;
signatures.push_back(form_structure->FormSignatureAsStr());
// Reset the manager (such as during a navigation).
autofill_manager_->Reset();
base::HistogramTester histogram_tester;
autofill_manager_->OnLoadedServerPredictions(response_string, signatures);
// Verify that FormStructure::ParseQueryResponse was NOT called.
histogram_tester.ExpectTotalCount("Autofill.ServerQueryResponse", 0);
}
// Test that we are able to save form data when forms are submitted and we only
// have server data for the field types.
TEST_F(AutofillManagerTest, FormSubmittedServerTypes) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
// Simulate having seen this form on page load.
// |form_structure| will be owned by |autofill_manager_|.
TestFormStructure* form_structure = new TestFormStructure(form);
form_structure->DetermineHeuristicTypes();
// Clear the heuristic types, and instead set the appropriate server types.
std::vector<ServerFieldType> heuristic_types, server_types;
for (size_t i = 0; i < form.fields.size(); ++i) {
heuristic_types.push_back(UNKNOWN_TYPE);
server_types.push_back(form_structure->field(i)->heuristic_type());
}
form_structure->SetFieldTypes(heuristic_types, server_types);
autofill_manager_->AddSeenForm(form_structure);
// Fill the form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
// Simulate form submission. We should call into the PDM to try to save the
// filled data.
FormSubmitted(response_data);
EXPECT_EQ(1, personal_data_.num_times_save_imported_profile_called());
}
// Test that we are able to save form data after the possible types have been
// determined. We do two submissions and verify that only at the second
// submission are the possible types able to be inferred.
TEST_F(AutofillManagerTest, FormSubmittedPossibleTypesTwoSubmissions) {
// Set up our form data.
FormData form;
std::vector<ServerFieldTypeSet> expected_types;
test::CreateTestAddressFormData(&form, &expected_types);
// Fill the form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
ExpectFilledAddressFormElvis(response_page_id, response_data, kDefaultPageID,
false);
personal_data_.ClearAutofillProfiles();
// The default credit card is a Elvis card. It must be removed because name
// fields would be detected. However at least one profile or card is needed to
// start the upload process, which is why this other card is created.
personal_data_.ClearCreditCards();
personal_data_.CreateTestCreditCardsYearAndMonth("2999", "04");
ASSERT_EQ(0u, personal_data_.GetProfiles().size());
// Simulate form submission. The first submission should not count the data
// towards possible types. Therefore we expect all UNKNOWN_TYPE entries.
ServerFieldTypeSet type_set;
type_set.insert(UNKNOWN_TYPE);
std::vector<ServerFieldTypeSet> unknown_types(expected_types.size(),
type_set);
autofill_manager_->set_expected_submitted_field_types(unknown_types);
FormSubmitted(response_data);
ASSERT_EQ(1u, personal_data_.GetProfiles().size());
// The second submission should now have data by which to infer types.
autofill_manager_->set_expected_submitted_field_types(expected_types);
FormSubmitted(response_data);
ASSERT_EQ(2u, personal_data_.GetProfiles().size());
}
// Test that the form signature for an uploaded form always matches the form
// signature from the query.
TEST_F(AutofillManagerTest, FormSubmittedWithDifferentFields) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Cache the expected form signature.
std::string signature = FormStructure(form).FormSignatureAsStr();
// Change the structure of the form prior to submission.
// Websites would typically invoke JavaScript either on page load or on form
// submit to achieve this.
form.fields.pop_back();
FormFieldData field = form.fields[3];
form.fields[3] = form.fields[7];
form.fields[7] = field;
// Simulate form submission.
FormSubmitted(form);
EXPECT_EQ(signature, autofill_manager_->GetSubmittedFormSignature());
}
// Test that we do not save form data when submitted fields contain default
// values.
TEST_F(AutofillManagerTest, FormSubmittedWithDefaultValues) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
form.fields[3].value = ASCIIToUTF16("Enter your address");
// Convert the state field to a <select> popup, to make sure that we only
// reject default values for text fields.
ASSERT_TRUE(form.fields[6].name == ASCIIToUTF16("state"));
form.fields[6].form_control_type = "select-one";
form.fields[6].value = ASCIIToUTF16("Tennessee");
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Fill the form.
const char guid[] = "00000000-0000-0000-0000-000000000001";
int response_page_id = 0;
FormData response_data;
FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[3],
MakeFrontendID(std::string(), guid),
&response_page_id, &response_data);
// Simulate form submission. We should call into the PDM to try to save the
// filled data.
FormSubmitted(response_data);
EXPECT_EQ(1, personal_data_.num_times_save_imported_profile_called());
// Set the address field's value back to the default value.
response_data.fields[3].value = ASCIIToUTF16("Enter your address");
// Simulate form submission. We should not call into the PDM to try to save
// the filled data, since the filled form is effectively missing an address.
FormSubmitted(response_data);
EXPECT_EQ(1, personal_data_.num_times_save_imported_profile_called());
}
// Tests that credit card data are saved for forms on https
TEST_F(AutofillManagerTest, ImportFormDataCreditCardHTTPS) {
TestSaveCreditCards(true);
}
// Tests that credit card data are saved for forms on http
TEST_F(AutofillManagerTest, ImportFormDataCreditCardHTTP) {
TestSaveCreditCards(false);
}
// Tests that credit card data are saved when autocomplete=off for CC field.
TEST_F(AutofillManagerTest, CreditCardSavedWhenAutocompleteOff) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, false, false);
// Set "autocomplete=off" for cardnumber field.
form.fields[1].should_autocomplete = false;
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Edit the data, and submit.
form.fields[1].value = ASCIIToUTF16("4111111111111111");
form.fields[2].value = ASCIIToUTF16("11");
form.fields[3].value = ASCIIToUTF16("2017");
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(form);
}
// Tests that credit card data are not saved when CC number does not pass the
// Luhn test.
TEST_F(AutofillManagerTest, InvalidCreditCardNumberIsNotSaved) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Edit the data, and submit.
std::string card("4408041234567890");
ASSERT_FALSE(autofill::IsValidCreditCardNumber(ASCIIToUTF16(card)));
form.fields[1].value = ASCIIToUTF16(card);
form.fields[2].value = ASCIIToUTF16("11");
form.fields[3].value = ASCIIToUTF16("2017");
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(form);
}
// Tests that DeterminePossibleFieldTypesForUpload makes accurate matches.
TEST_F(AutofillManagerTest, DeterminePossibleFieldTypesForUpload) {
// Set up the test profiles.
std::vector<AutofillProfile> profiles;
AutofillProfile profile;
test::SetProfileInfo(&profile, "Elvis", "Aaron", "Presley",
"theking@gmail.com", "RCA", "3734 Elvis Presley Blvd.",
"Apt. 10", "Memphis", "Tennessee", "38116", "US",
"+1 (234) 567-8901");
profile.set_guid("00000000-0000-0000-0000-000000000001");
profiles.push_back(profile);
test::SetProfileInfo(&profile, "Charles", "", "Holley", "buddy@gmail.com",
"Decca", "123 Apple St.", "unit 6", "Lubbock", "TX",
"79401", "US", "5142821292");
profile.set_guid("00000000-0000-0000-0000-000000000002");
profiles.push_back(profile);
test::SetProfileInfo(&profile, "Charles", "", "Baudelaire",
"lesfleursdumal@gmail.com", "", "108 Rue Saint-Lazare",
"Apt. 10", "Paris", "Île de France", "75008", "FR",
"+33 2 49 19 70 70");
profile.set_guid("00000000-0000-0000-0000-000000000001");
profiles.push_back(profile);
// Set up the test credit cards.
std::vector<CreditCard> credit_cards;
CreditCard credit_card;
test::SetCreditCardInfo(&credit_card, "John Doe", "4234-5678-9012-3456", "04",
"2999");
credit_card.set_guid("00000000-0000-0000-0000-000000000003");
credit_cards.push_back(credit_card);
typedef struct {
std::string input_value; // The value to input in the field.
ServerFieldType field_type; // The expected field type to be determined.
} TestCase;
TestCase test_cases[] = {
// Profile fields matches.
{"Elvis", NAME_FIRST},
{"Aaron", NAME_MIDDLE},
{"A", NAME_MIDDLE_INITIAL},
{"Presley", NAME_LAST},
{"Elvis Aaron Presley", NAME_FULL},
{"theking@gmail.com", EMAIL_ADDRESS},
{"RCA", COMPANY_NAME},
{"3734 Elvis Presley Blvd.", ADDRESS_HOME_LINE1},
{"Apt. 10", ADDRESS_HOME_LINE2},
{"Memphis", ADDRESS_HOME_CITY},
{"Tennessee", ADDRESS_HOME_STATE},
{"38116", ADDRESS_HOME_ZIP},
{"USA", ADDRESS_HOME_COUNTRY},
{"United States", ADDRESS_HOME_COUNTRY},
{"12345678901", PHONE_HOME_WHOLE_NUMBER},
{"+1 (234) 567-8901", PHONE_HOME_WHOLE_NUMBER},
{"(234)567-8901", PHONE_HOME_CITY_AND_NUMBER},
{"2345678901", PHONE_HOME_CITY_AND_NUMBER},
{"1", PHONE_HOME_COUNTRY_CODE},
{"234", PHONE_HOME_CITY_CODE},
{"5678901", PHONE_HOME_NUMBER},
{"567", PHONE_HOME_NUMBER},
{"8901", PHONE_HOME_NUMBER},
// Test a European profile.
{"Paris", ADDRESS_HOME_CITY},
{"Île de France", ADDRESS_HOME_STATE}, // Exact match
{"Ile de France", ADDRESS_HOME_STATE}, // Missing accent.
{"-Ile-de-France-", ADDRESS_HOME_STATE}, // Extra punctuation.
{"île dÉ FrÃÑÇË", ADDRESS_HOME_STATE}, // Other accents & case mismatch.
{"75008", ADDRESS_HOME_ZIP},
{"FR", ADDRESS_HOME_COUNTRY},
{"France", ADDRESS_HOME_COUNTRY},
{"33249197070", PHONE_HOME_WHOLE_NUMBER},
{"+33 2 49 19 70 70", PHONE_HOME_WHOLE_NUMBER},
{"2 49 19 70 70", PHONE_HOME_CITY_AND_NUMBER},
{"249197070", PHONE_HOME_CITY_AND_NUMBER},
{"33", PHONE_HOME_COUNTRY_CODE},
{"2", PHONE_HOME_CITY_CODE},
// Credit card fields matches.
{"John Doe", CREDIT_CARD_NAME_FULL},
{"John", CREDIT_CARD_NAME_FIRST},
{"Doe", CREDIT_CARD_NAME_LAST},
{"4234-5678-9012-3456", CREDIT_CARD_NUMBER},
{"04", CREDIT_CARD_EXP_MONTH},
{"April", CREDIT_CARD_EXP_MONTH},
{"2999", CREDIT_CARD_EXP_4_DIGIT_YEAR},
{"99", CREDIT_CARD_EXP_2_DIGIT_YEAR},
{"04/2999", CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR},
// Make sure whitespace and invalid characters are handled properly.
{"", EMPTY_TYPE},
{" ", EMPTY_TYPE},
{"***", UNKNOWN_TYPE},
{" Elvis", NAME_FIRST},
{"Elvis ", NAME_FIRST},
// Make sure fields that differ by case match.
{"elvis ", NAME_FIRST},
{"UnItEd StAtEs", ADDRESS_HOME_COUNTRY},
// Make sure fields that differ by punctuation match.
{"3734 Elvis Presley Blvd", ADDRESS_HOME_LINE1},
{"3734, Elvis Presley Blvd.", ADDRESS_HOME_LINE1},
// Make sure that a state's full name and abbreviation match.
{"TN", ADDRESS_HOME_STATE}, // Saved as "Tennessee" in profile.
{"Texas", ADDRESS_HOME_STATE}, // Saved as "TX" in profile.
// Special phone number case. A profile with no country code should only
// match PHONE_HOME_CITY_AND_NUMBER.
{"5142821292", PHONE_HOME_CITY_AND_NUMBER},
// Make sure unsupported variants do not match.
{"Elvis Aaron", UNKNOWN_TYPE},
{"Mr. Presley", UNKNOWN_TYPE},
{"3734 Elvis Presley", UNKNOWN_TYPE},
{"38116-1023", UNKNOWN_TYPE},
{"5", UNKNOWN_TYPE},
{"56", UNKNOWN_TYPE},
{"901", UNKNOWN_TYPE}};
for (TestCase test_case : test_cases) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("", "1", "", "text", &field);
field.value = UTF8ToUTF16(test_case.input_value);
form.fields.push_back(field);
FormStructure form_structure(form);
AutofillManager::DeterminePossibleFieldTypesForUpload(
profiles, credit_cards, "en-us", &form_structure);
ASSERT_EQ(1U, form_structure.field_count());
ServerFieldTypeSet possible_types =
form_structure.field(0)->possible_types();
EXPECT_EQ(1U, possible_types.size());
EXPECT_NE(possible_types.end(), possible_types.find(test_case.field_type))
<< "Failed to determine type for: \"" << test_case.input_value << "\"";
}
}
// Tests that DeterminePossibleFieldTypesForUpload is called when a form is
// submitted.
TEST_F(AutofillManagerTest, DeterminePossibleFieldTypesForUpload_IsTriggered) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
std::vector<ServerFieldTypeSet> expected_types;
std::vector<base::string16> expected_values;
// These fields should all match.
FormFieldData field;
ServerFieldTypeSet types;
test::CreateTestFormField("", "1", "", "text", &field);
expected_values.push_back(ASCIIToUTF16("Elvis"));
types.clear();
types.insert(NAME_FIRST);
form.fields.push_back(field);
expected_types.push_back(types);
test::CreateTestFormField("", "2", "", "text", &field);
expected_values.push_back(ASCIIToUTF16("Aaron"));
types.clear();
types.insert(NAME_MIDDLE);
form.fields.push_back(field);
expected_types.push_back(types);
test::CreateTestFormField("", "3", "", "text", &field);
expected_values.push_back(ASCIIToUTF16("A"));
types.clear();
types.insert(NAME_MIDDLE_INITIAL);
form.fields.push_back(field);
expected_types.push_back(types);
// Make sure the form is in the cache so that it is processed for Autofill
// upload.
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Once the form is cached, fill the values.
EXPECT_EQ(form.fields.size(), expected_values.size());
for (size_t i = 0; i < expected_values.size(); i++) {
form.fields[i].value = expected_values[i];
}
autofill_manager_->set_expected_submitted_field_types(expected_types);
FormSubmitted(form);
}
// Tests that DisambiguateUploadTypes makes the correct choices.
TEST_F(AutofillManagerTest, DisambiguateUploadTypes) {
// Set up the test profile.
std::vector<AutofillProfile> profiles;
AutofillProfile profile;
test::SetProfileInfo(&profile, "Elvis", "Aaron", "Presley",
"theking@gmail.com", "RCA", "3734 Elvis Presley Blvd.",
"", "Memphis", "Tennessee", "38116", "US",
"(234) 567-8901");
profile.set_guid("00000000-0000-0000-0000-000000000001");
profiles.push_back(profile);
// Set up the test credit card.
std::vector<CreditCard> credit_cards;
CreditCard credit_card;
test::SetCreditCardInfo(&credit_card, "Elvis Presley", "4234-5678-9012-3456",
"04", "2999");
credit_card.set_guid("00000000-0000-0000-0000-000000000003");
credit_cards.push_back(credit_card);
typedef struct {
std::string input_value;
ServerFieldType predicted_type;
bool expect_disambiguation;
ServerFieldType expected_upload_type;
} TestFieldData;
std::vector<TestFieldData> test_cases[13];
// Address disambiguation.
// An ambiguous address line followed by a field predicted as a line 2 and
// that is empty should be disambiguated as an ADDRESS_HOME_LINE1.
test_cases[0].push_back({"3734 Elvis Presley Blvd.", ADDRESS_HOME_LINE1, true,
ADDRESS_HOME_LINE1});
test_cases[0].push_back({"", ADDRESS_HOME_LINE2, true, EMPTY_TYPE});
// An ambiguous address line followed by a field predicted as a line 2 but
// filled with another know profile value should be disambiguated as an
// ADDRESS_HOME_STREET_ADDRESS.
test_cases[1].push_back({"3734 Elvis Presley Blvd.",
ADDRESS_HOME_STREET_ADDRESS, true,
ADDRESS_HOME_STREET_ADDRESS});
test_cases[1].push_back(
{"38116", ADDRESS_HOME_LINE2, true, ADDRESS_HOME_ZIP});
// An ambiguous address line followed by an empty field predicted as
// something other than a line 2 should be disambiguated as an
// ADDRESS_HOME_STREET_ADDRESS.
test_cases[2].push_back({"3734 Elvis Presley Blvd.",
ADDRESS_HOME_STREET_ADDRESS, true,
ADDRESS_HOME_STREET_ADDRESS});
test_cases[2].push_back({"", ADDRESS_HOME_ZIP, true, EMPTY_TYPE});
// An ambiguous address line followed by no other field should be
// disambiguated as an ADDRESS_HOME_STREET_ADDRESS.
test_cases[3].push_back({"3734 Elvis Presley Blvd.",
ADDRESS_HOME_STREET_ADDRESS, true,
ADDRESS_HOME_STREET_ADDRESS});
// Phone number disambiguation.
// A field with possible types PHONE_HOME_CITY_AND_NUMBER and
// PHONE_HOME_WHOLE_NUMBER should be disambiguated as
// PHONE_HOME_CITY_AND_NUMBER
test_cases[4].push_back({"2345678901", PHONE_HOME_WHOLE_NUMBER, true,
PHONE_HOME_CITY_AND_NUMBER});
// Name disambiguation.
// An ambiguous name field that has no next field and that is preceded by
// a non credit card field should be disambiguated as a non credit card
// name.
test_cases[5].push_back(
{"Memphis", ADDRESS_HOME_CITY, true, ADDRESS_HOME_CITY});
test_cases[5].push_back({"Elvis", CREDIT_CARD_NAME_FIRST, true, NAME_FIRST});
test_cases[5].push_back({"Presley", CREDIT_CARD_NAME_LAST, true, NAME_LAST});
// An ambiguous name field that has no next field and that is preceded by
// a credit card field should be disambiguated as a credit card name.
test_cases[6].push_back(
{"4234-5678-9012-3456", CREDIT_CARD_NUMBER, true, CREDIT_CARD_NUMBER});
test_cases[6].push_back({"Elvis", NAME_FIRST, true, CREDIT_CARD_NAME_FIRST});
test_cases[6].push_back({"Presley", NAME_LAST, true, CREDIT_CARD_NAME_LAST});
// An ambiguous name field that has no previous field and that is
// followed by a non credit card field should be disambiguated as a non
// credit card name.
test_cases[7].push_back({"Elvis", CREDIT_CARD_NAME_FIRST, true, NAME_FIRST});
test_cases[7].push_back({"Presley", CREDIT_CARD_NAME_LAST, true, NAME_LAST});
test_cases[7].push_back(
{"Memphis", ADDRESS_HOME_CITY, true, ADDRESS_HOME_CITY});
// An ambiguous name field that has no previous field and that is followed
// by a credit card field should be disambiguated as a credit card name.
test_cases[8].push_back({"Elvis", NAME_FIRST, true, CREDIT_CARD_NAME_FIRST});
test_cases[8].push_back({"Presley", NAME_LAST, true, CREDIT_CARD_NAME_LAST});
test_cases[8].push_back(
{"4234-5678-9012-3456", CREDIT_CARD_NUMBER, true, CREDIT_CARD_NUMBER});
// An ambiguous name field that is preceded and followed by non credit
// card fields should be disambiguated as a non credit card name.
test_cases[9].push_back(
{"Memphis", ADDRESS_HOME_CITY, true, ADDRESS_HOME_CITY});
test_cases[9].push_back({"Elvis", CREDIT_CARD_NAME_FIRST, true, NAME_FIRST});
test_cases[9].push_back({"Presley", CREDIT_CARD_NAME_LAST, true, NAME_LAST});
test_cases[9].push_back(
{"Tennessee", ADDRESS_HOME_STATE, true, ADDRESS_HOME_STATE});
// An ambiguous name field that is preceded and followed by credit card
// fields should be disambiguated as a credit card name.
test_cases[10].push_back(
{"4234-5678-9012-3456", CREDIT_CARD_NUMBER, true, CREDIT_CARD_NUMBER});
test_cases[10].push_back({"Elvis", NAME_FIRST, true, CREDIT_CARD_NAME_FIRST});
test_cases[10].push_back({"Presley", NAME_LAST, true, CREDIT_CARD_NAME_LAST});
test_cases[10].push_back({"2999", CREDIT_CARD_EXP_4_DIGIT_YEAR, true,
CREDIT_CARD_EXP_4_DIGIT_YEAR});
// An ambiguous name field that is preceded by a non credit card field and
// followed by a credit card field should not be disambiguated.
test_cases[11].push_back(
{"Memphis", ADDRESS_HOME_CITY, true, ADDRESS_HOME_CITY});
test_cases[11].push_back(
{"Elvis", NAME_FIRST, false, CREDIT_CARD_NAME_FIRST});
test_cases[11].push_back(
{"Presley", NAME_LAST, false, CREDIT_CARD_NAME_LAST});
test_cases[11].push_back({"2999", CREDIT_CARD_EXP_4_DIGIT_YEAR, true,
CREDIT_CARD_EXP_4_DIGIT_YEAR});
// An ambiguous name field that is preceded by a credit card field and
// followed by a non credit card field should not be disambiguated.
test_cases[12].push_back({"2999", CREDIT_CARD_EXP_4_DIGIT_YEAR, true,
CREDIT_CARD_EXP_4_DIGIT_YEAR});
test_cases[12].push_back(
{"Elvis", NAME_FIRST, false, CREDIT_CARD_NAME_FIRST});
test_cases[12].push_back(
{"Presley", NAME_LAST, false, CREDIT_CARD_NAME_LAST});
test_cases[12].push_back(
{"Memphis", ADDRESS_HOME_CITY, true, ADDRESS_HOME_CITY});
for (const std::vector<TestFieldData>& test_fields : test_cases) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
// Create the form fields specified in the test case.
FormFieldData field;
for (const TestFieldData& test_field : test_fields) {
test::CreateTestFormField("", "1", "", "text", &field);
field.value = ASCIIToUTF16(test_field.input_value);
form.fields.push_back(field);
}
// Assign the specified predicted type for each field in the test case.
FormStructure form_structure(form);
for (size_t i = 0; i < test_fields.size(); ++i) {
form_structure.field(i)->set_server_type(test_fields[i].predicted_type);
}
AutofillManager::DeterminePossibleFieldTypesForUpload(
profiles, credit_cards, "en-us", &form_structure);
ASSERT_EQ(test_fields.size(), form_structure.field_count());
// Make sure the disambiguation method selects the expected upload type.
ServerFieldTypeSet possible_types;
for (size_t i = 0; i < test_fields.size(); ++i) {
possible_types = form_structure.field(i)->possible_types();
if (test_fields[i].expect_disambiguation) {
EXPECT_EQ(1U, possible_types.size());
EXPECT_NE(possible_types.end(),
possible_types.find(test_fields[i].expected_upload_type));
} else {
EXPECT_EQ(2U, possible_types.size());
}
}
}
}
TEST_F(AutofillManagerTest, RemoveProfile) {
// Add and remove an Autofill profile.
AutofillProfile* profile = new AutofillProfile;
const char guid[] = "00000000-0000-0000-0000-000000000102";
profile->set_guid(guid);
autofill_manager_->AddProfile(profile);
int id = MakeFrontendID(std::string(), guid);
autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
EXPECT_FALSE(autofill_manager_->GetProfileWithGUID(guid));
}
TEST_F(AutofillManagerTest, RemoveCreditCard) {
// Add and remove an Autofill credit card.
CreditCard* credit_card = new CreditCard;
const char guid[] = "00000000-0000-0000-0000-000000100007";
credit_card->set_guid(guid);
autofill_manager_->AddCreditCard(credit_card);
int id = MakeFrontendID(guid, std::string());
autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
EXPECT_FALSE(autofill_manager_->GetCreditCardWithGUID(guid));
}
// Test our external delegate is called at the right time.
TEST_F(AutofillManagerTest, TestExternalDelegate) {
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
const FormFieldData& field = form.fields[0];
GetAutofillSuggestions(form, field); // should call the delegate's OnQuery()
EXPECT_TRUE(external_delegate_->on_query_seen());
}
// Test that unfocusing a filled form sends an upload with types matching the
// fields.
TEST_F(AutofillManagerTest, OnTextFieldDidChangeAndUnfocus_Upload) {
// Set up our form data (it's already filled out with user data).
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
std::vector<ServerFieldTypeSet> expected_types;
ServerFieldTypeSet types;
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
form.fields.push_back(field);
types.insert(NAME_FIRST);
expected_types.push_back(types);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
form.fields.push_back(field);
types.clear();
types.insert(NAME_LAST);
expected_types.push_back(types);
test::CreateTestFormField("Email", "email", "", "text", &field);
form.fields.push_back(field);
types.clear();
types.insert(EMAIL_ADDRESS);
expected_types.push_back(types);
FormsSeen(std::vector<FormData>(1, form));
// We will expect these types in the upload and no observed submission (the
// callback initiated by WaitForAsyncUploadProcess checks these expectations.)
autofill_manager_->set_expected_submitted_field_types(expected_types);
autofill_manager_->set_expected_observed_submission(false);
// The fields are edited after calling FormsSeen on them. This is because
// default values are not used for upload comparisons.
form.fields[0].value = ASCIIToUTF16("Elvis");
form.fields[1].value = ASCIIToUTF16("Presley");
form.fields[2].value = ASCIIToUTF16("theking@gmail.com");
// Simulate editing a field.
autofill_manager_->OnTextFieldDidChange(form, form.fields.front(),
base::TimeTicks::Now());
autofill_manager_->ResetRunLoop();
// Simulate lost of focus on the form.
autofill_manager_->OnFocusNoLongerOnForm();
// Wait for upload to complete (will check expected types as well).
autofill_manager_->WaitForAsyncUploadProcess();
}
// Test that navigating with a filled form sends an upload with types matching
// the fields.
TEST_F(AutofillManagerTest, OnTextFieldDidChangeAndNavigation_Upload) {
// Set up our form data (it's already filled out with user data).
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
std::vector<ServerFieldTypeSet> expected_types;
ServerFieldTypeSet types;
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
form.fields.push_back(field);
types.insert(NAME_FIRST);
expected_types.push_back(types);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
form.fields.push_back(field);
types.clear();
types.insert(NAME_LAST);
expected_types.push_back(types);
test::CreateTestFormField("Email", "email", "", "text", &field);
form.fields.push_back(field);
types.clear();
types.insert(EMAIL_ADDRESS);
expected_types.push_back(types);
FormsSeen(std::vector<FormData>(1, form));
// We will expect these types in the upload and no observed submission. (the
// callback initiated by WaitForAsyncUploadProcess checks these expectations.)
autofill_manager_->set_expected_submitted_field_types(expected_types);
autofill_manager_->set_expected_observed_submission(false);
// The fields are edited after calling FormsSeen on them. This is because
// default values are not used for upload comparisons.
form.fields[0].value = ASCIIToUTF16("Elvis");
form.fields[1].value = ASCIIToUTF16("Presley");
form.fields[2].value = ASCIIToUTF16("theking@gmail.com");
// Simulate editing a field.
autofill_manager_->OnTextFieldDidChange(form, form.fields.front(),
base::TimeTicks::Now());
autofill_manager_->ResetRunLoop();
// Simulate a navigation so that the pending form is uploaded.
autofill_manager_->Reset();
// Wait for upload to complete (will check expected types as well).
autofill_manager_->WaitForAsyncUploadProcess();
}
// Test that unfocusing a filled form sends an upload with types matching the
// fields.
TEST_F(AutofillManagerTest, OnDidFillAutofillFormDataAndUnfocus_Upload) {
// Set up our form data (empty).
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
std::vector<ServerFieldTypeSet> expected_types;
// These fields should all match.
ServerFieldTypeSet types;
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
form.fields.push_back(field);
types.insert(NAME_FIRST);
expected_types.push_back(types);
test::CreateTestFormField("Last Name", "lastname", "", "text", &field);
form.fields.push_back(field);
types.clear();
types.insert(NAME_LAST);
expected_types.push_back(types);
test::CreateTestFormField("Email", "email", "", "text", &field);
form.fields.push_back(field);
types.clear();
types.insert(EMAIL_ADDRESS);
expected_types.push_back(types);
FormsSeen(std::vector<FormData>(1, form));
// We will expect these types in the upload and no observed submission. (the
// callback initiated by WaitForAsyncUploadProcess checks these expectations.)
autofill_manager_->set_expected_submitted_field_types(expected_types);
autofill_manager_->set_expected_observed_submission(false);
// Form was autofilled with user data.
form.fields[0].value = ASCIIToUTF16("Elvis");
form.fields[1].value = ASCIIToUTF16("Presley");
form.fields[2].value = ASCIIToUTF16("theking@gmail.com");
autofill_manager_->OnDidFillAutofillFormData(form, base::TimeTicks::Now());
autofill_manager_->ResetRunLoop();
// Simulate lost of focus on the form.
autofill_manager_->OnFocusNoLongerOnForm();
// Wait for upload to complete.
autofill_manager_->WaitForAsyncUploadProcess();
}
// Test that suggestions are returned for credit card fields with an
// unrecognized
// autocomplete attribute.
TEST_F(AutofillManagerTest, GetCreditCardSuggestions_UnrecognizedAttribute) {
// Set up the form data.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
// Set a valid autocomplete attribute on the card name.
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
field.autocomplete_attribute = "cc-name";
form.fields.push_back(field);
// Set no autocomplete attribute on the card number.
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
field.autocomplete_attribute = "";
form.fields.push_back(field);
// Set an unrecognized autocomplete attribute on the expiration month.
test::CreateTestFormField("Expiration Date", "ccmonth", "", "text", &field);
field.autocomplete_attribute = "unrecognized";
form.fields.push_back(field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Suggestions should be returned for the first two fields
GetAutofillSuggestions(form, form.fields[0]);
EXPECT_TRUE(external_delegate_->on_suggestions_returned_seen());
GetAutofillSuggestions(form, form.fields[1]);
EXPECT_TRUE(external_delegate_->on_suggestions_returned_seen());
// Suggestions should still be returned for the third field because it is a
// credit card field.
GetAutofillSuggestions(form, form.fields[2]);
EXPECT_TRUE(external_delegate_->on_suggestions_returned_seen());
}
// Test to verify suggestions appears for forms having credit card number split
// across fields.
TEST_F(AutofillManagerTest,
GetCreditCardSuggestions_ForNumberSpitAcrossFields) {
// Set up our form data with credit card number split across fields.
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("https://myform.com/form.html");
form.action = GURL("https://myform.com/submit.html");
FormFieldData name_field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text",
&name_field);
form.fields.push_back(name_field);
// Add new 4 |card_number_field|s to the |form|.
FormFieldData card_number_field;
card_number_field.max_length = 4;
test::CreateTestFormField("Card Number", "cardnumber_1", "", "text",
&card_number_field);
form.fields.push_back(card_number_field);
test::CreateTestFormField("", "cardnumber_2", "", "text", &card_number_field);
form.fields.push_back(card_number_field);
test::CreateTestFormField("", "cardnumber_3", "", "text", &card_number_field);
form.fields.push_back(card_number_field);
test::CreateTestFormField("", "cardnumber_4", "", "text", &card_number_field);
form.fields.push_back(card_number_field);
FormFieldData exp_field;
test::CreateTestFormField("Expiration Date", "ccmonth", "", "text",
&exp_field);
form.fields.push_back(exp_field);
test::CreateTestFormField("", "ccyear", "", "text", &exp_field);
form.fields.push_back(exp_field);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Verify whether suggestions are populated correctly for one of the middle
// credit card number fields when filled partially.
FormFieldData number_field = form.fields[3];
number_field.value = ASCIIToUTF16("901");
// Get the suggestions for already filled credit card |number_field|.
GetAutofillSuggestions(form, number_field);
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Visa\xC2\xA0\xE2\x8B\xAF"
"3456",
"04/99", kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)));
}
// Test that inputs detected to be CVC inputs are forced to
// !should_autocomplete for AutocompleteHistoryManager::OnWillSubmitForm.
TEST_F(AutofillManagerTest, DontSaveCvcInAutocompleteHistory) {
FormData form_seen_by_ahm;
MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager();
EXPECT_CALL(*m, OnWillSubmitForm(_)).WillOnce(SaveArg<0>(&form_seen_by_ahm));
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
struct {
const char* label;
const char* name;
const char* value;
ServerFieldType expected_field_type;
} fields[] = {
{"Card number", "1", "4234-5678-9012-3456", CREDIT_CARD_NUMBER},
{"Card verification code", "2", "123", CREDIT_CARD_VERIFICATION_CODE},
{"expiration date", "3", "04/2020", CREDIT_CARD_EXP_4_DIGIT_YEAR},
};
for (size_t i = 0; i < arraysize(fields); ++i) {
FormFieldData field;
test::CreateTestFormField(fields[i].label, fields[i].name, fields[i].value,
"text", &field);
form.fields.push_back(field);
}
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormSubmitted(form);
EXPECT_EQ(form.fields.size(), form_seen_by_ahm.fields.size());
ASSERT_EQ(arraysize(fields), form_seen_by_ahm.fields.size());
for (size_t i = 0; i < arraysize(fields); ++i) {
EXPECT_EQ(form_seen_by_ahm.fields[i].should_autocomplete,
fields[i].expected_field_type != CREDIT_CARD_VERIFICATION_CODE);
}
}
TEST_F(AutofillManagerTest, DontOfferToSavePaymentsCard) {
FormData form;
CreditCard card;
PrepareForRealPanResponse(&form, &card);
// Manually fill out |form| so we can use it in OnFormSubmitted.
for (size_t i = 0; i < form.fields.size(); ++i) {
if (form.fields[i].name == ASCIIToUTF16("cardnumber"))
form.fields[i].value = ASCIIToUTF16("4012888888881881");
else if (form.fields[i].name == ASCIIToUTF16("nameoncard"))
form.fields[i].value = ASCIIToUTF16("John H Dillinger");
else if (form.fields[i].name == ASCIIToUTF16("ccmonth"))
form.fields[i].value = ASCIIToUTF16("01");
else if (form.fields[i].name == ASCIIToUTF16("ccyear"))
form.fields[i].value = ASCIIToUTF16("2017");
}
CardUnmaskDelegate::UnmaskResponse response;
response.should_store_pan = false;
response.cvc = ASCIIToUTF16("123");
full_card_unmask_delegate()->OnUnmaskResponse(response);
autofill_manager_->OnDidGetRealPan(AutofillClient::SUCCESS,
"4012888888881881");
autofill_manager_->OnFormSubmitted(form);
}
TEST_F(AutofillManagerTest, FillInUpdatedExpirationDate) {
FormData form;
CreditCard card;
PrepareForRealPanResponse(&form, &card);
CardUnmaskDelegate::UnmaskResponse response;
response.should_store_pan = false;
response.cvc = ASCIIToUTF16("123");
response.exp_month = ASCIIToUTF16("02");
response.exp_year = ASCIIToUTF16("2018");
full_card_unmask_delegate()->OnUnmaskResponse(response);
autofill_manager_->OnDidGetRealPan(AutofillClient::SUCCESS,
"4012888888881881");
}
TEST_F(AutofillManagerTest, UploadCreditCard) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
FormSubmitted(credit_card_form);
EXPECT_TRUE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample("Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_OFFERED, 1);
}
TEST_F(AutofillManagerTest, UploadCreditCard_FeatureNotEnabled) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(false);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// The save prompt should be shown instead of doing an upload.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that no histogram entry was logged called.
histogram_tester.ExpectTotalCount("Autofill.CardUploadDecisionExpanded", 0);
}
TEST_F(AutofillManagerTest, UploadCreditCard_CvcUnavailable) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_CVC, 1);
rappor::TestRapporService* rappor_service =
autofill_client_.test_rappor_service();
EXPECT_EQ(1, rappor_service->GetReportsCount());
std::string sample;
rappor::RapporType type;
EXPECT_TRUE(rappor_service->GetRecordedSampleForMetric(
"Autofill.CardUploadNotOfferedNoCvc", &sample, &type));
EXPECT_EQ("myform.com", sample);
EXPECT_EQ(rappor::ETLD_PLUS_ONE_RAPPOR_TYPE, type);
}
TEST_F(AutofillManagerTest, UploadCreditCard_MultipleCvcFields) {
autofill_manager_->set_credit_card_upload_enabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearAutofillProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("CVC (hidden)", "cvc1", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("CVC", "cvc2", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
credit_card_form.fields[5].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// A CVC value appeared in one of the two CVC fields, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_OFFERED, 1);
}
TEST_F(AutofillManagerTest, UploadCreditCard_NoProfileAvailable) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Bob Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS, 1);
rappor::TestRapporService* rappor_service =
autofill_client_.test_rappor_service();
EXPECT_EQ(1, rappor_service->GetReportsCount());
std::string sample;
rappor::RapporType type;
EXPECT_TRUE(rappor_service->GetRecordedSampleForMetric(
"Autofill.CardUploadNotOfferedNoAddress", &sample, &type));
EXPECT_EQ("myform.com", sample);
EXPECT_EQ(rappor::ETLD_PLUS_ONE_RAPPOR_TYPE, type);
}
TEST_F(AutofillManagerTest, UploadCreditCard_NoNameAvailable) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// But omit the name:
ManuallyFillAddressForm("", "", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME, 1);
rappor::TestRapporService* rappor_service =
autofill_client_.test_rappor_service();
EXPECT_EQ(1, rappor_service->GetReportsCount());
std::string sample;
rappor::RapporType type;
EXPECT_TRUE(rappor_service->GetRecordedSampleForMetric(
"Autofill.CardUploadNotOfferedNoName", &sample, &type));
EXPECT_EQ("myform.com", sample);
EXPECT_EQ(rappor::ETLD_PLUS_ONE_RAPPOR_TYPE, type);
}
TEST_F(AutofillManagerTest, UploadCreditCard_ZipCodesConflict) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit two address forms with different zip codes.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ManuallyFillAddressForm("Flo", "Master", "77401-8294", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Flo", "Master", "77401-1234", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS, 1);
}
TEST_F(AutofillManagerTest, UploadCreditCard_ZipCodesHavePrefixMatch) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit two address forms with different zip codes.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Flo", "Master", "77401-8294", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// One zip is a prefix of the other, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_OFFERED, 1);
}
TEST_F(AutofillManagerTest, UploadCreditCard_NoZipCodeAvailable) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// Autofill's validation requirements for Venezuala ("VE", see
// src/components/autofill/core/browser/country_data.cc) do not require zip
// codes. We use Venezuala here because to use the US (or one of many other
// countries which autofill requires a zip code for) would result in no
// address being imported at all, and then we never reach the check for
// missing zip code in the upload code.
ManuallyFillAddressForm("Flo", "Master", "" /* zip_code */, "Venezuela",
&address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE, 1);
}
TEST_F(AutofillManagerTest, UploadCreditCard_NamesMatchLoosely) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
// Names can be different case.
ManuallyFillAddressForm("flo", "master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
// And they can have a middle initial even if the other names don't.
ManuallyFillAddressForm("Flo W", "Master", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but use the name with a middle initial *and* period, and
// submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo W. Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names match loosely, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_OFFERED, 1);
}
TEST_F(AutofillManagerTest, UploadCreditCard_NamesHaveToMatch) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Master", "Blaster", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but use yet another name, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Bob Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names are required to match, upload should not happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES, 1);
rappor::TestRapporService* rappor_service =
autofill_client_.test_rappor_service();
EXPECT_EQ(1, rappor_service->GetReportsCount());
std::string sample;
rappor::RapporType type;
EXPECT_TRUE(rappor_service->GetRecordedSampleForMetric(
"Autofill.CardUploadNotOfferedConflictingNames", &sample, &type));
EXPECT_EQ("myform.com", sample);
EXPECT_EQ(rappor::ETLD_PLUS_ONE_RAPPOR_TYPE, type);
}
TEST_F(AutofillManagerTest, UploadCreditCard_UploadDetailsFails) {
personal_data_.ClearAutofillProfiles();
autofill_manager_->set_credit_card_upload_enabled(true);
// Anything other than "en-US" will cause GetUploadDetails to return a failure
// response.
autofill_manager_->set_app_locale("pt-BR");
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16("2017");
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// The save prompt should be shown instead of doing an upload.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(credit_card_form);
EXPECT_FALSE(autofill_manager_->credit_card_was_uploaded());
// Verify that the correct histogram entry (and only that) was logged.
histogram_tester.ExpectUniqueSample(
"Autofill.CardUploadDecisionExpanded",
AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED, 1);
}
// Verify that typing "gmail" will match "theking@gmail.com" and
// "buddy@gmail.com" when substring matching is enabled.
TEST_F(AutofillManagerTest, DisplaySuggestionsWithMatchingTokens) {
// Token matching is currently behind a flag.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSuggestionsWithSubstringMatch);
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Email", "email", "gmail", "email", &field);
GetAutofillSuggestions(form, field);
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("buddy@gmail.com", "123 Apple St.", "", 1),
Suggestion("theking@gmail.com", "3734 Elvis Presley Blvd.", "", 2));
}
// Verify that typing "apple" will match "123 Apple St." when substring matching
// is enabled.
TEST_F(AutofillManagerTest, DisplaySuggestionsWithMatchingTokens_CaseIgnored) {
// Token matching is currently behind a flag.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSuggestionsWithSubstringMatch);
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Address Line 2", "addr2", "apple", "text", &field);
GetAutofillSuggestions(form, field);
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("123 Apple St., unit 6", "123 Apple St.", "", 1));
}
// Verify that typing "mail" will not match any of the "@gmail.com" email
// addresses when substring matching is enabled.
TEST_F(AutofillManagerTest, NoSuggestionForNonPrefixTokenMatch) {
// Token matching is currently behind a flag.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSuggestionsWithSubstringMatch);
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Email", "email", "mail", "email", &field);
GetAutofillSuggestions(form, field);
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Verify that typing "pres" will match "Elvis Presley" when substring matching
// is enabled.
TEST_F(AutofillManagerTest, DisplayCreditCardSuggestionsWithMatchingTokens) {
// Token matching is currently behind a flag.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSuggestionsWithSubstringMatch);
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "pres", "text",
&field);
GetAutofillSuggestions(form, field);
#if defined(OS_ANDROID)
static const char* kVisaSuggestion =
"Visa\xC2\xA0\xE2\x8B\xAF"
"3456";
#else
static const char* kVisaSuggestion = "*3456";
#endif
external_delegate_->CheckSuggestions(
kDefaultPageID, Suggestion("Elvis Presley", kVisaSuggestion, kVisaCard,
autofill_manager_->GetPackedCreditCardID(4)));
}
// Verify that typing "lvis" will not match any of the credit card name when
// substring matching is enabled.
TEST_F(AutofillManagerTest, NoCreditCardSuggestionsForNonPrefixTokenMatch) {
// Token matching is currently behind a flag.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSuggestionsWithSubstringMatch);
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "lvis", "text",
&field);
GetAutofillSuggestions(form, field);
// Autocomplete suggestions are queried, but not Autofill.
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
}
// Test that ShouldShowCreditCardSigninPromo behaves as expected for a credit
// card form, with no impression limit and the feature enabled.
TEST_F(AutofillManagerTest,
ShouldShowCreditCardSigninPromo_CreditCardField_NoLimit) {
// Enable the feature with no impression limit.
EnableCreditCardSigninPromoFeatureWithLimit(0);
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
// The result will depend on what ShouldShowSigninPromo(). We control its
// output and verify that both cases behave as expected.
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo())
.WillOnce(testing::Return(true));
EXPECT_TRUE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo())
.WillOnce(testing::Return(false));
EXPECT_FALSE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
}
// Test that ShouldShowCreditCardSigninPromo doesn't show for a credit card form
// when the feature is off.
TEST_F(AutofillManagerTest,
ShouldShowCreditCardSigninPromo_CreditCardField_FeatureOff) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
// Returns false without calling ShouldShowSigninPromo().
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo()).Times(0);
EXPECT_FALSE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
}
// Test that ShouldShowCreditCardSigninPromo behaves as expected for a credit
// card form with an impression limit and no impressions yet.
TEST_F(AutofillManagerTest,
ShouldShowCreditCardSigninPromo_CreditCardField_UnmetLimit) {
// Enable the feature with an impression limit.
EnableCreditCardSigninPromoFeatureWithLimit(10);
// No impressions yet.
ASSERT_EQ(0, autofill_client_.GetPrefs()->GetInteger(
prefs::kAutofillCreditCardSigninPromoImpressionCount));
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
// The mock implementation of ShouldShowSigninPromo() will return true here,
// creating an impression, and false below, preventing an impression.
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo())
.WillOnce(testing::Return(true));
EXPECT_TRUE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
// Expect to now have an impression.
EXPECT_EQ(1, autofill_client_.GetPrefs()->GetInteger(
prefs::kAutofillCreditCardSigninPromoImpressionCount));
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo())
.WillOnce(testing::Return(false));
EXPECT_FALSE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
// No additional impression.
EXPECT_EQ(1, autofill_client_.GetPrefs()->GetInteger(
prefs::kAutofillCreditCardSigninPromoImpressionCount));
}
// Test that ShouldShowCreditCardSigninPromo behaves as expected for a credit
// card form with an impression limit that has been attained already.
TEST_F(AutofillManagerTest,
ShouldShowCreditCardSigninPromo_CreditCardField_WithAttainedLimit) {
// Enable the feature with an impression limit.
EnableCreditCardSigninPromoFeatureWithLimit(10);
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
// Set the impression count to the same value as the limit.
autofill_client_.GetPrefs()->SetInteger(
prefs::kAutofillCreditCardSigninPromoImpressionCount, 10);
// Both calls will now return false, regardless of the mock implementation of
// ShouldShowSigninPromo().
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo())
.WillOnce(testing::Return(true));
EXPECT_FALSE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo())
.WillOnce(testing::Return(false));
EXPECT_FALSE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
// Number of impressions stay the same.
EXPECT_EQ(10, autofill_client_.GetPrefs()->GetInteger(
prefs::kAutofillCreditCardSigninPromoImpressionCount));
}
// Test that ShouldShowCreditCardSigninPromo behaves as expected for an address
// form.
TEST_F(AutofillManagerTest, ShouldShowCreditCardSigninPromo_AddressField) {
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
FormFieldData field;
test::CreateTestFormField("First Name", "firstname", "", "text", &field);
// Call will now return false, because it is initiated from an address field.
EXPECT_CALL(autofill_client_, ShouldShowSigninPromo()).Times(0);
EXPECT_FALSE(autofill_manager_->ShouldShowCreditCardSigninPromo(form, field));
}
// Verify that typing "S" into the middle name field will match and order middle
// names "Shawn Smith" followed by "Adam Smith" i.e. prefix matched followed by
// substring matched.
TEST_F(AutofillManagerTest,
DisplaySuggestionsWithPrefixesPrecedeSubstringMatched) {
// Token matching is currently behind a flag.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSuggestionsWithSubstringMatch);
// Set up our form data.
FormData form;
test::CreateTestAddressFormData(&form);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
AutofillProfile* profile1 = new AutofillProfile;
profile1->set_guid("00000000-0000-0000-0000-000000000103");
profile1->SetInfo(AutofillType(NAME_FIRST), ASCIIToUTF16("Robin"), "en-US");
profile1->SetInfo(AutofillType(NAME_MIDDLE), ASCIIToUTF16("Adam Smith"),
"en-US");
profile1->SetInfo(AutofillType(NAME_LAST), ASCIIToUTF16("Grimes"), "en-US");
profile1->SetInfo(AutofillType(ADDRESS_HOME_LINE1),
ASCIIToUTF16("1234 Smith Blvd."), "en-US");
autofill_manager_->AddProfile(profile1);
AutofillProfile* profile2 = new AutofillProfile;
profile2->set_guid("00000000-0000-0000-0000-000000000124");
profile2->SetInfo(AutofillType(NAME_FIRST), ASCIIToUTF16("Carl"), "en-US");
profile2->SetInfo(AutofillType(NAME_MIDDLE), ASCIIToUTF16("Shawn Smith"),
"en-US");
profile2->SetInfo(AutofillType(NAME_LAST), ASCIIToUTF16("Grimes"), "en-US");
profile2->SetInfo(AutofillType(ADDRESS_HOME_LINE1),
ASCIIToUTF16("1234 Smith Blvd."), "en-US");
autofill_manager_->AddProfile(profile2);
FormFieldData field;
test::CreateTestFormField("Middle Name", "middlename", "S", "text", &field);
GetAutofillSuggestions(form, field);
external_delegate_->CheckSuggestions(
kDefaultPageID,
Suggestion("Shawn Smith", "1234 Smith Blvd., Carl Shawn Smith Grimes", "",
1),
Suggestion("Adam Smith", "1234 Smith Blvd., Robin Adam Smith Grimes", "",
2));
}
TEST_F(AutofillManagerTest, ShouldUploadForm) {
FormData form;
form.name = ASCIIToUTF16("TestForm");
form.origin = GURL("http://example.com/form.html");
form.action = GURL("http://example.com/submit.html");
FormFieldData field;
test::CreateTestFormField("Name", "name", "", "text", &field);
form.fields.push_back(field);
test::CreateTestFormField("Email", "email", "", "text", &field);
form.fields.push_back(field);
FormStructure form_structure(form);
// Has less than 3 fields.
EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure));
// Has less than 3 fields but has autocomplete attribute.
form.fields[0].autocomplete_attribute = "given-name";
FormStructure form_structure_2(form);
EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_2));
// Has more than 3 fields, no autocomplete attribute.
form.fields[0].autocomplete_attribute = "";
test::CreateTestFormField("Country", "country", "", "text", &field);
form.fields.push_back(field);
FormStructure form_structure_3(form);
EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_3));
// Has more than 3 fields and at least one autocomplete attribute.
form.fields[0].autocomplete_attribute = "given-name";
FormStructure form_structure_4(form);
EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_4));
// Is off the record.
autofill_driver_->SetIsOffTheRecord(true);
EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_4));
// Make sure it's reset for the next test case.
autofill_driver_->SetIsOffTheRecord(false);
EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_4));
// Has one field which is a password field.
form.fields.clear();
test::CreateTestFormField("Password", "pw", "", "password", &field);
form.fields.push_back(field);
FormStructure form_structure_5(form);
EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_5));
// Has two fields which are password fields.
test::CreateTestFormField("New Password", "new_pw", "", "password", &field);
form.fields.push_back(field);
FormStructure form_structure_6(form);
EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_6));
// Autofill disabled.
autofill_manager_->set_autofill_enabled(false);
EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_3));
}
// Verify that no suggestions are shown on desktop for non credit card related
// fields if the initiating field has the "autocomplete" attribute set to off.
TEST_F(AutofillManagerTest, DisplaySuggestions_AutocompleteOff_AddressField) {
// Set up an address form.
FormData mixed_form;
mixed_form.name = ASCIIToUTF16("MyForm");
mixed_form.origin = GURL("https://myform.com/form.html");
mixed_form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("First name", "firstname", "", "text", &field);
field.should_autocomplete = false;
mixed_form.fields.push_back(field);
test::CreateTestFormField("Last name", "lastname", "", "text", &field);
field.should_autocomplete = true;
mixed_form.fields.push_back(field);
test::CreateTestFormField("Address", "address", "", "text", &field);
field.should_autocomplete = true;
mixed_form.fields.push_back(field);
std::vector<FormData> mixed_forms(1, mixed_form);
FormsSeen(mixed_forms);
// Suggestions should not be displayed on desktop for this field.
GetAutofillSuggestions(mixed_form, mixed_form.fields[0]);
if (IsDesktopPlatform()) {
EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
} else {
EXPECT_TRUE(external_delegate_->on_suggestions_returned_seen());
}
// Suggestions should always be displayed for all the other fields.
for (size_t i = 1U; i < mixed_form.fields.size(); ++i) {
GetAutofillSuggestions(mixed_form, mixed_form.fields[i]);
EXPECT_TRUE(external_delegate_->on_suggestions_returned_seen());
}
}
// Verify that suggestions are shown on desktop for credit card related fields
// even if the initiating field field has the "autocomplete" attribute set to
// off.
TEST_F(AutofillManagerTest,
DisplaySuggestions_AutocompleteOff_CreditCardField) {
// Set up a credit card form.
FormData mixed_form;
mixed_form.name = ASCIIToUTF16("MyForm");
mixed_form.origin = GURL("https://myform.com/form.html");
mixed_form.action = GURL("https://myform.com/submit.html");
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
field.should_autocomplete = false;
mixed_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
field.should_autocomplete = true;
mixed_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccexpiresmonth", "", "text",
&field);
field.should_autocomplete = false;
mixed_form.fields.push_back(field);
mixed_form.fields.push_back(field);
std::vector<FormData> mixed_forms(1, mixed_form);
FormsSeen(mixed_forms);
// Suggestions should always be displayed.
for (const FormFieldData& field : mixed_form.fields) {
GetAutofillSuggestions(mixed_form, field);
EXPECT_TRUE(external_delegate_->on_suggestions_returned_seen());
}
}
} // namespace autofill
| [
"support@opentext.com"
] | support@opentext.com |
a7c843aad9a46f17332583b5011e1e6cac950e07 | d842ad4b772bc9856f065ee38568aa1a6cd87890 | /CPP_thread.cpp | 042f81f0b3d82bf533d612f1943c66bae686eb0f | [] | no_license | skc7/Data-Structures | eaa2c59f04e1607623276f787d65778b4aab8a61 | 03e117526bbfb2908f25ba5a0a987647c8c07642 | refs/heads/master | 2021-05-01T21:53:05.079592 | 2019-08-02T09:38:53 | 2019-08-02T09:38:53 | 120,981,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | cpp | #include <iostream>
#include <thread>
using namespace std;
void tfun(int value){
cout << "\nInside thread\n";
}
int main(){
thread t1(tfun, 1);
t1.join();
return 0;
}
| [
"skc7893@hotmail.com"
] | skc7893@hotmail.com |
b0491c781e553f36c8ce0c29065aa01c98692cd6 | 043160352216a7fc21be4c8a44507e00f523bf80 | /src/libzerocoin/CoinSpend.h | accf6888b5b277632df8bd372bd01f1ae44111a4 | [
"MIT"
] | permissive | odinyblockchain/odinycoin | 5ef2a1bca374230882c91e8c6717bbb8faf889ad | 183751aac9357455913f1d8a415b1dcb04225ee0 | refs/heads/master | 2022-12-18T14:14:02.535216 | 2020-09-20T22:05:14 | 2020-09-20T22:05:14 | 295,208,711 | 0 | 2 | MIT | 2020-09-18T10:33:17 | 2020-09-13T18:06:52 | C++ | UTF-8 | C++ | false | false | 6,465 | h | /**
* @file CoinSpend.h
*
* @brief CoinSpend class for the Zerocoin library.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017-2019 The Odinycoin developers
#ifndef COINSPEND_H_
#define COINSPEND_H_
#include <streams.h>
#include <utilstrencodings.h>
#include "Accumulator.h"
#include "AccumulatorProofOfKnowledge.h"
#include "Coin.h"
#include "Commitment.h"
#include "Params.h"
#include "SerialNumberSignatureOfKnowledge.h"
#include "SpendType.h"
#include "bignum.h"
#include "pubkey.h"
#include "serialize.h"
namespace libzerocoin
{
/** The complete proof needed to spend a zerocoin.
* Composes together a proof that a coin is accumulated
* and that it has a given serial number.
*/
class CoinSpend
{
public:
CoinSpend(){};
//! \param paramsV1 - if this is a V1 zerocoin, then use params that existed with initial modulus, ignored otherwise
//! \param paramsV2 - params that begin when V2 zerocoins begin on the Odinycoin network
//! \param strm - a serialized CoinSpend
template <typename Stream>
CoinSpend(const ZerocoinParams* paramsV1, const ZerocoinParams* paramsV2, Stream& strm) :
accumulatorPoK(¶msV2->accumulatorParams),
serialNumberSoK(paramsV1),
commitmentPoK(¶msV1->serialNumberSoKCommitmentGroup, ¶msV2->accumulatorParams.accumulatorPoKCommitmentGroup)
{
Stream strmCopy = strm;
strm >> *this;
//Need to reset some parameters if v2
if (getCoinVersion() >= PrivateCoin::PUBKEY_VERSION) {
accumulatorPoK = AccumulatorProofOfKnowledge(¶msV2->accumulatorParams);
serialNumberSoK = SerialNumberSignatureOfKnowledge(paramsV2);
commitmentPoK = CommitmentProofOfKnowledge(¶msV2->serialNumberSoKCommitmentGroup, ¶msV2->accumulatorParams.accumulatorPoKCommitmentGroup);
strmCopy >> *this;
}
}
/**Generates a proof spending a zerocoin.
*
* To use this, provide an unspent PrivateCoin, the latest Accumulator
* (e.g from the most recent Bitcoin block) containing the public part
* of the coin, a witness to that, and whatever medeta data is needed.
*
* Once constructed, this proof can be serialized and sent.
* It is validated simply be calling validate.
* @warning Validation only checks that the proof is correct
* @warning for the specified values in this class. These values must be validated
* Clients ought to check that
* 1) params is the right params
* 2) the accumulator actually is in some block
* 3) that the serial number is unspent
* 4) that the transaction
*
* @param p cryptographic parameters
* @param coin The coin to be spend
* @param a The current accumulator containing the coin
* @param witness The witness showing that the accumulator contains the coin
* @param a hash of the partial transaction that contains this coin spend
* @throw ZerocoinException if the process fails
*/
CoinSpend(const ZerocoinParams* paramsCoin, const ZerocoinParams* paramsAcc, const PrivateCoin& coin, Accumulator& a, const uint32_t& checksum,
const AccumulatorWitness& witness, const uint256& ptxHash, const SpendType& spendType);
virtual ~CoinSpend(){};
/** Returns the serial number of the coin spend by this proof.
*
* @return the coin's serial number
*/
const CBigNum& getCoinSerialNumber() const { return this->coinSerialNumber; }
/**Gets the denomination of the coin spent in this proof.
*
* @return the denomination
*/
CoinDenomination getDenomination() const { return this->denomination; }
/**Gets the checksum of the accumulator used in this proof.
*
* @return the checksum
*/
uint32_t getAccumulatorChecksum() const { return this->accChecksum; }
/**Gets the txout hash used in this proof.
*
* @return the txout hash
*/
uint256 getTxOutHash() const { return ptxHash; }
CBigNum getAccCommitment() const { return accCommitmentToCoinValue; }
CBigNum getSerialComm() const { return serialCommitmentToCoinValue; }
uint8_t getVersion() const { return version; }
int getCoinVersion() const { return libzerocoin::ExtractVersionFromSerial(coinSerialNumber); }
CPubKey getPubKey() const { return pubkey; }
SpendType getSpendType() const { return spendType; }
std::vector<unsigned char> getSignature() const { return vchSig; }
static std::vector<unsigned char> ParseSerial(CDataStream& s);
virtual const uint256 signatureHash() const;
virtual bool Verify(const Accumulator& a, bool verifyParams = true) const;
bool HasValidSerial(ZerocoinParams* params) const;
bool HasValidSignature() const;
void setTxOutHash(uint256 txOutHash) { this->ptxHash = txOutHash; };
void setDenom(libzerocoin::CoinDenomination denom) { this->denomination = denom; }
void setPubKey(CPubKey pkey, bool fUpdateSerial = false);
CBigNum CalculateValidSerial(ZerocoinParams* params);
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(denomination);
READWRITE(ptxHash);
READWRITE(accChecksum);
READWRITE(accCommitmentToCoinValue);
READWRITE(serialCommitmentToCoinValue);
READWRITE(coinSerialNumber);
READWRITE(accumulatorPoK);
READWRITE(serialNumberSoK);
READWRITE(commitmentPoK);
try {
READWRITE(version);
READWRITE(pubkey);
READWRITE(vchSig);
READWRITE(spendType);
} catch (...) {
version = 1;
}
}
protected:
CoinDenomination denomination = ZQ_ERROR;
CBigNum coinSerialNumber;
uint8_t version;
//As of version 2
CPubKey pubkey;
std::vector<unsigned char> vchSig;
SpendType spendType;
uint256 ptxHash;
private:
uint32_t accChecksum;
CBigNum accCommitmentToCoinValue;
CBigNum serialCommitmentToCoinValue;
AccumulatorProofOfKnowledge accumulatorPoK;
SerialNumberSignatureOfKnowledge serialNumberSoK;
CommitmentProofOfKnowledge commitmentPoK;
};
} /* namespace libzerocoin */
#endif /* COINSPEND_H_ */
| [
"71228635+odinyblockchain@users.noreply.github.com"
] | 71228635+odinyblockchain@users.noreply.github.com |
6812194e87143597d30173609b6793e67bcf2293 | 45a4b38f5805957879ba8c8750750741556989a2 | /02_12_01_找和为特定值的两个数/02_12_01_找和为特定值的两个数.cpp | b49232f3bb8a473468c0a67e40aebf708f09fd2a | [] | no_license | keke2014/BeautyOfCoding | b96b1e47e4e1065df89594dc529879674b24bbe7 | 7ba680ca4d632c3130c02d9d8eef6e555668ce98 | refs/heads/master | 2022-12-14T04:29:31.404673 | 2020-08-30T12:27:42 | 2020-08-30T12:27:42 | 291,465,531 | 0 | 0 | null | 2020-08-30T12:24:26 | 2020-08-30T12:24:25 | null | GB18030 | C++ | false | false | 1,033 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <climits>
#include <cassert>
#include <>
//解法1:暴力遍历 O(N^2)
//解法2:先排序,然后对于每一个数arr[i],进行二分查找sum-arr[i]在数组中吗
std::vector<int> GetTwoNumOfSum2(std::vector<int> & arr, int aim)
{
std::sort(arr.begin(), arr.end());
for (size_t i = 0; i < arr.size(); ++i)
{
if (std::binary_search(arr.begin(), arr.end(), aim - arr[i])) //当然,这里没有考虑aim=16,数组里面有两个8的情况
return{ arr[i],aim - arr[i] };
}
return{ -1,-1 };
}
//解法3:哈希表来存
//解法4:先排序,然后双指针法
std::vector<int> GetTwoNumOfSum4(std::vector<int> & arr, int aim)
{
std::sort(arr.begin(), arr.end());
int left = 0, right = arr.size() - 1;
while (left < right)
{
if (arr[left] + arr[right] == aim)
return{ arr[left],arr[right] };
else if (arr[left] + arr[right] < aim)
++left;
else
--right;
}
return{ -1,-1 };
}
int main()
{
return 0;
} | [
"954222619@qq.com"
] | 954222619@qq.com |
135aa13a247b8c40f07293d650e4aa92477602d5 | e8c371da76a332c735eb27023eedd968481274d8 | /process/old/ProcessLD.h | e9cf4b0f9cc379164f932e1a0a3169a62a2fbb47 | [] | no_license | RitchieLab/PLATO | 74001472ab53fc0f3e5bea3fe77f6d6772471c55 | 5f718945498f7e926ce95919a3bbeb82e0e54700 | refs/heads/master | 2021-06-15T01:28:08.849694 | 2018-07-20T21:25:28 | 2018-07-20T21:25:28 | 90,042,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | h | #ifndef PROCESSLD_H
#define PROCESSLD_H
#include "Process.h"
class ProcessLD : public ProcessImpl<ProcessLD>{
private:
static const std::string stepname;
public:
ProcessLD(){name="LD calculations";}
virtual ~ProcessLD(){}
protected:
virtual void PrintSummary();
virtual void process(Methods::DataSet*);
};
#endif
| [
"jrw32@dce.psu.edu@9e62ecf6-770d-0410-a9d7-e62a33e3d092"
] | jrw32@dce.psu.edu@9e62ecf6-770d-0410-a9d7-e62a33e3d092 |
9ede2fe8869ba73c1ed590080d6320597ecb0092 | 00597c0e7206577be331ec062a9b97573daa0fc2 | /io.cxx | 2e0f3086acfaa5d2d7006ed2673f21d154f0a04d | [] | no_license | whigg/asicp | c5d7698537f2235c60c9a705adb8ff0c50b21e01 | 2a40cadbb1c1859f4107da115633b969bb20ab87 | refs/heads/master | 2020-12-15T14:01:17.941095 | 2019-07-30T05:31:38 | 2019-07-30T05:38:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | cxx | #include "io.h"
#include <iostream>
#include <fstream>
void read_ply_points(char *filename)
{
std::ofstream fp;
fp.open(filename, std::ios::in);
if(fp.is_open()) {
}
}
void write_points(char *filename, char *data)
{
}
| [
"cstew2@uwo.ca"
] | cstew2@uwo.ca |
7be04fef51f8e345f21ad6655189884297d2fa2d | 3ffccabeefafed0b7df9ccf6f3575dc4e952cbec | /513.find-bottom-left-tree-value.cpp | 51dc2ab7806bf994706e6771519d759a65a34841 | [] | no_license | tickscn/leetcode | 8f02dcf1d0a41d69735debd24e3f73a8bd362411 | 242c4e75a5598f1eed574393f0e344677c4ec24a | refs/heads/master | 2021-07-12T18:45:24.988368 | 2020-07-24T09:58:26 | 2020-07-24T09:58:26 | 184,757,828 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | cpp | /*
* @lc app=leetcode id=513 lang=cpp
*
* [513] Find Bottom Left Tree Value
*/
// @lc code=start
/**
* 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:
int findBottomLeftValue(TreeNode* root)
{
queue<TreeNode*> Qe;
Qe.push(root);
while (!Qe.empty())
{
root = Qe.front();
Qe.pop();
if (root->right) Qe.push(root->right);
if (root->left) Qe.push(root->left);
}
return root->val;
}
};
// @lc code=end
| [
"xiehuiwu1996@gmail.com"
] | xiehuiwu1996@gmail.com |
cc816f745457521e399e19e380f2b20550a1254a | 0b6d41311fd4800fdefa9c60e4b4f0287d06605e | /gradestest/grades.cpp | a805f9b66f151c77b2bf51f4cc0b2c31abdc9c78 | [] | no_license | zackcd/C-C-Code | a1eaff3fb534f30b6045cd1907bb160f103c17e0 | 8edf04a2e541a11ad7c2762927aabeef77115c64 | refs/heads/master | 2020-12-21T22:00:24.761091 | 2020-01-29T18:03:37 | 2020-01-29T18:03:37 | 236,576,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,595 | cpp | // Name: Zack Downing
// USC NetID: zdowning
// CSCI 455 PA5
// Spring 2018
/*
* grades.cpp
* A program to test the Table class.
* How to run it:
* grades [hashSize]
*
* the optional argument hashSize is the size of hash table to use.
* if it's not given, the program uses default size (Table::HASH_SIZE)
*
*/
#include "Table.h"
// cstdlib needed for call to atoi
#include <cstdlib>
void tableInsert(Table & grades);
void tableChange(Table & grades);
void tableLookup(Table & grades);
void tableRemove(Table & grades);
void help();
void readVals(string & name, int & score);
int main(int argc, char * argv[]) {
// gets the hash table size from the command line
int hashSize = Table::HASH_SIZE;
Table * grades; // Table is dynamically allocated below, so we can call
// different constructors depending on input from the user.
if (argc > 1) {
hashSize = atoi(argv[1]); // atoi converts c-string to int
if (hashSize < 1) {
cout << "Command line argument (hashSize) must be a positive number" << endl;
return 1;
}
grades = new Table(hashSize);
}
else { // no command line args given -- use default table size
grades = new Table();
}
grades->hashStats(cout);
// add more code here
// Reminder: use -> when calling Table methods, since grades is type Table*
string input = "";
while(input != "quit") {
cout << "cmd>";
cin >> input;
if(input == "insert") {
//tableInsert(*grades);
string name;
int score;
readVals(name, score);
if(grades->lookup(name)) {
cout << "Name is already present." << endl;
}
else
grades->insert(name, score);
}
else if(input == "change")
tableChange(*grades);
else if(input == "lookup")
tableLookup(*grades);
else if(input == "remove")
tableRemove(*grades);
else if(input == "print")
grades->printAll();
else if(input == "size")
cout << grades->numEntries() << endl;
else if(input == "stats")
grades->hashStats(cout);
else if(input == "help")
help();
else if(input == "quit")
return 0;
else {
cout << "ERROR: invalid command" << endl;
help();
}
}
return 0;
}
//Helper function to insert a name and grade in the table
void tableInsert(Table & grades) {
string name;
int score;
readVals(name, score);
if(grades.lookup(name)) {
cout << "Name is already present." << endl;
}
else
grades.insert(name, score);
}
//Helper function to change a grade in the table, given a target key
void tableChange(Table & grades) {
string target;
int newScore;
readVals(target, newScore);
int * lookup = grades.lookup(target);
if(lookup == NULL)
cout << "Student name not present" << endl;
else
*lookup = newScore;
}
//Helper function to remove a node with the given target key
void tableRemove(Table & grades) {
string target;
cin >> target;
if(!grades.lookup(target)) {
cout << "Name is not present." << endl;
}
else
grades.remove(target);
}
//Helper function to perform a lookup in the table given a target key
void tableLookup(Table & grades) {
string target;
cin >> target;
int * lookup = grades.lookup(target);
if(lookup == NULL)
cout << "Student name not present" << endl;
else {
cout << "Score: " << *lookup << endl;
}
}
//Helper function for above helper functions to read in values
void readVals(string & name, int & score) {
cin >> name;
cin >> score;
}
//Helper function to print list of commands
void help() {
cout << "Enter 'insert' to insert a name and score." << endl;
cout << "Enter 'change' to change the score for a name." << endl;
cout << "Enter 'lookup' to lookup the score for a name." << endl;
cout << "Enter 'remove' to remove a name entry." << endl;
cout << "Enter 'print' to print all names and scores." << endl;
cout << "Enter 'size' to print the number of entries." << endl;
cout << "Enter 'stats' to get statistics about the hash table at this point." << endl;
cout << "Enter 'help' for a command summary." << endl;
cout << "Enter 'quit' to exit the program." << endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
c9bfc96c40c47a6b8c33fcbb523be199010431ec | 350bef364f4852ae428e6e7e6b0e2ed1b31e1bfd | /codes_book_onlinegameserver/NetLib/VBuffer.cpp | 796f0d58d194635394121f57cb541a1cc76ab5a8 | [
"MIT"
] | permissive | true-bear/cpp_server_study_projects_Pub | 224e9b1c11dcb2345ae080835abd369d2ada564e | 070802570442e6ad91b7dc17f6d3685330de9eed | refs/heads/master | 2020-05-03T12:40:29.924827 | 2019-03-30T09:38:01 | 2019-03-30T09:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,787 | cpp | #include "Precompile.h"
#include "VBuffer.h"
#include "CommonDef.h"
IMPLEMENT_SINGLETON( VBuffer );
VBuffer::VBuffer( int nMaxBufSize )
{
m_pszVBuffer = new char[ nMaxBufSize ];
m_nMaxBufSize = nMaxBufSize;
Init();
}
VBuffer::~VBuffer(void)
{
if( NULL != m_pszVBuffer )
delete [] m_pszVBuffer;
}
void VBuffer::Init()
{
//PACKET_SIZE_LENGTH는 저절로 들어가게 만든다.
m_pCurMark = m_pszVBuffer + PACKET_SIZE_LENGTH;
m_nCurBufSize = PACKET_SIZE_LENGTH;
}
void VBuffer::GetChar( char& cCh )
{
cCh = (unsigned char)*m_pCurMark;
m_pCurMark += 1;
m_nCurBufSize += 1;
}
void VBuffer::GetShort( short& sNum )
{
sNum = (unsigned char)*m_pCurMark +
(((unsigned char)*(m_pCurMark + 1) )<< 8);
m_pCurMark += 2;
m_nCurBufSize += 2;
}
void VBuffer::GetInteger( int& nNum )
{
nNum = (unsigned char)m_pCurMark[0] +
((unsigned char)m_pCurMark[1] << 8) +
((unsigned char)m_pCurMark[2] << 16) +
((unsigned char)m_pCurMark[3] << 24);
m_pCurMark += 4;
m_nCurBufSize += 4;
}
//문자열말고 다른 byte stream을 읽을때 쓰인다
void VBuffer::GetStream( char* pszBuffer, short sLen)
{
if( sLen < 0 || sLen > MAX_PBUFSIZE )
return;
CopyMemory( pszBuffer , m_pCurMark , sLen );
m_pCurMark += sLen;
m_nCurBufSize += sLen;
}
void VBuffer::GetString( char* pszBuffer )
{
short sLength;
GetShort( sLength );
if( sLength < 0 || sLength > MAX_PBUFSIZE )
return;
strncpy( pszBuffer, m_pCurMark, sLength);
*(pszBuffer + sLength) = NULL;
m_pCurMark += sLength;
m_nCurBufSize += sLength;
}
void VBuffer::SetInteger( int nI )
{
*m_pCurMark++ = nI;
*m_pCurMark++ = nI >> 8;
*m_pCurMark++ = nI >> 16;
*m_pCurMark++ = nI >> 24;
m_nCurBufSize += 4;
}
void VBuffer::SetShort( short sShort )
{
*m_pCurMark++ = sShort;
*m_pCurMark++ = sShort >> 8;
m_nCurBufSize += 2;
}
void VBuffer::SetChar( char cCh)
{
*m_pCurMark++ = cCh;
m_nCurBufSize += 1;
}
//문자열말고 다른 byte stream을 넣을때 쓰인다
void VBuffer::SetStream( char* pszBuffer , short sLen )
{
CopyMemory( m_pCurMark , pszBuffer , sLen );
m_pCurMark += sLen;
m_nCurBufSize += sLen;
}
void VBuffer::SetString( char* pszBuffer )
{
short sLen = (short)strlen( pszBuffer );
if( sLen < 0 || sLen > MAX_PBUFSIZE )
return;
SetShort( sLen );
CopyMemory( m_pCurMark , pszBuffer , sLen );
m_pCurMark += sLen;
m_nCurBufSize += sLen;
}
bool VBuffer::CopyBuffer( char* pDestBuffer )
{
CopyMemory( m_pszVBuffer , (char*)&m_nCurBufSize
, PACKET_SIZE_LENGTH );
CopyMemory( pDestBuffer , m_pszVBuffer , m_nCurBufSize );
return true;
}
void VBuffer::SetBuffer( char* pVBuffer )
{
m_pCurMark = pVBuffer ;
m_nCurBufSize = 0;
}
| [
"jacking75@gmail.com"
] | jacking75@gmail.com |
30ff155d420e2c7d4a4d8b985af75f95d32f6aaa | c424c6bece141f0b4dc1eae6dcb6bdd167c89a29 | /src/ctrl/CFlush.cpp | 3b8bb578e80de4e1dc47027c81f703af50e954b4 | [] | no_license | ta-martins/Intideas | c904598bc93a27aecca4fb74e1f40e9d48314e1b | 1ffdf63589622df5dbef1b084d8a10ac14086c85 | refs/heads/master | 2020-05-07T11:32:51.709714 | 2019-04-09T23:56:58 | 2019-04-09T23:56:58 | 180,466,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,728 | cpp | #include "CFlush.h"
const unsigned int CFlush::THREAD_CONCURRENCY = std::thread::hardware_concurrency();
std::mutex CFlush::gm;
HANDLE CFlush::hConsole_c;
int CFlush::rows = 0;
int CFlush::columns = 0;
CONSOLE_SCREEN_BUFFER_INFO CFlush::csbi;
std::vector<std::string> CFlush::str_split(const std::string &str, char ch)
{
size_t pos = str.find(ch);
size_t initialPos = 0;
std::vector<std::string> rval;
//Decompose
while (pos != std::string::npos)
{
rval.push_back(str.substr(initialPos, pos - initialPos));
initialPos = pos + 1;
pos = str.find(ch, initialPos);
}
///This is wrong for the case of '\n' char... unless ....
//Add the last -- And prevent min from windef.h with parenthesis
//rval.push_back(str.substr(initialPos, (std::min)(pos, str.size()) - initialPos + 1));
return rval;
}
void CFlush::InitHandle(DWORD hnd)
{
hConsole_c = GetStdHandle(hnd);
//Assuming the console size can't be changed
GetConsoleScreenBufferInfo(hConsole_c, &csbi);
columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}
void CFlush::InitHandle()
{
hConsole_c = GetStdHandle(STD_OUTPUT_HANDLE);
//Assuming the console size can't be changed
GetConsoleScreenBufferInfo(hConsole_c, &csbi);
columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}
void CFlush::CloseHandle()
{
::CloseHandle(hConsole_c);
}
void CFlush::FlushConsoleStream(std::stringstream * ss)
{
std::string val = ss->str();
std::vector<std::string> split = str_split(val, '\n');
std::lock_guard<std::mutex> lock(gm);
#ifdef _WIN32
SetConsoleActiveScreenBuffer(hConsole_c);
for (int i = 0; i < split.size(); i++)
{
const char* buffer = split[i].c_str();
COORD pos = { 0, i < rows - THREAD_CONCURRENCY - 1 ? i : rows - THREAD_CONCURRENCY };
DWORD len = strlen(buffer);
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole_c, buffer, len, pos, &dwBytesWritten);
}
#else
//Linux code ???
#endif
ss->clear();
}
void CFlush::FlushConsoleString(std::string & str)
{
std::vector<std::string> split = str_split(str, '\n');
std::lock_guard<std::mutex> lock(gm);
#ifdef _WIN32
SetConsoleActiveScreenBuffer(hConsole_c);
for (int i = 0; i < split.size(); i++)
{
const char* buffer = split[i].c_str();
COORD pos = { 0, i < rows - THREAD_CONCURRENCY - 1 ? i : rows - THREAD_CONCURRENCY };
DWORD len = strlen(buffer);
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole_c, buffer, len, pos, &dwBytesWritten);
}
#else
//Linux code ???
#endif
}
void CFlush::FlushConsoleCharLP(const char * buffer)
{
std::string ex(buffer);
std::vector<std::string> split = str_split(ex, '\n');
std::lock_guard<std::mutex> lock(gm);
#ifdef _WIN32
SetConsoleActiveScreenBuffer(hConsole_c);
//Assuming the console size can be changed
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole_c, &csbi);
int columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
int rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
for (int i = 0; i < split.size(); i++)
{
const char* buffer = split[i].c_str();
COORD pos = { 0, i };
DWORD len = strlen(buffer);
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole_c, buffer, len, pos, &dwBytesWritten);
}
#else
//Linux code ???
#endif
}
void CFlush::ClearConsole(SHORT y, SHORT w)
{
std::lock_guard<std::mutex> lock(gm);
#ifdef _WIN32
//Assuming the console size can be changed
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole_c, &csbi);
DWORD dwBytesWrittenSC = 0;
FillConsoleOutputCharacter(hConsole_c, (TCHAR) ' ', csbi.dwSize.X * w,
COORD{ 0, y }, &dwBytesWrittenSC);
#endif
}
| [
"prime@DESKTOP-VEQ67I6"
] | prime@DESKTOP-VEQ67I6 |
5ad212847d109ec354beae5a7f27d540f71a1131 | fb538fc02eab8b18beb8784de5041f197947588e | /chrome/browser/memory/memory_pressure_monitor_utils.h | 4a5d8bb9421112831f34f483f185a3a00e41cd08 | [
"BSD-3-Clause"
] | permissive | HAN767/chromium-1 | 5229fcbcdfda7744d7487a30af3a6e0331569ef3 | a324a8ecb713980e5ac75af28f5680fd1ff635a8 | refs/heads/master | 2022-09-09T04:31:52.560824 | 2019-03-12T15:36:30 | 2019-03-12T15:36:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,364 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_UTILS_H_
#define CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_UTILS_H_
#include <deque>
#include <utility>
#include "base/macros.h"
#include "base/sequence_checker.h"
#include "base/time/time.h"
namespace base {
class TickClock;
}
namespace memory {
namespace internal {
// An observation window consists of a series of samples. Samples in this window
// will have a maximum age (the window length), samples that exceed that age
// will be automatically trimmed when a new one is available.
//
// Concurrent calls to instances of this class aren't allowed.
template <typename T>
class ObservationWindow {
public:
explicit ObservationWindow(base::TimeDelta window_length);
virtual ~ObservationWindow();
// Function that should be called each time a new sample is available. When a
// new sample gets added the entries that exceeds the age of this window will
// first be removed, and then the new one will be added to it.
void OnSample(const T sample);
protected:
using Observation = std::pair<const base::TimeTicks, const T>;
// Called each time a sample gets added to the observation window.
virtual void OnSampleAdded(const T& sample) = 0;
// Called each time a sample gets removed from the observation window.
virtual void OnSampleRemoved(const T& sample) = 0;
const std::deque<Observation>& observations_for_testing() {
return observations_;
}
void set_clock_for_testing(const base::TickClock* clock) { clock_ = clock; }
private:
// The length of the window. Samples older than |base::TimeTicks::Now() -
// window_length_| will automatically be removed from this window when a new
// one gets added.
const base::TimeDelta window_length_;
// The observations, in order of arrival.
std::deque<Observation> observations_;
// Allow for an injectable clock for testing.
const base::TickClock* clock_;
SEQUENCE_CHECKER(sequence_checker_);
DISALLOW_COPY_AND_ASSIGN(ObservationWindow);
};
} // namespace internal
} // namespace memory
#include "chrome/browser/memory/memory_pressure_monitor_utils_impl.h"
#endif // CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_UTILS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b106cbe09a6bd6aeebc99a3f94fe30a39022342a | af396dd6e9d8087ad5f6b411730aae234f448b23 | /base/event/eventtimeout.h | 8fc5bb39f02377951a163047c148dc2d2cc13340 | [] | no_license | ijaychen/jengine | bc90763b6d81472150eb5baa135e60c971f3aa26 | 11ad34c0494b6d23ab067b7edc48af85a93b8d68 | refs/heads/master | 2021-01-10T09:41:52.418984 | 2015-10-26T03:58:48 | 2015-10-26T03:58:48 | 44,941,600 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | h | #ifndef BASE_EVENT_EVENTTIMEOUT_H
#define BASE_EVENT_EVENTTIMEOUT_H
#include "../object.h"
namespace base
{
namespace event
{
class Dispatcher;
// 定时器事件
class EventTimeout : public Object
{
public:
// 构造函数
// delay 延时(ms)
EventTimeout(int delay) : delay_(delay) {}
virtual ~EventTimeout() {}
int delay() const {
return delay_;
}
// 添加到事件派发器中
void AddToDispatcher();
// 从事件派发器中移除
void RemoveFromDispatcher();
private:
// 定时器触发
virtual void OnTimeout() = 0;
int delay_;
friend class Dispatcher;
};
}
}
#endif
| [
"jason@localhost.localdomain"
] | jason@localhost.localdomain |
af10e110fd240799b466923c838caaf3df64c210 | 5b41e312db8aeb5532ba59498c93e2ec1dccd4ff | /Tools/Simulator/Simulator/CProgressBarViewForm.cpp | 12d5581d96837a7362f4912e239c74c6650b6cfb | [] | no_license | frankilfrancis/KPO_HMI_vs17 | 10d96c6cb4aebffb83254e6ca38fe6d1033eba79 | de49aa55eccd8a7abc165f6057088a28426a1ceb | refs/heads/master | 2020-04-15T16:40:14.366351 | 2019-11-14T15:33:25 | 2019-11-14T15:33:25 | 164,845,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,459 | cpp | #include "StdAfx.h"
#include "CProgressBarViewForm.h"
#include "CLogWriterWrapper.h"
using namespace simulator;
void CProgressBarViewForm::setAfterInfoView()
{
labPreCendDesc->Visible = false;
labPerCentView->Visible = false;
//Cancel Button ausblenden
butCancel->Visible = false;
label1->Text=" ";
/* panCancelView->Dock = System::Windows::Forms::DockStyle::;*/
/*label1->Dock = System::Windows::Forms::DockStyle::Top;*/
label1->ForeColor = System::Drawing::Color::Black;
if (butCancel->Enabled)
label1->Text="New telegrams are accepted and sorted ...";
else
label1->Text="New telegrams are removed ...";
while (true)
{
progressBar->Value = 1;
for (int i=1;i<=95;i++)
{
progressBar->Step =1;
progressBar->PerformStep();
progressBar->Refresh();
System::Threading::Thread::Sleep(30);
}
}
}
//---------------------------------------------------------------------
void CProgressBarViewForm::Close()
{
formClosed = true;
Form::Close();
}
//-------------------------------------------------------------------
bool CProgressBarViewForm::isFormClosed()
{
return formClosed;
}
//-------------------------------------------------------------------
void CProgressBarViewForm::updateStep(long step)
{
if (step > 0)
{
double temp = 0;
long temp1 = 0;
temp = step;
if ((maximum-minimum) > 0)
{
temp /= (maximum-minimum);
temp *=100;
if ((temp + restDif) < 1)
restDif +=temp;
else
{
progressBar->Step = restDif + temp;
progressBar->PerformStep();
totalStep += restDif + temp;
if (totalStep <= 100)
labPerCentView->Text=System::Convert::ToString(totalStep);
else
labPerCentView->Text=System::Convert::ToString(100);
Refresh();
temp1 = long ((restDif + temp)*100);
temp1 = temp1 % 100;
restDif /=100;
}
}
/* if (totalStep>80 && butCancel->Visible == true)
{
butCancel->Visible = false;
label1->Text=" ";
}*/
}
}
//-------------------------------------------------------------------
void CProgressBarViewForm::setMinAndMax(long min,__int64 max)
{
minimum=min;
maximum=max;
}
//-------------------------------------------------------------------
void CProgressBarViewForm::setSourceLab(String^ source)
{
labSource->Text=source;
}
//-------------------------------------------------------------------
void CProgressBarViewForm::setCancelButtonVisible(bool mode)
{
butCancel->Visible = mode;
/*label1->Text="By Cancel will removed all loaded telegramm";*/
label1->Visible = mode;
}
//-------------------------------------------------------------------
void CProgressBarViewForm::setBarViewAbortDelTyp(BarViewAbortDelTyp^ event)
{
BarViewAbortEvent=event;
}
//-------------------------------------------------------------------
System::Void CProgressBarViewForm::butCancel_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (BarViewAbortEvent != nullptr)
{
CLogWriterWrapper::getLogWriterWrapper()->WriteMessage(CLogWriterWrapper::MessTyp::Info,
"AbortEvent triggered",
__FILE__,__FUNCTION__,__LINE__,gcnew Diagnostics::StackTrace(true),3);
//Cancel Button deaktivieren
butCancel->Enabled = false;
label1->Text=" ";
BarViewAbortEvent->Invoke();
}
} | [
"52784069+FrankilPacha@users.noreply.github.com"
] | 52784069+FrankilPacha@users.noreply.github.com |
8aad1aa8d78479029c67e1031e4c10a10d82c6be | 0d3ae5ec1a69995fd21b45cd971874f86c08cf5e | /src/governance-validators.h | f6582aabe6bad30e02ffaf8f876b01d8355b34fc | [
"MIT"
] | permissive | jamesdwilson/emrals | 685ee06794cfeebfc5e568c51ab0e61e0790685d | 06c18f8291c3502d9950d582d4e05b865143ec1d | refs/heads/master | 2020-04-19T15:37:57.272118 | 2018-10-15T00:44:20 | 2018-10-15T00:44:20 | 168,279,961 | 0 | 1 | MIT | 2019-01-30T04:36:00 | 2019-01-30T04:36:00 | null | UTF-8 | C++ | false | false | 1,330 | h | // Copyright (c) 2014-2017 The Emrals Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GOVERNANCE_VALIDATORS_H
#define GOVERNANCE_VALIDATORS_H
#include <string>
#include <univalue.h>
class CProposalValidator {
public:
CProposalValidator(const std::string& strDataHexIn = std::string());
void Clear();
void SetHexData(const std::string& strDataHexIn);
bool Validate();
bool ValidateJSON();
bool ValidateName();
bool ValidateStartEndEpoch();
bool ValidatePaymentAmount();
bool ValidatePaymentAddress();
bool ValidateURL();
const std::string& GetErrorMessages()
{
return strErrorMessages;
}
private:
void ParseJSONData();
bool GetDataValue(const std::string& strKey, std::string& strValue);
bool GetDataValue(const std::string& strKey, int64_t& nValue);
bool GetDataValue(const std::string& strKey, double& dValue);
static std::string StripWhitespace(const std::string& strIn);
static bool CheckURL(const std::string& strURLIn);
private:
std::string strData;
UniValue objJSON;
bool fJSONValid;
std::string strErrorMessages;
};
#endif
| [
"TaylorFrazier@gmail.com"
] | TaylorFrazier@gmail.com |
57d22ae82f061e09793321a02a961f0a9114268d | 2a440aea43b5b880fd433f58098ac3bbc66fcfec | /cloudesl/src/model/DeleteItemBySkuIdResult.cc | 0e2b631d0092c6e3fe05b47a60e54e1de91a99d7 | [
"Apache-2.0"
] | permissive | longkai1028/aliyun-openapi-cpp-sdk | 30d6553e508c6a38d190557487972553a6ae64d5 | 97286a49ca7ae8754984f6b8abce1a8e6f48117c | refs/heads/master | 2023-04-04T00:13:25.713899 | 2021-04-13T02:28:45 | 2021-04-13T02:28:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,711 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/cloudesl/model/DeleteItemBySkuIdResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Cloudesl;
using namespace AlibabaCloud::Cloudesl::Model;
DeleteItemBySkuIdResult::DeleteItemBySkuIdResult() :
ServiceResult()
{}
DeleteItemBySkuIdResult::DeleteItemBySkuIdResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DeleteItemBySkuIdResult::~DeleteItemBySkuIdResult()
{}
void DeleteItemBySkuIdResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
}
std::string DeleteItemBySkuIdResult::getMessage()const
{
return message_;
}
std::string DeleteItemBySkuIdResult::getErrorCode()const
{
return errorCode_;
}
bool DeleteItemBySkuIdResult::getSuccess()const
{
return success_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
d78354cfa17e92af06574bec9fca6f0104912cf5 | 9d3950b80a90487398ee59208ac5164b85610517 | /Cpp/Path_Sum.cpp | 7cdb27849099a2fd293ede362f4c35ed186747a2 | [] | no_license | chenleo/Leetcode | 075b3ff03dfeff702e93b86e9f9a31380ad88cb6 | da631abbbdb96355e553084137260bb158f8eb27 | refs/heads/master | 2016-09-06T14:46:28.155544 | 2013-12-31T23:18:58 | 2013-12-31T23:18:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 689 | cpp | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL)
return false;
else if (root -> left == NULL && root -> right == NULL)
{
return (root -> val == sum);
}
else
{
return (hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val));
}
}
};
| [
"maverickcc@gmail.com"
] | maverickcc@gmail.com |
4909bdefd692f355baf458fd25528b45c5fd7e2f | 19df97f8a0276993166654c7fa9bf567c50c01ba | /FairyLandClient/Classes/core/YYConfig.h | 53e66d42b6d22a65c1474a516e5dc846f52a017f | [] | no_license | fchsg/cocos2dx_fairy_land | df56add8a9233e83392c1d47193bdd3babdd0d15 | f7022c2d07e1b4bf890fa9a31b589c551df893e9 | refs/heads/master | 2020-07-15T23:04:48.345987 | 2019-09-01T23:09:10 | 2019-09-01T23:09:10 | 205,665,788 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,908 | h | #ifndef __FAIRLAND__CONFIG__
#define __FAIRLAND__CONFIG__
#include "cocos2d.h"
#define LIST_SERVER_MAX 4
#define RECENT_SERVER_MAX 4
/**
渠道名称 渠道号
UC 500001
360 500002
当乐 500003
口袋巴士 500004
手游天下 500005
一起手游 500006
3533 500007
摩游游 500008
OPPO 500009
渠道1 500010
渠道2 500011
渠道3 500012
*/
struct LoginInfo
{
std::string userID;//用户名
std::string password;//密码
std::string mail;//邮箱
std::string channel;//渠道
std::string version;//版本号
std::string phoneInfo;//手机信息(包含机型,号码,运营商,imei)
int encording;
};
class ServerItem: public cocos2d::CCObject
{
public:
ServerItem(const char* line);
~ServerItem(){}
std::string serverName;
std::string serverHost;
int16_t serverPort;
uint8_t serverStatus;
std::string serverID;
bool isNew;
};
class Config: public cocos2d::CCObject
{
private:
std::string m_sUserID; //用户账号
std::string m_sPassword; //密码
std::string m_sVersion; //版本号
std::string m_sChannel; //渠道
std::string m_sListServer; //游戏服务器列表服务器,用于获取游戏服务器列表
int m_nListServerIndex;
int m_nListServerCount;
std::string m_sRecentServer[RECENT_SERVER_MAX]; //最后玩过的服务器
int m_nRecentServerCount;
cocos2d::CCArray *m_pServerListArray; //游戏服务器
int m_nGameServerIndex;
bool m_bBGMusicPlay;
bool m_bEffectPlay;
bool m_bSoundOff;
bool m_bAroundPlayerShow;
std::string m_sUserPhoneInfo; //用户手机信息
LoginInfo loginInfo; // 登录信息
public:
Config();
~Config();
static Config *getInstance();
void loadConfig(); //加载配置
void saveConfig(); //保存配置
LoginInfo getLoginInfo();
//
std::string getUserID(); //获取 UserID
void setUserID(std::string &u);
std::string getPassword();
void setPassword(std::string &p);
std::string getVersion();
void setVersion(std::string &str);
std::string getChannel();
void setChannel(std::string &p);
std::string getRoleName();
void setRoleName(const char *);
std::string getRoleID();
void setRoleID(const char *);
int getProfessionIndex(); //获取职业
void setProfessionIndex(int pi);
void clearRoleInfo();
std::string getListServer();
inline void setRecentServerCount(int count)
{
m_nRecentServerCount = count;
}
inline int getRecentServerCount()
{
return m_nRecentServerCount;
}
std::string getRecentServer(int i);
void addServerInofToList(const char * serverInfo); //将选中的服务器信息添加到近期玩过的服务器列表中
void sortRecentServerList(const char * serverInfo,int i);//选中了已经加入近期服务器列表的服务器则重新排序
int getGameServerCount();
void setGameServer(cocos2d::CCArray *array);
cocos2d::CCString * getGameServer(int i);
inline bool isBackgroundMusicPlay()
{
return m_bBGMusicPlay;
}
inline void setBackgroundMusicPlay(bool _bPlay)
{
m_bBGMusicPlay = _bPlay;
}
inline bool isEffectPlay()
{
return m_bEffectPlay;
}
inline void setEffectPlay(bool _bPlay)
{
m_bEffectPlay = _bPlay;
}
inline bool isSoundOff()
{
return m_bSoundOff;
}
inline void setSoundOff(bool _bOff)
{
m_bSoundOff = _bOff;
}
inline bool isAroundPlayerShow()
{
return m_bAroundPlayerShow;
}
inline void setAroundPlayerShow(bool _bVisible)
{
m_bAroundPlayerShow = _bVisible;
}
inline std::string getPhoneInfo()
{
return m_sUserPhoneInfo;
}
std::string getAndroidPhoneInfo();
};
#endif
| [
"940299880@qq.com"
] | 940299880@qq.com |
fa310c30833b1e8f4aad6db6a0038b91a6885b2d | b8dc02dabf916093d5963414775a160930adc7a1 | /src/c++/sqrbr.cc | efd3cd572dad8d67e45a145d989f82f555552658 | [] | no_license | dgvncsz0f/spoj | 9a62d2553da39919f0a47e2c3d964b53f8b9e54b | b02eb8ab6d6bca128d7259855230a9eb52436e7b | refs/heads/master | 2021-01-18T16:36:43.819367 | 2011-09-28T15:25:17 | 2011-09-28T15:25:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,433 | cc | #vapyhqr <fgqvag.u>
#vapyhqr <fgevat>
#vapyhqr <yvfg>
#vapyhqr <frg>
#vapyhqr <znc>
#vapyhqr <vbfgernz>
pynff orkcerffvba
{
choyvp:
rahz oenpxrg_g
{
EVTUG = 0,
YRSG = 1
};
orkcerffvba(pbafg hvag8_g &a):
_a(a*2),
_f(0),
_obthf(0)
{
}
ibvq chfu(pbafg oenpxrg_g &g)
{
_obthf += (g == YRSG ? 1 : -1);
_f += 1;
}
ibvq cbc(pbafg oenpxrg_g &g)
{
_obthf -= (g == YRSG ? 1 : -1);
_f -= 1;
}
obby pbzcyrgr() pbafg
{
erghea(_f == _a);
}
obby obthf() pbafg
{
erghea(_obthf < 0 || (pbzcyrgr() && _obthf != 0));
}
hvag8_g fgngr() pbafg
{
erghea(_obthf);
}
hvag8_g fvmr() pbafg
{
erghea(_f);
}
hvag8_g vaqrk() pbafg
{
erghea(_f - 1);
}
cevingr:
hvag8_g _a;
hvag8_g _f;
vag8_g _obthf;
};
pynff fdeoe
{
choyvp:
iveghny ~fdeoe()
{}
ibvq svk_yflzoby(hvag8_g v)
{
_yf.vafreg(v);
}
iveghny hvag32_g inyvq_rkcef(orkcerffvba *o)
{
vs (o->obthf())
erghea(0);
vs (o->pbzcyrgr())
erghea(1);
ryfr
{
hvag32_g e = 0;
o->chfu(orkcerffvba::YRSG);
e += inyvq_rkcef(o);
o->cbc(orkcerffvba::YRSG);
vs (_yf.svaq(o->fvmr()) == _yf.raq())
{
o->chfu(orkcerffvba::EVTUG);
e += inyvq_rkcef(o);
o->cbc(orkcerffvba::EVTUG);
}
erghea(e);
}
}
cevingr:
fgq::frg<hvag8_g> _yf;
};
pynff fdeoe_cebkl : choyvp fdeoe
{
choyvp:
iveghny hvag32_g inyvq_rkcef(orkcerffvba *o)
{
pbafg hvag16_g x = ((o->fgngr()&0kSS) << 8) | (o->vaqrk()&0kSS);
fgq::znc<hvag16_g,hvag32_g>::vgrengbe vg;
vs ((vg=_pnpur.svaq(x)) != _pnpur.raq())
erghea(vg->frpbaq);
hvag32_g e = fdeoe::inyvq_rkcef(o);
_pnpur[x] = e;
erghea(e);
}
cevingr:
fgq::znc<hvag16_g,hvag32_g> _pnpur;
};
vag znva()
{
hafvtarq vag grfg_pnfrf;
fgq::pva >> grfg_pnfrf;
sbe (hafvtarq vag v=0; v<grfg_pnfrf; v++)
{
hafvtarq vag a, x;
fgq::pva >> a;
fgq::pva >> x;
fdeoe_cebkl bow;
bow.svk_yflzoby(0);
sbe (hafvtarq vag v=0; v<x; v++)
{
hafvtarq vag f;
fgq::pva >> f;
bow.svk_yflzoby(f-1);
}
orkcerffvba rkc(a);
fgq::pbhg << bow.inyvq_rkcef(&rkc) << fgq::raqy;
}
erghea(0);
}
| [
"dsouza@bitforest.org"
] | dsouza@bitforest.org |
d4020c7a599f4028cfb01c7405b3f2cc9cf3caf9 | 82b575d0d830367cc9edff1a3d1d2e517d5e6e9e | /Bitmasking_4.cpp | 483a24f03e75ab8bb799b885b02521800feaa2d1 | [] | no_license | NishantDhanda/CP | 58d9b5cf287bf54681f869d67e22558423927bc6 | 180f34f6153ed1ec1c0d4f1568f4fe0154c05d89 | refs/heads/master | 2020-07-10T03:19:47.402709 | 2019-09-06T14:13:41 | 2019-09-06T14:13:41 | 204,154,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | cpp | // Swapping by xor
#include<iostream>
using namespace std;
int main()
{
int a,b,n,i,j,k;
cout<<"Enter a and b\n";
cin>>a>>b;
cout<<"a is "<<a<<" and b is "<<b<<endl;
a=a^b;
b=a^b;
a=a^b;
cout<<"After swapping a is "<<a<<" and b is "<<b<<endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
5953b91aabe18015b6ce1b1723fa072abe4a45c7 | 00f023ec19b7bfcf89fc12431d3edb159b2b8f2e | /array/array_rotation/7.Find_Max_Sum_In_Array_Through_Rotation.cpp | fa834b33721d77656f2f2177238f2040817124af | [] | no_license | garima-b8/coding_interview_questions | eac4a59c19132991a294f027274665790cd73a43 | ed1e7d7c3bb594f03cbff89e924c8ac5547d0654 | refs/heads/master | 2021-05-21T04:46:57.383631 | 2020-05-19T13:22:26 | 2020-05-19T13:22:26 | 252,549,550 | 0 | 0 | null | 2020-05-19T13:22:27 | 2020-04-02T19:38:09 | C++ | UTF-8 | C++ | false | false | 1,483 | cpp | /*
* Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
* Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possbile of * * summati* on of i*arr[i].
* Examples :
*
*Input: arr[] = {1, 20, 2, 10}
*Output: 72
*We can 72 by rotating array twice.
*{2, 10, 1, 20}
*20*3 + 1*2 + 10*1 + 2*0 = 72
*
*Input: arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9};
*Output: 330
*We can 330 by rotating array 9 times.
*{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
* 0*1 + 1*2 + 2*3 ... 9*10 = 330
*
*/
#include<iostream>
using namespace std;
// Returns max possible value of i*arr[i]
int maxSum(int arr[], int n)
{
// Find array sum and i*arr[i] with no rotation
int arrSum = 0; // Stores sum of arr[i]
int currVal = 0; // Stores sum of i*arr[i]
for (int i=0; i<n; i++)
{
arrSum = arrSum + arr[i];
currVal = currVal+(i*arr[i]);
}
// Initialize result as 0 rotation sum
int maxVal = currVal;
// Try all rotations one by one and find
// the maximum rotation sum.
for (int j=1; j<n; j++)
{
currVal = currVal + arrSum-n*arr[n-j];
if (currVal > maxVal)
maxVal = currVal;
}
// Return result
return maxVal;
}
int main()
{
int arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "\nMax sum is " << maxSum(arr, n);
return 0;
}
| [
"garima_b08@yahoo.com"
] | garima_b08@yahoo.com |
d59804388e156ea8cc9e9a5f4f97f646f1f7c198 | 25680ce9e45bcbb2b7a7909fd656905cd723c6d8 | /EX2/TCP/信息收发/B16012117_TCP_S/B16012117_TCP_S.cpp | 64a6f4c24f58e66b2b38f97c48659b3713db1d58 | [] | no_license | ikirito98612/NJUPT-software-design-course | 96cf16dc33601b42e8d00dc99ea9ef02f361ba33 | 9610a70623ad8a85727109336ea11d761c7c05f2 | refs/heads/main | 2023-03-26T10:56:59.842371 | 2021-03-06T21:24:40 | 2021-03-06T21:24:40 | 345,197,492 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,283 | cpp | // B16012117_TCP_S.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "B16012117_TCP_S.h"
#include "B16012117_TCP_SDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CB16012117_TCP_SApp
BEGIN_MESSAGE_MAP(CB16012117_TCP_SApp, CWinApp)
//{{AFX_MSG_MAP(CB16012117_TCP_SApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CB16012117_TCP_SApp construction
CB16012117_TCP_SApp::CB16012117_TCP_SApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CB16012117_TCP_SApp object
CB16012117_TCP_SApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CB16012117_TCP_SApp initialization
BOOL CB16012117_TCP_SApp::InitInstance()
{
if (!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CB16012117_TCP_SDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"noreply@github.com"
] | noreply@github.com |
7b49d8027bbb47085b54e9bcb15ac69f0ea8717d | ac87a0e387e795ccb862eb2f76107a9f66fd319f | /PersonalPractice/Best Time to Buy and Sell Stock.cpp | 06b6cb4afff844b7e6cb364dde4788ea8c4d4dd7 | [] | no_license | prasanjit15/DailyCode | ac9541aa82276cc92224c356356143d5e0b287c2 | cf19c808d6c343b6a47386debc90ba47e8c2abef | refs/heads/master | 2023-05-14T00:06:21.092812 | 2021-06-02T06:44:36 | 2021-06-02T06:44:36 | 284,071,833 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | cpp | //Best Time to Buy and Sell Stock
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy = INT_MAX;
int profit = 0;
for(int i = 0; i<prices.size();i++){
if(prices[i]<buy)
buy = prices[i];
else if(prices[i] - buy > profit)
profit = prices[i]-buy;
}
return profit;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
a2620bb16a6a29e87c05f38ce987ab3c3abd0532 | 3801cfabaa94d1c98b3ce945f18bccb68300b32e | /samples/2_Cookbook/10_inline_asm/inline_asm.cpp | c47486e91a1f2e907cc684b79fc3674a02709a39 | [
"MIT"
] | permissive | wenkaidu/HIP | 76174055f71d07a5b57223eb62f1804a56e62dc9 | 70f01fad7319417ac48dd77dcdaada7123733a26 | refs/heads/master | 2020-05-23T19:14:08.840890 | 2019-05-15T17:18:51 | 2019-05-15T17:18:51 | 186,906,730 | 0 | 0 | NOASSERTION | 2019-05-15T21:43:06 | 2019-05-15T21:43:06 | null | UTF-8 | C++ | false | false | 4,947 | cpp | /*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
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 <iostream>
// hip header file
#include "hip/hip_runtime.h"
#define WIDTH 1024
#define NUM (WIDTH * WIDTH)
#define THREADS_PER_BLOCK_X 4
#define THREADS_PER_BLOCK_Y 4
#define THREADS_PER_BLOCK_Z 1
// Device (Kernel) function, it must be void
__global__ void matrixTranspose(float* out, float* in, const int width) {
int x = hipBlockDim_x * hipBlockIdx_x + hipThreadIdx_x;
int y = hipBlockDim_y * hipBlockIdx_y + hipThreadIdx_y;
asm volatile("v_mov_b32_e32 %0, %1" : "=v"(out[x * width + y]) : "v"(in[y * width + x]));
}
// CPU implementation of matrix transpose
void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) {
for (unsigned int j = 0; j < width; j++) {
for (unsigned int i = 0; i < width; i++) {
output[i * width + j] = input[j * width + i];
}
}
}
int main() {
float* Matrix;
float* TransposeMatrix;
float* cpuTransposeMatrix;
float* gpuMatrix;
float* gpuTransposeMatrix;
hipDeviceProp_t devProp;
hipGetDeviceProperties(&devProp, 0);
std::cout << "Device name " << devProp.name << std::endl;
hipEvent_t start, stop;
hipEventCreate(&start);
hipEventCreate(&stop);
float eventMs = 1.0f;
int i;
int errors;
Matrix = (float*)malloc(NUM * sizeof(float));
TransposeMatrix = (float*)malloc(NUM * sizeof(float));
cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float));
// initialize the input data
for (i = 0; i < NUM; i++) {
Matrix[i] = (float)i * 10.0f;
}
// allocate the memory on the device side
hipMalloc((void**)&gpuMatrix, NUM * sizeof(float));
hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float));
// Record the start event
hipEventRecord(start, NULL);
// Memory transfer from host to device
hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice);
// Record the stop event
hipEventRecord(stop, NULL);
hipEventSynchronize(stop);
hipEventElapsedTime(&eventMs, start, stop);
printf("hipMemcpyHostToDevice time taken = %6.3fms\n", eventMs);
// Record the start event
hipEventRecord(start, NULL);
// Lauching kernel from host
hipLaunchKernelGGL(matrixTranspose, dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y),
dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix,
gpuMatrix, WIDTH);
// Record the stop event
hipEventRecord(stop, NULL);
hipEventSynchronize(stop);
hipEventElapsedTime(&eventMs, start, stop);
printf("kernel Execution time = %6.3fms\n", eventMs);
// Record the start event
hipEventRecord(start, NULL);
// Memory transfer from device to host
hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost);
// Record the stop event
hipEventRecord(stop, NULL);
hipEventSynchronize(stop);
hipEventElapsedTime(&eventMs, start, stop);
printf("hipMemcpyDeviceToHost time taken = %6.3fms\n", eventMs);
// CPU MatrixTranspose computation
matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH);
// verify the results
errors = 0;
double eps = 1.0E-6;
for (i = 0; i < NUM; i++) {
if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) {
printf("gpu%f cpu %f \n", TransposeMatrix[i], cpuTransposeMatrix[i]);
errors++;
}
}
if (errors != 0) {
printf("FAILED: %d errors\n", errors);
} else {
printf("PASSED!\n");
}
// free the resources on device side
hipFree(gpuMatrix);
hipFree(gpuTransposeMatrix);
// free the resources on host side
free(Matrix);
free(TransposeMatrix);
free(cpuTransposeMatrix);
return errors;
}
| [
"maneesh.gupta@amd.com"
] | maneesh.gupta@amd.com |
15c63de915e291b5a84fc3012f29e7e4c95f7051 | f06090a81a8606023c06bd80eb05e3ac953f2773 | /Flamingo/Flamingo.ino | 4e94d708071f25510f4539d4086d87dc84b363a2 | [] | no_license | BBQBradley/KernModule_IXD1 | fd9fb67b569c81c2a0c935bdd4cfa60ba3eb6f2f | 4ccda5dfda46923bbc825420d02035959b649eeb | refs/heads/master | 2020-05-22T14:37:04.553016 | 2019-06-26T15:30:28 | 2019-06-26T15:30:28 | 186,391,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,152 | ino | #include <Wtv020sd16p.h>
///////////////////////////////// AUDIO //////////////////////////////////////////
int resetPin = 2;
int clockPin = 3;
int dataPin = 4;
int busyPin = 5;
Wtv020sd16p wtv020sd16p(resetPin,clockPin,dataPin,busyPin);
//////////////////////////////// HARTSLAG //////////////////////////////////////
const unsigned char _heartbeat_values[] = {21,21,21,21,21,21,21,21,21,21,21,21,21,22,23,25,
28,34,42,54,71,92,117,145,175,203,228,246,255,254,242,220,191,157,121,87,
58,34,17,6,1,0,2,5,9,13,16,18,19,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21};
const unsigned char _HEARTBEAT_INDEXES = 64; //64
byte ledPin = 9; //Must be PWM capable pin
//int heartbeat_period = 500; //[ms] 60000/120 (120 beats x min, baby)
//int heartbeat_period = 857; //[ms] 60000/70 (70 beats x min, adult in rest)
int heartbeat_period = 1000; // slower, feels like soothing
void heartbeat()
{
int index = (millis()%heartbeat_period) * _HEARTBEAT_INDEXES / heartbeat_period;
analogWrite(ledPin, _heartbeat_values[index]);
}
///////////////////////////////// SENSOR /////////////////////////////////////////
int pressPin = 0;
int pressValue = 0;
int pressTimer = 0;
int pressTimerSwitch = 0;
boolean finished = false;
///////////////////////////////////////////////////////////////////////////////////
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT);
wtv020sd16p.reset();
heartbeat();
}
void loop()
{
pressValue = analogRead(pressPin);
//Serial.println(pressValue);
//Serial.println(pressTimer);
//Serial.println(pressTimerSwitch);
if (pressValue > 600)
{
pressTimerSwitch = +1;
}
if (pressTimerSwitch == 1)
{
wtv020sd16p.asyncPlayVoice(0);
delay(15);
while (digitalRead(busyPin) == HIGH and pressTimer < 1920)
{
Serial.println(pressTimer);
pressTimer = pressTimer +1;
heartbeat();
}
delay(10);
finished = true;
}
if (pressTimer == 50)
{
pressTimerSwitch = 0;
pressTimer = 0;
}
if (finished == true)
{
pressTimerSwitch = 0;
pressTimer = 0;
}
}
| [
"35529740+BradleyLangguth@users.noreply.github.com"
] | 35529740+BradleyLangguth@users.noreply.github.com |
9eb8f814420378b2d326ae114db4ff38c820863f | e0c9fdd0c4dd0b043152fe871898c19bb7359b09 | /tisCameraDriver/Common/VCDButtonButton.cpp | ca3d3d318cc21fca32682af3ac89e5c8308d1b7b | [] | no_license | jsayres82/Robot_CV | 88377be1ebf56ae6b81645f5c13663b8554b8faa | 2aece6cf8c9cc41f038d8c39aab2dea936c586ca | refs/heads/master | 2020-04-12T04:33:46.923782 | 2019-01-08T19:26:15 | 2019-01-08T19:26:15 | 162,299,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | cpp | // VCDButtonButton.cpp : implementation file
//
#include "stdafx.h"
#include "VCDButtonButton.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CVCDButtonButton
CVCDButtonButton::CVCDButtonButton()
{
}
CVCDButtonButton::~CVCDButtonButton()
{
}
BEGIN_MESSAGE_MAP(CVCDButtonButton, CButton)
//{{AFX_MSG_MAP(CVCDButtonButton)
ON_CONTROL_REFLECT(BN_CLICKED, OnClicked)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CVCDButtonButton message handlers
//////////////////////////////////////////////////////////////////////////
/*! Initialize the control
*/
void CVCDButtonButton::setupCtrl( DShowLib::tIVCDButtonPropertyPtr pItf, tControlVectorPtr pGroup )
{
m_pButtonItf = pItf;
update();
}
//////////////////////////////////////////////////////////////////////////
/*! Set the button's availability
*/
void CVCDButtonButton::update()
{
EnableWindow( m_pButtonItf->getAvailable() );
}
//////////////////////////////////////////////////////////////////////////
/*! Invoke the push method on the controlled interface
*/
void CVCDButtonButton::OnClicked()
{
try
{
m_pButtonItf->push();
}
catch( HRESULT )
{
AfxMessageBox( TEXT("Error Setting Property") );
}
}
| [
"sayres.justin@gmail.com"
] | sayres.justin@gmail.com |
be45a85e5d9cf08f67feeadf2c61e24ccfab1701 | 887f3a72757ff8f691c1481618944b727d4d9ff5 | /third_party/gecko_1.9.2/osx/gecko_sdk/include/nsIRDFContainerUtils.h | 7f810f4b68345be8db4dd0b0a723555b87d658fc | [] | no_license | zied-ellouze/gears | 329f754f7f9e9baa3afbbd652e7893a82b5013d1 | d3da1ed772ed5ae9b82f46f9ecafeb67070d6899 | refs/heads/master | 2020-04-05T08:27:05.806590 | 2015-09-03T13:07:39 | 2015-09-03T13:07:39 | 41,813,794 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,267 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/mozilla-1.9.2-macosx-xulrunner/build/rdf/base/idl/nsIRDFContainerUtils.idl
*/
#ifndef __gen_nsIRDFContainerUtils_h__
#define __gen_nsIRDFContainerUtils_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
#ifndef __gen_nsIRDFContainer_h__
#include "nsIRDFContainer.h"
#endif
#ifndef __gen_nsIRDFResource_h__
#include "nsIRDFResource.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIRDFContainerUtils */
#define NS_IRDFCONTAINERUTILS_IID_STR "d4214e91-fb94-11d2-bdd8-00104bde6048"
#define NS_IRDFCONTAINERUTILS_IID \
{0xd4214e91, 0xfb94, 0x11d2, \
{ 0xbd, 0xd8, 0x00, 0x10, 0x4b, 0xde, 0x60, 0x48 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIRDFContainerUtils : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IRDFCONTAINERUTILS_IID)
/**
* Returns 'true' if the property is an RDF ordinal property.
*/
/* boolean IsOrdinalProperty (in nsIRDFResource aProperty); */
NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Convert the specified index to an ordinal property.
*/
/* nsIRDFResource IndexToOrdinalResource (in long aIndex); */
NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource **_retval NS_OUTPARAM) = 0;
/**
* Convert the specified ordinal property into an index
*/
/* long OrdinalResourceToIndex (in nsIRDFResource aOrdinal); */
NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM) = 0;
/**
* Return 'true' if the specified resource is a container
*/
/* boolean IsContainer (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Return 'true' if the specified resource is a container and it is empty
*/
/* boolean IsEmpty (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Return 'true' if the specified resource is a bag
*/
/* boolean IsBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Return 'true' if the specified resource is a sequence
*/
/* boolean IsSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Return 'true' if the specified resource is an alternation
*/
/* boolean IsAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Decorates the specified resource appropriately to make it
* usable as an empty bag in the specified data source.
*/
/* nsIRDFContainer MakeBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) = 0;
/**
* Decorates the specified resource appropriately to make it
* usable as an empty sequence in the specified data source.
*/
/* nsIRDFContainer MakeSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) = 0;
/**
* Decorates the specified resource appropriately to make it
* usable as an empty alternation in the specified data source.
*/
/* nsIRDFContainer MakeAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) = 0;
/**
* Retrieve the index of element in the container. Returns -1 if
* the element is not in the container.
*/
/* long indexOf (in nsIRDFDataSource aDataSource, in nsIRDFResource aContainer, in nsIRDFNode aElement); */
NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIRDFContainerUtils, NS_IRDFCONTAINERUTILS_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIRDFCONTAINERUTILS \
NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIRDFCONTAINERUTILS(_to) \
NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, PRBool *_retval NS_OUTPARAM) { return _to IsOrdinalProperty(aProperty, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource **_retval NS_OUTPARAM) { return _to IndexToOrdinalResource(aIndex, _retval); } \
NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM) { return _to OrdinalResourceToIndex(aOrdinal, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return _to IsContainer(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return _to IsEmpty(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return _to IsBag(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return _to IsSeq(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return _to IsAlt(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) { return _to MakeBag(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) { return _to MakeSeq(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) { return _to MakeAlt(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM) { return _to IndexOf(aDataSource, aContainer, aElement, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIRDFCONTAINERUTILS(_to) \
NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsOrdinalProperty(aProperty, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IndexToOrdinalResource(aIndex, _retval); } \
NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->OrdinalResourceToIndex(aOrdinal, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsContainer(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsEmpty(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsBag(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsSeq(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsAlt(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->MakeBag(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->MakeSeq(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->MakeAlt(aDataSource, aResource, _retval); } \
NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IndexOf(aDataSource, aContainer, aElement, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsRDFContainerUtils : public nsIRDFContainerUtils
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIRDFCONTAINERUTILS
nsRDFContainerUtils();
private:
~nsRDFContainerUtils();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsRDFContainerUtils, nsIRDFContainerUtils)
nsRDFContainerUtils::nsRDFContainerUtils()
{
/* member initializers and constructor code */
}
nsRDFContainerUtils::~nsRDFContainerUtils()
{
/* destructor code */
}
/* boolean IsOrdinalProperty (in nsIRDFResource aProperty); */
NS_IMETHODIMP nsRDFContainerUtils::IsOrdinalProperty(nsIRDFResource *aProperty, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIRDFResource IndexToOrdinalResource (in long aIndex); */
NS_IMETHODIMP nsRDFContainerUtils::IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* long OrdinalResourceToIndex (in nsIRDFResource aOrdinal); */
NS_IMETHODIMP nsRDFContainerUtils::OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean IsContainer (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean IsEmpty (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean IsBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean IsSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean IsAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIRDFContainer MakeBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIRDFContainer MakeSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIRDFContainer MakeAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* long indexOf (in nsIRDFDataSource aDataSource, in nsIRDFResource aContainer, in nsIRDFNode aElement); */
NS_IMETHODIMP nsRDFContainerUtils::IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
extern nsresult
NS_NewRDFContainerUtils(nsIRDFContainerUtils** aResult);
#endif /* __gen_nsIRDFContainerUtils_h__ */
| [
"gears.daemon@fe895e04-df30-0410-9975-d76d301b4276"
] | gears.daemon@fe895e04-df30-0410-9975-d76d301b4276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.