hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
5481fa8a02fb3b0a6225ff1f8169b05ac29afdf1
3,688
css
CSS
module-8/css/styles.css
Kolomiits/goit_fecore_5
7d3a76f8ccf661d97ac7b5637f49515b3e49ed32
[ "Unlicense" ]
null
null
null
module-8/css/styles.css
Kolomiits/goit_fecore_5
7d3a76f8ccf661d97ac7b5637f49515b3e49ed32
[ "Unlicense" ]
null
null
null
module-8/css/styles.css
Kolomiits/goit_fecore_5
7d3a76f8ccf661d97ac7b5637f49515b3e49ed32
[ "Unlicense" ]
null
null
null
html { box-sizing: border-box; font-family: "Montserrat", sans-serif; font-size: 14px; } *, *::before, *::after { box-sizing: inherit; } .visually-hidden:not(:focus):not(:active), input[type="checkbox"].visually-hidden, input[type="radio"].visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; border: 0; padding: 0; white-space: nowrap; clip-path: inset(100%); clip: rect(0 0 0 0); overflow: hidden; } a { text-decoration-line: none; } ul { list-style-type: none; padding: 0px; } img { display: block; max-width: 100%; height: auto; } button { cursor: pointer; } .header-wrapper { text-align: center; background-color: #000000; background-image: url("../img/holiday.png"); background-repeat: no-repeat; background-size: cover; background-position: center; min-height: 540px; color: #ffffff; padding: 10px; } .nav-main__btn { margin-bottom: 130px; } .nav-main__btn { font-weight: 700; border: none; background: transparent; width: 94px; height: 40px; padding: 0px; } .nav-main__btn--white { color: #ffffff; } .nav-main__btn--hover:hover { border: 2px solid #ffffff; border-radius: 25px; } .nav-logo { font-size: 20px; font-weight: 600; text-transform: uppercase; margin-bottom: 30px; } .nav-logo__color { color: #ffffff; } .header-wrapper h2 { font-size: 52px; font-weight: 700; text-transform: uppercase; margin-bottom: 0px; word-wrap: break-word; } .header-wrapper p { font-size: 18px; font-family: "Roboto"; font-weight: 300; color: rgb(255, 255, 255); margin-top: 10px; margin-bottom: 40px; } .header-wrapper__btn { font-weight: 700; border: none; border-radius: 20px; width: 280px; height: 40px; } .header-wrapper__btn--red { color: #ffffff; background: #ff4e50; } .header-wrapper__btn--hover:hover { color: #ff4e50; background: #ffffff; border: 2px solid #ff4e50; } .main-wrapper { padding: 10px; text-align: center; } .main-wrapper h2 { font-size: 22px; font-weight: 700; color: rgb(51, 51, 51); } .partners-list__item { max-width: 220px; margin: 0 auto; margin-bottom: 30px; } .partners-list__item--title { color: rgb(51, 51, 51); font-weight: 700; font-size: 14px; } .partners-list__item--desc { font-size: 14px; font-family: "Roboto"; color: #666666; } .main-wrapper__btn { font-weight: 700; border-radius: 20px; width: 284px; height: 44px; } .main-wrapper__btn--red { color: #ff4e50; border: 2px solid rgb(255, 78, 80); background-color: #ffffff; } .main-wrapper__btn--hover:hover { color: #ffffff; background: #ff4e50; } .main-wrapper__img::after { display: block; content: ""; width: 37px; height: 37px; position: absolute; right: 0px; bottom: 0px; border-radius: 50%; border: 4px solid #ffffff; background-repeat: no-repeat; background-position: center; } .main-wrapper__img { position: relative; width: 120px; height: 120px; margin: 0 auto; } .img-partner-1::after { background: rgb(255, 78, 80); background-image: url("../img/tv.png"); background-repeat: no-repeat; background-position: center; } .img-partner-2::after { background: rgb(255, 165, 7); background-image: url("../img/beaker.png"); background-repeat: no-repeat; background-position: center; } .img-partner-3::after { background: rgb(28, 215, 173); background-image: url("../img/coffee.png"); background-repeat: no-repeat; background-position: center; } .img-partner-4::after { background: rgb(78, 115, 219); background-image: url("../img/airplane.png"); background-repeat: no-repeat; background-position: center; }
16.612613
47
0.659436
ef4c966c213e4cb681ed5f07cd8b7a4b471a4158
200,449
c
C
Python/aot_ceval_jit.c
mananpal1997/pyston
d24bcf5690ab09f37d04549e70561656eaea4445
[ "0BSD" ]
null
null
null
Python/aot_ceval_jit.c
mananpal1997/pyston
d24bcf5690ab09f37d04549e70561656eaea4445
[ "0BSD" ]
null
null
null
Python/aot_ceval_jit.c
mananpal1997/pyston
d24bcf5690ab09f37d04549e70561656eaea4445
[ "0BSD" ]
null
null
null
// This file contains the JIT compiler // The main design choices/goals are: // - removing the dispatching overhead of the interpreter // - reducing reference counting overhead // - reducing overhead related to Python value stack push/pops // - inlined caches // - generates calls to ahead of time generated type specific traces of bytescodes // - e.g. 'float * float' -> PyNumber_MultiplyFloatFloat2 // - very fast compilation speed // - uses DynAsm - good documentation at: https://corsix.github.io/dynasm-doc/index.html // - jit thresholds are very low // - most bytecode instructions are complex and are handled by calls to functions // which means even a more clever compiler can't do much better (when not inlining) // - mostly using static register allocation is fine // because of all the external calls which restrict register assignment // - machine code gets emitted immediately, no IR, passes etc.. // - can switch from interpreter to compiled function at // - function entry // - any bytecode which is the target of jump from another bytecode // - deoptimization is possible at the start of every bytecode // - currently used to implement cpythons 'tracing' support // - main task is creating the python value stack for the interpreter to continue // // Some assumptions: // - we currently only support amd64 systems with SystemV calling convention and AArch64 // - code gets emitted into memory area which fits into 32bit address // - makes sure we can use relative addressing most of the time // - saves some space // - we use a custom calling convention to make external calls fast: // - args get past/returned following the SystemV calling convention // - in addition we have the following often used values in fixed callee saved registers // (which means we can call normal C function without changes because have to save them): // - r12/x23 - PyObject** python value stack pointer // - r13/x19 - PyFrameObject* frame object of currently executing function // - r15/x22 - PyThreadState* tstate of currently executing thread // - code inside aot_ceval_jit_helper.c is using this special convention // via gcc global register variable extension // (which prevents us from using LTO on that translation unit) // // 'Deferred value stack': // - we don't emit python value stack operations (PUSH(), POP(),...) immediately // like the interpreter does instead we defer them until the use // - this removes many memory operations // - we can directly use the correct register when doing a external call // - we can avoid some reference counting updates // - code which needs the interpreters value stack needs to call: // - deferred_vs_apply() // - if a instruction modifies register 'res' (=rax) it needs to first call: // - deferred_vs_convert_reg_to_stack() // // Future bigger ideas: // - we support deoptimizations at the start of every bytecode which we could use // to generate faster more specialiced code which makes some assumptions // - get ride of frame->f_lasti updates // - update/overwrite inline cache entries when they start to fail // #define PY_LOCAL_AGGRESSIVE #include "Python.h" #include "pycore_ceval.h" #ifdef PYSTON_LITE // make sure this points to the Pyston version of this file: #include "../../Include/internal/pycore_code.h" #else #include "pycore_code.h" #endif #include "pycore_object.h" #include "pycore_pyerrors.h" #include "pycore_pylifecycle.h" #include "pycore_pystate.h" #include "pycore_tupleobject.h" #include "code.h" #ifdef PYSTON_LITE // Use the cpython version of this file: #include "dict-common.h" #else #include "../Objects/dict-common.h" #endif #include "dictobject.h" #include "frameobject.h" #include "opcode.h" #ifdef PYSTON_LITE #undef WITH_DTRACE #endif #include "pydtrace.h" #include "setobject.h" #include "structmember.h" #ifdef PYSTON_LITE #define IS_IMMORTAL(x) (0) #endif // enable runtime checks to catch jit compiler bugs //#define JIT_DEBUG 1 #if JIT_DEBUG #define DASM_CHECKS 1 #define _STRINGIFY(N) #N #define STRINGIFY(N) _STRINGIFY(N) #define JIT_ASSERT(condition, fmt, ...) \ do { \ if (!(condition)) { \ fprintf(stderr, __FILE__ ":" STRINGIFY(__LINE__) ": %s: Assertion `" #condition "' failed: " fmt "\n", \ __PRETTY_FUNCTION__, ##__VA_ARGS__); \ abort(); \ } \ } while (0) #else #define JIT_ASSERT(x, m, ...) assert(x) #endif #ifdef PYSTON_LITE #define ENABLE_DEFINED_TRACKING 0 #else #define ENABLE_DEFINED_TRACKING 1 #endif #define DEFERRED_VS_MAX 16 /* used by STORE_SUBSCR */ #define NUM_MANUAL_STACK_SLOTS 2 /* used by STORE_SUBSCR */ typedef enum ValueStackLoc { CONST, FAST, REGISTER, STACK, } ValueStackLoc; // Enum values for ref_status: typedef enum RefStatus { BORROWED, OWNED, IMMORTAL, } RefStatus; typedef enum Section { SECTION_CODE, SECTION_COLD, SECTION_DEOPT, SECTION_ENTRY, SECTION_OPCODE_ADDR, } Section; typedef struct DeferredValueStackEntry { ValueStackLoc loc; unsigned long val; } DeferredValueStackEntry; // We have a very simple analysis method: // When we see a LOAD_METHOD bytecode, we try to gather some hints that // can help the corresponding CALL_METHOD. // // The corresponding LOAD_METHOD and CALL_METHOD can be a bit hard to determine, // so the strategy used here is to just put the hints in a stack for LOAD_METHOD, // and pop them off for CALL_METHOD. // // The reason this optimization is valuable is because the LOAD_METHOD bytecode // might have a decent amount of information available: typically the value of // the callable on the fast path. // // Some of this is gained from using AOT speculation, but there are more fields // that can be specialized on than we have in our traces. Plus we can skip extra // guards by doing a single type check at the beginning. // // There is always a hint object defined for each LOAD_METHOD bytecode, and one // consumed by each CALL_METHOD bytecode. If no hinting information was found // then the hint object will contain NULL entries. typedef struct CallMethodHint { struct CallMethodHint* next; // next item in this linked list PyTypeObject* type; // type of the object we got the attribute from PyObject* attr; // the attribute that we fetched char meth_found; char is_self_const; // self set via LOAD_CONST } CallMethodHint; typedef struct Jit { struct dasm_State* d; char failed; PyCodeObject* co; OpCache* opcache; PyObject* co_consts; PyObject* co_names; int deferred_vs_next; DeferredValueStackEntry deferred_vs[DEFERRED_VS_MAX]; int num_deferred_stack_slots; int deferred_stack_slot_next; Section current_section; // =1 if an entry in deferred_vs is using the vs_preserved_reg int deferred_vs_preserved_reg_used; // =1 if an entry in deferred_vs is using the 'res' register int deferred_vs_res_used; int num_opcodes; const _Py_CODEUNIT *first_instr; char* is_jmp_target; // need to be free()d #if ENABLE_DEFINED_TRACKING // this keeps track of which fast local variable we know are set (!= 0) // if we don't know if they are set or if they are 0 is defined will be 0 // currently we only track definedness inside a basic block and in addition the function args // TODO: could use a bitvector instead of a byte per local variable char* known_defined; // need to be free()d #endif // used by emit_instr_start to keep state across calls int old_line_number; int emitted_trace_check_for_line; CallMethodHint* call_method_hints; // linked list, each item needs to be freed } Jit; #define Dst_DECL Jit* Dst #define Dst_REF Dst->d // ignore this false warning #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" #include <dynasm/dasm_proto.h> #ifdef __aarch64__ #include <dynasm/dasm_arm64.h> #else #include <dynasm/dasm_x86.h> #endif #pragma GCC diagnostic pop #if JIT_DEBUG // checks after every instruction sequence emitted if a DynASM error got generated // helps with catching operands which are out of range for the specified instruction. #define dasm_put(...) do { dasm_put(__VA_ARGS__); JIT_ASSERT(Dst_REF->status == DASM_S_OK, "dasm check failed %x", Dst_REF->status); } while (0) #endif #include <sys/mman.h> #include <ctype.h> #ifdef PYSTON_LITE PyObject* cmp_outcome(PyThreadState *tstate, int, PyObject *v, PyObject *w); PyObject* PyNumber_PowerNone(PyObject *v, PyObject *w); PyObject* PyNumber_InPlacePowerNone(PyObject *v, PyObject *w); PyObject* call_function_ceval_no_kw(PyThreadState *tstate, PyObject **stack, Py_ssize_t oparg); PyObject* call_function_ceval_kw(PyThreadState *tstate, PyObject **stack, Py_ssize_t oparg, PyObject* kwnames); PyObject* cmp_outcomePyCmp_LT(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_LE(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_EQ(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_NE(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_GT(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_GE(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_IN(PyObject *v, PyObject *w); PyObject* cmp_outcomePyCmp_NOT_IN(PyObject *v, PyObject *w); #else #include "aot.h" #endif #include "aot_ceval_jit_helper.h" // used if JIT_PERF_MAP is enabled static FILE *perf_map_file = NULL, *perf_map_opcode_map = NULL; static long perf_map_num_funcs = 0; struct PerfMapEntry { char* func_name; // must call free() on it void* func_addr; long func_size; } *perf_map_funcs; static int jit_use_aot = 1, jit_use_ics = 1; static PyObject* cmp_outcomePyCmp_BAD(PyObject *v, PyObject *w) { return cmp_outcome(NULL, PyCmp_BAD, v, w); } PyObject* cmp_outcomePyCmp_EXC_MATCH(PyObject *v, PyObject *w); int eval_breaker_jit_helper(); PyObject* loadAttrCacheAttrNotFound(PyObject *owner, PyObject *name); #ifndef PYSTON_LITE int setItemSplitDictCache(PyObject* dict, Py_ssize_t splitdict_index, PyObject* v, PyObject* name); int setItemInitSplitDictCache(PyObject** dictptr, PyObject* obj, PyObject* v, Py_ssize_t splitdict_index,PyObject* name); #endif PyObject * import_name(PyThreadState *, PyFrameObject *, PyObject *, PyObject *, PyObject *); PyObject * import_from(PyThreadState *, PyObject *, PyObject *); void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg); #ifdef PYSTON_LITE void* lookdict_split_value; #define lookdict_split lookdict_split_value static void* method_vectorcall_NOARGS_value; static void* method_vectorcall_O_value; static void* method_vectorcall_FASTCALL_value; static void* method_vectorcall_FASTCALL_KEYWORDS_value; static void* method_vectorcall_VARARGS_value; static void* method_vectorcall_VARARGS_KEYWORDS_value; #define method_vectorcall_NOARGS method_vectorcall_NOARGS_value #define method_vectorcall_O method_vectorcall_O_value #define method_vectorcall_FASTCALL method_vectorcall_FASTCALL_value #define method_vectorcall_FASTCALL_KEYWORDS method_vectorcall_FASTCALL_KEYWORDS_value #define method_vectorcall_VARARGS method_vectorcall_VARARGS_value #define method_vectorcall_VARARGS_KEYWORDS method_vectorcall_VARARGS_KEYWORDS_value #else Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject **value_addr); PyObject * method_vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); PyObject * method_vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); PyObject * method_vectorcall_FASTCALL(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); PyObject * method_vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); PyObject * method_vectorcall_VARARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); PyObject * method_vectorcall_VARARGS_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); #endif PyObject* PySlice_NewSteal(PyObject *start, PyObject *stop, PyObject *step); static void decref_array(PyObject** vec, int n) { for (int i = -1; i >= -n; i--) { Py_DECREF(vec[i]); } } __attribute__((flatten)) static void decref_array3(PyObject** vec) { decref_array(vec, 3); } __attribute__((flatten)) static void decref_array4(PyObject** vec) { decref_array(vec, 4); } static void* __attribute__ ((const)) get_addr_of_helper_func(int opcode, int oparg) { switch (opcode) { #define JIT_HELPER_ADDR(name) case name: return JIT_HELPER_##name JIT_HELPER_ADDR(PRINT_EXPR); JIT_HELPER_ADDR(RAISE_VARARGS); JIT_HELPER_ADDR(GET_AITER); JIT_HELPER_ADDR(GET_ANEXT); JIT_HELPER_ADDR(GET_AWAITABLE); JIT_HELPER_ADDR(YIELD_FROM); JIT_HELPER_ADDR(POP_EXCEPT); JIT_HELPER_ADDR(POP_FINALLY); JIT_HELPER_ADDR(END_ASYNC_FOR); JIT_HELPER_ADDR(LOAD_BUILD_CLASS); JIT_HELPER_ADDR(STORE_NAME); JIT_HELPER_ADDR(DELETE_NAME); JIT_HELPER_ADDR(UNPACK_EX); JIT_HELPER_ADDR(DELETE_GLOBAL); JIT_HELPER_ADDR(LOAD_NAME); JIT_HELPER_ADDR(LOAD_CLASSDEREF); JIT_HELPER_ADDR(BUILD_STRING); JIT_HELPER_ADDR(BUILD_TUPLE_UNPACK_WITH_CALL); JIT_HELPER_ADDR(BUILD_TUPLE_UNPACK); JIT_HELPER_ADDR(BUILD_LIST_UNPACK); JIT_HELPER_ADDR(BUILD_SET); JIT_HELPER_ADDR(BUILD_SET_UNPACK); JIT_HELPER_ADDR(BUILD_MAP); JIT_HELPER_ADDR(SETUP_ANNOTATIONS); JIT_HELPER_ADDR(BUILD_CONST_KEY_MAP); JIT_HELPER_ADDR(BUILD_MAP_UNPACK); JIT_HELPER_ADDR(BUILD_MAP_UNPACK_WITH_CALL); JIT_HELPER_ADDR(IMPORT_STAR); JIT_HELPER_ADDR(GET_YIELD_FROM_ITER); JIT_HELPER_ADDR(BEFORE_ASYNC_WITH); JIT_HELPER_ADDR(SETUP_WITH); JIT_HELPER_ADDR(WITH_CLEANUP_START); JIT_HELPER_ADDR(WITH_CLEANUP_FINISH); JIT_HELPER_ADDR(MAKE_FUNCTION); JIT_HELPER_ADDR(FORMAT_VALUE); case UNPACK_SEQUENCE: if (oparg == 2) return JIT_HELPER_UNPACK_SEQUENCE2; if (oparg == 3) return JIT_HELPER_UNPACK_SEQUENCE3; return JIT_HELPER_UNPACK_SEQUENCE; case CALL_FUNCTION_EX: if (oparg == 0) return JIT_HELPER_CALL_FUNCTION_EX_NOKWARGS; if (oparg == 1) return JIT_HELPER_CALL_FUNCTION_EX_KWARGS; printf("could not find helper for opcode: %d oparg: %d\n", opcode, oparg); abort(); default: printf("could not find helper for opcode: %d oparg: %d\n", opcode, oparg); abort(); } #undef JIT_HELPER_ADDR } static void* __attribute__ ((const)) get_addr_of_aot_func(int opcode, int oparg, int opcache_available) { #define OPCODE_STATIC(x, func) if (opcode == x) return (func) #ifdef PYSTON_LITE #define OPCODE_PROFILE(x, func) OPCODE_STATIC(x, func) #else #define OPCODE_PROFILE(x, func) OPCODE_STATIC(x, jit_use_aot ? func##Profile : func) #endif OPCODE_PROFILE(UNARY_POSITIVE, PyNumber_Positive); OPCODE_PROFILE(UNARY_NEGATIVE, PyNumber_Negative); OPCODE_PROFILE(UNARY_INVERT, PyNumber_Invert); OPCODE_PROFILE(UNARY_NOT, PyObject_IsTrue); OPCODE_PROFILE(GET_ITER, PyObject_GetIter); OPCODE_PROFILE(BINARY_MULTIPLY, PyNumber_Multiply); OPCODE_PROFILE(BINARY_MATRIX_MULTIPLY, PyNumber_MatrixMultiply); OPCODE_PROFILE(BINARY_TRUE_DIVIDE, PyNumber_TrueDivide); OPCODE_PROFILE(BINARY_FLOOR_DIVIDE, PyNumber_FloorDivide); OPCODE_PROFILE(BINARY_MODULO, PyNumber_Remainder); OPCODE_PROFILE(BINARY_ADD, PyNumber_Add); OPCODE_PROFILE(BINARY_SUBTRACT, PyNumber_Subtract); OPCODE_PROFILE(BINARY_LSHIFT, PyNumber_Lshift); OPCODE_PROFILE(BINARY_RSHIFT, PyNumber_Rshift); OPCODE_PROFILE(BINARY_AND, PyNumber_And); OPCODE_PROFILE(BINARY_XOR, PyNumber_Xor); OPCODE_PROFILE(BINARY_OR, PyNumber_Or); OPCODE_PROFILE(INPLACE_MULTIPLY, PyNumber_InPlaceMultiply); OPCODE_PROFILE(INPLACE_MATRIX_MULTIPLY, PyNumber_InPlaceMatrixMultiply); OPCODE_PROFILE(INPLACE_TRUE_DIVIDE, PyNumber_InPlaceTrueDivide); OPCODE_PROFILE(INPLACE_FLOOR_DIVIDE, PyNumber_InPlaceFloorDivide); OPCODE_PROFILE(INPLACE_MODULO, PyNumber_InPlaceRemainder); OPCODE_PROFILE(INPLACE_ADD, PyNumber_InPlaceAdd); OPCODE_PROFILE(INPLACE_SUBTRACT, PyNumber_InPlaceSubtract); OPCODE_PROFILE(INPLACE_LSHIFT, PyNumber_InPlaceLshift); OPCODE_PROFILE(INPLACE_RSHIFT, PyNumber_InPlaceRshift); OPCODE_PROFILE(INPLACE_AND, PyNumber_InPlaceAnd); OPCODE_PROFILE(INPLACE_XOR, PyNumber_InPlaceXor); OPCODE_PROFILE(INPLACE_OR, PyNumber_InPlaceOr); // the normaly have 3 args but we created special versions because last is always None OPCODE_PROFILE(BINARY_POWER, PyNumber_PowerNone); OPCODE_PROFILE(INPLACE_POWER, PyNumber_InPlacePowerNone); OPCODE_PROFILE(CALL_FUNCTION, call_function_ceval_no_kw); OPCODE_PROFILE(CALL_METHOD, call_function_ceval_no_kw); OPCODE_PROFILE(CALL_FUNCTION_KW, call_function_ceval_kw); OPCODE_PROFILE(STORE_SUBSCR, PyObject_SetItem); OPCODE_PROFILE(BINARY_SUBSCR, PyObject_GetItem); OPCODE_PROFILE(DELETE_SUBSCR, PyObject_DelItem); OPCODE_STATIC(LOAD_GLOBAL, JIT_HELPER_LOAD_GLOBAL); if (opcache_available) { OPCODE_STATIC(LOAD_ATTR, JIT_HELPER_LOAD_ATTR_CACHED); OPCODE_STATIC(STORE_ATTR, JIT_HELPER_STORE_ATTR_CACHED); OPCODE_STATIC(LOAD_METHOD, JIT_HELPER_LOAD_METHOD_CACHED); } else { OPCODE_STATIC(LOAD_ATTR, JIT_HELPER_LOAD_ATTR); OPCODE_STATIC(STORE_ATTR, JIT_HELPER_STORE_ATTR); OPCODE_STATIC(LOAD_METHOD, JIT_HELPER_LOAD_METHOD); } if (opcode == COMPARE_OP) { #ifndef PYSTON_LITE if (jit_use_aot) { switch (oparg) { case PyCmp_LT: return cmp_outcomePyCmp_LTProfile; case PyCmp_LE: return cmp_outcomePyCmp_LEProfile; case PyCmp_EQ: return cmp_outcomePyCmp_EQProfile; case PyCmp_NE: return cmp_outcomePyCmp_NEProfile; case PyCmp_GT: return cmp_outcomePyCmp_GTProfile; case PyCmp_GE: return cmp_outcomePyCmp_GEProfile; case PyCmp_IN: return cmp_outcomePyCmp_INProfile; case PyCmp_NOT_IN: return cmp_outcomePyCmp_NOT_INProfile; } } #endif switch (oparg) { case PyCmp_LT: return cmp_outcomePyCmp_LT; case PyCmp_LE: return cmp_outcomePyCmp_LE; case PyCmp_EQ: return cmp_outcomePyCmp_EQ; case PyCmp_NE: return cmp_outcomePyCmp_NE; case PyCmp_GT: return cmp_outcomePyCmp_GT; case PyCmp_GE: return cmp_outcomePyCmp_GE; case PyCmp_IN: return cmp_outcomePyCmp_IN; case PyCmp_NOT_IN: return cmp_outcomePyCmp_NOT_IN; // we don't create type specific version for those so use non Profile final versions case PyCmp_BAD: return cmp_outcomePyCmp_BAD; case PyCmp_EXC_MATCH: return cmp_outcomePyCmp_EXC_MATCH; case PyCmp_IS: case PyCmp_IS_NOT: printf("unreachable: PyCmp_IS and PyCmp_IS_NOT are inlined\n"); abort(); } } #undef OPCODE_STATIC #undef OPCODE_PROFILE printf("could not find aot func for opcode: %d oparg: %d\n", opcode, oparg); abort(); return 0; } static const char* get_opcode_name(int opcode) { #define OPCODE_NAME(op) case op: return #op switch (opcode) { OPCODE_NAME(POP_TOP); OPCODE_NAME(ROT_TWO); OPCODE_NAME(ROT_THREE); OPCODE_NAME(DUP_TOP); OPCODE_NAME(DUP_TOP_TWO); OPCODE_NAME(ROT_FOUR); OPCODE_NAME(NOP); OPCODE_NAME(UNARY_POSITIVE); OPCODE_NAME(UNARY_NEGATIVE); OPCODE_NAME(UNARY_NOT); OPCODE_NAME(UNARY_INVERT); OPCODE_NAME(BINARY_MATRIX_MULTIPLY); OPCODE_NAME(INPLACE_MATRIX_MULTIPLY); OPCODE_NAME(BINARY_POWER); OPCODE_NAME(BINARY_MULTIPLY); OPCODE_NAME(BINARY_MODULO); OPCODE_NAME(BINARY_ADD); OPCODE_NAME(BINARY_SUBTRACT); OPCODE_NAME(BINARY_SUBSCR); OPCODE_NAME(BINARY_FLOOR_DIVIDE); OPCODE_NAME(BINARY_TRUE_DIVIDE); OPCODE_NAME(INPLACE_FLOOR_DIVIDE); OPCODE_NAME(INPLACE_TRUE_DIVIDE); OPCODE_NAME(GET_AITER); OPCODE_NAME(GET_ANEXT); OPCODE_NAME(BEFORE_ASYNC_WITH); OPCODE_NAME(BEGIN_FINALLY); OPCODE_NAME(END_ASYNC_FOR); OPCODE_NAME(INPLACE_ADD); OPCODE_NAME(INPLACE_SUBTRACT); OPCODE_NAME(INPLACE_MULTIPLY); OPCODE_NAME(INPLACE_MODULO); OPCODE_NAME(STORE_SUBSCR); OPCODE_NAME(DELETE_SUBSCR); OPCODE_NAME(BINARY_LSHIFT); OPCODE_NAME(BINARY_RSHIFT); OPCODE_NAME(BINARY_AND); OPCODE_NAME(BINARY_XOR); OPCODE_NAME(BINARY_OR); OPCODE_NAME(INPLACE_POWER); OPCODE_NAME(GET_ITER); OPCODE_NAME(GET_YIELD_FROM_ITER); OPCODE_NAME(PRINT_EXPR); OPCODE_NAME(LOAD_BUILD_CLASS); OPCODE_NAME(YIELD_FROM); OPCODE_NAME(GET_AWAITABLE); OPCODE_NAME(INPLACE_LSHIFT); OPCODE_NAME(INPLACE_RSHIFT); OPCODE_NAME(INPLACE_AND); OPCODE_NAME(INPLACE_XOR); OPCODE_NAME(INPLACE_OR); OPCODE_NAME(WITH_CLEANUP_START); OPCODE_NAME(WITH_CLEANUP_FINISH); OPCODE_NAME(RETURN_VALUE); OPCODE_NAME(IMPORT_STAR); OPCODE_NAME(SETUP_ANNOTATIONS); OPCODE_NAME(YIELD_VALUE); OPCODE_NAME(POP_BLOCK); OPCODE_NAME(END_FINALLY); OPCODE_NAME(POP_EXCEPT); OPCODE_NAME(STORE_NAME); OPCODE_NAME(DELETE_NAME); OPCODE_NAME(UNPACK_SEQUENCE); OPCODE_NAME(FOR_ITER); OPCODE_NAME(UNPACK_EX); OPCODE_NAME(STORE_ATTR); OPCODE_NAME(DELETE_ATTR); OPCODE_NAME(STORE_GLOBAL); OPCODE_NAME(DELETE_GLOBAL); OPCODE_NAME(LOAD_CONST); OPCODE_NAME(LOAD_NAME); OPCODE_NAME(BUILD_TUPLE); OPCODE_NAME(BUILD_LIST); OPCODE_NAME(BUILD_SET); OPCODE_NAME(BUILD_MAP); OPCODE_NAME(LOAD_ATTR); OPCODE_NAME(COMPARE_OP); OPCODE_NAME(IMPORT_NAME); OPCODE_NAME(IMPORT_FROM); OPCODE_NAME(JUMP_FORWARD); OPCODE_NAME(JUMP_IF_FALSE_OR_POP); OPCODE_NAME(JUMP_IF_TRUE_OR_POP); OPCODE_NAME(JUMP_ABSOLUTE); OPCODE_NAME(POP_JUMP_IF_FALSE); OPCODE_NAME(POP_JUMP_IF_TRUE); OPCODE_NAME(LOAD_GLOBAL); OPCODE_NAME(SETUP_FINALLY); OPCODE_NAME(LOAD_FAST); OPCODE_NAME(STORE_FAST); OPCODE_NAME(DELETE_FAST); OPCODE_NAME(RAISE_VARARGS); OPCODE_NAME(CALL_FUNCTION); OPCODE_NAME(MAKE_FUNCTION); OPCODE_NAME(BUILD_SLICE); OPCODE_NAME(LOAD_CLOSURE); OPCODE_NAME(LOAD_DEREF); OPCODE_NAME(STORE_DEREF); OPCODE_NAME(DELETE_DEREF); OPCODE_NAME(CALL_FUNCTION_KW); OPCODE_NAME(CALL_FUNCTION_EX); OPCODE_NAME(SETUP_WITH); OPCODE_NAME(EXTENDED_ARG); OPCODE_NAME(LIST_APPEND); OPCODE_NAME(SET_ADD); OPCODE_NAME(MAP_ADD); OPCODE_NAME(LOAD_CLASSDEREF); OPCODE_NAME(BUILD_LIST_UNPACK); OPCODE_NAME(BUILD_MAP_UNPACK); OPCODE_NAME(BUILD_MAP_UNPACK_WITH_CALL); OPCODE_NAME(BUILD_TUPLE_UNPACK); OPCODE_NAME(BUILD_SET_UNPACK); OPCODE_NAME(SETUP_ASYNC_WITH); OPCODE_NAME(FORMAT_VALUE); OPCODE_NAME(BUILD_CONST_KEY_MAP); OPCODE_NAME(BUILD_STRING); OPCODE_NAME(BUILD_TUPLE_UNPACK_WITH_CALL); OPCODE_NAME(LOAD_METHOD); OPCODE_NAME(CALL_METHOD); OPCODE_NAME(CALL_FINALLY); OPCODE_NAME(POP_FINALLY); }; #undef OPCODE_NAME return "UNKNOWN"; } #define IS_16BIT_VAL(x) ((unsigned long)(x) <= UINT16_MAX) #define IS_32BIT_VAL(x) ((unsigned long)(x) <= UINT32_MAX) #define IS_32BIT_SIGNED_VAL(x) ((int32_t)(x) == (int64_t)(x)) // looks which instruction can be reached by jumps // this is important for the deferred stack operations because // if a instruction can be reached by a jump we can't use this optimization. // which means we have make sure to call deferred_vs_apply. // // result must be freed() static char* calculate_jmp_targets(Jit* Dst) { // TODO: could be a bit vector char* is_jmp_target = malloc(Dst->num_opcodes); memset(is_jmp_target, 0, Dst->num_opcodes); // first instruction is always a jump target because entry can reach it if (Dst->num_opcodes > 0) is_jmp_target[0] = 1; int oldoparg = 0; for (int inst_idx = 0; inst_idx < Dst->num_opcodes; ++inst_idx) { _Py_CODEUNIT word = Dst->first_instr[inst_idx]; int opcode = _Py_OPCODE(word); int oparg = _Py_OPARG(word); // this is used for the special EXTENDED_ARG opcode oparg |= oldoparg; oldoparg = 0; switch (opcode) { case JUMP_ABSOLUTE: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: is_jmp_target[oparg/2] = 1; break; case JUMP_FORWARD: case FOR_ITER: case END_ASYNC_FOR: is_jmp_target[oparg/2 + inst_idx + 1] = 1; break; case CALL_FINALLY: is_jmp_target[inst_idx + 1] = 1; is_jmp_target[oparg/2 + inst_idx + 1] = 1; break; // this opcodes use PyFrame_BlockSetup which is similar to a jump in case of exception case SETUP_ASYNC_WITH: case SETUP_FINALLY: case SETUP_WITH: is_jmp_target[inst_idx + 1] = 1; is_jmp_target[oparg/2 + inst_idx + 1] = 1; break; case YIELD_FROM: is_jmp_target[inst_idx + 0] = 1; is_jmp_target[inst_idx + 1] = 1; break; case YIELD_VALUE: is_jmp_target[inst_idx + 1] = 1; break; case EXTENDED_ARG: oldoparg = oparg << 8; break; } } return is_jmp_target; } #if ENABLE_DEFINED_TRACKING // returns if any of the functions arguments get deleted (checks for DELETE_FAST) static int check_func_args_never_deleted(Jit* Dst) { const int num_args = Dst->co->co_argcount; int oldoparg = 0; for (int inst_idx = 0; inst_idx < Dst->num_opcodes; ++inst_idx) { _Py_CODEUNIT word = Dst->first_instr[inst_idx]; int opcode = _Py_OPCODE(word); int oparg = _Py_OPARG(word); // this is used for the special EXTENDED_ARG opcode oparg |= oldoparg; oldoparg = 0; switch (opcode) { case DELETE_FAST: if (oparg < num_args) return 0; // this is deleting a function arg! break; case EXTENDED_ARG: oldoparg = oparg << 8; break; } } return 1; } #endif static int8_t* mem_chunk = NULL; static size_t mem_chunk_bytes_remaining = 0; static long mem_bytes_allocated = 0, mem_bytes_used = 0; static long mem_bytes_used_max = 100*1000*1000; // will stop emitting code after that many bytes static int jit_num_funcs = 0, jit_num_failed = 0; static long total_compilation_time_in_us = 0; static int jit_stats_enabled = 0; static unsigned long jit_stat_load_attr_hit, jit_stat_load_attr_miss, jit_stat_load_attr_inline, jit_stat_load_attr_total; static unsigned long jit_stat_store_attr_hit, jit_stat_store_attr_miss, jit_stat_store_attr_inline, jit_stat_store_attr_total; static unsigned long jit_stat_load_method_hit, jit_stat_load_method_miss, jit_stat_load_method_inline, jit_stat_load_method_total; static unsigned long jit_stat_load_global_hit, jit_stat_load_global_miss, jit_stat_load_global_inline, jit_stat_load_global_total; static unsigned long jit_stat_call_method_hit, jit_stat_call_method_miss, jit_stat_call_method_inline, jit_stat_call_method_total; static unsigned long jit_stat_getitemlong, jit_stat_getitemlong_inlined, jit_stat_setitemlong_inlined; static unsigned long jit_stat_load_attr_poly, jit_stat_load_attr_poly_entries; static unsigned long jit_stat_load_method_poly, jit_stat_load_method_poly_entries; static unsigned long jit_stat_binary_op_inplace, jit_stat_binary_op_inplace_miss, jit_stat_binary_op_inplace_hit; static unsigned long jit_stat_concat_inplace, jit_stat_concat_inplace_miss, jit_stat_concat_inplace_hit; #define ENABLE_DEFERRED_RES_PUSH 1 #define ENABLE_AVOID_SIG_TRACE_CHECK 1 @ARM|.arch arm64 @X86|.arch x64 // section layout is same as specified here from left to right |.section entry, code, cold, deopt, opcode_addr //////////////////////////////// // REGISTER DEFINITIONS |.macro define_reg, name, name_idx, reg_amd64, reg_amd64_idx, reg_arm64, reg_arm64_idx @ARM| .define name, reg_arm64 @ARM|| #define name_idx reg_arm64_idx @X86| .define name, reg_amd64 @X86|| #define name_idx reg_amd64_idx |.endmacro // all this values are in callee saved registers // NOTE: r13 and rbp need 1 byte more to encode a direct memory access without offset // e.g. mov rax, [rbp] is encoded as mov rax, [rbp + 0] | define_reg f, f_idx, r13, 13, x19, 19 // PyFrameObject* // this register gets used when we have to make a call but preserve a value across it. // It can never get used in the deferred_vs / will never get used across bytecode instructions // One has to manually check the surrounding code if it's safe to use this register. // This register will not automatically get xdecrefed on error / return // so no need to clear it after use. | define_reg tmp_preserved_reg, tmp_preserved_reg_idx, rbp, 5, x20, 20 // PyFrameObject* // this register gets mainly used by deferred_vs when we have to make a call // but preserve a value which is inside the 'res' register (same as stack slot entry but faster). // Code needs to always check Dst->deferred_vs_preserved_reg_used to see if it's available. // On error or return we will always xdecref this register which means that // code must manually clear the register if it does not want the decref. | define_reg vs_preserved_reg, vs_preserved_reg_idx, r14, 14, x21, 21 // PyFrameObject* | define_reg tstate, tstate_idx, r15, 15, x22, 22 // PyThreadState* | define_reg vsp, vsp_idx, r12, 12, x23, 23 // PyObject** - python value stack pointer // pointer to ceval->tracing_possible | define_reg interrupt, interrupt_idx, rbx, 3, x24, 24 // if you change this you may have to adjust jmp_to_inst_idx // follow AMD64 calling convention // instruction indices can be found here: https://corsix.github.io/dynasm-doc/instructions.html // function arguments | define_reg arg1, arg1_idx, rdi, 7, x0, 0 | define_reg arg2, arg2_idx, rsi, 6, x1, 1 | define_reg arg3, arg3_idx, rdx, 2, x2, 2 | define_reg arg4, arg4_idx, rcx, 1, x3, 3 | define_reg arg5, arg5_idx, r8, 8, x4, 4 | define_reg arg6, arg6_idx, r9, 9, x5, 5 // careful same as register 'tmp' // return values | define_reg res, res_idx, rax, 0, x7, 7 // on arm this is a dummy reg | define_reg res2, res2_idx, rdx, 2, x1, 1 // second return value // Our JIT code assumes that 'arg1' and 'res' are not the same but on ARM64 they are. // We can work around this by using a temporary register for 'res' and copying // the real return value of a call to it (and the value we like to return from compiled code). // This has the cost of a few unnecessary 'mov reg, regs' but they should be super cheap. // On x86 this is not needed and res and real_res will be the same. | define_reg real_res, real_res_idx, res, res_idx, x0, 0 // will be used by macros |.define tmp, arg6 #define tmp_idx arg6_idx // cpu stack pointer | define_reg sp_reg, sp_reg_idx, rsp, 4, sp, 31 @ARM_START // ARM64 requires one more temporary reg because it needs an additional temporary for many operations // e.g. when comparing 64bit immediate with a memory location we need to load the imm into a reg and the // memory value in a different one and then compare it. |.define tmp2, x6 #define tmp2_idx 6 // this is currently only used in deferred_vs_emit() which requires a temporary reg which is different from the two other we already have |.define tmp_pair, x8 #define tmp_pair_idx 8 |.define zero_reg, xzr // this register is always 0 - nice for clearing memory #define zero_reg_idx 31 @ARM_END // GET_DEFERRED[-1] == top deferred stack entry // GET_DEFERRED[-2] == second deferred stack entry.. #define GET_DEFERRED (&Dst->deferred_vs[Dst->deferred_vs_next]) static void deferred_vs_apply(Jit* Dst); static void switch_section(Jit* Dst, Section new_section) { JIT_ASSERT(Dst->current_section != new_section, "safe todo but may be sign of a bug"); Dst->current_section = new_section; if (new_section == SECTION_CODE) { |.code } else if (new_section == SECTION_COLD) { |.cold } else if (new_section == SECTION_DEOPT) { |.deopt } else if (new_section == SECTION_ENTRY) { |.entry } else if (new_section == SECTION_OPCODE_ADDR) { |.opcode_addr } else { JIT_ASSERT(0, "unknwon section"); } } |.macro branch, dst @ARM| b dst @X86| jmp dst |.endmacro |.macro branch_reg, dst @ARM| br Rx(dst) @X86| jmp Rq(dst) |.endmacro |.macro branch_eq, dst @ARM| beq dst @X86| je dst |.endmacro |.macro branch_z, dst | branch_eq dst |.endmacro |.macro branch_ne, dst @ARM| bne dst @X86| jne dst |.endmacro |.macro branch_nz, dst | branch_ne dst |.endmacro |.macro branch_lt, dst @ARM| blt dst @X86| jl dst |.endmacro |.macro branch_gt, dst @ARM| bgt dst @X86| jg dst |.endmacro |.macro branch_ge, dst @ARM| bge dst @X86| jge dst |.endmacro |.macro branch_le, dst @ARM| ble dst @X86| jle dst |.endmacro |.macro branch_le_unsigned, dst @ARM| bls dst @X86| jbe dst |.endmacro // compares r_object_idx->ob_type with type // branches to false_branch on inequality else continues |.macro type_check, r_object_idx, type, false_branch || emit_cmp64_mem_imm(Dst, r_object_idx, offsetof(PyObject, ob_type), (uint64_t)type); | branch_ne false_branch |.endmacro // compares r_type_idx->tp_version_tag with type_ver // branches to false_branch on inequality else continues |.macro type_version_check, r_type_idx, type_ver, false_branch ||#ifdef PYSTON_LITE || JIT_ASSERT(Py_TPFLAGS_VALID_VERSION_TAG == (1UL << 19), "need to update these offsets"); @ARM|| emit_load32_mem(Dst, get_tmp_reg(r_type_idx), r_type_idx, offsetof(PyTypeObject, tp_flags)); @ARM| tbz Rw(get_tmp_reg(r_type_idx)), #19, false_branch // Test Bit Zero: jump to false_branch if bit 19 is zero @X86|| emit_test8_mem_imm(Dst, r_type_idx, offsetof(PyTypeObject, tp_flags) + 2, 0x08); @X86| branch_eq false_branch || emit_cmp32_mem_imm(Dst, r_type_idx, offsetof(PyTypeObject, tp_version_tag), (unsigned int)type_ver); ||#else || emit_cmp64_mem_imm(Dst, r_type_idx, offsetof(PyTypeObject, tp_version_tag), (unsigned int)type_ver); ||#endif | branch_ne false_branch |.endmacro @ARM_START // both bounds are inclusive static int is_in_range(long val, long min_val, long max_val) { return val >= min_val && val <= max_val; } // some ARM instructions (e.g. add/sub) support this kind of immediates static int fits_in_12bit_with_12bit_rshift(long val) { return (val & 0xFFF) == 0 && is_in_range(val>>12, 0, 4095); } @ARM_END // On ARM, we try to put the JIT code close to the code that it calls // to try to take advantage of efficient relative addressing. // This is a representative function that we might try to call, which // we will try to locate the code near, as well as measure offsets against. #define LAYOUT_TARGET (PyObject_IsTrue) static int can_use_relative_call(void *addr) { // bl only supports +-128MB - for additional safety we try to stay +-64MB away from this AOT symbol. @ARMreturn labs((int64_t)addr-(int64_t)LAYOUT_TARGET) < 64*1024*1024; @X86return IS_32BIT_VAL((long)addr); } // writes 32bit value to executable memory static void emit_32bit_value(Jit* Dst, long value) { |.long value // this is called long but actually emits a 32bit value } // emits: $r_dst = $r_src static void emit_mov64_reg(Jit* Dst, int r_dst, int r_src) { if (r_dst == r_src) return; @ARM| mov Rx(r_dst), Rx(r_src) @X86| mov Rq(r_dst), Rq(r_src) } @ARM_START // returns reg 'tmp' if it's not already used else 'tmp2' static int get_tmp_reg(int r_idx) { if (r_idx == tmp_idx) return tmp2_idx; return tmp_idx; } @ARM_END // emits: $r_dst = val static void emit_mov_imm(Jit* Dst, int r_idx, unsigned long val) { @ARM_START | movz Rx(r_idx), #(val >> 0) & UINT16_MAX if ((val >> 16) & UINT16_MAX) { | movk Rx(r_idx), #(val >> 16) & UINT16_MAX, lsl #16 } if ((val >> 32) & UINT16_MAX) { | movk Rx(r_idx), #(val >> 32) & UINT16_MAX, lsl #32 } if ((val >> 48) & UINT16_MAX) { | movk Rx(r_idx), #(val >> 48) & UINT16_MAX, lsl #48 } @ARM_END @X86_START if (val == 0) { | xor Rd(r_idx), Rd(r_idx) } else if (IS_32BIT_VAL(val)) { | mov Rd(r_idx), (unsigned int)val } else { | mov64 Rq(r_idx), (unsigned long)val } @X86_END } // emits: (int)$r_idx == val static void emit_cmp32_imm(Jit* Dst, int r_idx, unsigned long val) { @ARM_START if (is_in_range(val, -4095, 4095)) { | cmp Rw(r_idx), #val /* this will automatically emit cmn for negative numbers*/ } else { emit_mov_imm(Dst, get_tmp_reg(r_idx), val); | cmp Rw(r_idx), Rw(get_tmp_reg(r_idx)) } @ARM_END @X86_START if (val == 0) { | test Rd(r_idx), Rd(r_idx) } else if (IS_32BIT_VAL(val)) { | cmp Rd(r_idx), (unsigned int)val } else { JIT_ASSERT(0, "should not reach this"); } @X86_END } // emits: (long)$r_idx == val static void emit_cmp64_imm(Jit* Dst, int r_idx, unsigned long val) { @ARM_START if (is_in_range(val, -4095, 4095)) { | cmp Rx(r_idx), #val /* this will automatically emit cmn for negative numbers*/ } else { emit_mov_imm(Dst, get_tmp_reg(r_idx), val); | cmp Rx(r_idx), Rx(get_tmp_reg(r_idx)) } @ARM_END @X86_START if (val == 0) { | test Rq(r_idx), Rq(r_idx) } else if (IS_32BIT_VAL(val)) { | cmp Rq(r_idx), (unsigned int)val } else { | mov64 tmp, (unsigned long)val | cmp Rq(r_idx), tmp } @X86_END } // emits: $r_dst = *(int*)((char*)$r_mem[offset_in_bytes]) static void emit_load32_mem(Jit* Dst, int r_dst, int r_mem, long offset_in_bytes) { @ARM_START if (is_in_range(offset_in_bytes, -256, 255) || (is_in_range(offset_in_bytes, 0, 32760) && offset_in_bytes % 8 == 0)) { | ldr Rw(r_dst), [Rx(r_mem), #offset_in_bytes] } else { emit_mov_imm(Dst, get_tmp_reg(r_dst), offset_in_bytes); | ldr Rw(r_dst), [Rx(r_mem), Rx(get_tmp_reg(r_dst))] } @ARM_END @X86| mov Rd(r_dst), [Rq(r_mem)+ offset_in_bytes] } // emits: $r_dst = *(long*)((char*)$r_mem[offset_in_bytes]) static void emit_load64_mem(Jit* Dst, int r_dst, int r_mem, long offset_in_bytes) { @ARM_START if (is_in_range(offset_in_bytes, -256, 255) || (is_in_range(offset_in_bytes, 0, 32760) && offset_in_bytes % 8 == 0)) { | ldr Rx(r_dst), [Rx(r_mem), #offset_in_bytes] } else { emit_mov_imm(Dst, get_tmp_reg(r_dst), offset_in_bytes); | ldr Rx(r_dst), [Rx(r_mem), Rx(get_tmp_reg(r_dst))] } @ARM_END @X86| mov Rq(r_dst), [Rq(r_mem)+ offset_in_bytes] } // emits: *(long*)((char*)$r_mem[offset_in_bytes]) = $r_val static void emit_store64_mem(Jit* Dst, int r_val, int r_mem, long offset_in_bytes) { @ARM_START if (is_in_range(offset_in_bytes, -256, 255) || (is_in_range(offset_in_bytes, 0, 32760) && offset_in_bytes % 8 == 0)) { | str Rx(r_val), [Rx(r_mem), #offset_in_bytes] } else { emit_mov_imm(Dst, get_tmp_reg(r_val), offset_in_bytes); | str Rx(r_val), [Rx(r_mem), Rx(get_tmp_reg(r_val))] } @ARM_END @X86| mov [Rq(r_mem)+ offset_in_bytes], Rq(r_val) } // emits: *(long*)((char*)$r_mem[offset_in_bytes]) = val static void emit_store64_mem_imm(Jit* Dst, unsigned long val, int r_mem, long offset) { @ARM_START int tmpreg = get_tmp_reg(r_mem); if (val == 0) { emit_store64_mem(Dst, zero_reg_idx, r_mem, offset); return; } @ARM_END @X86_START int tmpreg = tmp_idx; if (IS_32BIT_VAL(val)) { | mov qword [Rq(r_mem)+ offset], (unsigned int)val return; } @X86_END emit_mov_imm(Dst, tmpreg, val); emit_store64_mem(Dst, tmpreg, r_mem, offset); } // emits: *(long*)((char*)$r_mem[offset_in_bytes]) == val static void emit_cmp64_mem_imm(Jit* Dst, int r_mem, long offset, unsigned long val) { @ARM_START emit_load64_mem(Dst, get_tmp_reg(r_mem), r_mem, offset); emit_cmp64_imm(Dst, get_tmp_reg(r_mem), val); @ARM_END @X86_START if (IS_32BIT_VAL(val)) { | cmp qword [Rq(r_mem)+ offset], (unsigned int)val return; } emit_mov_imm(Dst, tmp_idx, val); | cmp qword [Rq(r_mem)+ offset], tmp @X86_END } // emits: *(char*)((char*)$r_mem[offset_in_bytes]) & val static void emit_test8_mem_imm(Jit* Dst, int r_mem, long offset, unsigned long val) { @ARM abort(); @X86| test byte [Rq(r_mem)+ offset], (unsigned int)val } // emits: *(int*)((char*)$r_mem[offset_in_bytes]) == val static void emit_cmp32_mem_imm(Jit* Dst, int r_mem, long offset, unsigned long val) { @ARMemit_load32_mem(Dst, get_tmp_reg(r_mem), r_mem, offset); @ARMemit_cmp32_imm(Dst, get_tmp_reg(r_mem), val); @X86| cmp dword [Rq(r_mem)+ offset], (unsigned int)val } // returns 1 if we can encode it in one instruction and 0 if we need multiple static int emit_add_or_sub_imm_can_encode_as_single_instruction(Jit* Dst, int r_dst, int r_src1, long imm) { @ARMif (is_in_range(imm, -4095, 4095) || fits_in_12bit_with_12bit_rshift(labs(imm))) @X86if (IS_32BIT_SIGNED_VAL(imm)) return 1; return 0; } // emits: (long)r_dst = (long)r_src1 + (long)imm // Useful for general calculations and address calculaions // This three operand add uses lea or add/sub on x86 // and make sure that negative immediates are handled by a subtract on ARM // which can't encode them. static void emit_add_or_sub_imm(Jit* Dst, int r_dst, int r_src1, long imm) { if (imm == 0) { emit_mov64_reg(Dst, r_dst, r_src1); return; } if (emit_add_or_sub_imm_can_encode_as_single_instruction(Dst, r_dst, r_src1, imm)) { @ARM_START // ARM64 can't encode negative immediated for adds. // generate add/sub automatically depending on immediate if (imm > 0) { | add Rx(r_dst), Rx(r_src1), #imm } else { | sub Rx(r_dst), Rx(r_src1), #-imm } @ARM_END @X86_START if (r_dst != r_src1) { // do we need 3 operands? | lea Rq(r_dst), [Rq(r_src1)+ imm] } else if (imm > 0) { | add Rq(r_dst), imm } else { | sub Rq(r_dst), -imm } @X86_END } else { JIT_ASSERT(r_src1 != tmp_idx, ""); emit_mov_imm(Dst, tmp_idx, imm); @ARM | add Rx(r_dst), Rx(r_src1), tmp @X86_START if (r_dst != r_src1) { // do we need 3 operands? | lea Rq(r_dst), [Rq(r_src1)+ tmp] } else { | add Rq(r_dst), tmp } @X86_END } } // moves the value stack pointer by num_values python objects static void emit_adjust_vs(Jit* Dst, int num_values) { emit_add_or_sub_imm(Dst, vsp_idx, vsp_idx, 8*num_values); } static void emit_push_v(Jit* Dst, int r_idx) { deferred_vs_apply(Dst); emit_store64_mem(Dst, r_idx, vsp_idx, 0 /*= offset */); emit_adjust_vs(Dst, 1); } static void emit_pop_v(Jit* Dst, int r_idx) { deferred_vs_apply(Dst); emit_adjust_vs(Dst, -1); emit_load64_mem(Dst, r_idx, vsp_idx, 0 /*= offset */); } // top = 1, second = 2, third = 3,... static void emit_read_vs(Jit* Dst, int r_idx, int stack_offset) { deferred_vs_apply(Dst); emit_load64_mem(Dst, r_idx, vsp_idx, -8*stack_offset); } static void emit_write_vs(Jit* Dst, int r_idx, int stack_offset) { deferred_vs_apply(Dst); emit_store64_mem(Dst, r_idx, vsp_idx, -8*stack_offset); } static void emit_write_imm_vs(Jit* Dst, unsigned long val, int stack_offset) { deferred_vs_apply(Dst); emit_store64_mem_imm(Dst, val, vsp_idx, -8*stack_offset); } // emits: *(long*)r_idx += diff // diff must be either -1 or 1 static void emit_inc_or_dec_mem(Jit* Dst, int r_idx, int diff) { JIT_ASSERT(diff == 1 || diff == -1, ""); @ARM_START int tmpreg = get_tmp_reg(r_idx); emit_load64_mem(Dst, tmpreg, r_idx, 0); emit_add_or_sub_imm(Dst, tmpreg, tmpreg, diff); emit_store64_mem(Dst, tmpreg, r_idx, 0); @ARM_END @X86| add qword [Rq(r_idx)], diff } // emits: *(long*)ptr += diff where ptr is an immediate // diff must be either -1 or 1 static void emit_inc_or_dec_qword_ptr(Jit* Dst, void* ptr, int can_use_tmp_reg, int diff) { JIT_ASSERT(diff == 1 || diff == -1, ""); @X86_START // the JIT always emits code to address which fit into 32bit // but if PIC is enabled non JIT code may use a larger address space. // This causes issues because x86_64 rip memory access only use 32bit offsets. // To solve this issue we have to load the pointer into a register. if (IS_32BIT_VAL(ptr)) { | add qword [ptr], diff return; } @X86_END if (!can_use_tmp_reg) { JIT_ASSERT(2 <= NUM_MANUAL_STACK_SLOTS, ""); emit_store64_mem(Dst, tmp_idx, sp_reg_idx, 0); @ARM emit_store64_mem(Dst, tmp2_idx, sp_reg_idx, 8); } emit_mov_imm(Dst, tmp_idx, (unsigned long)ptr); emit_inc_or_dec_mem(Dst, tmp_idx, diff); if (!can_use_tmp_reg) { emit_load64_mem(Dst, tmp_idx, sp_reg_idx, 0); @ARM emit_load64_mem(Dst, tmp2_idx, sp_reg_idx, 8); } } static void emit_inc_qword_ptr(Jit* Dst, void* ptr, int can_use_tmp_reg) { emit_inc_or_dec_qword_ptr(Dst, ptr, can_use_tmp_reg, 1); } static void emit_incref(Jit* Dst, int r_idx) { _Static_assert(offsetof(PyObject, ob_refcnt) == 0, "add needs to be modified"); #ifdef Py_REF_DEBUG // calling code assumes that we are not modifying tmp_reg _Static_assert(sizeof(_Py_RefTotal) == 8, "adjust inc qword"); emit_inc_qword_ptr(Dst, &_Py_RefTotal, 0 /*=can't use tmp_reg*/); #endif emit_inc_or_dec_mem(Dst, r_idx, 1 /*=value*/); } // Loads a register `r_idx` with a value `addr`, potentially doing a lea // of another register `other_idx` which contains a known value `other_addr` static void emit_mov_imm_using_diff(Jit* Dst, int r_idx, int other_idx, void* addr, void* other_addr) { ptrdiff_t diff = (uintptr_t)addr - (uintptr_t)other_addr; if (diff == 0) { emit_mov64_reg(Dst, r_idx, other_idx); return; } // just use a mov instruction if it fits in a single (small) mov @ARMint fits_in_mov = IS_16BIT_VAL(addr); @X86int fits_in_mov = IS_32BIT_VAL(addr); if (!fits_in_mov && emit_add_or_sub_imm_can_encode_as_single_instruction(Dst, r_idx, other_idx, diff)) { emit_add_or_sub_imm(Dst, r_idx, other_idx, diff); return; } emit_mov_imm(Dst, r_idx, (unsigned long)addr); } // sets register r_idx1 = addr1 and r_idx2 = addr2. Uses a lea/add/sub if beneficial. static void emit_mov_imm2(Jit* Dst, int r_idx1, void* addr1, int r_idx2, void* addr2) { emit_mov_imm(Dst, r_idx1, (unsigned long)addr1); emit_mov_imm_using_diff(Dst, r_idx2, r_idx1, addr2, addr1); } static void emit_if_res_0_error(Jit* Dst) { JIT_ASSERT(Dst->deferred_vs_res_used == 0, "error this would not get decrefed"); emit_cmp64_imm(Dst, res_idx, 0); | branch_eq ->error } static void emit_if_res_32b_not_0_error(Jit* Dst) { JIT_ASSERT(Dst->deferred_vs_res_used == 0, "error this would not get decrefed"); emit_cmp32_imm(Dst, res_idx, 0); | branch_ne ->error } static void emit_jump_by_n_bytecodes(Jit* Dst, int num_bytes, int inst_idx) { int dst_idx = num_bytes/2+inst_idx+1; JIT_ASSERT(Dst->is_jmp_target[dst_idx], "calculate_jmp_targets needs adjustment"); JIT_ASSERT(dst_idx >= 0 && dst_idx < Dst->num_opcodes, ""); | branch =>dst_idx } static void emit_jump_to_bytecode_n(Jit* Dst, int num_bytes) { int dst_idx = num_bytes/2; JIT_ASSERT(Dst->is_jmp_target[dst_idx], "calculate_jmp_targets needs adjustment"); JIT_ASSERT(dst_idx >= 0 && dst_idx < Dst->num_opcodes, ""); | branch =>dst_idx } static void emit_je_to_bytecode_n(Jit* Dst, int num_bytes) { int dst_idx = num_bytes/2; JIT_ASSERT(Dst->is_jmp_target[dst_idx], "calculate_jmp_targets needs adjustment"); JIT_ASSERT(dst_idx >= 0 && dst_idx < Dst->num_opcodes, ""); | branch_eq =>dst_idx } static void emit_jg_to_bytecode_n(Jit* Dst, int num_bytes) { int dst_idx = num_bytes/2; JIT_ASSERT(Dst->is_jmp_target[dst_idx], "calculate_jmp_targets needs adjustment"); JIT_ASSERT(dst_idx >= 0 && dst_idx < Dst->num_opcodes, ""); | branch_gt =>dst_idx } static void emit_call_ext_func(Jit* Dst, void* addr) { @ARM_START // WARNING: if you modify this you have to adopt SET_JIT_AOT_FUNC because this call can be patched. if (can_use_relative_call(addr)) { | bl &addr // +-128MB from current IP } else { JIT_ASSERT(tmp2_idx == 6, "SET_JIT_AOT_FUNC needs to be adopted"); // we can't use 'emit_mov_imm' because we have to make sure // that we always generate this 5 instruction sequence because SET_JIT_AOT_FUNC is patching it later. // encodes as: 0x52800006 | (addr&0xFFFF)<<5 (=Rw(tmp2_idx)) or 0xD2800006 (=Rx(tmp2_idx)) // note: we use Rx() DynASM sometimes encodes the instruction as Rw() here // because the 32bit op clears the higher 32bit it does not change things. | mov Rx(tmp2_idx), #(unsigned long)addr&UINT16_MAX // encodes as: 0xF2A00006 | ((addr>>16)&0xFFFF)<<5 | movk Rx(tmp2_idx), #((unsigned long)addr>>16)&UINT16_MAX, lsl #16 // encodes as: 0xF2C00006 | ((addr>>32)&0xFFFF)<<5 | movk Rx(tmp2_idx), #((unsigned long)addr>>32)&UINT16_MAX, lsl #32 // encodes as: 0xF2E00006 | ((addr>>48)&0xFFFF)<<5 | movk Rx(tmp2_idx), #((unsigned long)addr>>48)&UINT16_MAX, lsl #48 // encodes as: 0xD63F00C0 | blr tmp2 } | mov res, real_res @ARM_END @X86_START if (can_use_relative_call(addr)) { // This emits a relative call. The dynasm syntax is confusing // it will not actually take the address of addr (even though it says &addr). // Put instead just take the value of addr and calculate the difference to the emitted instruction address. (generated code: dasm_put(Dst, 135, (ptrdiff_t)(addr))) // We emit a relative call to the destination function here which can be patched. // The address of the call is retrieved via __builtin_return_address(0) inside the AOT func and // then the destination of the call instruction (=relative address of the function to call) is modified. | call qword &addr // 5byte inst } else { | mov64 res, (unsigned long)addr | call res // compiles to: 0xff 0xd0 } @X86_END } // r_idx contains the PyObject to decref // Note: this macro clobbers all registers except 'res' if preserve_res is set // Can't use label 9 here because it will end up being the target // of xdecref's jump // it's best to decref arg1 because it uses one less mov instruction static void emit_decref(Jit* Dst, int r_idx, int preserve_res) { _Static_assert(offsetof(PyObject, ob_refcnt) == 0, "sub needs to be modified"); #ifdef Py_REF_DEBUG emit_inc_or_dec_qword_ptr(Dst, &_Py_RefTotal, 1 /* can_use_tmp_reg */, -1 /*= dec*/); #endif @ARM| ldr tmp, [Rx(r_idx)] @ARM| subs tmp, tmp, #1 // must use instruction which sets the flags! @ARM| str tmp, [Rx(r_idx)] @X86| add qword [Rq(r_idx)], -1 // normally we emit the dealloc call into the cold section but if we are already inside it // we have to instead emit it inline int use_inline_decref = Dst->current_section == SECTION_COLD; if (use_inline_decref) { | branch_nz >8 } else { | branch_z >8 switch_section(Dst, SECTION_COLD); |8: } if (r_idx != arg1_idx) { // setup the call argument emit_mov64_reg(Dst, arg1_idx, r_idx); } if (preserve_res) { | mov tmp_preserved_reg, res // save the result } // inline _Py_Dealloc // call_ext_func _Py_Dealloc emit_load64_mem(Dst, res_idx, arg1_idx, offsetof(PyObject, ob_type)); @ARM| ldr tmp, [res, #offsetof(PyTypeObject, tp_dealloc)] @ARM| blr tmp @ARM// mov res, real_res // we don't need this here because the function returns void @X86| call qword [res + offsetof(PyTypeObject, tp_dealloc)] if (preserve_res) { | mov res, tmp_preserved_reg } if (use_inline_decref) { |8: } else { | branch >8 switch_section(Dst, SECTION_CODE); |8: } } // Decrefs two registers and makes sure that a call to _Py_Dealloc does not clobber // the registers of the second variable to decref and the 'res' register. static void emit_decref2(Jit* Dst, int r_idx, int r_idx2, int preserve_res) { const int can_use_vs_preserved_reg = Dst->deferred_vs_preserved_reg_used == 0; enum { TMP_REG, VS_REG, STACK_SLOT, } LocationOfVar2; if (!preserve_res) { // if we don't need to preserve the result, we can store the second var to decref where we would store it (tmp_preserved_reg) emit_mov64_reg(Dst, tmp_preserved_reg_idx, r_idx2); LocationOfVar2 = TMP_REG; } else if (can_use_vs_preserved_reg) { // we have the second preserved register available use it emit_mov64_reg(Dst, vs_preserved_reg_idx, r_idx2); LocationOfVar2 = VS_REG; } else { // have to use the stack emit_store64_mem(Dst, r_idx2, sp_reg_idx, 0 /* stack slot */); LocationOfVar2 = STACK_SLOT; } emit_decref(Dst, r_idx, preserve_res); if (LocationOfVar2 == TMP_REG) { emit_decref(Dst, tmp_preserved_reg_idx, preserve_res); } else if (LocationOfVar2 == VS_REG) { emit_decref(Dst, vs_preserved_reg_idx, preserve_res); emit_mov_imm(Dst, vs_preserved_reg_idx, 0); // we have to clear it because error path will xdecref } else { emit_load64_mem(Dst, arg1_idx, sp_reg_idx, 0 /* stack slot */); emit_decref(Dst, arg1_idx, preserve_res); } } static void emit_xdecref(Jit* Dst, int reg_idx) { @ARM| cbz Rx(reg_idx), >9 // compare and branch on zero. only allows to jump up to 126 byte but is okay here because it's much closer @X86emit_cmp64_imm(Dst, reg_idx, 0); @X86| branch_eq >9 emit_decref(Dst, reg_idx, 0 /* don't preserve res */); |9: } // emits a call afterwards decrefs OWNED arguments // regs and ref_status arrays must be at least num entries long static void emit_call_decref_args(Jit* Dst, void* func, int num, int regs[], RefStatus ref_status[]) { // we have to move owned args to preserved regs (callee saved regs) or to slack slots // to be able to decref after the call // if no deferred vs entry is using vs_preserved_reg we can use it because we don't generate new // deferred vs entries inside this function and will release it afterwards so nobody // will notice we used it here temporarily. // Priorities for storage location are: // - tmp_preserved_reg // - vs_preserved_reg - if available // - stack slot const int can_use_vs_preserved_reg = Dst->deferred_vs_preserved_reg_used == 0; for (int i=0, num_owned = 0; i<num; ++i) { if (ref_status[i] != OWNED) continue; if (num_owned == 0) { emit_mov64_reg(Dst, tmp_preserved_reg_idx, regs[i]); } else if (num_owned == 1 && can_use_vs_preserved_reg) { emit_mov64_reg(Dst, vs_preserved_reg_idx, regs[i]); } else { int stack_slot = num_owned - can_use_vs_preserved_reg -1; // this should never happen if it does adjust NUM_MANUAL_STACK_SLOTS JIT_ASSERT(stack_slot < NUM_MANUAL_STACK_SLOTS, ""); emit_store64_mem(Dst, regs[i], sp_reg_idx, stack_slot*8); } ++num_owned; } emit_call_ext_func(Dst, func); for (int i=0, num_decref=0; i<num; ++i) { if (ref_status[i] != OWNED) continue; if (num_decref == 0) { emit_decref(Dst, tmp_preserved_reg_idx, 1); /*= preserve res */ } else if (num_decref == 1 && can_use_vs_preserved_reg) { emit_decref(Dst, vs_preserved_reg_idx, 1); /*= preserve res */ emit_mov_imm(Dst, vs_preserved_reg_idx, 0); // we have to clear it because error path will xdecref } else { int stack_slot = num_decref - can_use_vs_preserved_reg -1; // this should never happen if it does adjust NUM_MANUAL_STACK_SLOTS JIT_ASSERT(stack_slot < NUM_MANUAL_STACK_SLOTS, ""); emit_load64_mem(Dst, arg1_idx, sp_reg_idx, stack_slot*8); emit_decref(Dst, arg1_idx, 1); /*= preserve res */ } ++num_decref; } } static void emit_call_decref_args1(Jit* Dst, void* func, int r1_idx, RefStatus ref_status[]) { int regs[] = { r1_idx }; emit_call_decref_args(Dst, func, 1, regs, ref_status); } static void emit_call_decref_args2(Jit* Dst, void* func, int r1_idx, int r2_idx, RefStatus ref_status[]) { int regs[] = { r1_idx, r2_idx }; emit_call_decref_args(Dst, func, 2, regs, ref_status); } static void emit_call_decref_args3(Jit* Dst, void* func, int r1_idx, int r2_idx, int r3_idx, RefStatus ref_status[]) { int regs[] = { r1_idx, r2_idx, r3_idx }; emit_call_decref_args(Dst, func, 3, regs, ref_status); } static void* get_aot_func_addr(Jit* Dst, int opcode, int oparg, int opcache_available) { return get_addr_of_aot_func(opcode, oparg, opcache_available); } static void emit_mov_inst_addr_to_tmp(Jit* Dst, int r_inst_idx) { // every entry is 32bit in size and marks the relative offset from opcode_offset_begin to the IP of the bytecode instruction @ARM_START | adr tmp, ->opcode_offset_begin // can only address +-1MB | asr Rw(tmp2_idx), Rw(r_inst_idx), #1 | ldrsw tmp2, [tmp, tmp2, lsl #2] | add tmp, tmp, tmp2 @ARM_END @X86_START // *2 instead of *4 because: // entries are 4byte wide addresses but lasti needs to be divided by 2 // because it tracks offset in bytecode (2bytes long) array not the index | lea tmp, [->opcode_offset_begin] | movsxd Rq(r_inst_idx), dword [tmp + Rq(r_inst_idx)*2] | add tmp, Rq(r_inst_idx) @X86_END } static void emit_jmp_to_inst_idx(Jit* Dst, int r_idx) { JIT_ASSERT(r_idx != tmp_idx, "can't be tmp"); emit_mov_inst_addr_to_tmp(Dst, r_idx); | branch_reg tmp_idx } #if JIT_DEBUG static void debug_error_not_a_jump_target(PyFrameObject* f) { JIT_ASSERT(0, "ERROR: jit entry points to f->f_lasti %d which is not a jump target", f->f_lasti); } #endif static int get_fastlocal_offset(int fastlocal_idx) { return offsetof(PyFrameObject, f_localsplus) + fastlocal_idx * 8; } // this does the same as: r = freevars[num] static void emit_load_freevar(Jit* Dst, int r_idx, int num) { // PyObject *cell = (f->f_localsplus + co->co_nlocals)[oparg]; emit_load64_mem(Dst, r_idx, f_idx, get_fastlocal_offset(Dst->co->co_nlocals + num)); } // compares ceval->tracing_possible == 0 and eval_breaker == 0 in one (64bit) // Always emits instructions using the same number of bytes. static void emit_tracing_possible_and_eval_breaker_check(Jit* Dst) { // the interpreter is using a '_Py_atomic_load_relaxed(eval_breaker)' check // but on x86 and ARM64 this is just a normal load. @ARM// insts are 2*4=8 bytes long @ARM| ldr Rx(tmp_idx), [interrupt] @ARM| cmp Rx(tmp_idx), xzr @X86| cmp qword [interrupt], 0 // inst is 4 bytes long } // compares ceval->tracing_possible == 0 (32bit) // Always emits instructions using the same number of bytes. static void emit_tracing_possible_check(Jit* Dst) { @ARM// insts are 2*4=8 bytes long @ARM| ldr Rw(tmp_idx), [interrupt] @ARM| cmp Rw(tmp_idx), wzr @X86| cmp dword [interrupt], 0 // inst is 3 bytes long } // emits: d->f_lasti = val // Always emits instructions using the same number of bytes. static void emit_update_f_lasti(Jit* Dst, long val) { int can_encode = 1; @ARMif (val >= 32768) can_encode = 0; @X86if (!IS_32BIT_VAL(val)) can_encode = 0; if (!can_encode) { // the mov can't encode this immediate, we would have to use multiple instructions // but because our interrupt and tracing code requires a fixed instruction sequence // we just abort compiling this function Dst->failed = 1; return; } @ARM// insts are 2*4=8 bytes long @ARM| mov tmp, #val @ARM| str Rw(tmp_idx), [f, #offsetof(PyFrameObject, f_lasti)] @X86// inst is 8 bytes long @X86| mov dword [f + offsetof(PyFrameObject, f_lasti)], val } ////////////////////////////////////////////////////////////// // Deferred value stack functions static void deferred_vs_emit(Jit* Dst) { if (Dst->deferred_vs_next) { int clear_vs_preserved_reg = 0; // we use this to generate store pair instructions on arm // if the value is not -1 at the beginning it means we have a not yet stored value which is lives in register 'prev_store_reg' @ARM int prev_store_reg = -1; for (int i=Dst->deferred_vs_next; i>0; --i) { int delayed_store = 1; int tmpreg = tmp_idx; @ARM if (prev_store_reg == -1) @ARM tmpreg = tmp_pair_idx; DeferredValueStackEntry* entry = &Dst->deferred_vs[i-1]; if (entry->loc == CONST) { PyObject* obj = (PyObject*)entry->val; // don't use this path on arm because it prevents storing a pair and arm does not have a store instructions which support immediates // which means it will expanded into a mov + store - we can do better in the common path which at least handles pairs. @ARM if (0) { @X86 if (obj == NULL || IS_IMMORTAL(obj)) { emit_store64_mem_imm(Dst, (unsigned long)obj, vsp_idx, 8 * (i-1)); delayed_store = 0; } else { emit_mov_imm(Dst, tmpreg, (unsigned long)obj); if (obj != NULL && !IS_IMMORTAL(obj)) { emit_incref(Dst, tmpreg); } } } else if (entry->loc == FAST) { emit_load64_mem(Dst, tmpreg, f_idx, get_fastlocal_offset(entry->val)); emit_incref(Dst, tmpreg); } else if (entry->loc == REGISTER) { tmpreg = entry->val; if (entry->val == vs_preserved_reg_idx) { clear_vs_preserved_reg = 1; } } else if (entry->loc == STACK) { emit_load64_mem(Dst, tmpreg, sp_reg_idx, (entry->val + NUM_MANUAL_STACK_SLOTS) * 8); emit_store64_mem_imm(Dst, 0 /* = value */, sp_reg_idx, (entry->val + NUM_MANUAL_STACK_SLOTS) * 8); } else { JIT_ASSERT(0, "entry->loc not implemented"); } if (delayed_store) { @ARM_START if (prev_store_reg != -1) { if (i > 1) { | stp Rx(tmpreg), Rx(prev_store_reg), [vsp, #8 * (i-1)] } else { | stp Rx(tmpreg), Rx(prev_store_reg), [vsp], #8 * Dst->deferred_vs_next } prev_store_reg = -1; } else { if (i > 1) { prev_store_reg = tmpreg; } else { | str Rx(tmpreg), [vsp], #8 * Dst->deferred_vs_next } } @ARM_END @X86 emit_store64_mem(Dst, tmpreg, vsp_idx, 8 * (i-1)); } } if (clear_vs_preserved_reg) { emit_mov_imm(Dst, vs_preserved_reg_idx, 0); // we have to clear it because error path will xdecref } @X86 emit_adjust_vs(Dst, Dst->deferred_vs_next); } } // Look at the top value of the value stack and if its a constant return the constant value, // otherwise return NULL static PyObject* deferred_vs_peek_const(Jit* Dst) { if (Dst->deferred_vs_next == 0) return NULL; DeferredValueStackEntry* entry = &Dst->deferred_vs[Dst->deferred_vs_next - 1]; if (entry->loc == CONST) return (PyObject*)entry->val; return NULL; } // if there are any deferred python value stack operations they will be emitted // and the value stack variables are reset static void deferred_vs_apply(Jit* Dst) { if (Dst->deferred_vs_next) { deferred_vs_emit(Dst); Dst->deferred_vs_next = 0; Dst->deferred_stack_slot_next = 0; Dst->deferred_vs_preserved_reg_used = 0; Dst->deferred_vs_res_used = 0; } } static void deferred_vs_push_no_assert(Jit* Dst, int location, unsigned long value) { if (location == REGISTER && value == res_idx && !(ENABLE_DEFERRED_RES_PUSH)) { emit_push_v(Dst, res_idx); } else { if (Dst->deferred_vs_next + 1 >= DEFERRED_VS_MAX) { // make sure we are not writing out of bounds deferred_vs_apply(Dst); // TODO: we could just materialize the first stack item instead of all } GET_DEFERRED[0].loc = location; GET_DEFERRED[0].val = value; ++Dst->deferred_vs_next; if (location == REGISTER && value == res_idx) Dst->deferred_vs_res_used = 1; if (location == REGISTER && value == vs_preserved_reg_idx) Dst->deferred_vs_preserved_reg_used = 1; } } static void deferred_vs_push(Jit* Dst, int location, unsigned long value) { if (location == REGISTER) { JIT_ASSERT(value == res_idx, "this is they only registers allowed currently"); } deferred_vs_push_no_assert(Dst, location, value); } // returns one of OWNED, BORROWED, or IMMORTAL based on the reference ownership status static RefStatus deferred_vs_peek(Jit* Dst, int r_idx, int num) { JIT_ASSERT(num >= 1, ""); RefStatus ref_status = OWNED; if (Dst->deferred_vs_next >= num) { int idx = Dst->deferred_vs_next-(num); DeferredValueStackEntry* entry = &Dst->deferred_vs[idx]; if (entry->loc == CONST) { PyObject* obj = (PyObject*)entry->val; emit_mov_imm(Dst, r_idx, (unsigned long)obj); ref_status = IS_IMMORTAL(obj) ? IMMORTAL : BORROWED; } else if (entry->loc == FAST) { emit_load64_mem(Dst, r_idx, f_idx, get_fastlocal_offset(entry->val)); ref_status = BORROWED; } else if (entry->loc == REGISTER) { // only generate mov if src and dst is different if (r_idx != (int)entry->val) { emit_mov64_reg(Dst, r_idx, entry->val); } ref_status = OWNED; } else if (entry->loc == STACK) { emit_load64_mem(Dst, r_idx, sp_reg_idx, (entry->val + NUM_MANUAL_STACK_SLOTS) * 8); ref_status = OWNED; } else { JIT_ASSERT(0, "entry->loc not implemented"); } } else { emit_load64_mem(Dst, r_idx, vsp_idx, -8*(num-Dst->deferred_vs_next)); ref_status = OWNED; } return ref_status; } // increfs borrowed references static void emit_make_owned(Jit* Dst, int r_idx, RefStatus ref_status) { if (ref_status == BORROWED) { emit_incref(Dst, r_idx); } } static void deferred_vs_peek_owned(Jit* Dst, int r_idx, int num) { RefStatus ref_status = deferred_vs_peek(Dst, r_idx, num); emit_make_owned(Dst, r_idx, ref_status); } // checks if register 'res' is used and if so either moves it to 'preserve_reg2' or to the stack static void deferred_vs_convert_reg_to_stack(Jit* Dst) { if (!Dst->deferred_vs_res_used) return; // nothing todo for (int i=Dst->deferred_vs_next; i>0; --i) { DeferredValueStackEntry* entry = &Dst->deferred_vs[i-1]; if (entry->loc != REGISTER) continue; // we only need to handle register 'res' because 'vs_preserved_reg' will not // get overwritten by a call. if (entry->val != res_idx) continue; // if we have 'vs_preserved_reg' available use it over a stack slot if (!Dst->deferred_vs_preserved_reg_used) { emit_mov64_reg(Dst, vs_preserved_reg_idx, entry->val); entry->loc = REGISTER; entry->val = vs_preserved_reg_idx; Dst->deferred_vs_preserved_reg_used = 1; } else { // have to use a stack slot if (Dst->num_deferred_stack_slots <= Dst->deferred_stack_slot_next) ++Dst->num_deferred_stack_slots; emit_store64_mem(Dst, res_idx, sp_reg_idx, (Dst->deferred_stack_slot_next + NUM_MANUAL_STACK_SLOTS) * 8); entry->loc = STACK; entry->val = Dst->deferred_stack_slot_next; ++Dst->deferred_stack_slot_next; } JIT_ASSERT(Dst->deferred_vs_res_used, ""); Dst->deferred_vs_res_used = 0; break; // finished only reg 'res' needs special handling } } // removes the top num elements from the value stack static void deferred_vs_remove(Jit* Dst, int num_to_remove) { JIT_ASSERT(num_to_remove >= 0, ""); if (!num_to_remove) return; for (int i=0; i < num_to_remove && Dst->deferred_vs_next > i; ++i) { DeferredValueStackEntry* entry = &GET_DEFERRED[-i-1]; if (entry->loc == STACK) { emit_store64_mem_imm(Dst, 0 /*= value */, sp_reg_idx, (entry->val + NUM_MANUAL_STACK_SLOTS) * 8); if (Dst->deferred_stack_slot_next-1 == (int)entry->val) --Dst->deferred_stack_slot_next; } else if (entry->loc == REGISTER) { if (entry->val == vs_preserved_reg_idx) { emit_mov_imm(Dst, vs_preserved_reg_idx, 0); // we have to clear it because error path will xdecref JIT_ASSERT(Dst->deferred_vs_preserved_reg_used, "should be set"); Dst->deferred_vs_preserved_reg_used = 0; } else if (entry->val == res_idx) { JIT_ASSERT(Dst->deferred_vs_res_used, "should be set"); Dst->deferred_vs_res_used = 0; } } } if (Dst->deferred_vs_next >= num_to_remove) { Dst->deferred_vs_next -= num_to_remove; } else { emit_adjust_vs(Dst, -(num_to_remove - Dst->deferred_vs_next)); Dst->deferred_vs_next = 0; } } // pushes a register to the top of the value stack and afterwards calls deferred_vs_apply. // this allowes the use of any register not only 'res'. static void deferred_vs_push_reg_and_apply(Jit* Dst, int r_idx) { // in this special case (=instant call to deferred_vs_apply) it's safe to // use any register so skip the assert. deferred_vs_push_no_assert(Dst, REGISTER, r_idx); deferred_vs_apply(Dst); } // peeks the top stack entry into register r_idx_top and afterwards calls deferred_vs_apply // generates better code than doing it split static void deferred_vs_peek_top_and_apply(Jit* Dst, int r_idx_top) { JIT_ASSERT(r_idx_top != res_idx && r_idx_top != vs_preserved_reg_idx, "they need special handling"); if (Dst->deferred_vs_next) { // load the value into the destination register and replace the deferred_vs entry // with one which accesses the register instead. // This is safe because we erase all deferred_vs entries afterwards in deferred_vs_apply. // so no additional code needs to know about this register use. // Without this we would e.g. generate two memory loads if the top entry is a FAST var access. // owned because deferred_vs_apply will consume one ref deferred_vs_peek_owned(Dst, r_idx_top, 1 /*=top*/); deferred_vs_remove(Dst, 1); deferred_vs_push_reg_and_apply(Dst, r_idx_top); } else { deferred_vs_peek(Dst, r_idx_top, 1 /*=top*/); } } static void deferred_vs_pop_n(Jit* Dst, int num, const int* const regs, RefStatus out_ref_status[]) { if (num <= 0) return; // how many values come from the deferred value stack int num_deferred = Dst->deferred_vs_next < num ? Dst->deferred_vs_next : num; // how many values come from the value stack int num_vs = num - num_deferred; for (int i=0; i<num_deferred; ++i) { // check for duplicates: // if this is a CONST or FAST entry and we already loaded it // replace it with a register mov. // This just does a linear search but because we only have very few num_deferred entries this should not be a perf problem. // (most of the times it's 2-3 entries and can't be more than DEFERRED_VS_MAX) DeferredValueStackEntry* entry = &GET_DEFERRED[-i-1]; // using 'res' as a destination while it's used in by a deferred value stack entry needs // to be handled specially. // e.g. if the stack looks like this: REGISTER(res), FAST(0) and we call pop1 // which moves FAST(0) into 'res' we would overwrite 'res' and the // REGISTER(res) entry would be corrupt... if (Dst->deferred_vs_res_used && regs[i] == res_idx) { if (entry->loc == REGISTER && entry->val == res_idx) { // nothing todo the destination is res and the source too. // we can just use it } else { // we have to move register 'res' into a free register or into a stack slot deferred_vs_convert_reg_to_stack(Dst); } } int found_duplicate = 0; if (entry->loc == CONST || entry->loc == FAST) { for (int prev=0; prev < i; ++prev) { DeferredValueStackEntry* entry_prev = &GET_DEFERRED[-prev-1]; if (entry->loc == entry_prev->loc && entry->val == entry_prev->val) { // found a duplicate: replace it with a register mov emit_mov64_reg(Dst, regs[i], regs[prev]); out_ref_status[i] = out_ref_status[prev]; found_duplicate = 1; break; } } } if (!found_duplicate) { out_ref_status[i] = deferred_vs_peek(Dst, regs[i], i+1); } } deferred_vs_remove(Dst, num_deferred); if (num_vs) { for (int i=0, reverse_i=num-1; i<num_vs; ++i, --reverse_i) { out_ref_status[reverse_i] = OWNED; if (i == 0) { // on arm we can adjust the value stack pointer directly // in the load instruction. @ARM | ldr Rx(regs[reverse_i]), [vsp, #-8*num_vs]! @ARM continue; @X86 emit_adjust_vs(Dst, -num_vs); } emit_load64_mem(Dst, regs[reverse_i], vsp_idx, 8*i); } } } // returns one of BORROWED, OWNED, or IMMORTAL static RefStatus deferred_vs_pop1(Jit* Dst, int r_idx1) { int regs[] = { r_idx1 }; RefStatus ref_status; deferred_vs_pop_n(Dst, 1, regs, &ref_status); return ref_status; } typedef struct RegAndStatus { int reg_idx; RefStatus ref_status; } RegAndStatus; static RegAndStatus deferred_vs_pop1_anyreg(Jit* Dst, int preferred_reg_idx, int only_if_owned) { int reg_idx = preferred_reg_idx; if (Dst->deferred_vs_next > 0) { int idx = Dst->deferred_vs_next - 1; DeferredValueStackEntry* entry = &Dst->deferred_vs[idx]; if (only_if_owned && (entry->loc == FAST || entry->loc == CONST)) { RegAndStatus r; r.ref_status = BORROWED; deferred_vs_remove(Dst, 1); return r; } // Can't use vs_preserved_reg as a general-purpose reg because // it has a special meaning on exit if (entry->loc == REGISTER && entry->val != vs_preserved_reg_idx) { reg_idx = entry->val; } } int regs[] = { reg_idx }; RefStatus ref_status; deferred_vs_pop_n(Dst, 1, regs, &ref_status); RegAndStatus r; r.reg_idx = reg_idx; r.ref_status = ref_status; return r; } static int deferred_vs_pop1_anyreg_owned(Jit* Dst, int preferred_reg_idx) { RegAndStatus ret = deferred_vs_pop1_anyreg(Dst, preferred_reg_idx, 0); emit_make_owned(Dst, ret.reg_idx, ret.ref_status); return ret.reg_idx; } static void deferred_vs_pop2(Jit* Dst, int r_idx1, int r_idx2, RefStatus out_ref_status[]) { int regs[] = { r_idx1, r_idx2 }; deferred_vs_pop_n(Dst, 2, regs, out_ref_status); } static void deferred_vs_pop3(Jit* Dst, int r_idx1, int r_idx2, int r_idx3, RefStatus out_ref_status[]) { int regs[] = { r_idx1, r_idx2, r_idx3 }; deferred_vs_pop_n(Dst, 3, regs, out_ref_status); } static void deferred_vs_pop_n_owned(Jit* Dst, int num, const int* const regs) { RefStatus ref_status[num]; deferred_vs_pop_n(Dst, num, regs, ref_status); for (int i=0; i<num; ++i) { emit_make_owned(Dst, regs[i], ref_status[i]); } } static void deferred_vs_pop1_owned(Jit* Dst, int r_idx1) { int regs[] = { r_idx1 }; deferred_vs_pop_n_owned(Dst, 1, regs); } static void deferred_vs_pop2_owned(Jit* Dst, int r_idx1, int r_idx2) { int regs[] = { r_idx1, r_idx2 }; deferred_vs_pop_n_owned(Dst, 2, regs); } static void deferred_vs_pop3_owned(Jit* Dst, int r_idx1, int r_idx2, int r_idx3) { int regs[] = { r_idx1, r_idx2, r_idx3 }; deferred_vs_pop_n_owned(Dst, 3, regs); } // if the same variable is inside our deferred value array we have to create the stack static void deferred_vs_apply_if_same_var(Jit* Dst, int var_idx) { int materialize_stack = 0; for (int i=Dst->deferred_vs_next; i>0; --i) { DeferredValueStackEntry* entry = &Dst->deferred_vs[i-1]; if (entry->loc == FAST && (int)entry->val == var_idx) { materialize_stack = 1; break; } } if (materialize_stack) { deferred_vs_apply(Dst); } else { deferred_vs_convert_reg_to_stack(Dst); } } static void emit_jump_if_false(Jit* Dst, int oparg, RefStatus ref_status) { emit_cmp64_imm(Dst, arg1_idx, (unsigned long)Py_False); emit_je_to_bytecode_n(Dst, oparg); emit_cmp64_imm(Dst, arg1_idx, (unsigned long)Py_True); | branch_ne >1 switch_section(Dst, SECTION_COLD); |1: void* func = PyObject_IsTrue; #ifndef PYSTON_LITE if (jit_use_aot) func = PyObject_IsTrueProfile; #endif emit_call_decref_args1(Dst, func, arg1_idx, &ref_status); emit_cmp32_imm(Dst, res_idx, 0); emit_je_to_bytecode_n(Dst, oparg); | branch_lt ->error | branch >3 switch_section(Dst, SECTION_CODE); |3: // continue here } static void emit_jump_if_true(Jit* Dst, int oparg, RefStatus ref_status) { emit_cmp64_imm(Dst, arg1_idx, (unsigned long)Py_True); emit_je_to_bytecode_n(Dst, oparg); emit_cmp64_imm(Dst, arg1_idx, (unsigned long)Py_False); | branch_ne >1 switch_section(Dst, SECTION_COLD); |1: void* func = PyObject_IsTrue; #ifndef PYSTON_LITE if (jit_use_aot) func = PyObject_IsTrueProfile; #endif emit_call_decref_args1(Dst, func, arg1_idx, &ref_status); emit_cmp32_imm(Dst, res_idx, 0); emit_jg_to_bytecode_n(Dst, oparg); | branch_lt ->error | branch >3 switch_section(Dst, SECTION_CODE); |3: // continue here } static void emit_exit_yielding_label(Jit* Dst) { |->exit_yielding: // to differentiate from a normal return we set the second lowest bit @ARM| orr real_res, res, #2 @X86| or real_res, 2 | branch ->return } static _PyOpcache* get_opcache_entry(OpCache* opcache, int inst_idx) { _PyOpcache* co_opcache = NULL; if (opcache->oc_opcache != NULL) { unsigned char co_opt_offset = opcache->oc_opcache_map[inst_idx + 1]; if (co_opt_offset > 0) { JIT_ASSERT(co_opt_offset <= opcache->oc_opcache_size, ""); co_opcache = &opcache->oc_opcache[co_opt_offset - 1]; JIT_ASSERT(co_opcache != NULL, ""); } } return co_opcache; } // returns 0 if generation succeeded static int emit_special_binary_subscr(Jit* Dst, int inst_idx, PyObject* const_val, RefStatus ref_status[2]) { if (!const_val || !PyLong_CheckExact(const_val)) { return -1; } Py_ssize_t n = PyLong_AsSsize_t(const_val); if (n == -1 && PyErr_Occurred()) { PyErr_Clear(); return -1; } _PyOpcache* co_opcache = get_opcache_entry(Dst->opcache, inst_idx); PyTypeObject* cached_type = co_opcache ? co_opcache->u.t.type : NULL; int use_cold_section = 0; // special path: if we have a >= 0 index and during profiling encountered tuple or lists // we emit assembler code for the access if (n >= 0 && ref_status[0] != OWNED /* this is the index/const_val object */ && (cached_type == &PyList_Type || cached_type == &PyTuple_Type)) { | type_check arg1_idx, cached_type, >1 emit_cmp64_mem_imm(Dst, arg1_idx, offsetof(PyVarObject, ob_size), n /* = value */); | branch_le_unsigned >1 if (cached_type == &PyList_Type) { emit_load64_mem(Dst, arg4_idx, arg1_idx, offsetof(PyListObject, ob_item)); emit_load64_mem(Dst, res_idx, arg4_idx, n*sizeof(PyObject*)); } else { emit_load64_mem(Dst, res_idx, arg1_idx, offsetof(PyTupleObject, ob_item) + n*sizeof(PyObject*)); } emit_incref(Dst, res_idx); if (ref_status[1] == OWNED /* check if the container is owned */) { emit_decref(Dst, arg1_idx, 1 /* preserve res */); } use_cold_section = 1; ++jit_stat_getitemlong_inlined; } if (use_cold_section) { switch_section(Dst, SECTION_COLD); } |1: #ifdef PYSTON_LITE void* func = PyObject_GetItem; #else emit_mov_imm(Dst, arg3_idx, n); void* func = jit_use_aot ? PyObject_GetItemLongProfile : PyObject_GetItemLong; #endif emit_call_decref_args2(Dst, func, arg2_idx, arg1_idx, ref_status); emit_if_res_0_error(Dst); if (use_cold_section) { | branch >2 switch_section(Dst, SECTION_CODE); } |2: deferred_vs_push(Dst, REGISTER, res_idx); ++jit_stat_getitemlong; return 0; } // returns 0 if generation succeeded static int emit_special_store_subscr(Jit* Dst, int inst_idx, int opcode, int oparg, PyObject* const_val, RefStatus ref_status[3]) { if (!const_val || !PyLong_CheckExact(const_val)) { return -1; } Py_ssize_t n = PyLong_AsSsize_t(const_val); if (n == -1 && PyErr_Occurred()) { PyErr_Clear(); return -1; } if (n < 0 || ref_status[0] == OWNED /* this is the index/const_val object */) { return -1; } _PyOpcache* co_opcache = get_opcache_entry(Dst->opcache, inst_idx); PyTypeObject* cached_type = co_opcache ? co_opcache->u.t.type : NULL; if (cached_type != &PyList_Type) { return -1; } // special path: if we have a >= 0 index and during profiling encountered a lists // we emit assembler code for the store | type_check arg1_idx, cached_type, >1 emit_cmp64_mem_imm(Dst, arg1_idx, offsetof(PyVarObject, ob_size), n /* = value */); | branch_le_unsigned >1 emit_make_owned(Dst, arg3_idx, ref_status[2]); /* this is the new value */ emit_load64_mem(Dst, arg4_idx, arg1_idx, offsetof(PyListObject, ob_item)); emit_load64_mem(Dst, res_idx, arg4_idx, n*sizeof(PyObject*)); emit_store64_mem(Dst, arg3_idx, arg4_idx, n*sizeof(PyObject*)); if (ref_status[1] == OWNED /* check if the container is owned */) { emit_decref(Dst, arg1_idx, 1 /* preserve res */); } emit_xdecref(Dst, res_idx); switch_section(Dst, SECTION_COLD); |1: void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); emit_call_decref_args3(Dst, func, arg2_idx, arg1_idx, arg3_idx, ref_status); emit_if_res_32b_not_0_error(Dst); | branch >2 switch_section(Dst, SECTION_CODE); |2: ++jit_stat_setitemlong_inlined; return 0; } // returns 0 if generation succeeded static int emit_special_compare_op(Jit* Dst, int oparg, RefStatus ref_status[2]) { if (oparg != PyCmp_IS && oparg != PyCmp_IS_NOT) { return -1; } emit_mov_imm2(Dst, res_idx, Py_True, tmp_idx, Py_False); | cmp arg1, arg2 if (oparg == PyCmp_IS) { @ARM | csel res, res, tmp, eq @X86 | cmovne res, tmp } else { @ARM | csel res, res, tmp, ne @X86 | cmove res, tmp } // don't need to incref Py_True/Py_False because they are immortals if (ref_status[0] == OWNED && ref_status[1] == OWNED) emit_decref2(Dst, arg2_idx, arg1_idx, 1 /*= preserve res */); else if (ref_status[0] == OWNED) emit_decref(Dst, arg2_idx, 1 /*= preserve res */); else if (ref_status[1] == OWNED) emit_decref(Dst, arg1_idx, 1 /*= preserve res */); deferred_vs_push(Dst, REGISTER, res_idx); return 0; } static int emit_inline_cache_loadattr_is_version_zero(_PyOpcache_LoadAttr *la) { #ifdef PYSTON_LITE int version_zero = (la->cache_type == LA_CACHE_VALUE_CACHE_DICT && la->u.value_cache.dict_ver == 0); #else int version_zero = (la->cache_type == LA_CACHE_VALUE_CACHE_DICT && la->u.value_cache.dict_ver == 0) || (la->cache_type == LA_CACHE_IDX_SPLIT_DICT && la->u.split_dict_cache.splitdict_keys_version == 0); #endif #ifndef PYSTON_LITE if (version_zero == 1 && la->cache_type == LA_CACHE_IDX_SPLIT_DICT) { // This case is currently impossible since it will always be a miss and we don't cache // misses, so it's untested. fprintf(stderr, "untested jit case"); abort(); } #endif return version_zero; } // returns 1 if IC generation is possible static int emit_inline_cache_loadattr_supported(_PyOpcache *co_opcache, _PyOpcache_LoadAttr *la) { if (!co_opcache->optimized) return 0; int version_zero = emit_inline_cache_loadattr_is_version_zero(la); if (la->cache_type != LA_CACHE_BUILTIN && la->cache_type != LA_CACHE_DATA_DESCR && la->cache_type != LA_CACHE_SLOT_CACHE) { // fail the cache if dictoffset<0 rather than do the lengthier dict_ptr computation if (version_zero) { if (la->type_tp_dictoffset < 0) return 0; } else { if (la->type_tp_dictoffset <= 0) return 0; } } if (la->cache_type == LA_CACHE_POLYMORPHIC) { for (int i=0, num=la->u.poly_cache.num_used; i<num; ++i) { _PyOpcache *co_opcache_entry = &la->u.poly_cache.caches[i]; _PyOpcache_LoadAttr *la_entry = &co_opcache_entry->u.la; if (co_opcache_entry->num_failed == 0 && emit_inline_cache_loadattr_supported(co_opcache_entry, la_entry)) { return 1; } } return 0; } return 1; } static void emit_inline_cache_loadattr_entry(Jit* Dst, int opcode, int oparg, _PyOpcache_LoadAttr *la, int* emit_load_attr_res_0_helper) { int version_zero = emit_inline_cache_loadattr_is_version_zero(la); if (la->cache_type == LA_CACHE_BUILTIN) { | type_check arg1_idx, la->type, >1 } else { // PyTypeObject *arg2 = Py_TYPE(obj) emit_load64_mem(Dst, arg2_idx, arg1_idx, offsetof(PyObject, ob_type)); | type_version_check, arg2_idx, la->type_ver, >1 if (la->cache_type == LA_CACHE_DATA_DESCR) { // save the obj so we can access it after the call | mov tmp_preserved_reg, arg1 PyObject* descr = la->u.descr_cache.descr; emit_mov_imm(Dst, arg5_idx, (uint64_t)descr); emit_load64_mem(Dst, arg2_idx, arg5_idx, offsetof(PyObject, ob_type)); | type_version_check, arg2_idx, la->u.descr_cache.descr_type_ver, >1 // res = descr->ob_type->tp_descr_get(descr, owner, (PyObject *)owner->ob_type); | mov arg1, arg5 | mov arg2, tmp_preserved_reg emit_load64_mem(Dst, arg3_idx, tmp_preserved_reg_idx, offsetof(PyObject, ob_type)); emit_call_ext_func(Dst, descr->ob_type->tp_descr_get); | mov arg1, tmp_preserved_reg // restore the obj so that the decref code works // attr can be NULL emit_cmp64_imm(Dst, res_idx, 0); | branch_eq >3 *emit_load_attr_res_0_helper = 1; // makes sure we emit label 3 } else if (la->cache_type == LA_CACHE_SLOT_CACHE) { // nothing todo } else if (version_zero && la->type_tp_dictoffset == 0) { // tp_dict_offset==0 implies dict_ptr==NULL implies dict version (either split keys or not) is 0 } else { // arg2 = *(obj + dictoffset) emit_load64_mem(Dst, arg2_idx, arg1_idx, la->type_tp_dictoffset); emit_cmp64_imm(Dst, arg2_idx, 0); if (version_zero) { // null dict is always a cache hit | branch_eq >2 } else { // null dict is always a cache miss | branch_eq >1 } } } if (la->cache_type == LA_CACHE_OFFSET_CACHE) { // if (mp->ma_keys->dk_size != dk_size) goto slow_path; emit_load64_mem(Dst, res_idx, arg2_idx, offsetof(PyDictObject, ma_keys)); emit_cmp64_mem_imm(Dst, res_idx, offsetof(PyDictKeysObject, dk_size), (uint64_t)la->u.offset_cache.dk_size); | branch_ne >1 // if (mp->ma_keys->dk_lookup == lookdict_split) goto slow_path; emit_cmp64_mem_imm(Dst, res_idx, offsetof(PyDictKeysObject, dk_lookup), (uint64_t)lookdict_split); | branch_eq >1 // PyDictKeyEntry *arg3 = (PyDictKeyEntry*)(mp->ma_keys->dk_indices + offset); uint64_t total_offset = offsetof(PyDictKeysObject, dk_indices) + la->u.offset_cache.offset; emit_add_or_sub_imm(Dst, arg3_idx, res_idx, total_offset); // if (ep->me_key != key) goto slow_path; emit_cmp64_mem_imm(Dst, arg3_idx, offsetof(PyDictKeyEntry, me_key), (uint64_t)PyTuple_GET_ITEM(Dst->co_names, oparg)); | branch_ne >1 // res = ep->me_value; emit_load64_mem(Dst, res_idx, arg3_idx, offsetof(PyDictKeyEntry, me_value)); emit_incref(Dst, res_idx); } else if (la->cache_type == LA_CACHE_OFFSET_CACHE_SPLIT) { // if (mp->ma_keys->dk_size != dk_size) goto slow_path; emit_load64_mem(Dst, res_idx, arg2_idx, offsetof(PyDictObject, ma_keys)); uint64_t size = (uint64_t)la->u.offset_cache_split.dk_size; emit_cmp64_mem_imm(Dst, res_idx, offsetof(PyDictKeysObject, dk_size), size); | branch_ne >1 // if (mp->ma_keys->dk_lookup != lookdict_split) goto slow_path; emit_cmp64_mem_imm(Dst, res_idx, offsetof(PyDictKeysObject, dk_lookup), (uint64_t)lookdict_split); | branch_ne >1 #define DK_IXSIZE(sz) \ (sz <= 0xff ? \ 1 : sz <= 0xffff ? \ 2 : sizeof(int32_t)) // PyDictKeyEntry *arg3 = DK_ENTRIES(mp->ma_keys) + ix; uint64_t total_offset = offsetof(PyDictKeysObject, dk_indices) + size * DK_IXSIZE(size) + la->u.offset_cache_split.ix * sizeof(PyDictKeyEntry); emit_add_or_sub_imm(Dst, arg3_idx, res_idx, total_offset); // if (ep->me_key != key) goto slow_path; emit_cmp64_mem_imm(Dst, arg3_idx, offsetof(PyDictKeyEntry, me_key), (uint64_t)PyTuple_GET_ITEM(Dst->co_names, oparg)); | branch_ne >1 // PyObject** arg3 = mp->ma_values emit_load64_mem(Dst, arg3_idx, arg2_idx, offsetof(PyDictObject, ma_values)); // res = arg3[ix] emit_load64_mem(Dst, res_idx, arg3_idx, la->u.offset_cache_split.ix * sizeof(PyObject*)); // attr can be NULL emit_cmp64_imm(Dst, res_idx, 0); | branch_eq >3 *emit_load_attr_res_0_helper = 1; // makes sure we emit label 3 emit_incref(Dst, res_idx); } else if (la->cache_type == LA_CACHE_SLOT_CACHE) { emit_load64_mem(Dst, res_idx, arg1_idx, la->u.slot_cache.offset); // attr can be NULL emit_cmp64_imm(Dst, res_idx, 0); // we can't just jump to label 3 because it would output a different exception message // instead jump to the slow path | branch_eq >1 emit_incref(Dst, res_idx); } else if (la->cache_type == LA_CACHE_VALUE_CACHE_DICT || #ifndef PYSTON_LITE la->cache_type == LA_CACHE_VALUE_CACHE_SPLIT_DICT || #endif la->cache_type == LA_CACHE_BUILTIN) { if (version_zero && la->type_tp_dictoffset == 0) { // Already guarded } #ifndef PYSTON_LITE else if (la->cache_type == LA_CACHE_VALUE_CACHE_SPLIT_DICT) { emit_cmp64_mem_imm(Dst, arg2_idx, offsetof(PyDictObject, ma_values), 0); | branch_eq >1 // fail if dict->ma_values == NULL // _PyDict_GetDictKeyVersionFromSplitDict: // arg3 = arg2->ma_keys emit_load64_mem(Dst, arg3_idx, arg2_idx, offsetof(PyDictObject, ma_keys)); emit_cmp64_mem_imm(Dst, arg3_idx, offsetof(PyDictKeysObject, dk_version_tag), (uint64_t)la->u.value_cache.dict_ver); | branch_ne >1 } #endif else if (la->cache_type == LA_CACHE_VALUE_CACHE_DICT) { emit_cmp64_mem_imm(Dst, arg2_idx, offsetof(PyDictObject, ma_version_tag), (uint64_t)la->u.value_cache.dict_ver); | branch_ne >1 } else { // Already guarded } | 2: PyObject* r = la->u.value_cache.obj; emit_mov_imm(Dst, res_idx, (uint64_t)r); // In theory we could remove some of these checks, since we could prove that tp_descr_get wouldn't // be able to change. But we have to do that determination at cache-set time, because that's the // only time we know that the cached value is alive. So it's unclear if it's worth it, especially // for the complexity. if (la->guard_tp_descr_get) { emit_load64_mem(Dst, arg2_idx, res_idx, offsetof(PyObject, ob_type)); emit_cmp64_mem_imm(Dst, arg2_idx, offsetof(PyTypeObject, tp_descr_get), 0); | branch_ne >1 } if (!IS_IMMORTAL(r)) emit_incref(Dst, res_idx); } #ifndef PYSTON_LITE else if (la->cache_type == LA_CACHE_IDX_SPLIT_DICT) { // arg4 = dict->ma_values emit_load64_mem(Dst, arg4_idx, arg2_idx, offsetof(PyDictObject, ma_values)); emit_cmp64_imm(Dst, arg4_idx, 0); | branch_eq >1 // fail if dict->ma_values == NULL // _PyDict_GetDictKeyVersionFromSplitDict: // arg3 = arg2->ma_keys emit_load64_mem(Dst, arg3_idx, arg2_idx, offsetof(PyDictObject, ma_keys)); emit_cmp64_mem_imm(Dst, arg3_idx, offsetof(PyDictKeysObject, dk_version_tag), (uint64_t)la->u.split_dict_cache.splitdict_keys_version); | branch_ne >1 // res = arg4[splitdict_index] emit_load64_mem(Dst, res_idx, arg4_idx, sizeof(PyObject*) * la->u.split_dict_cache.splitdict_index); // attr can be NULL emit_cmp64_imm(Dst, res_idx, 0); | branch_eq >3 *emit_load_attr_res_0_helper = 1; // makes sure we emit label 3 emit_incref(Dst, res_idx); } #endif } // special inplace modification code for float math functions // can modify either the left or right operand // returns 0 if generation succeeded static int emit_special_binary_op_inplace(Jit* Dst, int inst_idx, int opcode, int oparg, RefStatus ref_status_left, RefStatus ref_status_right, int load_store_left_idx, PyObject* const_right_val) { switch (opcode) { case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_MULTIPLY: case INPLACE_ADD: case INPLACE_SUBTRACT: case INPLACE_MULTIPLY: break; default: return -1; } _PyOpcache* opcache = get_opcache_entry(Dst->opcache, inst_idx); if (!opcache || !opcache->optimized) { return -1; } _PyOpcache_TypeRefcnt* cache = &opcache->u.t_refcnt; if (cache->type != &PyFloat_Type) { return -1; } // if the left operand is a fast variable and the result is stored in it we can do a special // optimization if we know it's not stored anywhere else. // In the interpreter this cases have refcnt == 2 because the variable is stored in the // fast arg array and on the value stack. // if profiling showed that the right operand can be inplace modifed more often use it instead int load_store_left = load_store_left_idx != -1 && cache->refcnt2_left >= cache->refcnt1_right; if (!cache->refcnt1_left && !cache->refcnt1_right && !load_store_left) { return -1; } // should we inplace modify the right operand? int use_right = !load_store_left && ref_status_right == OWNED && cache->refcnt1_right >= cache->refcnt1_left && cache->refcnt1_right >= opcache->optimized/2; if (!load_store_left && !use_right) { // try the left // the inplace modified reference must be owned otherwise the refcnt==1 does not mean it's temporary. if (ref_status_left != OWNED) return -1; // some simple heuristics: if it looks like the refcnt is only 1 in less than half the cases // don't inline it if (cache->refcnt1_left < opcache->optimized/2) return -1; } int inplace_reg = arg1_idx; int other_reg = arg2_idx; RefStatus other_reg_ref_status = ref_status_right; if (use_right) { inplace_reg = arg2_idx; other_reg = arg1_idx; other_reg_ref_status = ref_status_left; } ++jit_stat_binary_op_inplace; // check that PyREFCNT()==1 // this is also correct in case of ''load_store_left=1' because the JIT borrows the reference emit_cmp64_mem_imm(Dst, inplace_reg, 0, 1 /* value */); | branch_ne >1 | type_check arg1_idx, cache->type, >1 if (const_right_val && Py_TYPE(const_right_val) == cache->type) { // right operand is constant, don't have to check the type JIT_ASSERT(use_right == 0, ""); } else { | type_check arg2_idx, cache->type, >1 } if (cache->type == &PyFloat_Type) { const int offset_fval = offsetof(PyFloatObject, ob_fval); @ARM | ldr d0, [arg1, #offset_fval] @ARM | ldr d1, [arg2, #offset_fval] @X86 | movsd xmm0, qword [arg1+offset_fval] if (opcode == BINARY_ADD || opcode == INPLACE_ADD) { @ARM | fadd d0, d0, d1 @X86 | addsd xmm0, qword [arg2+offset_fval] } else if (opcode == BINARY_SUBTRACT || opcode == INPLACE_SUBTRACT) { @ARM | fsub d0, d0, d1 @X86 | subsd xmm0, qword [arg2+offset_fval] } else if (opcode == BINARY_MULTIPLY || opcode == INPLACE_MULTIPLY) { @ARM | fmul d0, d0, d1 @X86 | mulsd xmm0, qword [arg2+offset_fval] } else { JIT_ASSERT(0, ""); } @ARM | str d0, [Rx(inplace_reg),#offset_fval] @X86 | movsd qword [Rq(inplace_reg)+offset_fval], xmm0 emit_mov64_reg(Dst, res_idx, inplace_reg); if (other_reg_ref_status == OWNED) { emit_decref(Dst, other_reg, 1 /* preserve res */); } } else { JIT_ASSERT(0, ""); } if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_binary_op_inplace_hit, 0 /*=can't use tmp_reg*/); } if (load_store_left) { // skip STORE_FAST int dst_idx = inst_idx+2; JIT_ASSERT(dst_idx >= 0 && dst_idx < Dst->num_opcodes, ""); | branch =>dst_idx } // slowpath { switch_section(Dst, SECTION_COLD); |1: void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); RefStatus ref_status[] = { ref_status_right, ref_status_left }; emit_call_decref_args2(Dst, func, arg2_idx, arg1_idx, ref_status); emit_if_res_0_error(Dst); if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_binary_op_inplace_miss, 0 /*=can't use tmp_reg*/); } | branch >2 switch_section(Dst, SECTION_CODE); } |2: deferred_vs_push(Dst, REGISTER, res_idx); return 0; } // Same signature as PyUnicode_Append // except that it only handles the case where pleft refcnt = 1 static void list_append(PyObject **pleft, PyObject *right) { if (!PyList_CheckExact(*pleft) || !PyList_CheckExact(right)) { __builtin_unreachable(); } JIT_ASSERT(Py_REFCNT(*pleft)==1, ""); // returns Py_None on success... PyObject* none = _PyList_Extend((PyListObject*)*pleft, right); if (none == NULL) { Py_CLEAR(*pleft); return; } Py_DECREF(none); } // special inplace modification code for string and list concatenations // only supports modifying the left operand inplace. // returns 0 if generation succeeded static int emit_special_concat_inplace(Jit* Dst, int inst_idx, int opcode, int oparg, RefStatus ref_status_left, RefStatus ref_status_right, int load_store_left_idx, PyObject* const_right_val) { if (opcode != BINARY_ADD && opcode != INPLACE_ADD) { return -1; } _PyOpcache* opcache = get_opcache_entry(Dst->opcache, inst_idx); if (!opcache || !opcache->optimized) { return -1; } _PyOpcache_TypeRefcnt* cache = &opcache->u.t_refcnt; if (cache->type != &PyUnicode_Type && cache->type != &PyList_Type) { return -1; } // some simple heuristics: if the object can only inplace modified in less than half the cases // don't do the optimization if (load_store_left_idx != -1) { // it's 2 here because the interpreter holds a reference in the locals array and one in the value stack while the JIT will only hold 1 if (cache->refcnt2_left < opcache->optimized/2) { return -1; } } else { if (cache->refcnt1_left < opcache->optimized/2) { return -1; } } if (load_store_left_idx != -1) { JIT_ASSERT(ref_status_left == BORROWED, ""); } else if (ref_status_left != OWNED) { // we can't do the optimization return -1; } ++jit_stat_concat_inplace; // check that PyREFCNT()==1 emit_cmp64_mem_imm(Dst, arg1_idx, 0, 1 /* value */); | branch_ne >1 | type_check arg1_idx, cache->type, >1 if (const_right_val && Py_TYPE(const_right_val) == cache->type) { // right operand is constant, don't have to check the type } else { | type_check arg2_idx, cache->type, >1 } void* func = cache->type == &PyUnicode_Type ? PyUnicode_Append : list_append; if (load_store_left_idx != -1) { // load address of fast local entry emit_add_or_sub_imm(Dst, arg1_idx, f_idx, get_fastlocal_offset(load_store_left_idx)); } else { // store owned temporary into stack slot so that we can get a pointer to it emit_store64_mem(Dst, arg1_idx, sp_reg_idx, 0 /* stack slot */); // move address of stack slot entry into arg1 // can't use emit_mov64_reg on arm because it will generate 'mov arg1, xzr' because xzr and sp have the same reg index // and the encoder does not know we actually want to read sp instead of zeroing the reg. @ARM | mov arg1, sp @X86 emit_mov64_reg(Dst, arg1_idx, sp_reg_idx); } emit_call_decref_args1(Dst, func, arg2_idx, &ref_status_right); // result got written into address arg1 pointed to if (load_store_left_idx != -1) { // we don't have to load the result because we modified the fast local array entry directly and will // jump to the instruction after the store. // we just need to to check if it's 0 which means a error happened. emit_cmp64_mem_imm(Dst, f_idx, get_fastlocal_offset(load_store_left_idx), 0 /* value */); | branch_eq ->error } else { // load result into res emit_load64_mem(Dst, res_idx, sp_reg_idx, 0 /* stack slot */); emit_if_res_0_error(Dst); } if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_concat_inplace_hit, 0 /*=can't use tmp_reg*/); } if (load_store_left_idx != -1) { // skip STORE_FAST int dst_idx = inst_idx+2; JIT_ASSERT(dst_idx >= 0 && dst_idx < Dst->num_opcodes, ""); | branch =>dst_idx } // slowpath { switch_section(Dst, SECTION_COLD); |1: void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); RefStatus ref_status[] = { ref_status_right, ref_status_left }; emit_call_decref_args2(Dst, func, arg2_idx, arg1_idx, ref_status); emit_if_res_0_error(Dst); if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_concat_inplace_miss, 0 /*=can't use tmp_reg*/); } | branch >2 switch_section(Dst, SECTION_CODE); } |2: deferred_vs_push(Dst, REGISTER, res_idx); return 0; } // returns 0 if IC generation succeeded static int emit_inline_cache(Jit* Dst, int opcode, int oparg, _PyOpcache* co_opcache) { if (co_opcache == NULL || !jit_use_ics) return 1; // do we have a valid cache entry? if (!co_opcache->optimized) return 1; if (opcode == LOAD_GLOBAL) { ++jit_stat_load_global_total; // The co_opcache->num_failed==0 check is to try to avoid writing out inline // caches that might end up missing, since we currently don't rewrite them. // It looks like the check is largely useless on our benchmarks, and doesn't // meaningfully cut down on the (extremely small) number of cache misses. // I think it's still worth leaving it in to reduce potential downside in bad cases, // as it definitely helps with the other opcodes. // globals_ver != 0 makes sure we don't write out an always-failing inline cache if (co_opcache->num_failed == 0 && co_opcache->u.lg.globals_ver != 0) { _PyOpcache_LoadGlobal *lg = &co_opcache->u.lg; ++jit_stat_load_global_inline; deferred_vs_convert_reg_to_stack(Dst); emit_load64_mem(Dst, arg3_idx, f_idx, offsetof(PyFrameObject, f_globals)); emit_cmp64_mem_imm(Dst, arg3_idx, offsetof(PyDictObject, ma_version_tag), (uint64_t)lg->globals_ver); | branch_ne >1 if (lg->builtins_ver != LOADGLOBAL_WAS_GLOBAL) { emit_load64_mem(Dst, arg3_idx, f_idx, offsetof(PyFrameObject, f_builtins)); emit_cmp64_mem_imm(Dst, arg3_idx, offsetof(PyDictObject, ma_version_tag), (uint64_t)lg->builtins_ver); | branch_ne >1 } emit_mov_imm(Dst, res_idx, (uint64_t)lg->ptr); if (!IS_IMMORTAL(lg->ptr)) emit_incref(Dst, res_idx); if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_load_global_hit, 1 /*=can use tmp_reg*/); } |4: // fallthrough to next opcode // Put the slowpath in a cold section switch_section(Dst, SECTION_COLD); | 1: if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_load_global_miss, 1 /*=can use tmp_reg*/); } emit_mov_imm2(Dst, arg1_idx, PyTuple_GET_ITEM(Dst->co_names, oparg), arg2_idx, co_opcache); emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, co_opcache != 0 /*= use op cache */)); emit_if_res_0_error(Dst); | branch <4 // jump to the common code which pushes the result // Switch back to the normal section switch_section(Dst, SECTION_CODE); deferred_vs_push(Dst, REGISTER, res_idx); return 0; } } else if (opcode == LOAD_ATTR || opcode == LOAD_METHOD) { if (opcode == LOAD_ATTR) ++jit_stat_load_attr_total; else ++jit_stat_load_method_total; _PyOpcache_LoadAttr *la = &co_opcache->u.la; if (co_opcache->num_failed == 0 && emit_inline_cache_loadattr_supported(co_opcache, la)) { if (opcode == LOAD_ATTR) ++jit_stat_load_attr_inline; else ++jit_stat_load_method_inline; PyObject* const_val = deferred_vs_peek_const(Dst); RefStatus ref_status = 0; if (opcode == LOAD_ATTR) { // PyObject *owner = POP(); ref_status = deferred_vs_pop1(Dst, arg1_idx); deferred_vs_convert_reg_to_stack(Dst); } else { if (la->cache_type == LA_CACHE_BUILTIN) { CallMethodHint* hint = Dst->call_method_hints; if (hint) { hint->type = la->type; hint->attr = la->u.value_cache.obj; hint->meth_found = la->meth_found; hint->is_self_const = const_val != NULL; } } // special case for method loads on constant objects. // mostly used for "".join() and "".format() if (const_val && la->cache_type == LA_CACHE_BUILTIN && la->meth_found && la->type == Py_TYPE(const_val)) { deferred_vs_remove(Dst, 1); // this is LOAD_CONST 'self' deferred_vs_push(Dst, CONST, (unsigned long)la->u.value_cache.obj); deferred_vs_push(Dst, CONST, (unsigned long)const_val); if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_load_method_hit, 1 /*=can use tmp_reg*/); } return 0; } else { // PyObject *obj = TOP(); deferred_vs_peek_top_and_apply(Dst, arg1_idx); } } int meth_found = 0; int emit_load_attr_res_0_helper = 0; if (la->cache_type == LA_CACHE_POLYMORPHIC) { if (opcode == LOAD_ATTR) { ++jit_stat_load_attr_poly; } else { ++jit_stat_load_method_poly; } int first = 1; for (int i=0, num=la->u.poly_cache.num_used; i<num; ++i) { _PyOpcache *co_opcache_entry = &la->u.poly_cache.caches[i]; _PyOpcache_LoadAttr *la_entry = &co_opcache_entry->u.la; if (co_opcache_entry->num_failed != 0) { continue; } if (!emit_inline_cache_loadattr_supported(co_opcache_entry, la_entry)) { continue; } if (first) { // remember if this is a meth_found entry. // currently all entries require this to be the same because they all branch to 4, // which generates different code depending on the value of meth_found meth_found = la_entry->meth_found; } else { if (meth_found != la_entry->meth_found) { // can't use this because meth_found is different continue; } } if (!first) { // if we reach here it means we found the attribute jump to the sucess branch | branch >4 // attribute not found: |1: } if (opcode == LOAD_ATTR) { ++jit_stat_load_attr_poly_entries; } else { ++jit_stat_load_method_poly_entries; } emit_inline_cache_loadattr_entry(Dst, opcode, oparg, la_entry, &emit_load_attr_res_0_helper); first = 0; } if (first == 1) { // make sure that we emit at least one entry else we would generate invalid code // because of the checks we do before we should never get here if we don't have an // entry to emit. JIT_ASSERT(0, "likely error in emit_inline_cache_loadattr_supported"); } } else { emit_inline_cache_loadattr_entry(Dst, opcode, oparg, la, &emit_load_attr_res_0_helper); meth_found = la->meth_found; } |4: if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, opcode == LOAD_ATTR ? &jit_stat_load_attr_hit : &jit_stat_load_method_hit, 1 /*=can use tmp_reg*/); } if (opcode == LOAD_ATTR) { if (ref_status == OWNED) { emit_decref(Dst, arg1_idx, 1 /*= preserve res */); } } else { if (meth_found) { emit_write_vs(Dst, res_idx, 1 /*=top*/); | mov res, arg1 } else { emit_write_imm_vs(Dst, 0 /*=value*/, 1 /*=top*/); emit_decref(Dst, arg1_idx, 1 /*= preserve res */); } } |5: // fallthrough to next opcode // slowpath { switch_section(Dst, SECTION_COLD); | 1: if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, opcode == LOAD_ATTR ? &jit_stat_load_attr_miss : &jit_stat_load_method_miss, 1 /*=can use tmp_reg*/); } if (opcode == LOAD_ATTR) { | mov arg2, arg1 // helper function needs a owned value emit_make_owned(Dst, arg2_idx, ref_status); emit_mov_imm2(Dst, arg1_idx, PyTuple_GET_ITEM(Dst->co_names, oparg), arg3_idx, co_opcache); } else { emit_mov_imm2(Dst, arg1_idx, PyTuple_GET_ITEM(Dst->co_names, oparg), arg2_idx, co_opcache); } emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, co_opcache != 0 /*= use op cache */)); emit_if_res_0_error(Dst); | branch <5 // jump to the common code which pushes the result if (emit_load_attr_res_0_helper) { // we only emit this code if it's used |3: | mov tmp_preserved_reg, arg1 emit_mov_imm(Dst, arg2_idx, (uint64_t)PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_ext_func(Dst, loadAttrCacheAttrNotFound); | mov arg1, tmp_preserved_reg emit_cmp64_imm(Dst, res_idx, 0); | branch_ne <4 // jump to the common code which decrefs the obj and pushes the result if (ref_status == OWNED) { emit_decref(Dst, tmp_preserved_reg_idx, 0 /*= don't preserve res */); } if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, opcode == LOAD_ATTR ? &jit_stat_load_attr_hit : &jit_stat_load_method_hit, 1 /*=can use tmp_reg*/); } | branch ->error } switch_section(Dst, SECTION_CODE); } deferred_vs_push(Dst, REGISTER, res_idx); return 0; } } else if (opcode == STORE_ATTR) { ++jit_stat_store_attr_total; _PyOpcache_StoreAttr *sa = &co_opcache->u.sa; if (co_opcache->num_failed == 0 && sa->type_ver != 0 && co_opcache->optimized) { #ifndef PYSTON_LITE if ((sa->cache_type == SA_CACHE_IDX_SPLIT_DICT || sa->cache_type == SA_CACHE_IDX_SPLIT_DICT_INIT) && sa->type_tp_dictoffset <= 0) { // fail the cache if dictoffset<=0 rather than do the lengthier dict_ptr computation return -1; } #endif ++jit_stat_store_attr_inline; RefStatus ref_status[2]; deferred_vs_pop2(Dst, arg2_idx, arg3_idx, ref_status); deferred_vs_convert_reg_to_stack(Dst); emit_load64_mem(Dst, arg1_idx, arg2_idx, offsetof(PyObject, ob_type)); | type_version_check, arg1_idx, sa->type_ver, >1 if (sa->cache_type == SA_CACHE_SLOT_CACHE) { emit_make_owned(Dst, arg3_idx, ref_status[1]); emit_load64_mem(Dst, res_idx, arg2_idx, sa->u.slot_cache.offset); emit_store64_mem(Dst, arg3_idx, arg2_idx, sa->u.slot_cache.offset); if (ref_status[0] == OWNED) { emit_decref(Dst, arg2_idx, 1 /*= preserve res */); } emit_xdecref(Dst, res_idx); } else { #ifndef PYSTON_LITE if (sa->cache_type == SA_CACHE_IDX_SPLIT_DICT) { // arg1 = *(obj + dictoffset) emit_load64_mem(Dst, arg1_idx, arg2_idx, sa->type_tp_dictoffset); emit_cmp64_imm(Dst, arg1_idx, 0); | branch_eq >1 // dict->ma_values == 0 emit_cmp64_mem_imm(Dst, arg1_idx, offsetof(PyDictObject, ma_values), 0 /* =value */); | branch_eq >1 // fail if dict->ma_values == NULL // _PyDict_GetDictKeyVersionFromSplitDict: // arg5 = arg1->ma_keys emit_load64_mem(Dst, arg5_idx, arg1_idx, offsetof(PyDictObject, ma_keys)); emit_cmp64_mem_imm(Dst, arg5_idx, offsetof(PyDictKeysObject, dk_version_tag), (uint64_t)sa->u.split_dict_cache.splitdict_keys_version); | branch_ne >1 if (ref_status[0] == OWNED) { // dummy we need to to decref this but it's not an arg of SetItemSplitDict // so just but in it in a unused arg so that emit_call_decref_args2 can decref it. | mov arg5, arg2 } emit_mov_imm2(Dst, arg2_idx, (void*)sa->u.split_dict_cache.splitdict_index, arg4_idx, PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_decref_args2(Dst, setItemSplitDictCache, arg5_idx, arg3_idx, ref_status); emit_if_res_32b_not_0_error(Dst); } else { // arg1 = (obj + dictoffset) emit_add_or_sub_imm(Dst, arg1_idx, arg2_idx, sa->type_tp_dictoffset); // *arg1 == 0 emit_cmp64_mem_imm(Dst, arg1_idx, 0 /* offset */, 0 /* value */); | branch_ne >1 //PyDictKeysObject* keys = ((PyHeapTypeObject*)tp)->ht_cached_keys; emit_load64_mem(Dst, arg4_idx, arg2_idx, offsetof(PyObject, ob_type)); emit_load64_mem(Dst, arg4_idx, arg4_idx, offsetof(PyHeapTypeObject, ht_cached_keys)); emit_cmp64_imm(Dst, arg4_idx, 0); | branch_eq >1 //if (_PyDict_GetDictKeyVersionFromKeys((PyObject*)keys) != sa->u.split_dict_cache.splitdict_keys_version) emit_cmp64_mem_imm(Dst, arg4_idx, offsetof(PyDictKeysObject, dk_version_tag), (uint64_t)sa->u.split_dict_cache.splitdict_keys_version); | branch_ne >1 emit_mov_imm2(Dst, arg4_idx, (void*)sa->u.split_dict_cache.splitdict_index, arg5_idx, PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_decref_args2(Dst, setItemInitSplitDictCache, arg2_idx, arg3_idx, ref_status); emit_if_res_32b_not_0_error(Dst); } #endif } if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_store_attr_hit, 1 /*=can use tmp_reg*/); } |5: // fallthrough to next opcode // slowpath { switch_section(Dst, SECTION_COLD); |1: if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_store_attr_miss, 1 /*=can use tmp_reg*/); } // slow path expects owned objects emit_make_owned(Dst, arg2_idx, ref_status[0]); emit_make_owned(Dst, arg3_idx, ref_status[1]); emit_mov_imm2(Dst, arg1_idx, PyTuple_GET_ITEM(Dst->co_names, oparg), arg4_idx, co_opcache); emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, co_opcache != 0 /*= use op cache */)); emit_if_res_0_error(Dst); | branch <5 // jump to the common code which pushes the result switch_section(Dst, SECTION_CODE); } return 0; } } return 1; } static void emit_instr_start(Jit* Dst, int inst_idx, int opcode, int oparg) { // The interpreter will only generate a trace line for the first bytecode of line number in the source file. // This means that if tracing gets enabled in the middle of a sequence of bytecodes it skips until the start // of the next line. // Because we don't generate trace checks for some bytecodes we have to manually check // if a tracing check is the first for a specific line number even though it may not be the first bytecode // for this line. // In case it's the first check for a specific line we will overwrite the logic in the interpreter on deopt and // force writing out the line trace. int current_line_number = PyCode_Addr2Line(Dst->co, inst_idx * 2); if (current_line_number != Dst->old_line_number) Dst->emitted_trace_check_for_line = 0; Dst->old_line_number = current_line_number; // we don't emit signal and tracing checks for this opcodes // because we know they are not calling into any python function. switch (opcode) { #if ENABLE_AVOID_SIG_TRACE_CHECK case NOP: case EXTENDED_ARG: case ROT_TWO: case ROT_THREE: case ROT_FOUR: case POP_TOP: case DUP_TOP: case DUP_TOP_TWO: case LOAD_CLOSURE: case LOAD_CONST: return; case LOAD_FAST: #if ENABLE_DEFINED_TRACKING if (Dst->known_defined[oparg]) return; // don't do a sig check if we know the load can't throw #endif break; case STORE_FAST: // only avoid check if we already generated one for the current line. if (Dst->emitted_trace_check_for_line) return; break; #endif // ENABLE_AVOID_SIG_TRACE_CHECK } // WARNING: if you adjust anything here check if you have to adjust jmp_to_inst_idx // set opcode pointer. we do it before checking for signals to make deopt easier emit_update_f_lasti(Dst, inst_idx*2); if (Dst->failed) return; // if the current opcode has an EXTENDED_ARG prefix (or more of them - not sure if possible but we handle it here) // we need to modify f_lasti in case of deopt. // Otherwise the interpreter would skip the EXTENDED_ARG opcodes and would end up generating a completely // wrong oparg. int num_extended_arg = 0; #if ENABLE_AVOID_SIG_TRACE_CHECK for (int prev_inst_idx = inst_idx-1; prev_inst_idx >= 0 && _Py_OPCODE(Dst->first_instr[prev_inst_idx]) == EXTENDED_ARG; --prev_inst_idx) ++num_extended_arg; #endif // generate the signal and tracing checks switch (opcode) { // cpython does not do signal checks for the following opcodes // so only generate a trace check for this else test_generators.py will fail case SETUP_FINALLY: case SETUP_WITH: case BEFORE_ASYNC_WITH: case YIELD_FROM: // compares ceval->tracing_possible == 0 (32bit) emit_tracing_possible_check(Dst); // if we deferred stack operations we have to emit a special deopt path if (Dst->deferred_vs_next || num_extended_arg) { | branch_ne >1 switch_section(Dst, SECTION_DEOPT); |1: deferred_vs_emit(Dst); // adjust f_lasti to point to the first EXTENDED_ARG if (num_extended_arg) { emit_update_f_lasti(Dst, (inst_idx-num_extended_arg) *2); } if (!Dst->emitted_trace_check_for_line) { | branch ->deopt_return_new_line } else { | branch ->deopt_return } switch_section(Dst, SECTION_CODE); } else { if (!Dst->emitted_trace_check_for_line) { | branch_ne ->deopt_return_new_line } else { | branch_ne ->deopt_return } } break; default: { _Static_assert(offsetof(struct _ceval_runtime_state, tracing_possible) == 4, "cmp need to be modified"); _Static_assert(offsetof(struct _ceval_runtime_state, eval_breaker) == 8, "cmp need to be modified"); // compares ceval->tracing_possible == 0 and eval_breaker == 0 in one (64bit) emit_tracing_possible_and_eval_breaker_check(Dst); // if we deferred stack operations we have to emit a special deopt path if (Dst->deferred_vs_next || num_extended_arg) { | branch_ne >1 switch_section(Dst, SECTION_DEOPT); |1: // compares ceval->tracing_possible == 0 (32bit) emit_tracing_possible_check(Dst); if (Dst->deferred_vs_res_used) { | branch_eq ->handle_signal_res_in_use } else { | branch_eq ->handle_signal_res_not_in_use } deferred_vs_emit(Dst); // adjust f_lasti to point to the first EXTENDED_ARG if (num_extended_arg) { emit_update_f_lasti(Dst, (inst_idx-num_extended_arg) *2); } if (!Dst->emitted_trace_check_for_line) { | branch ->deopt_return_new_line } else { | branch ->deopt_return } switch_section(Dst, SECTION_CODE); } else { if (!Dst->emitted_trace_check_for_line) { | branch_ne ->handle_tracing_or_signal_no_deferred_stack_new_line } else { | branch_ne ->handle_tracing_or_signal_no_deferred_stack } } break; } } Dst->emitted_trace_check_for_line = 1; } |.globals lbl_ |.actionlist bf_actions #if JIT_DEBUG __attribute__((optimize("-O0"))) // enable to make "source tools/dis_jit_gdb.py" work #endif #ifdef PYSTON_LITE void* jit_func_lite(PyCodeObject* co, PyThreadState* tstate) { #else void* jit_func(PyCodeObject* co, PyThreadState* tstate) { #endif if (mem_bytes_used_max <= mem_bytes_used) // stop emitting code we used up all memory return NULL; int success = 0; struct timespec compilation_start; if (jit_stats_enabled) clock_gettime(CLOCK_MONOTONIC, &compilation_start); // setup jit context, will get accessed from all dynasm functions via the name 'Dst' Jit jit; memset(&jit, 0, sizeof(jit)); jit.co = co; jit.co_consts = co->co_consts; jit.co_names = co->co_names; jit.current_section = -1; OpCache* opcache = jit.opcache = _PyCode_GetOpcache(co); jit.num_opcodes = PyBytes_Size(co->co_code)/sizeof(_Py_CODEUNIT); jit.first_instr = (_Py_CODEUNIT *)PyBytes_AS_STRING(co->co_code); Jit* Dst = &jit; dasm_init(Dst, DASM_MAXSECTION); void* labels[lbl__MAX]; dasm_setupglobal(Dst, labels, lbl__MAX); dasm_setup(Dst, bf_actions); // allocate enough space for emitting a dynamic label for the start of every bytecode dasm_growpc(Dst, Dst->num_opcodes + 1); // we emit the opcode implementations first and afterwards the entry point of the function because // we don't know how much stack it will use etc.. switch_section(Dst, SECTION_CODE); jit.is_jmp_target = calculate_jmp_targets(Dst); #if ENABLE_DEFINED_TRACKING jit.known_defined = (char*)malloc(co->co_nlocals); const int funcs_args_are_always_defined = check_func_args_never_deleted(Dst); #endif // did we emit the * label already? int end_finally_label = 0; int exit_yielding_label = 0; int deref_error_label = 0; int exception_unwind_label_used = 0; int exit_yielding_label_used = 0; Dst->old_line_number = -1; Dst->emitted_trace_check_for_line = 0; // this is used for the special EXTENDED_ARG opcode int oldoparg = 0; for (int inst_idx = 0; inst_idx < Dst->num_opcodes && !Dst->failed; ++inst_idx) { _Py_CODEUNIT word = Dst->first_instr[inst_idx]; int opcode = _Py_OPCODE(word); int oparg = _Py_OPARG(word); // this is used for the special EXTENDED_ARG opcode oparg |= oldoparg; oldoparg = 0; // if an instruction can jump to this one we need to make sure the deferred stack is clear if (Dst->is_jmp_target[inst_idx]) { deferred_vs_apply(Dst); } #if ENABLE_DEFINED_TRACKING // if we can jump to this opcode or it's the first in the function // we reset the definedness info. if ((inst_idx == 0 || Dst->is_jmp_target[inst_idx])) { memset(Dst->known_defined, 0, co->co_nlocals); for (int i=0; funcs_args_are_always_defined && i<co->co_argcount; ++i) { Dst->known_defined[i] = 1; // function arg is defined } } #endif // set jump target for current inst index // we can later jump here via =>oparg etc.. // also used for the opcode_addr table |=>inst_idx: // emits f->f_lasti update, signal and trace check emit_instr_start(Dst, inst_idx, opcode, oparg); if (Dst->failed) goto failed; switch(opcode) { case NOP: break; case EXTENDED_ARG: oldoparg = oparg << 8; break; case JUMP_ABSOLUTE: deferred_vs_apply(Dst); emit_jump_to_bytecode_n(Dst, oparg); break; case JUMP_FORWARD: deferred_vs_apply(Dst); emit_jump_by_n_bytecodes(Dst, oparg, inst_idx); break; case LOAD_FAST: { int known_defined = 0; #if ENABLE_DEFINED_TRACKING known_defined = Dst->known_defined[oparg]; #endif if (!known_defined /* can be null */) { emit_cmp64_mem_imm(Dst, f_idx, get_fastlocal_offset(oparg), 0 /* = value */); | branch_eq >1 switch_section(Dst, SECTION_COLD); |1: emit_mov_imm(Dst, arg1_idx, oparg); // need to copy it in arg1 because of unboundlocal_error | branch ->unboundlocal_error // arg1 must be oparg! switch_section(Dst, SECTION_CODE); #if ENABLE_DEFINED_TRACKING Dst->known_defined[oparg] = 1; #endif } deferred_vs_push(Dst, FAST, oparg); break; } case LOAD_CONST: deferred_vs_push(Dst, CONST, (unsigned long)PyTuple_GET_ITEM(Dst->co_consts, oparg)); break; case STORE_FAST: { int new_value_reg = deferred_vs_pop1_anyreg_owned(Dst, arg2_idx); JIT_ASSERT(new_value_reg != arg1_idx, ""); deferred_vs_apply_if_same_var(Dst, oparg); emit_load64_mem(Dst, arg1_idx, f_idx, get_fastlocal_offset(oparg)); emit_store64_mem(Dst, new_value_reg, f_idx, get_fastlocal_offset(oparg)); int known_defined = 0; #if ENABLE_DEFINED_TRACKING known_defined = Dst->known_defined[oparg]; #endif if (known_defined) { emit_decref(Dst, arg1_idx, 0 /* don't preserve res */); } else { emit_xdecref(Dst, arg1_idx); } #if ENABLE_DEFINED_TRACKING Dst->known_defined[oparg] = 1; #endif break; } case DELETE_FAST: { deferred_vs_apply_if_same_var(Dst, oparg); emit_load64_mem(Dst, arg2_idx, f_idx, get_fastlocal_offset(oparg)); int known_defined = 0; #if ENABLE_DEFINED_TRACKING known_defined = Dst->known_defined[oparg]; #endif if (!known_defined /* can be null */) { emit_cmp64_imm(Dst, arg2_idx, 0); | branch_eq >1 switch_section(Dst, SECTION_COLD); |1: emit_mov_imm(Dst, arg1_idx, oparg); | branch ->unboundlocal_error // arg1 must be oparg! switch_section(Dst, SECTION_CODE); } emit_store64_mem_imm(Dst, 0 /*= value */, f_idx, get_fastlocal_offset(oparg)); emit_decref(Dst, arg2_idx, 0 /*= don't preserve res */); #if ENABLE_DEFINED_TRACKING Dst->known_defined[oparg] = 0; #endif break; } case POP_TOP: { RegAndStatus reg_and_status = deferred_vs_pop1_anyreg(Dst, arg1_idx, 1 /* only_if_owned */); if (reg_and_status.ref_status == OWNED) { emit_decref(Dst, reg_and_status.reg_idx, Dst->deferred_vs_res_used /*= preserve res */); } break; } case ROT_TWO: if (Dst->deferred_vs_next >= 2) { DeferredValueStackEntry tmp[2]; memcpy(tmp, &GET_DEFERRED[-2], sizeof(tmp)); GET_DEFERRED[-1] = tmp[0]; GET_DEFERRED[-2] = tmp[1]; } else { deferred_vs_apply(Dst); emit_read_vs(Dst, arg1_idx, 1 /*=top*/); emit_read_vs(Dst, res_idx, 2 /*=second*/); emit_write_vs(Dst, arg1_idx, 2 /*=second*/); emit_write_vs(Dst, res_idx, 1 /*=top*/); } break; case ROT_THREE: if (Dst->deferred_vs_next >= 3) { DeferredValueStackEntry tmp[3]; memcpy(tmp, &GET_DEFERRED[-3], sizeof(tmp)); GET_DEFERRED[-1] = tmp[1]; GET_DEFERRED[-2] = tmp[0]; GET_DEFERRED[-3] = tmp[2]; } else { deferred_vs_apply(Dst); emit_read_vs(Dst, arg1_idx, 1 /*=top*/); emit_read_vs(Dst, res_idx, 2 /*=second*/); emit_read_vs(Dst, arg3_idx, 3 /*=third*/); emit_write_vs(Dst, arg3_idx, 2 /*=second*/); emit_write_vs(Dst, arg1_idx, 3 /*=third*/); emit_write_vs(Dst, res_idx, 1 /*=top*/); } break; case ROT_FOUR: if (Dst->deferred_vs_next >= 4) { DeferredValueStackEntry tmp[4]; memcpy(tmp, &GET_DEFERRED[-4], sizeof(tmp)); GET_DEFERRED[-1] = tmp[2]; GET_DEFERRED[-2] = tmp[1]; GET_DEFERRED[-3] = tmp[0]; GET_DEFERRED[-4] = tmp[3]; } else { deferred_vs_apply(Dst); emit_read_vs(Dst, arg1_idx, 1 /*=top*/); emit_read_vs(Dst, res_idx, 2 /*=second*/); emit_read_vs(Dst, arg3_idx, 3 /*=third*/); emit_read_vs(Dst, arg4_idx, 4 /*=fourth*/); emit_write_vs(Dst, arg3_idx, 2 /*=second*/); emit_write_vs(Dst, arg4_idx, 3 /*=third*/); emit_write_vs(Dst, arg1_idx, 4 /*=fourth*/); emit_write_vs(Dst, res_idx, 1 /*=top*/); } break; case DUP_TOP: if (Dst->deferred_vs_next >= 1 && Dst->deferred_vs_next + 1 < DEFERRED_VS_MAX && (GET_DEFERRED[-1].loc == CONST || GET_DEFERRED[-1].loc == FAST)) { GET_DEFERRED[0] = GET_DEFERRED[-1]; Dst->deferred_vs_next += 1; } else { deferred_vs_apply(Dst); emit_read_vs(Dst, res_idx, 1 /*=top*/); emit_incref(Dst, res_idx); deferred_vs_push(Dst, REGISTER, res_idx); } break; case DUP_TOP_TWO: if (Dst->deferred_vs_next >= 2 && Dst->deferred_vs_next + 2 < DEFERRED_VS_MAX && (GET_DEFERRED[-1].loc == CONST || GET_DEFERRED[-1].loc == FAST) && (GET_DEFERRED[-2].loc == CONST || GET_DEFERRED[-2].loc == FAST)) { GET_DEFERRED[0] = GET_DEFERRED[-2]; GET_DEFERRED[1] = GET_DEFERRED[-1]; Dst->deferred_vs_next += 2; } else { deferred_vs_apply(Dst); emit_read_vs(Dst, arg1_idx, 1 /*=top*/); emit_read_vs(Dst, arg2_idx, 2 /*=second*/); emit_incref(Dst, arg1_idx); emit_incref(Dst, arg2_idx); emit_adjust_vs(Dst, 2); emit_write_vs(Dst, arg1_idx, 1 /*=top*/); emit_write_vs(Dst, arg2_idx, 2 /*=second*/); } break; case RETURN_VALUE: deferred_vs_pop1_owned(Dst, res_idx); deferred_vs_apply(Dst); @ARM | mov real_res, res | branch ->return break; case BINARY_MULTIPLY: case BINARY_MATRIX_MULTIPLY: case BINARY_TRUE_DIVIDE: case BINARY_FLOOR_DIVIDE: case BINARY_MODULO: // TODO: add special handling like in the interp case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_LSHIFT: case BINARY_RSHIFT: case BINARY_AND: case BINARY_XOR: case BINARY_OR: case BINARY_POWER: case INPLACE_MULTIPLY: case INPLACE_MATRIX_MULTIPLY: case INPLACE_TRUE_DIVIDE: case INPLACE_FLOOR_DIVIDE: case INPLACE_MODULO: case INPLACE_ADD: case INPLACE_SUBTRACT: case INPLACE_LSHIFT: case INPLACE_RSHIFT: case INPLACE_AND: case INPLACE_XOR: case INPLACE_OR: case INPLACE_POWER: case COMPARE_OP: case BINARY_SUBSCR: { RefStatus ref_status[2]; // if the left operand is coming from a local variable (LOAD_FAST) // and is replaced by the result of the opcode (STORE_FAST) we store the index of the // fast variable else it's -1 int load_store_left_idx = -1; if (Dst->deferred_vs_next >= 2 && GET_DEFERRED[-2].loc == FAST && inst_idx + 1 < Dst->num_opcodes) { _Py_CODEUNIT next_word = Dst->first_instr[inst_idx + 1]; int next_opcode = _Py_OPCODE(next_word); int next_oparg = _Py_OPARG(next_word); if (next_opcode == STORE_FAST && next_oparg == (int)GET_DEFERRED[-2].val && !Dst->is_jmp_target[inst_idx + 1]) { load_store_left_idx = next_oparg; } } PyObject* const_val = deferred_vs_peek_const(Dst); deferred_vs_pop2(Dst, arg2_idx, arg1_idx, ref_status); deferred_vs_convert_reg_to_stack(Dst); if (opcode == BINARY_SUBSCR && emit_special_binary_subscr(Dst, inst_idx, const_val, ref_status) == 0) { break; // we are finished } if (opcode == COMPARE_OP && emit_special_compare_op(Dst, oparg, ref_status) == 0) { break; // we are finished } if (emit_special_binary_op_inplace(Dst, inst_idx, opcode, oparg, ref_status[1], ref_status[0], load_store_left_idx, const_val) == 0) { break; // we are finished } if (emit_special_concat_inplace(Dst, inst_idx, opcode, oparg, ref_status[1], ref_status[0], load_store_left_idx, const_val) == 0) { break; // we are finished } // generic path |1: void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); emit_call_decref_args2(Dst, func, arg2_idx, arg1_idx, ref_status); emit_if_res_0_error(Dst); deferred_vs_push(Dst, REGISTER, res_idx); break; } case POP_JUMP_IF_FALSE: { RefStatus ref_status = deferred_vs_pop1(Dst, arg1_idx); deferred_vs_apply(Dst); emit_jump_if_false(Dst, oparg, ref_status); break; } case POP_JUMP_IF_TRUE: { RefStatus ref_status = deferred_vs_pop1(Dst, arg1_idx); deferred_vs_apply(Dst); emit_jump_if_true(Dst, oparg, ref_status); break; } case JUMP_IF_FALSE_OR_POP: deferred_vs_peek_top_and_apply(Dst, arg1_idx); emit_jump_if_false(Dst, oparg, BORROWED); emit_pop_v(Dst, arg1_idx); emit_decref(Dst, arg1_idx, 0 /*= don't preserve res */); break; case JUMP_IF_TRUE_OR_POP: deferred_vs_peek_top_and_apply(Dst, arg1_idx); emit_jump_if_true(Dst, oparg, BORROWED); emit_pop_v(Dst, arg1_idx); emit_decref(Dst, arg1_idx, 0 /*= don't preserve res */); break; case CALL_FUNCTION: case CALL_FUNCTION_KW: case CALL_METHOD: if (opcode == CALL_FUNCTION_KW) { deferred_vs_pop1_owned(Dst, arg4_idx); } deferred_vs_apply(Dst); char wrote_inline_cache = 0; if (opcode == CALL_METHOD) { ++jit_stat_call_method_total; CallMethodHint* hint = Dst->call_method_hints; // For proper bytecode there should be exactly // one hint per hint-usage, but check for the existence // of the hint just in case: if (hint) Dst->call_method_hints = hint->next; if (hint && hint->attr && hint->meth_found && jit_use_ics) { int num_args = oparg + hint->meth_found; // number of arguments to the function, including a potential "self" int num_vs_args = num_args + 1; // number of python values; one more than the number of arguments since it includes the callable if (hint->attr->ob_type == &PyMethodDescr_Type) { PyMethodDescrObject* method = (PyMethodDescrObject*)hint->attr; void* funcptr = method->d_method->ml_meth; if (funcptr && _PyObject_RealIsSubclass((PyObject*)hint->type, (PyObject *)PyDescr_TYPE(method))) { wrote_inline_cache = 1; // Strategy: // First guard on tstate->use_tracing == 0 // It looks like we have to guard on this variable, even though we already // guarded on ceval->tracing_possible, because it looks like a profile // function will set use_tracing but not tracing_possible // // Then guard that meth != NULL. // We need this to verify that the object in the "self" stack slot // is actually the self object and not a non-method attribute. // // Then guard that self->ob_type == hint->type // // We skip the recursion check since we know we did one when // entering this python frame. ++jit_stat_call_method_inline; JIT_ASSERT(sizeof(tstate->use_tracing) == 4, ""); emit_cmp32_mem_imm(Dst, tstate_idx, offsetof(PyThreadState, use_tracing), 0); | branch_ne >1 if (!hint->is_self_const) { emit_cmp64_mem_imm(Dst, vsp_idx, -8 * num_vs_args, 0); // callable | branch_eq >1 } emit_load64_mem(Dst, arg1_idx, vsp_idx, -8 * num_args); // self if (!hint->is_self_const) { | type_check arg1_idx, hint->type, >1 } if (method->vectorcall == method_vectorcall_NOARGS && num_args == 1) { emit_call_ext_func(Dst, funcptr); } else if (method->vectorcall == method_vectorcall_O && num_args == 2) { // first python arg emit_load64_mem(Dst, arg2_idx, vsp_idx, -8 * num_args + 8); emit_call_ext_func(Dst, funcptr); } else if (method->vectorcall == method_vectorcall_FASTCALL || method->vectorcall == method_vectorcall_FASTCALL_KEYWORDS) { emit_add_or_sub_imm(Dst, arg2_idx, vsp_idx, -8 * num_args + 8); emit_mov_imm(Dst, arg3_idx, num_args - 1); if (method->vectorcall == method_vectorcall_FASTCALL_KEYWORDS) emit_mov_imm(Dst, arg4_idx, 0); // kwnames emit_call_ext_func(Dst, funcptr); } else if (method->vectorcall == method_vectorcall_VARARGS || method->vectorcall == method_vectorcall_VARARGS_KEYWORDS) { // Convert stack to tuple: emit_add_or_sub_imm(Dst, arg1_idx, vsp_idx, -8 * num_args + 8); emit_mov_imm(Dst, arg2_idx, num_args - 1); #ifdef PYSTON_LITE emit_call_ext_func(Dst, _PyTuple_FromArray); #else emit_call_ext_func(Dst, _PyTuple_FromArray_Borrowed); #endif emit_if_res_0_error(Dst); | mov tmp_preserved_reg, res emit_load64_mem(Dst, arg1_idx, vsp_idx, -8 * num_args); // self | mov arg2, res // args if (method->vectorcall == method_vectorcall_VARARGS_KEYWORDS) emit_mov_imm(Dst, arg3_idx, 0); // kwargs emit_call_ext_func(Dst, funcptr); | mov arg1, tmp_preserved_reg | mov tmp_preserved_reg, res #ifdef PYSTON_LITE emit_decref(Dst, arg1_idx, 0); #else emit_call_ext_func(Dst, _PyTuple_Decref_Borrowed); #endif | mov res, tmp_preserved_reg } else { // We assume that all cases are handled, that we don't need to keep track // of whether we were able to generate an IC or not. abort(); } int num_decrefs = num_vs_args; if (IS_IMMORTAL(hint->attr)) num_decrefs--; // Inlining the decrefs into the jitted code seems to help in some cases and hurt in others. // For now use the heuristic that we'll inline a small // number of decrefs into the jitted code. // This could use more research. int do_inline_decrefs = num_decrefs < 3; if (!do_inline_decrefs) { | mov tmp_preserved_reg, res | mov arg1, vsp if (num_decrefs == 3) { emit_call_ext_func(Dst, decref_array3); } else if (num_decrefs == 4) { emit_call_ext_func(Dst, decref_array4); } else { emit_mov_imm(Dst, arg2_idx, num_decrefs); emit_call_ext_func(Dst, decref_array); } | mov res, tmp_preserved_reg } else { for (int i = 0; i < num_decrefs; i++) { emit_load64_mem(Dst, arg1_idx, vsp_idx, -(i + 1) * 8); emit_decref(Dst, arg1_idx, 1 /* preserve res */); } } emit_adjust_vs(Dst, -num_vs_args); if (jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_call_method_hit, 1 /*=can use tmp_reg*/); } emit_if_res_0_error(Dst); } } } if (hint) free(hint); } if (wrote_inline_cache) switch_section(Dst, SECTION_COLD); |1: if (wrote_inline_cache && jit_stats_enabled) { emit_inc_qword_ptr(Dst, &jit_stat_call_method_miss, 1 /*=can use tmp_reg*/); } | mov arg1, tstate // arg2 = vsp | mov arg2, vsp emit_mov_imm(Dst, arg3_idx, oparg); int num_vs_args = oparg + 1; if (opcode == CALL_METHOD) { num_vs_args += 1; @ARM emit_cmp64_mem_imm(Dst, vsp_idx, -8*num_vs_args, 0 /* = value */); @ARM | cinc arg3, arg3, ne @X86 // this is taken from clang: @X86 // meth = PEEK(oparg + 2); @X86 // arg3 = ((meth == 0) ? 0 : 1) + oparg @X86 | cmp qword [vsp - (8*num_vs_args)], 1 @X86 | sbb arg3, -1 } emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */)); emit_adjust_vs(Dst, -num_vs_args); emit_if_res_0_error(Dst); if (wrote_inline_cache) { | branch >2 switch_section(Dst, SECTION_CODE); |2: } deferred_vs_push(Dst, REGISTER, res_idx); break; case FOR_ITER: deferred_vs_peek_top_and_apply(Dst, arg1_idx); emit_load64_mem(Dst, tmp_idx, arg1_idx, offsetof(PyObject, ob_type)); @ARM | ldr tmp, [tmp, #offsetof(PyTypeObject, tp_iternext)] @ARM | blr tmp @ARM | mov res, real_res @X86 | call qword [tmp + offsetof(PyTypeObject, tp_iternext)] emit_cmp64_imm(Dst, res_idx, 0); | branch_eq >1 switch_section(Dst, SECTION_COLD); |1: emit_call_ext_func(Dst, JIT_HELPER_FOR_ITER_SECOND_PART); emit_if_res_0_error(Dst); emit_jump_by_n_bytecodes(Dst, oparg, inst_idx); switch_section(Dst, SECTION_CODE); deferred_vs_push(Dst, REGISTER, res_idx); break; case UNARY_POSITIVE: case UNARY_NEGATIVE: case UNARY_NOT: case UNARY_INVERT: case GET_ITER: { RefStatus ref_status = deferred_vs_pop1(Dst, arg1_idx); deferred_vs_convert_reg_to_stack(Dst); void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); emit_call_decref_args1(Dst, func, arg1_idx, &ref_status); if (opcode == UNARY_NOT) { @ARM emit_mov_imm2(Dst, arg3_idx, Py_True, arg4_idx, Py_False); @ARM emit_cmp32_imm(Dst, res_idx, 0); // 32bit comparison! @ARM | branch_lt ->error // < 0, means error @ARM | csel res, arg3, arg4, eq @X86 | mov Rd(arg1_idx), Rd(res_idx) // save result for comparison @X86 emit_mov_imm2(Dst, res_idx, Py_True, tmp_idx, Py_False); @X86 emit_cmp32_imm(Dst, arg1_idx, 0); // 32bit comparison! @X86 | branch_lt ->error // < 0, means error @X86 | cmovne Rq(res_idx), Rq(tmp_idx) // don't need to incref Py_True/Py_False are immortals } else { emit_if_res_0_error(Dst); } deferred_vs_push(Dst, REGISTER, res_idx); break; } case STORE_SUBSCR: if (Dst->deferred_vs_next >= 3) { RefStatus ref_status[3]; PyObject* const_val = deferred_vs_peek_const(Dst); deferred_vs_pop3(Dst, arg2_idx, arg1_idx, arg3_idx, ref_status); deferred_vs_convert_reg_to_stack(Dst); if (emit_special_store_subscr(Dst, inst_idx, opcode, oparg, const_val, ref_status)<0) { void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); emit_call_decref_args3(Dst, func, arg2_idx, arg1_idx, arg3_idx, ref_status); emit_if_res_32b_not_0_error(Dst); } } else { deferred_vs_apply(Dst); emit_read_vs(Dst, arg2_idx, 1 /*=top*/); emit_read_vs(Dst, arg1_idx, 2 /*=second*/); emit_read_vs(Dst, arg3_idx, 3 /*=third*/); emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */)); emit_if_res_32b_not_0_error(Dst); for (int i=0; i<3; ++i) { emit_read_vs(Dst, arg1_idx, i+1); emit_decref(Dst, arg1_idx, 0 /*= don't preserve res */); } emit_adjust_vs(Dst, -3); } break; case DELETE_SUBSCR: { RefStatus ref_status[2]; deferred_vs_pop2(Dst, arg2_idx, arg1_idx, ref_status); deferred_vs_convert_reg_to_stack(Dst); void* func = get_aot_func_addr(Dst, opcode, oparg, 0 /*= no op cache */); emit_call_decref_args2(Dst, func, arg2_idx, arg1_idx, ref_status); emit_if_res_32b_not_0_error(Dst); break; } case CALL_FINALLY: deferred_vs_apply(Dst); // todo: handle during bytecode generation, // this could be normal code object constant entry emit_mov_imm(Dst, arg1_idx, (inst_idx+1) * 2); emit_call_ext_func(Dst, PyLong_FromLong); emit_if_res_0_error(Dst); emit_push_v(Dst, res_idx); emit_jump_by_n_bytecodes(Dst, oparg, inst_idx); break; case END_FINALLY: { RefStatus ref_status = OWNED; deferred_vs_pop1_owned(Dst, arg1_idx); deferred_vs_apply(Dst); emit_cmp64_imm(Dst, arg1_idx, 0); | branch_ne ->end_finally if (!end_finally_label) { end_finally_label = 1; switch_section(Dst, SECTION_COLD); |->end_finally: | type_check arg1_idx, &PyLong_Type, >2 // inside CALL_FINALLY we created a long with the bytecode offset to the next instruction // extract it and jump to it emit_call_decref_args1(Dst, PyLong_AsLong, arg1_idx, &ref_status); emit_jmp_to_inst_idx(Dst, res_idx); |2: | mov arg2, arg1 | mov arg1, tstate emit_read_vs(Dst, arg3_idx, 1 /*=top*/); emit_read_vs(Dst, arg4_idx, 2 /*=second*/); emit_adjust_vs(Dst, -2); emit_call_ext_func(Dst, _PyErr_Restore); | branch ->exception_unwind exception_unwind_label_used = 1; switch_section(Dst, SECTION_CODE); } break; } case SET_ADD: case LIST_APPEND: { RefStatus ref_status = deferred_vs_pop1(Dst, arg2_idx); deferred_vs_peek(Dst, arg1_idx, oparg); deferred_vs_convert_reg_to_stack(Dst); void* func = opcode == SET_ADD ? PySet_Add : PyList_Append; emit_call_decref_args1(Dst, func, arg2_idx, &ref_status); emit_if_res_32b_not_0_error(Dst); break; } case MAP_ADD: { RefStatus ref_status[2]; deferred_vs_pop2(Dst, arg3_idx, arg2_idx, ref_status); deferred_vs_peek(Dst, arg1_idx, oparg); deferred_vs_convert_reg_to_stack(Dst); emit_call_decref_args2(Dst, PyDict_SetItem, arg3_idx, arg2_idx, ref_status); emit_if_res_32b_not_0_error(Dst); break; } case IMPORT_NAME: { RefStatus ref_status[2]; deferred_vs_pop2(Dst, arg4_idx, arg5_idx, ref_status); deferred_vs_convert_reg_to_stack(Dst); | mov arg1, tstate | mov arg2, f emit_mov_imm(Dst, arg3_idx, (unsigned long)PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_decref_args2(Dst, import_name, arg4_idx, arg5_idx, ref_status); emit_if_res_0_error(Dst); deferred_vs_push(Dst, REGISTER, res_idx); break; } case IMPORT_FROM: deferred_vs_peek(Dst, arg2_idx, 1); deferred_vs_convert_reg_to_stack(Dst); | mov arg1, tstate emit_mov_imm(Dst, arg3_idx, (unsigned long)PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_ext_func(Dst, import_from); emit_if_res_0_error(Dst); deferred_vs_push(Dst, REGISTER, res_idx); break; case DELETE_ATTR: { RefStatus ref_status = deferred_vs_pop1(Dst, arg1_idx); deferred_vs_convert_reg_to_stack(Dst); emit_mov_imm(Dst, arg2_idx, (unsigned long)PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_mov_imm(Dst, arg3_idx, 0); emit_call_decref_args1(Dst, PyObject_SetAttr, arg1_idx, &ref_status); emit_if_res_32b_not_0_error(Dst); break; } case STORE_GLOBAL: { RefStatus ref_status = deferred_vs_pop1(Dst, arg3_idx); deferred_vs_convert_reg_to_stack(Dst); emit_load64_mem(Dst, arg1_idx, f_idx, offsetof(PyFrameObject, f_globals)); emit_mov_imm(Dst, arg2_idx, (unsigned long)PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_decref_args1(Dst, PyDict_SetItem, arg3_idx, &ref_status); emit_if_res_32b_not_0_error(Dst); break; } case BUILD_SLICE: if (oparg == 3) { deferred_vs_pop3_owned(Dst, arg3_idx, arg2_idx, arg1_idx); } else { emit_mov_imm(Dst, arg3_idx, (uint64_t)Py_None); if (!IS_IMMORTAL(Py_None)) { emit_incref(Dst, arg3_idx); } deferred_vs_pop2_owned(Dst, arg2_idx, arg1_idx); } deferred_vs_convert_reg_to_stack(Dst); emit_call_ext_func(Dst, PySlice_NewSteal); emit_if_res_0_error(Dst); deferred_vs_push(Dst, REGISTER, res_idx); break; case BUILD_TUPLE: // empty tuple optimization if (oparg == 0) { // todo: handle during bytecode generation PyObject* empty_tuple = PyTuple_New(0); deferred_vs_push(Dst, CONST, (unsigned long)empty_tuple); Py_DECREF(empty_tuple); break; } __attribute__ ((fallthrough)); case BUILD_LIST: deferred_vs_convert_reg_to_stack(Dst); emit_mov_imm(Dst, arg1_idx, oparg); #ifdef PYSTON_LITE emit_call_ext_func(Dst, opcode == BUILD_LIST ? PyList_New : PyTuple_New); #else emit_call_ext_func(Dst, opcode == BUILD_LIST ? PyList_New : PyTuple_New_Nonzeroed); #endif emit_if_res_0_error(Dst); if (oparg) { // PyTupleObject stores the elements directly inside the object // while PyListObject has ob_item which points to an array of elements to support resizing. if (opcode == BUILD_LIST) { emit_load64_mem(Dst, arg2_idx, res_idx, offsetof(PyListObject, ob_item)); } int i = oparg; while (--i >= 0) { deferred_vs_peek_owned(Dst, arg1_idx, (oparg - i)); if (opcode == BUILD_LIST) { emit_store64_mem(Dst, arg1_idx, arg2_idx, 8*i); } else { emit_store64_mem(Dst, arg1_idx, res_idx, offsetof(PyTupleObject, ob_item) + 8*i); } } deferred_vs_remove(Dst, oparg); } deferred_vs_push(Dst, REGISTER, res_idx); break; case LOAD_CLOSURE: deferred_vs_convert_reg_to_stack(Dst); // PyObject *cell = freevars[oparg]; emit_load_freevar(Dst, res_idx, oparg); emit_incref(Dst, res_idx); deferred_vs_push(Dst, REGISTER, res_idx); break; case STORE_DEREF: { int new_value_reg = deferred_vs_pop1_anyreg_owned(Dst, arg2_idx); JIT_ASSERT(new_value_reg != arg1_idx && new_value_reg != arg3_idx, ""); deferred_vs_convert_reg_to_stack(Dst); // PyObject *cell = freevars[oparg]; emit_load_freevar(Dst, arg3_idx, oparg); // PyObject *oldobj = PyCell_GET(cell); emit_load64_mem(Dst, arg1_idx, arg3_idx, offsetof(PyCellObject, ob_ref)); // PyCell_SET(cell, v); emit_store64_mem(Dst, new_value_reg, arg3_idx, offsetof(PyCellObject, ob_ref)); emit_xdecref(Dst, arg1_idx); break; } case LOAD_DEREF: case DELETE_DEREF: deferred_vs_convert_reg_to_stack(Dst); // PyObject *cell = freevars[oparg]; emit_load_freevar(Dst, arg1_idx, oparg); // PyObject *value = PyCell_GET(cell); emit_load64_mem(Dst, res_idx, arg1_idx, offsetof(PyCellObject, ob_ref)); emit_cmp64_imm(Dst, res_idx, 0); | branch_eq >1 switch_section(Dst, SECTION_COLD); |1: emit_mov_imm(Dst, arg3_idx, oparg); // deref_error assumes that oparg is in arg3! if (deref_error_label) { | branch ->deref_error } else { deref_error_label = 1; |->deref_error: // assumes that oparg is in arg3! | mov arg1, tstate emit_mov_imm(Dst, arg2_idx, (unsigned long)co); emit_call_ext_func(Dst, format_exc_unbound); | branch ->error } switch_section(Dst, SECTION_CODE); if (opcode == LOAD_DEREF) { emit_incref(Dst, res_idx); deferred_vs_push(Dst, REGISTER, res_idx); } else { // DELETE_DEREF emit_store64_mem_imm(Dst, 0, arg1_idx, offsetof(PyCellObject, ob_ref)); emit_decref(Dst, res_idx, 0 /*= don't preserve res */); } break; case SETUP_FINALLY: case SETUP_ASYNC_WITH: deferred_vs_apply(Dst); // PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, STACK_LEVEL()); | mov arg1, f emit_mov_imm(Dst, arg2_idx, SETUP_FINALLY); emit_mov_imm(Dst, arg3_idx, (inst_idx + 1)*2 + oparg); // STACK_LEVEL() @ARM_START int src_idx = vsp_idx; if (opcode == SETUP_ASYNC_WITH) { | sub arg4, vsp, #8 src_idx = arg4_idx; } | ldr tmp, [f, #offsetof(PyFrameObject, f_valuestack)] | sub arg4, Rx(src_idx), tmp | asr arg4, arg4, #3 @ARM_END @X86_START if (opcode == SETUP_ASYNC_WITH) { // the interpreter pops the top value and pushes it afterwards // we instead just calculate the stack level with the vsp minus one value. | lea arg4, [vsp - 8] } else { | mov arg4, vsp } | sub arg4, [f + offsetof(PyFrameObject, f_valuestack)] | sar arg4, 3 // divide by 8 = sizeof(void*) @X86_END emit_call_ext_func(Dst, PyFrame_BlockSetup); break; case POP_BLOCK: deferred_vs_convert_reg_to_stack(Dst); | mov arg1, f emit_call_ext_func(Dst, PyFrame_BlockPop); break; case BEGIN_FINALLY: /* Push NULL onto the stack for using it in END_FINALLY, POP_FINALLY, WITH_CLEANUP_START and WITH_CLEANUP_FINISH. */ // PUSH(NULL); deferred_vs_push(Dst, CONST, 0); deferred_vs_apply(Dst); break; case YIELD_VALUE: if (co->co_flags & CO_ASYNC_GENERATOR) { RefStatus ref_status = deferred_vs_pop1(Dst, arg1_idx); deferred_vs_apply(Dst); emit_call_decref_args1(Dst, _PyAsyncGenValueWrapperNew, arg1_idx, &ref_status); emit_if_res_0_error(Dst); } else { deferred_vs_pop1_owned(Dst, res_idx); deferred_vs_apply(Dst); } emit_store64_mem(Dst, vsp_idx, f_idx, offsetof(PyFrameObject, f_stacktop)); exit_yielding_label_used = 1; if (exit_yielding_label) { | branch ->exit_yielding } else { emit_exit_yielding_label(Dst); exit_yielding_label = 1; } break; default: // compiler complains if the first line after a label is a declaration and not a statement: (void)0; _PyOpcache* co_opcache = get_opcache_entry(opcache, inst_idx); if (opcode == LOAD_METHOD) { CallMethodHint* hint = (CallMethodHint*)calloc(1, sizeof(CallMethodHint)); hint->next = Dst->call_method_hints; Dst->call_method_hints = hint; } // try emitting a IC for the operation if possible if (emit_inline_cache(Dst, opcode, oparg, co_opcache) == 0) continue; // this opcode is implemented via the helpers in aot_ceval_jit_helper.c // some take a fixed number of python values as arguments switch (opcode) { // ### ONE PYTHON ARGS ### // JIT_HELPER1 case PRINT_EXPR: case GET_AITER: case GET_AWAITABLE: case YIELD_FROM: case END_ASYNC_FOR: case UNPACK_SEQUENCE: case UNPACK_EX: case IMPORT_STAR: case GET_YIELD_FROM_ITER: // JIT_HELPER_WITH_NAME1 case STORE_NAME: // JIT_HELPER_WITH_NAME_OPCACHE_AOT1 case LOAD_ATTR: deferred_vs_pop1_owned(Dst, arg2_idx); break; // ### TWO PYTHON ARGS ### // JIT_HELPER2 case WITH_CLEANUP_FINISH: case MAKE_FUNCTION: // JIT_HELPER_WITH_NAME_OPCACHE_AOT2 case STORE_ATTR: deferred_vs_pop2_owned(Dst, arg2_idx, arg3_idx); break; // ### TWO OR THREE PYTHON ARGS ### case CALL_FUNCTION_EX: if (oparg & 1) { deferred_vs_pop3_owned(Dst, arg2_idx, arg3_idx, arg4_idx); } else { deferred_vs_pop2_owned(Dst, arg2_idx, arg3_idx); } break; // ### NO PYTHON ARGS ### default: break; } switch (opcode) { // the following opcodes don't access the python value stack (no PUSH, POP etc) // which means we don't need to create it we just have to spill the 'res' reg if it's used case PRINT_EXPR: case GET_AITER: case GET_AWAITABLE: case LOAD_BUILD_CLASS: case STORE_NAME: case DELETE_NAME: case STORE_ATTR: case DELETE_GLOBAL: case LOAD_NAME: case LOAD_GLOBAL: case LOAD_CLASSDEREF: case SETUP_ANNOTATIONS: case LOAD_ATTR: case IMPORT_STAR: case GET_YIELD_FROM_ITER: case CALL_FUNCTION_EX: deferred_vs_convert_reg_to_stack(Dst); break; default: deferred_vs_apply(Dst); } // Some opcodes just use oparg to look up the name and are implemented // with JIT_HELPER_WITH_NAME, and for those we pass the statically-resolved // name as the first arg and don't pass oparg switch (opcode) { // *_WITH_NAME: case STORE_NAME: case DELETE_NAME: case STORE_ATTR: case DELETE_GLOBAL: case LOAD_NAME: case LOAD_GLOBAL: case LOAD_ATTR: case LOAD_METHOD: emit_mov_imm(Dst, arg1_idx, (unsigned long)PyTuple_GET_ITEM(Dst->co_names, oparg)); break; // *_WITH_OPARG: case RAISE_VARARGS: case POP_FINALLY: case UNPACK_SEQUENCE: case UNPACK_EX: case LOAD_CLASSDEREF: case BUILD_STRING: case BUILD_TUPLE_UNPACK_WITH_CALL: case BUILD_TUPLE_UNPACK: case BUILD_LIST_UNPACK: case BUILD_SET: case BUILD_SET_UNPACK: case BUILD_MAP: case BUILD_CONST_KEY_MAP: case BUILD_MAP_UNPACK: case BUILD_MAP_UNPACK_WITH_CALL: case SETUP_WITH: case CALL_FUNCTION_EX: case MAKE_FUNCTION: case FORMAT_VALUE: emit_mov_imm(Dst, arg1_idx, oparg); break; default: // For all other opcodes, we don't pass anything in the first arg break; } switch (opcode) { // some of the opcodes called JIT_HELPER_WITH_NAME_OPCACHE_AOT // take a 3th arg which is a pointer to _PyOpcache* // and a 4th arg which is a pointer to the func address so it can patch itself case LOAD_METHOD: case LOAD_GLOBAL: // Often the name and opcache pointers are close to each other, // so instead of doing two 64-bit moves, we can do the second // one as a lea off the first one and save a few bytes emit_mov_imm_using_diff(Dst, arg2_idx, arg1_idx, co_opcache, PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, co_opcache != 0 /*= use op cache */)); break; case LOAD_ATTR: emit_mov_imm_using_diff(Dst, arg3_idx, arg1_idx, co_opcache, PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, co_opcache != 0 /*= use op cache */)); break; case STORE_ATTR: emit_mov_imm_using_diff(Dst, arg4_idx, arg1_idx, co_opcache, PyTuple_GET_ITEM(Dst->co_names, oparg)); emit_call_ext_func(Dst, get_aot_func_addr(Dst, opcode, oparg, co_opcache != 0 /*= use op cache */)); break; // default path which nearly all opcodes take: just generate a normal call default: emit_call_ext_func(Dst, get_addr_of_helper_func(opcode, oparg)); } // process the return value of the helper function switch (opcode) { // this opcodes don't continue to the next op but instead branch to special labels // they are tightly coupled with the C helper functions // be careful when introducing new paths / updating cpython case YIELD_FROM: // res is the PyObject* returned // res == 0 means error // res == 1 means execute next opcode (=fallthrough) // res == 2 means goto exit_yielding emit_if_res_0_error(Dst); emit_cmp64_imm(Dst, res_idx, 1); | branch_ne ->exit_yielding exit_yielding_label_used = 1; break; case RAISE_VARARGS: // res == 0 means error // res == 2 means goto exception_unwind emit_if_res_0_error(Dst); exception_unwind_label_used = 1; | branch ->exception_unwind break; case END_ASYNC_FOR: // res == 1 means JUMP_BY(oparg) (only other value) // res == 2 means goto exception_unwind emit_cmp64_imm(Dst, res_idx, 2); | branch_eq ->exception_unwind exception_unwind_label_used = 1; emit_jump_by_n_bytecodes(Dst, oparg, inst_idx); break; // opcodes helper functions which return the result instead of pushing to the value stack case GET_AITER: case GET_ANEXT: case GET_AWAITABLE: case LOAD_BUILD_CLASS: case LOAD_NAME: case LOAD_GLOBAL: case LOAD_CLASSDEREF: case BUILD_STRING: case BUILD_TUPLE_UNPACK_WITH_CALL: case BUILD_TUPLE_UNPACK: case BUILD_LIST_UNPACK: case BUILD_SET: case BUILD_SET_UNPACK: case BUILD_MAP: case BUILD_CONST_KEY_MAP: case BUILD_MAP_UNPACK: case BUILD_MAP_UNPACK_WITH_CALL: case LOAD_ATTR: case GET_YIELD_FROM_ITER: case BEFORE_ASYNC_WITH: case SETUP_WITH: case WITH_CLEANUP_START: case LOAD_METHOD: case CALL_FUNCTION_EX: case MAKE_FUNCTION: case FORMAT_VALUE: // res == 0 means error // all other values are the returned python object emit_if_res_0_error(Dst); deferred_vs_push(Dst, REGISTER, res_idx); break; default: // res == 0 means error // res == 1 means execute next opcode (=fallthrough) emit_if_res_0_error(Dst); break; } } } //////////////////////////////// // CALCULATE NUMBER OF STACK VARIABLES // stack must be aligned which means it must be a uneven number of slots on X86 // (because a call will push the return address to the stack which makes it aligned) // and even on ARM64! unsigned long num_stack_slots = Dst->num_deferred_stack_slots + NUM_MANUAL_STACK_SLOTS; #ifdef __aarch64__ if ((num_stack_slots & 1) != 0) ++num_stack_slots; #else if ((num_stack_slots & 1) == 0) ++num_stack_slots; #endif //////////////////////////////// // EPILOG OF EMITTED CODE: jump target to different exit path |->epilog: |->return: // ret value one must already be set // second is the value stackpointer | mov res2, vsp // remove stack variable @ARMconst int num_callee_saved = 8; @ARM| add sp, sp, #(num_callee_saved+num_stack_slots)*8 @X86| add rsp, num_stack_slots*8 // restore callee saves @ARM_START | ldp x29, x30, [sp, #-16] | ldp vs_preserved_reg, tmp_preserved_reg, [sp, #-32] | ldp f, tstate, [sp, #-48] | ldp vsp, interrupt, [sp, #-64] | ret @ARM_END @X86_START | pop interrupt | pop vsp | pop tstate | pop f | pop tmp_preserved_reg | pop vs_preserved_reg | ret @X86_END if (exception_unwind_label_used) { |->exception_unwind: emit_mov_imm(Dst, real_res_idx, 1); | branch ->return } if (exit_yielding_label_used && exit_yielding_label == 0) { emit_exit_yielding_label(Dst); exit_yielding_label = 1; } |->handle_signal_res_in_use: // we have to preserve res because it's used by our deferred stack optimizations | mov tmp_preserved_reg, res emit_call_ext_func(Dst, eval_breaker_jit_helper); emit_cmp32_imm(Dst, res_idx, 0); // on error we have to decref 'res' (which is now in 'tmp_preserved_reg') | branch_ne ->error_decref_tmp_preserved_reg // no error, restore 'res' and continue executing | mov res, tmp_preserved_reg | branch ->handle_signal_jump_to_inst |->handle_signal_res_not_in_use: emit_call_ext_func(Dst, eval_breaker_jit_helper); emit_if_res_32b_not_0_error(Dst); // fall through |->handle_signal_jump_to_inst: emit_load32_mem(Dst, arg1_idx, f_idx, offsetof(PyFrameObject, f_lasti)); emit_mov_inst_addr_to_tmp(Dst, arg1_idx); // tmp points now to the beginning of the bytecode implementation // but we want to skip the signal check. @ARM| add tmp, tmp, #5 * 4 /*= num instructions * size of every instruction */ @X86_START // We can't just directly jump after the signal check beause the jne instruction is variable size // so instead jump before the conditional jump and set the flags so that we don't jump // size of 'mov dword [lasti + offsetof(PyFrameObject, f_lasti)], inst_idx*2' = 8byte // + 'cmp qword [interrupt], 0' = 4byte (64bit cmp) // Not that we are in the handle_signal label which can only be reached if we generated // the code mentioned above. | add tmp, 8 + 4 | cmp tmp, tmp // dummy to set the flags for 'jne ...' to fail @X86_END | branch_reg tmp_idx |->handle_tracing_or_signal_no_deferred_stack: // compares ceval->tracing_possible == 0 (32bit) emit_tracing_possible_check(Dst); // there is no deferred stack so we don't have to jump to handle_signal_res_in_use | branch_eq ->handle_signal_res_not_in_use | branch ->deopt_return |->handle_tracing_or_signal_no_deferred_stack_new_line: // compares ceval->tracing_possible == 0 (32bit) emit_tracing_possible_check(Dst); // there is no deferred stack so we don't have to jump to handle_signal_res_in_use | branch_eq ->handle_signal_res_not_in_use // falltrough |->deopt_return_new_line: emit_mov_imm(Dst, real_res_idx, (1 << 2) /* this means first trace check for this line */ | 3 /*= deopt */); | branch ->return |->deopt_return: emit_mov_imm(Dst, real_res_idx, 3 /*= deopt */); | branch ->return |->error_decref_tmp_preserved_reg: emit_decref(Dst, tmp_preserved_reg_idx, 0 /*= don't preserve res */); | branch ->error // we come here if the result of LOAD_FAST or DELETE_FAST is null |->unboundlocal_error: // arg1 must be oparg! emit_call_ext_func(Dst, JIT_HELPER_UNBOUNDLOCAL_ERROR); // fallthrough to error |->error: // we have to decref all python object stored in the deferred stack array | mov arg1, vs_preserved_reg emit_xdecref(Dst, arg1_idx); for (int i=0; i<Dst->num_deferred_stack_slots; ++i) { emit_load64_mem(Dst, arg1_idx, sp_reg_idx, (NUM_MANUAL_STACK_SLOTS + i) * 8); emit_xdecref(Dst, arg1_idx); } emit_mov_imm(Dst, real_res_idx, 0); | branch ->return //////////////////////////////// // ENTRY OF EMITTED FUNCTION switch_section(Dst, SECTION_ENTRY); |.align 16 |->entry: // callee saved @ARM_START | stp x29, x30, [sp, #-16] | stp vs_preserved_reg, tmp_preserved_reg, [sp, #-32] | stp f, tstate, [sp, #-48] | stp vsp, interrupt, [sp, #-64] @ARM_END @X86_START | push vs_preserved_reg | push tmp_preserved_reg | push f | push tstate | push vsp | push interrupt @X86_END // Signature: // (PyFrameObject* f, PyThread* tstate, PyObject** sp){ | mov f, arg1 | mov tstate, arg2 | mov vsp, arg3 // allocate stack variables @ARM| sub sp, sp, #(num_callee_saved+num_stack_slots)*8 @X86| sub rsp, num_stack_slots*8 // We store the address of _PyRuntime.ceval.tracing_possible and eval_breaker inside a register // this makes it possible to compare this two 4 byte variables at the same time to 0 // via one 4 byte long (machine code size) 'cmp qword [interrupt], 0' instruction // (using the address as immediate instead of the reg would require 8/9bytes) // and this adds up because we emit it infront of every opcode. // The offsets of the fields are not important as long as the two fields are next to each other and fit in 8bytes -> assert is overly strict _Static_assert(offsetof(struct _ceval_runtime_state, tracing_possible) == 4, ""); _Static_assert(offsetof(struct _ceval_runtime_state, eval_breaker) == 8, ""); _Static_assert(sizeof(((struct _ceval_runtime_state*)0)->tracing_possible) == 4, ""); _Static_assert(sizeof(((struct _ceval_runtime_state*)0)->eval_breaker) == 4, ""); emit_mov_imm(Dst, interrupt_idx, (unsigned long)&_PyRuntime.ceval.tracing_possible); // clear deferred stack space (skip manual stack slots because they don't need to be zero) // we clear it so in case of error we can just decref this space emit_mov_imm(Dst, vs_preserved_reg_idx, 0); for (int i=0; i<Dst->num_deferred_stack_slots; ++i) { emit_store64_mem_imm(Dst, 0 /* =value */, sp_reg_idx, (NUM_MANUAL_STACK_SLOTS + i) * 8); } // in the most common case where f_lasti is < 0 it just fallsthrough to the first opcode // in the other cases it will jump to the opcode f_lasti + 2. emit_load32_mem(Dst, arg1_idx, f_idx, offsetof(PyFrameObject, f_lasti)); emit_cmp32_imm(Dst, arg1_idx, 0); | branch_ge >1 int prev_section = Dst->current_section; JIT_ASSERT(prev_section == SECTION_ENTRY, ""); switch_section(Dst, SECTION_CODE); |1: emit_add_or_sub_imm(Dst, arg1_idx, arg1_idx, 2); // we have to increment the value by 2. #if JIT_DEBUG // generate code to check that the instruction we jump to had 'is_jmp_target' set // every entry in the is_jmp_target array is 4 bytes long. 'lasti / 2' is the index @ARM| adr arg2, ->is_jmp_target @ARM| lsl tmp, arg1, #1 @ARM| ldr tmp, [arg2, tmp] @ARM| cmp tmp, #0 @X86| lea arg2, [->is_jmp_target] @X86| cmp dword [arg2 + arg1*2], 0 | branch_ne >9 | mov arg1, f emit_call_ext_func(Dst, debug_error_not_a_jump_target); |9: #endif emit_jmp_to_inst_idx(Dst, arg1_idx); switch_section(Dst, prev_section); // code assumes that the opcodes follows here... //////////////////////////////// // OPCODE TABLE // space for the table of bytecode index -> IP offset from opcode_offset_begin // used e.g. for continuing generators // will fill in the actual address after dasm_link switch_section(Dst, SECTION_OPCODE_ADDR); |->opcode_offset_begin: for (int i=0; i<Dst->num_opcodes; ++i) { // fill all bytes with this value to catch bugs emit_32bit_value(Dst, UINT_MAX); } #if JIT_DEBUG |->is_jmp_target: for (int i=0; i<Dst->num_opcodes; ++i) { emit_32bit_value(Dst, jit.is_jmp_target[i]); } #endif if (Dst->failed) goto failed; #ifdef DASM_CHECKS int dasm_checkstep_err = dasm_checkstep(Dst, -1); if (dasm_checkstep_err) { JIT_ASSERT(0, "dasm_checkstep returned error %x", dasm_checkstep_err); } #endif size_t size; int dasm_link_err = dasm_link(Dst, &size); if (dasm_link_err) { #if JIT_DEBUG JIT_ASSERT(0, "dynasm_link() returned error %x", dasm_link_err); #endif goto failed; } // Align code regions to cache line boundaries. // I don't know concretely that this is important but seems like // something maybe you're supposed to do? size = (size + 15) / 16 * 16; // Allocate jitted code regions in 256KB chunks: if (size > mem_chunk_bytes_remaining) { mem_chunk_bytes_remaining = size > (1<<18) ? size : (1<<18); #ifdef __amd64__ // allocate memory which address fits inside a 32bit pointer (makes sure we can use 32bit rip relative addressing) void* new_chunk = mmap(0, mem_chunk_bytes_remaining, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_32BIT | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #elif __aarch64__ // we try to allocate a memory block close to our AOT functions, because on ARM64 the relative call insruction 'bl' // can only address +-128MB from current IP. And this allows us to use bl for most calls. void* new_chunk = MAP_FAILED; // try allocate memory 25MB after this AOT func. char* start_addr = (char*)(((uint64_t)LAYOUT_TARGET + 25*1024*1024 + 4095) / 4096 * 4096); for (int i=0; i<8 && new_chunk == MAP_FAILED; ++i, start_addr += 5*1024*1024) { // MAP_FIXED_NOREPLACE is available from linux 4.17, but older glibc don't define it. // Older kernel will ignore this flag and will try to allocate the address supplied as hint // but if not possible will just return a different address. // If the returned adddress does not fix in 32bit we abort the JIT compilation. #ifndef MAP_FIXED_NOREPLACE #define MAP_FIXED_NOREPLACE 0x100000 #endif new_chunk = mmap(start_addr + mem_bytes_allocated, mem_chunk_bytes_remaining, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED_NOREPLACE | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } #else #error "unknown arch" #endif if (new_chunk == MAP_FAILED || !can_use_relative_call(new_chunk)) { #if JIT_DEBUG JIT_ASSERT(0, "mmap() returned error %d", errno); #endif if (new_chunk != MAP_FAILED) munmap(new_chunk, mem_chunk_bytes_remaining); mem_chunk_bytes_remaining = 0; goto failed; } mem_chunk = new_chunk; mem_bytes_allocated += (mem_chunk_bytes_remaining + 4095) / 4096 * 4096; } void* mem = mem_chunk; mem_chunk += size; mem_chunk_bytes_remaining -= size; mem_bytes_used += size; int dasm_encode_err = dasm_encode(Dst, mem); if (dasm_encode_err) { #if JIT_DEBUG JIT_ASSERT(0, "dynasm_encode() returned error %x", dasm_encode_err); #endif goto failed; } // fill in the table of bytecode index -> IP offset from opcode_offset_begin for (int inst_idx=0; inst_idx < Dst->num_opcodes; ++inst_idx) { // emit 4byte offset to start of implementation of instruction with index 'inst_idx' // relative to the start of the opcode_offset_begin table int* opcode_offset_begin = (int*)labels[lbl_opcode_offset_begin]; long offset = dasm_getpclabel(Dst, inst_idx) - ((unsigned long)opcode_offset_begin - (unsigned long)mem); JIT_ASSERT(IS_32BIT_SIGNED_VAL(offset),""); opcode_offset_begin[inst_idx] = (int)offset; } if (perf_map_file) { PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); _Py_static_string(PyId_slash, "/"); PyObject *slash = _PyUnicode_FromId(&PyId_slash); /* borrowed */ PyObject *partitioned = PyUnicode_RPartition(co->co_filename, slash); // Function naming: there are a couple ways we can name the functions. // Ideally we would have access to the function object, and would do // function.__module__ + "." + function.__qualname__ // The code object just has the function name + file name, so use that // plus the line number for now. Maybe it's too much info. // Add an index at the end in the case of a name clash. PyObject* function_name = PyUnicode_FromFormat("%U:%d:%U", PyTuple_GET_ITEM(partitioned, 2), co->co_firstlineno, co->co_name); PyObject* function_name_bytes = PyUnicode_AsASCIIString(function_name); char* function_name_cstr = PyBytes_AS_STRING(function_name_bytes); ++perf_map_num_funcs; perf_map_funcs = realloc(perf_map_funcs, perf_map_num_funcs*sizeof(struct PerfMapEntry)); perf_map_funcs[perf_map_num_funcs-1].func_name = strdup(function_name_cstr); perf_map_funcs[perf_map_num_funcs-1].func_size = size; perf_map_funcs[perf_map_num_funcs-1].func_addr = mem; Py_DECREF(function_name); Py_DECREF(function_name_bytes); Py_DECREF(partitioned); PyErr_Restore(type, value, traceback); } if (perf_map_opcode_map) { // table of bytecode index -> IP (4byte address) int* opcode_offset_begin = (int*)labels[lbl_opcode_offset_begin]; // write addr and opcode info into a file which tools/perf_jit.py uses // to annotate the 'perf report' output long extended_arg = 0; // display filepath, line number and function name at the top fprintf(perf_map_opcode_map, "%p,%s:%d %s\n", mem, PyUnicode_AsUTF8(co->co_filename), co->co_firstlineno, PyUnicode_AsUTF8(co->co_name)); PyObject* str_newline = PyUnicode_FromString("\n"); PyObject* str_newline_escaped = PyUnicode_FromString("\\n"); for (int inst_idx = 0; inst_idx < Dst->num_opcodes; ++inst_idx) { _Py_CODEUNIT word = Dst->first_instr[inst_idx]; int opcode = _Py_OPCODE(word); int oparg = _Py_OPARG(word); void* addr = &((char*)opcode_offset_begin)[opcode_offset_begin[inst_idx]]; const char* jmp_dst = Dst->is_jmp_target[inst_idx] ? "->" : " "; fprintf(perf_map_opcode_map, "%p,%s %4d %-30s %3d", addr, jmp_dst, inst_idx*2, get_opcode_name(opcode), oparg); if (opcode == LOAD_CONST) { PyObject* c = PyTuple_GET_ITEM(Dst->co_consts, oparg | extended_arg); PyObject* str = PyObject_Repr(c); PyObject* str_escaped = PyUnicode_Replace(str, str_newline, str_newline_escaped, -1); fprintf(perf_map_opcode_map, " (%s: %.60s)\n", c->ob_type->tp_name, PyUnicode_AsUTF8(str_escaped)); Py_DECREF(str); Py_DECREF(str_escaped); } else if (opcode == LOAD_FAST || opcode == STORE_FAST || opcode == DELETE_FAST) { PyObject* name = PyTuple_GET_ITEM(co->co_varnames, oparg | extended_arg); fprintf(perf_map_opcode_map, " (%.60s)\n", PyUnicode_AsUTF8(name)); } else if (opcode == LOAD_ATTR || opcode == STORE_ATTR || opcode == DELETE_ATTR || opcode == LOAD_METHOD || opcode == LOAD_GLOBAL) { PyObject* name = PyTuple_GET_ITEM(co->co_names, oparg | extended_arg); fprintf(perf_map_opcode_map, " (%.60s)\n", PyUnicode_AsUTF8(name)); } else { fprintf(perf_map_opcode_map, "\n"); } if (opcode == EXTENDED_ARG) { extended_arg |= oparg << 8; } else { extended_arg = 0; } } Py_DECREF(str_newline); Py_DECREF(str_newline_escaped); } __builtin___clear_cache((char*)mem, &((char*)mem)[size]); ++jit_num_funcs; success = 1; cleanup: dasm_free(Dst); free(Dst->is_jmp_target); Dst->is_jmp_target = NULL; #if ENABLE_DEFINED_TRACKING free(Dst->known_defined); Dst->known_defined = NULL; #endif // For reasonable bytecode we won't have any hints // left because we will have consumed them all. But // for the sake of completeness free any that might // be left due to weird bytecode: CallMethodHint *hint = Dst->call_method_hints; Dst->call_method_hints = NULL; while (hint) { CallMethodHint *new_hint = hint->next; free(hint); hint = new_hint; } if (jit_stats_enabled) { struct timespec compilation_end; clock_gettime(CLOCK_MONOTONIC, &compilation_end); total_compilation_time_in_us += 1000000 * (compilation_end.tv_sec - compilation_start.tv_sec) + (compilation_end.tv_nsec - compilation_start.tv_nsec) / 1000; } return success ? labels[lbl_entry] : NULL; failed: if (jit_stats_enabled) { fprintf(stderr, "Could not JIT compile %s:%d %s\n", PyUnicode_AsUTF8(co->co_filename), co->co_firstlineno, PyUnicode_AsUTF8(co->co_name)); fprintf(stderr, "\tnumber of bytecode instructions: %d\n", Dst->num_opcodes); } ++jit_num_failed; goto cleanup; } static void show_jit_stats() { fprintf(stderr, "jit: successfully compiled %d functions, failed to compile %d functions\n", jit_num_funcs, jit_num_failed); fprintf(stderr, "jit: took %ld ms to compile all functions\n", total_compilation_time_in_us/1000); fprintf(stderr, "jit: %ld bytes used (%.1f%% of allocated)\n", mem_bytes_used, 100.0 * mem_bytes_used / mem_bytes_allocated); #define PRINT_STAT(name, opcode) fprintf(stderr, "jit: inlined %lu (of total %lu) %s caches: %lu hits %lu misses (=%lu%%)\n", \ jit_stat_##name##_inline, jit_stat_##name##_total, #opcode, jit_stat_##name##_hit, jit_stat_##name##_miss, \ jit_stat_##name##_miss ? jit_stat_##name##_miss*100 / (jit_stat_##name##_hit + jit_stat_##name##_miss) : 0) PRINT_STAT(load_attr, LOAD_ATTR); PRINT_STAT(load_method, LOAD_METHOD); PRINT_STAT(load_global, LOAD_GLOBAL); PRINT_STAT(call_method, CALL_METHOD); PRINT_STAT(store_attr, STORE_ATTR); fprintf(stderr, "jit: num GetItemLong: %lu inlined: %lu\n", jit_stat_getitemlong, jit_stat_getitemlong_inlined); fprintf(stderr, "jit: num SetItemLong: %lu inlined: %lu\n", jit_stat_setitemlong_inlined, jit_stat_setitemlong_inlined); fprintf(stderr, "jit: num inplace binary op: %lu hits: %lu misses: %lu\n", jit_stat_binary_op_inplace, jit_stat_binary_op_inplace_hit, jit_stat_binary_op_inplace_miss); fprintf(stderr, "jit: num inplace concat: %lu hits: %lu misses: %lu\n", jit_stat_concat_inplace, jit_stat_concat_inplace_hit, jit_stat_concat_inplace_miss); fprintf(stderr, "jit: num polymorphic LOAD_ATTR sites: %lu with %lu entries\n", jit_stat_load_attr_poly, jit_stat_load_attr_poly_entries); fprintf(stderr, "jit: num polymorphic LOAD_METHOD sites: %lu with %lu entries\n", jit_stat_load_method_poly, jit_stat_load_method_poly_entries); } #ifdef PYSTON_LITE void jit_start_lite() { #else void jit_start() { #endif if (getenv("JIT_PERF_MAP") != NULL) { char buf[80]; snprintf(buf, 80, "/tmp/perf-%d.map", getpid()); perf_map_file = fopen(buf, "w"); system("rm -rf /tmp/perf_map"); system("mkdir /tmp/perf_map"); FILE* executable_file = fopen("/tmp/perf_map/executable.txt", "w"); PyObject* executable = PySys_GetObject("executable"); PyObject_Print(executable, executable_file, Py_PRINT_RAW); fclose(executable_file); perf_map_opcode_map = fopen("/tmp/perf_map/opcode_map.txt", "w"); } char* val = getenv("JIT_MAX_MEM"); if (val) mem_bytes_used_max = atol(val); val = getenv("SHOW_JIT_STATS"); // legacy name if (!val) val = getenv("JIT_SHOW_STATS"); if (val) jit_stats_enabled = atoi(val); val = getenv("JIT_USE_AOT"); if (val) jit_use_aot = atoi(val); val = getenv("JIT_USE_ICS"); if (val) jit_use_ics = atoi(val); #ifdef PYSTON_LITE // This is to get the value of lookdict_split, which is a static function: PyDictKeysObject* tmp_keys = _PyDict_NewKeysForClass(); lookdict_split_value = tmp_keys->dk_lookup; // Unfortunately I can't find an easy way to deallocate this temporary object. // To get the values of these functions we have to find methods that use them, and then fish the value out: method_vectorcall_NOARGS_value = ((PyMethodDescrObject*)PyDict_GetItemString(PyList_Type.tp_dict, "clear"))->vectorcall; method_vectorcall_O_value = ((PyMethodDescrObject*)PyDict_GetItemString(PyList_Type.tp_dict, "append"))->vectorcall; method_vectorcall_FASTCALL_value = ((PyMethodDescrObject*)PyDict_GetItemString(PyList_Type.tp_dict, "pop"))->vectorcall; method_vectorcall_FASTCALL_KEYWORDS_value = ((PyMethodDescrObject*)PyDict_GetItemString(PyList_Type.tp_dict, "sort"))->vectorcall; method_vectorcall_VARARGS_value = ((PyMethodDescrObject*)PyDict_GetItemString(PyBytes_Type.tp_dict, "count"))->vectorcall; method_vectorcall_VARARGS_KEYWORDS_value = ((PyMethodDescrObject*)PyDict_GetItemString(PyUnicode_Type.tp_dict, "format"))->vectorcall; #endif } #ifdef PYSTON_LITE void jit_finish_lite() { #else void jit_finish() { #endif if (jit_stats_enabled) show_jit_stats(); if (perf_map_file) { // dump emitted functions for 'perf report' for (int i=0; i<perf_map_num_funcs; ++i) { struct PerfMapEntry* entry = &perf_map_funcs[i]; char fn[150]; char func_name_unique[120]; int index = 0; do { snprintf(func_name_unique, sizeof(func_name_unique), index == 0 ? "%s" : "%s.%d", entry->func_name, index); snprintf(fn, sizeof(fn), "/tmp/perf_map/%s", func_name_unique); ++index; } while (access(fn, F_OK) != -1); fprintf(perf_map_file, "%lx %lx %s\n", (uintptr_t)entry->func_addr, entry->func_size, func_name_unique); FILE* data_f = fopen(fn, "wb"); if (data_f) { fwrite(entry->func_addr, 1, entry->func_size, data_f); fclose(data_f); } free(entry->func_name); } free(perf_map_funcs); fclose(perf_map_file); } if (perf_map_opcode_map) fclose(perf_map_opcode_map); }
39.953957
197
0.617858
ecd17e9d023ab10c3754dd8a95652316784ca6b9
109
ps1
PowerShell
Basic/Errors-of-unusual-type/test.6.1.missing.property.strict.ps1
ImportTaste/PowerShellTraps
f43c215b67073cb8f22be662aab5825f72658f5a
[ "Apache-2.0" ]
348
2015-04-09T19:04:40.000Z
2022-03-17T07:32:52.000Z
Basic/Errors-of-unusual-type/test.6.1.missing.property.strict.ps1
ImportTaste/PowerShellTraps
f43c215b67073cb8f22be662aab5825f72658f5a
[ "Apache-2.0" ]
12
2015-05-20T17:17:26.000Z
2021-04-06T09:19:28.000Z
Basic/Errors-of-unusual-type/test.6.1.missing.property.strict.ps1
ImportTaste/PowerShellTraps
f43c215b67073cb8f22be662aab5825f72658f5a
[ "Apache-2.0" ]
37
2015-05-25T08:08:51.000Z
2022-01-20T06:26:13.000Z
$ErrorActionPreference = 'Continue' Set-StrictMode -Version 2 $Host.MissingProperty 'Continued after error'
18.166667
35
0.807339
bde0deb8a30d3592e55d3c909d9c4861873e5efd
1,318
dart
Dart
test/google_sign_in_test.dart
kevmoo/angular_fire
858f42a6490db41e7564668e08735d767b28e30f
[ "BSD-3-Clause" ]
1
2021-07-07T13:49:30.000Z
2021-07-07T13:49:30.000Z
test/google_sign_in_test.dart
kevmoo/angular_fire
858f42a6490db41e7564668e08735d767b28e30f
[ "BSD-3-Clause" ]
null
null
null
test/google_sign_in_test.dart
kevmoo/angular_fire
858f42a6490db41e7564668e08735d767b28e30f
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017, Google Inc. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @TestOn('browser') @Tags(const ['aot']) import 'package:angular2/angular2.dart'; import 'package:angular_fire/angular_fire.dart'; import 'package:angular_test/angular_test.dart'; import 'package:test/test.dart'; @AngularEntrypoint() void main() { test('should render a $GoogleSignInComponent', () async { final fixture = await new NgTestBed<TestGoogleSignIn>().create(); expect(fixture.rootElement, isNotNull); final button = fixture.rootElement.querySelector('google-sign-in'); expect(fixture.text, contains('Pressed: 0')); await fixture.update((_) => button.click()); expect(fixture.text, contains('Pressed: 1')); expect( button.getComputedStyle().backgroundImage, startsWith( 'url(http://localhost:8080/assets/btn_google_signin_light_normal_web', ), ); }); } @Component( selector: 'google-sign-in-test', directives: const <dynamic>[ GoogleSignInComponent, ], template: r''' <google-sign-in (trigger)="pressCount = pressCount + 1"></google-sign-in> Pressed: {{pressCount}} ''', ) class TestGoogleSignIn { int pressCount = 0; }
29.288889
78
0.69651
2c3490f95d78a6bd141324a95a17ddc6564b7cb5
3,232
py
Python
python/find_dots.py
philwilkes/branch-extraction
9e5ac58e06fbb728835db50e3c94eee5eabc65fb
[ "Unlicense" ]
4
2021-04-21T21:09:11.000Z
2022-01-02T21:05:41.000Z
python/find_dots.py
philwilkes/branch-extraction
9e5ac58e06fbb728835db50e3c94eee5eabc65fb
[ "Unlicense" ]
null
null
null
python/find_dots.py
philwilkes/branch-extraction
9e5ac58e06fbb728835db50e3c94eee5eabc65fb
[ "Unlicense" ]
2
2021-04-21T21:09:37.000Z
2021-07-09T11:13:49.000Z
import os import sys import glob import numpy as np import pandas as pd from scipy.spatial import distance_matrix as distance_matrix import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import ply_io import qrdar rotation = np.array([[0, 0, 1, 0], [0, -1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]]) def identify_ground(pc): #voxelise and identify ground pc.loc[:, 'xx'] = pc.x.round() pc.loc[:, 'yy'] = pc.y.round() # rigid transform ground_plane = pc.groupby(['xx', 'yy']).z.min().reset_index() nominal_plane = ground_plane.copy() nominal_plane.z = 0 M = qrdar.common.rigid_transform_3D(ground_plane.values, nominal_plane.values) pc.loc[:, ['x', 'y', 'z']] = qrdar.common.apply_rotation(M, pc) return pc[pc.z < .15][['x', 'y', 'z', 'reflectance']], M def distanceFilter(corners, template): tdM = qrdar.common.expected_distances(template) # remove points that are not ~ correct distance from at least # 1 other according to template dist = distance_matrix(corners[['x', 'y', 'z']], corners[['x', 'y', 'z']]) dist_bool = np.array([False if v == 0 else True if np.any(np.isclose(v, tdM, atol=.02)) else False for v in dist.flatten()]).reshape(dist.shape) corners.loc[:, 'num_nbrs'] = [len(np.where(r == True)[0]) for r in dist_bool] remove_idx = corners[corners.num_nbrs < 1].index return remove_idx if __name__ == '__main__': rp = sys.argv[1] print('processing:', rp) os.chdir(rp) n_sp = len(glob.glob('ScanPos*')) if not os.path.isdir('stickers'): os.makedirs('stickers') if not os.path.isdir('ply'): raise Exception('process rxp2ply and put in riproject folder') os.chdir('ply') for pcn in glob.glob('*.ply'): print('\tprocessing scan:', pcn) pc = ply_io.read_ply(pcn) pc = pc[pc.deviation <= 10] # specific to RIEGL pc.loc[:, ['x', 'y', 'z']] = qrdar.common.apply_rotation(rotation, pc) # only required if scans are tilted pc = pc[(pc.x.between(-2.5, 2.5)) & (pc.y.between(-3, 0)) & (pc.z.between(-1.5, 0))] # may need adjusting ground, ground_m = identify_ground(pc) bright = qrdar.search4stickers.find(ground[ground.reflectance > -1], verbose=False) bright = qrdar.search4stickers.filterBySize(bright, verbose=False, max_size=.05) stickers = bright.groupby('sticker_labels_').mean() idx = distanceFilter(stickers, qrdar.common.template()) stickers = stickers.loc[~stickers.index.isin(idx)] if len(stickers) == 0: print('\t', pcn, 'no stickers found') continue stickers.loc[:, ['x', 'y', 'z']] = qrdar.common.apply_rotation(np.linalg.inv(ground_m), stickers) stickers.loc[:, ['x', 'y', 'z']] = qrdar.common.apply_rotation(np.linalg.inv(rotation), stickers) stickers[['x', 'y', 'z']].to_csv(os.path.join('../stickers/', pcn[:-4] + '.stickers.txt'), sep=' ', header=True) print('\t', pcn, len(stickers), 'found')
34.382979
114
0.587252
209386a0f3b8a13f773dbfa7af031e5e776df058
1,925
cs
C#
Assets/FullInspector2/Modules/tkControl/Controls/tkMargin.cs
bakiya-sefer/bakiya-sefer
ead07668ffacb2f6752a88128e7e209316259b53
[ "MIT" ]
103
2015-02-10T14:34:47.000Z
2022-03-29T19:33:18.000Z
Assets/FullInspector2/Modules/tkControl/Controls/tkMargin.cs
bakiya-sefer/bakiya-sefer
ead07668ffacb2f6752a88128e7e209316259b53
[ "MIT" ]
119
2015-01-08T07:08:59.000Z
2020-06-08T20:32:32.000Z
Assets/FullInspector2/Modules/tkControl/Controls/tkMargin.cs
bakiya-sefer/bakiya-sefer
ead07668ffacb2f6752a88128e7e209316259b53
[ "MIT" ]
34
2015-09-15T13:22:22.000Z
2022-02-19T20:07:23.000Z
using UnityEngine; namespace FullInspector { public partial class tk<T, TContext> { public class Margin : tkControl<T, TContext> { [ShowInInspector] private readonly Value<float> _left, _top, _right, _bottom; [ShowInInspector] private readonly tkControl<T, TContext> _control; public Margin(Value<float> margin, tkControl<T, TContext> control) : this(margin, margin, margin, margin, control) { } public Margin(Value<float> left, Value<float> top, tkControl<T, TContext> control) : this(left, top, left, top, control) { } public Margin(Value<float> left, Value<float> top, Value<float> right, Value<float> bottom, tkControl<T, TContext> control) { _left = left; _top = top; _right = right; _bottom = bottom; _control = control; } protected override T DoEdit(Rect rect, T obj, TContext context, fiGraphMetadata metadata) { var left = _left.GetCurrentValue(obj, context); var right = _right.GetCurrentValue(obj, context); var top = _top.GetCurrentValue(obj, context); var bottom = _bottom.GetCurrentValue(obj, context); rect.x += left; rect.width -= left + right; rect.y += top; rect.height -= top + bottom; return _control.Edit(rect, obj, context, metadata); } protected override float DoGetHeight(T obj, TContext context, fiGraphMetadata metadata) { var top = _top.GetCurrentValue(obj, context); var bottom = _bottom.GetCurrentValue(obj, context); return _control.GetHeight(obj, context, metadata) + top + bottom; } } } }
40.104167
137
0.554805
741d5b8319ae07094bdb4578e66e4b3c20c6b56c
3,371
go
Go
runes.go
ktnyt/pars
7d104a3a896c1954e3ba24347255e7edbcf506d1
[ "MIT" ]
null
null
null
runes.go
ktnyt/pars
7d104a3a896c1954e3ba24347255e7edbcf506d1
[ "MIT" ]
null
null
null
runes.go
ktnyt/pars
7d104a3a896c1954e3ba24347255e7edbcf506d1
[ "MIT" ]
1
2020-01-06T17:23:40.000Z
2020-01-06T17:23:40.000Z
package pars import ( "bytes" "errors" "fmt" "strings" "unicode/utf8" "github.com/go-ascii/ascii" ) func runeRep(r rune) string { n := utf8.RuneLen(r) if n > 1 { return fmt.Sprintf("%c", r) } p := make([]byte, 1) utf8.EncodeRune(p, r) return ascii.Rep(p[0]) } func runeReps(p []rune) []string { r := make([]string, len(p)) for i, c := range p { r[i] = runeRep(c) } return r } func readRune(state *State) (rune, error) { for i := 0; i < 4; i++ { if err := state.Request(i + 1); err != nil { return utf8.RuneError, err } p := state.Buffer() if utf8.Valid(p) { r, _ := utf8.DecodeRune(p) return r, nil } } return utf8.RuneError, errors.New("unable to read valid rune") } // Rune creates a Parser which will attempt to match the next single rune. // If no runes are given, it will match any rune. // Otherwise, the given runes will be tested for a match. func Rune(rs ...rune) Parser { switch len(rs) { case 0: return func(state *State, result *Result) error { r, err := readRune(state) if err != nil { return NewNestedError("Rune", err) } result.SetValue(r) state.Advance() return nil } case 1: r := rs[0] rep := runeRep(r) name := fmt.Sprintf("Rune(%s)", rep) what := fmt.Sprintf("expected `%s`", rep) n := utf8.RuneLen(r) p := make([]byte, n) utf8.EncodeRune(p, r) return func(state *State, result *Result) error { if err := state.Request(n); err != nil { return NewNestedError(name, err) } if !bytes.Equal(state.Buffer(), p) { return NewError(what, state.Position()) } result.SetValue(r) state.Advance() return nil } default: reps := strings.Join(runeReps(rs), ", ") name := fmt.Sprintf("Rune(%s)", reps) what := fmt.Sprintf("expected one of [%s]", reps) s := string(rs) mismatch := func(r rune) bool { return !strings.ContainsRune(s, r) } return func(state *State, result *Result) error { r, err := readRune(state) if err != nil { return NewNestedError(name, err) } if mismatch(r) { return NewError(what, state.Position()) } result.SetValue(r) state.Advance() return nil } } } // RuneRange creates a Parser which will attempt to match any rune within the // given range inclusively. func RuneRange(begin, end rune) Parser { if begin < end { rbegin, rend := runeRep(begin), runeRep(end) name := fmt.Sprintf("RuneRange(%s, %s)", rbegin, rend) what := fmt.Sprintf("expected in range %s-%s", rbegin, rend) return func(state *State, result *Result) error { r, err := readRune(state) if err != nil { return NewNestedError(name, err) } if r < begin || end < r { return NewError(what, state.Position()) } result.SetValue(r) state.Advance() return nil } } panic("invalid rune range") } // Runes creates a parser which will attempt to match the given sequence of runes. func Runes(rs []rune) Parser { reps := fmt.Sprintf("[%s]", strings.Join(runeReps(rs), ", ")) name := fmt.Sprintf("Rune(%s)", reps) what := fmt.Sprintf("expected [%s]", reps) p := []byte(string(rs)) return func(state *State, result *Result) error { if err := state.Request(len(p)); err != nil { return NewNestedError(name, err) } if !bytes.Equal(state.Buffer(), p) { return NewError(what, state.Position()) } result.SetValue(rs) state.Advance() return nil } }
22.931973
82
0.624147
4bb9ead4e506077a4414a01d0d8c39b7458eb9d3
1,508
cpp
C++
src/tests/src/loader/token-test.cpp
Penguin-Guru/imgbrd-grabber
69bdd5566dc2b2cb3a67456bf1a159d544699bc9
[ "Apache-2.0" ]
1,449
2015-03-16T02:21:41.000Z
2022-03-31T22:49:10.000Z
src/tests/src/loader/token-test.cpp
sisco0/imgbrd-grabber
89bf97ccab3df62286784baac242f00bf006d562
[ "Apache-2.0" ]
2,325
2015-03-16T02:23:30.000Z
2022-03-31T21:38:26.000Z
src/tests/src/loader/token-test.cpp
evanjs/imgbrd-grabber
491f8f3c05be3fc02bc10007735c5afa19d47449
[ "Apache-2.0" ]
242
2015-03-22T11:00:54.000Z
2022-03-31T12:37:15.000Z
#include "loader/token.h" #include "catch.h" TEST_CASE("Token") { SECTION("LazyNotCalled") { int callCount = 0; Token token([&callCount]() { return ++callCount; }); REQUIRE(callCount == 0); } SECTION("LazyWithCaching") { int callCount = 0; Token token([&callCount]() { return ++callCount; }, true); token.value(); int val = token.value().toInt(); REQUIRE(callCount == 1); REQUIRE(val == 1); } SECTION("LazyWithoutCaching") { int callCount = 0; Token token([&callCount]() { return ++callCount; }, false); token.value(); int val = token.value().toInt(); REQUIRE(callCount == 2); REQUIRE(val == 2); } SECTION("Compare") { REQUIRE(Token(13) == Token(13)); REQUIRE(Token(13) != Token(17)); REQUIRE(Token("test") == Token("test")); REQUIRE(Token("test") != Token("not_test")); REQUIRE(Token(QStringList() << "1" << "2") == Token(QStringList() << "1" << "2")); REQUIRE(Token(QStringList() << "1" << "2") != Token(QStringList() << "1" << "2" << "3")); } SECTION("Value") { Token token(13); QVariant val = token.value(); REQUIRE(val.toInt() == 13); const QVariant &valRef = token.value(); REQUIRE(valRef.toInt() == 13); } SECTION("Value template") { REQUIRE(Token(13).value<int>() == 13); Token token("test"); REQUIRE(token.value<QString>() == "test"); QString val = token.value<QString>(); REQUIRE(val.toUpper() == "TEST"); const QString &valRef = token.value<QString>(); REQUIRE(valRef.toUpper() == "TEST"); } }
19.842105
91
0.596154
7abfd28c4945462f0cf02fff536b736ec7a3b8a6
1,393
lua
Lua
service/network/auth.lua
Bobhu1995/skynet-demo
a4810c61c7f85b1b6cbc92006b3140a7f33d181c
[ "MIT" ]
9
2020-11-30T09:23:30.000Z
2021-02-02T11:01:31.000Z
service/network/auth.lua
Bobhu1995/skynet-demo
a4810c61c7f85b1b6cbc92006b3140a7f33d181c
[ "MIT" ]
null
null
null
service/network/auth.lua
Bobhu1995/skynet-demo
a4810c61c7f85b1b6cbc92006b3140a7f33d181c
[ "MIT" ]
1
2021-03-05T15:48:26.000Z
2021-03-05T15:48:26.000Z
local skynet = require "skynet" local service = require "service" local client = require "client" local log = require "log" local Table = require "table_op" local auth = {} local users = {} local cli = client.handler() local redis_mgr local SUCC = { ok = true } local FAIL = { ok = false } function cli:signup(args) log("signup userid = %s", args.userid) if users[args.userid] then return FAIL else users[args.userid] = true local result = skynet.call(redis_mgr, "lua", "set", "auth", args.userid, "SUCC") if result == "OK" then return SUCC else users[args.userid] = nil return FAIL end end end function cli:signin(args) log("signin userid = %s", args.userid) if users[args.userid] then self.userid = args.userid self.exit = true return SUCC else local result = skynet.call(redis_mgr, "lua", "get", "auth", args.userid) if result then self.userid = args.userid self.exit = true return SUCC else return FAIL end end end function cli:ping() log("ping") end function auth.shakehand(fd) local c = client.dispatch { fd = fd } return c.userid end function auth.init() redis_mgr = skynet.uniqueservice "redis_mgr" end service.init { command = auth, info = users, init = client.init "proto", initself = auth.init, }
20.485294
88
0.626705
c61323f988124c309c68286148eaf61ee7396241
1,175
rb
Ruby
spec/lib/locasms/helpers/date_time_helper_spec.rb
ztmeyer/locasms
639ad73644a6dcc84b8e2204bcff5113c4fa0f33
[ "MIT" ]
null
null
null
spec/lib/locasms/helpers/date_time_helper_spec.rb
ztmeyer/locasms
639ad73644a6dcc84b8e2204bcff5113c4fa0f33
[ "MIT" ]
null
null
null
spec/lib/locasms/helpers/date_time_helper_spec.rb
ztmeyer/locasms
639ad73644a6dcc84b8e2204bcff5113c4fa0f33
[ "MIT" ]
null
null
null
require 'spec_helper' describe LocaSMS::Helpers::DateTimeHelper do subject { LocaSMS::Helpers::DateTimeHelper } describe '#parse' do it 'Should call the class method' do expect(subject).to receive(:parse) .once .with(:value) subject.new.parse(:value) end end describe '#split' do it 'Should call the class method' do expect(subject).to receive(:split) .once .with(:value) subject.new.split(:value) end end describe '.parse' do let(:expected) { Time.parse '1977-03-14 14:12:00' } def try_for(value) subject.parse(value) == expected end it { try_for DateTime.parse('1977-03-14 14:12:00') } it { try_for Time.parse('1977-03-14 14:12:00') } it { try_for '1977-03-14 14:12:00' } it { try_for 227207520 } end describe '.split' do it 'Should break a date into date and time' do expect(subject).to receive(:parse) .once .with(:datetime) .and_return(Time.parse('1977-03-14 14:12:00')) expect(subject.split(:datetime)).to eq(%w(14/03/1977 14:12)) end end end
23.5
66
0.588085
04c3162e616a6b03a5e4ad8a642f0fe371d28920
10,945
lua
Lua
resources/[esx]/[illegal]/esx_drugs/client/extazy.lua
techniciantucker/AdezouRP
f3b56984bef16ffb60f26c6cfde5527a87a71a9b
[ "MIT" ]
1
2022-01-09T22:42:04.000Z
2022-01-09T22:42:04.000Z
resources/[esx]/[illegal]/esx_drugs/client/extazy.lua
techniciantucker/AdezouRP
f3b56984bef16ffb60f26c6cfde5527a87a71a9b
[ "MIT" ]
null
null
null
resources/[esx]/[illegal]/esx_drugs/client/extazy.lua
techniciantucker/AdezouRP
f3b56984bef16ffb60f26c6cfde5527a87a71a9b
[ "MIT" ]
null
null
null
local spawnedMdmas = 0 local mdmaPlants = {} local isPickingUp, isProcessing = false, false local spawnedAmphets = 0 local amphetPlants = {} -- boucle pour spawn plants Citizen.CreateThread(function() while true do Citizen.Wait(10) local coords = GetEntityCoords(PlayerPedId()) if GetDistanceBetweenCoords(coords, Config.CircleZones.MdmaField.coords, true) < 20 then SpawnMdmaPlants() Citizen.Wait(500) elseif GetDistanceBetweenCoords(coords, Config.CircleZones.AmphetField.coords, true) < 20 then SpawnAmphetPlants() Citizen.Wait(500) Citizen.Wait(500) end end end) -- boucle pour traiter Citizen.CreateThread(function() while true do Citizen.Wait(0) local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) if GetDistanceBetweenCoords(coords, Config.CircleZones.ExtapProcessing.coords, true) < 2 then --if not isProcessing then --ESX.ShowHelpNotification(_U('exta_processprompt')) --end if IsControlJustReleased(0, Keys['E']) and not isProcessing then if Config.LicenseEnable then ESX.TriggerServerCallback('esx_license:checkLicense', function(hasProcessingLicense) if hasProcessingLicense then ProcessExtap() else OpenBuyLicenseMenu('extap_processing') end end, GetPlayerServerId(PlayerId()), 'extap_processing') else ProcessExtap() end end else Citizen.Wait(500) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) if GetDistanceBetweenCoords(coords, Config.CircleZones.ExtaProcessing.coords, true) < 2 then --if not isProcessing then --ESX.ShowHelpNotification(_U('exta_processprompt')) --end if IsControlJustReleased(0, Keys['E']) and not isProcessing then if Config.LicenseEnable then ESX.TriggerServerCallback('esx_license:checkLicense', function(hasProcessingLicense) if hasProcessingLicense then ProcessExta() else OpenBuyLicenseMenu('exta_processing') end end, GetPlayerServerId(PlayerId()), 'exta_processing') else ProcessExta() end end else Citizen.Wait(500) end end end) function ProcessExtap() isProcessing = true -- ESX.ShowNotification(_U('extap_processingstarted')) TriggerServerEvent('esx_illegal:processExtap') local timeLeft = Config.Delays.ExtapProcessing / 1000 local playerPed = PlayerPedId() while timeLeft > 0 do Citizen.Wait(1000) timeLeft = timeLeft - 1 if GetDistanceBetweenCoords(GetEntityCoords(playerPed), Config.CircleZones.ExtapProcessing.coords, false) > 2 then ESX.ShowNotification(_U('exta_processingtoofar')) TriggerServerEvent('esx_illegal:cancelProcessing') break end end isProcessing = false end function ProcessExta() isProcessing = true ESX.ShowNotification(_U('exta_processingstarted')) TriggerServerEvent('esx_illegal:processExta') local timeLeft = Config.Delays.ExtaProcessing / 1000 local playerPed = PlayerPedId() while timeLeft > 0 do Citizen.Wait(1000) timeLeft = timeLeft - 1 if GetDistanceBetweenCoords(GetEntityCoords(playerPed), Config.CircleZones.ExtaProcessing.coords, false) > 2 then ESX.ShowNotification(_U('exta_processingtoofar')) TriggerServerEvent('esx_illegal:cancelProcessing') break end end isProcessing = false end -- boucle pour récolter Citizen.CreateThread(function() while true do Citizen.Wait(0) local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) local nearbyObject, nearbyID for i=1, #mdmaPlants, 1 do if GetDistanceBetweenCoords(coords, GetEntityCoords(mdmaPlants[i]), false) < 2 then nearbyObject, nearbyID = mdmaPlants[i], i end end if nearbyObject and IsPedOnFoot(playerPed) then --if not isPickingUp then --ESX.ShowHelpNotification(_U('mdma_pickupprompt')) --end if IsControlJustReleased(0, Keys['E']) and not isPickingUp then isPickingUp = true ESX.TriggerServerCallback('esx_illegal:canPickUp', function(canPickUp) if canPickUp then TaskStartScenarioInPlace(playerPed, 'world_human_gardener_plant', 0, false) Citizen.Wait(2000) ClearPedTasks(playerPed) Citizen.Wait(1500) ESX.Game.DeleteObject(nearbyObject) table.remove(mdmaPlants, nearbyID) spawnedMdmas = spawnedMdmas - 1 TriggerServerEvent('esx_illegal:pickedUpMdma') else ESX.ShowNotification(_U('Mdma_inventoryfull')) end isPickingUp = false end, 'extamdma') end else Citizen.Wait(500) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) local nearbyObject, nearbyID for i=1, #amphetPlants, 1 do if GetDistanceBetweenCoords(coords, GetEntityCoords(amphetPlants[i]), false) < 2 then nearbyObject, nearbyID = amphetPlants[i], i end end if nearbyObject and IsPedOnFoot(playerPed) then --if not isPickingUp then --ESX.ShowHelpNotification(_U('amphet_pickupprompt')) --end if IsControlJustReleased(0, Keys['E']) and not isPickingUp then isPickingUp = true ESX.TriggerServerCallback('esx_illegal:canPickUp', function(canPickUp) if canPickUp then TaskStartScenarioInPlace(playerPed, 'world_human_gardener_plant', 0, false) Citizen.Wait(2000) ClearPedTasks(playerPed) Citizen.Wait(1500) ESX.Game.DeleteObject(nearbyObject) table.remove(amphetPlants, nearbyID) spawnedAmphets = spawnedAmphets - 1 TriggerServerEvent('esx_illegal:pickedUpAmphet') else ESX.ShowNotification(_U('Amphet_inventoryfull')) end isPickingUp = false end, 'extaamphetamine') end else Citizen.Wait(500) end end end) --Enleve les item apres AddEventHandler('onResourceStop', function(resource) if resource == GetCurrentResourceName() then for k, v in pairs(mdmaPlants) do ESX.Game.DeleteObject(v) end for k, v in pairs(amphetPlants) do ESX.Game.DeleteObject(v) end end end) function SpawnMdmaPlants() while spawnedMdmas < 2 do Citizen.Wait(0) local mdmaCoords = GenerateMdmaCoords() ESX.Game.SpawnLocalObject('prop_drug_package_02', mdmaCoords, function(obj) PlaceObjectOnGroundProperly(obj) FreezeEntityPosition(obj, true) table.insert(mdmaPlants, obj) spawnedMdmas = spawnedMdmas + 1 end) end end function SpawnAmphetPlants() while spawnedAmphets < 2 do Citizen.Wait(0) local amphetCoords = GenerateAmphetCoords() ESX.Game.SpawnLocalObject('ex_office_swag_pills2', amphetCoords, function(obj) PlaceObjectOnGroundProperly(obj) FreezeEntityPosition(obj, true) table.insert(amphetPlants, obj) spawnedAmphets = spawnedAmphets + 1 end) end end function ValidateMdmaCoord(plantCoord) if spawnedMdmas > 0 then local validate = true for k, v in pairs(mdmaPlants) do if GetDistanceBetweenCoords(plantCoord, GetEntityCoords(v), true) < 2 then validate = false end end if GetDistanceBetweenCoords(plantCoord, Config.CircleZones.MdmaField.coords, false) > 20 then validate = false end return validate else return true end end function ValidateAmphetCoord(plantCoord) if spawnedAmphets > 0 then local validate = true for k, v in pairs(amphetPlants) do if GetDistanceBetweenCoords(plantCoord, GetEntityCoords(v), true) < 2 then validate = false end end if GetDistanceBetweenCoords(plantCoord, Config.CircleZones.AmphetField.coords, false) > 20 then validate = false end return validate else return true end end function GenerateMdmaCoords() while true do Citizen.Wait(1) local mdmaCoordX, mdmaCoordY math.randomseed(GetGameTimer()) local modX = math.random(-3, 3) Citizen.Wait(100) math.randomseed(GetGameTimer()) local modY = math.random(-3, 3) mdmaCoordX = Config.CircleZones.MdmaField.coords.x + modX mdmaCoordY = Config.CircleZones.MdmaField.coords.y + modY local coordZ = GetCoordZMdma(mdmaCoordX, mdmaCoordY) local coord = vector3(mdmaCoordX, mdmaCoordY, coordZ) if ValidateMdmaCoord(coord) then return coord end end end function GenerateAmphetCoords() while true do Citizen.Wait(1) local amphetCoordX, amphetCoordY math.randomseed(GetGameTimer()) local modX = math.random(-3, 3) Citizen.Wait(100) math.randomseed(GetGameTimer()) local modY = math.random(-3, 3) amphetCoordX = Config.CircleZones.AmphetField.coords.x + modX amphetCoordY = Config.CircleZones.AmphetField.coords.y + modY local coordZ = GetCoordZAmphet(amphetCoordX, amphetCoordY) local coord = vector3(amphetCoordX, amphetCoordY, coordZ) if ValidateAmphetCoord(coord) then return coord end end end -- Hauteur du props possible function GetCoordZMdma(x, y) local groundCheckHeights = { 2.0 } for i, height in ipairs(groundCheckHeights) do local foundGround, z = GetGroundZFor_3dCoord(x, y, height) if foundGround then return z end end return 2.16 end function GetCoordZAmphet(x, y) local groundCheckHeights = { 105.0, 106.0 } for i, height in ipairs(groundCheckHeights) do local foundGround, z = GetGroundZFor_3dCoord(x, y, height) if foundGround then return z end end return 105.37 end -- infos Citizen.CreateThread(function() while true do Citizen.Wait(0) local plyPed = PlayerPedId() local coords = GetEntityCoords(plyPed) local door = vector4(-675.96, -885.01, 23.47, 272.59) if GetDistanceBetweenCoords(coords, door, true) < Config.DrawTextDist then ESX.ShowHelpNotification("Appuyez sur ~INPUT_CONTEXT~ pour frapper à la porte") if IsControlJustPressed(0, Keys["E"]) then ESX.UI.Menu.CloseAll() KnockDoor(door) ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'weed_info', { title = 'Emile', align = 'left', elements = { { label = 'Récolte 1 ('.. Config.CircleZones.MdmaField.price ..'$)', value = 'fieldMdma'}, { label = 'Récolte 2 ('.. Config.CircleZones.AmphetField.price ..'$)', value = 'fieldAmphet'}, { label = 'Deux Traitement ('.. Config.CircleZones.ExtaProcessing.price ..'$)', value = 'processExta'} } }, function(data, menu) menu.close() if data.current.value == 'fieldMdma' then BuyField(Config.CircleZones.MdmaField.coords, Config.CircleZones.MdmaField.price) elseif data.current.value == 'fieldAmphet' then BuyField(Config.CircleZones.AmphetField.coords, Config.CircleZones.AmphetField.price) elseif data.current.value == 'processExta' then BuyProcess(Config.CircleZones.ExtaProcessing.coords, Config.CircleZones.ExtaProcessing.price) ESX.ShowNotification("Il y a deux traitements à cette position, ne l'oublie pas") end end, function(data, menu) menu.close() end) end else Citizen.Wait(500) end end end)
24.214602
116
0.727181
64159686010cda84f115c8c65c316794d2fa1f14
350
py
Python
tests/test_checks.py
PeterJCLaw/flake8-multiline-containers
490fab7dfe0cbe306841c179d9d55abc0a2ed2b2
[ "MIT" ]
null
null
null
tests/test_checks.py
PeterJCLaw/flake8-multiline-containers
490fab7dfe0cbe306841c179d9d55abc0a2ed2b2
[ "MIT" ]
null
null
null
tests/test_checks.py
PeterJCLaw/flake8-multiline-containers
490fab7dfe0cbe306841c179d9d55abc0a2ed2b2
[ "MIT" ]
null
null
null
from flake8_multiline_containers import ErrorCodes def test_check_opening_contains_error(linter): linter._check_opening('{', '}', 0, "foo={a\n", ErrorCodes.JS101) assert 1 == len(linter.errors) def test_check_opening_no_error(linter): linter._check_opening('{', '}', 0, "foo={\n", ErrorCodes.JS101) assert 0 == len(linter.errors)
29.166667
68
0.714286
46d353f6906ceeeda62ca23d8a5e5a761fd3aeee
543
py
Python
tutorials/simple_flexx.py
Telcrome/ai-trainer
54bca3252e194c054bdd3af2b94d6dde940a2a86
[ "MIT" ]
1
2021-05-05T12:57:42.000Z
2021-05-05T12:57:42.000Z
tutorials/simple_flexx.py
Telcrome/ai-trainer
54bca3252e194c054bdd3af2b94d6dde940a2a86
[ "MIT" ]
null
null
null
tutorials/simple_flexx.py
Telcrome/ai-trainer
54bca3252e194c054bdd3af2b94d6dde940a2a86
[ "MIT" ]
null
null
null
import os from flexx import flx class Example(flx.PyWidget): def __init__(self): self.button, self.lbl = None, None super().__init__() def init(self): self.button = flx.Button(text='hello') self.lbl = flx.Label(flex=1, style='overflow-y: scroll;') @flx.reaction('button.pointer_click') def some_stuff(self, *events): self.lbl.set_html('<br />'.join(os.listdir('.'))) print(events) app = flx.App(Example) app.export('example.html', link=0) app.launch('browser') flx.run()
20.884615
65
0.622468
07c2b1c9196edae14082755ccc932a8253447502
855
dart
Dart
test/src/array_column_test.dart
Montana/phparray
a65afc30e9ddc2afa3cf197ef4c5d7d18ea8f411
[ "MIT" ]
null
null
null
test/src/array_column_test.dart
Montana/phparray
a65afc30e9ddc2afa3cf197ef4c5d7d18ea8f411
[ "MIT" ]
null
null
null
test/src/array_column_test.dart
Montana/phparray
a65afc30e9ddc2afa3cf197ef4c5d7d18ea8f411
[ "MIT" ]
null
null
null
library php_array.array_column_test.test; import 'package:unittest/unittest.dart'; import 'package:php_array/php_array.dart'; main(){ var testCaseList = [ { 'id': 10, 'c1': 'value11', 'c2': 'value12', }, { 'id': 20, 'c1': 'value21', 'c2': 'value22', }, { 'id': 30, 'c1': 'value31', 'c2': 'value32', }, { 'id': 40, 'c1': 'value41', 'c2': 'value42', } ]; test("array_column()", (){ var expactList=['value11', 'value21', 'value31', 'value41']; expect(array_column(testCaseList, 'c1'), expactList); }); test("array_column() with index_key", (){ var expactList={10: 'value11', 20: 'value21', 30: 'value31', 40: 'value41'}; expect(array_column(testCaseList, 'c1', 'id'), expactList); }); }
21.923077
84
0.506433
7758d426e0e1aa52d170085ab070a94bc2d0d0b2
11,124
lua
Lua
bin/shared/Compile.lua
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
bin/shared/Compile.lua
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
bin/shared/Compile.lua
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
#!/usr/bin/env lua -------------------------------------------------------------------------------- -- NOTE: this script is functionally equivalent to bin/mac/CompileScripts.sh -- If you are changing this one, you probably want to change the other. -------------------------------------------------------------------------------- local args = {...} -------------------------------------------------------------------------------- -- Functions -------------------------------------------------------------------------------- local function fileExists( path ) local f = io.open( path, "r" ) if f then f:close() return true end return false end local function checkError( passesCheck, msg ) if not passesCheck then if not msg then msg = "Exiting due to errors (above)." end print( "ERROR: ", msg ) -- os.exit( -1 ) end end local function execute( ... ) local args = { ... } local cmd = table.concat( args, ' ' ) local f = io.popen( cmd ) local result = f:read( "*a" ) f:close() return result end local function os_execute( ... ) local args = { ... } local cmd = table.concat( args, ' ' ) local rc = os.execute( cmd ) print("execute: ", cmd, "retcode: ", rc) return rc end local function touch( path ) io.open( path, "w" ):close() end local function escape( param ) return '"' .. param .. '"' end -------------------------------------------------------------------------------- -- Arguments -------------------------------------------------------------------------------- local PLATFORM local CORONA_ROOT if args then PLATFORM = args[1] CORONA_ROOT = args[2] end --[[ -- Platform of caller local PLATFORM if os.getenv("WINDIR") then PLATFORM = "win32" else local ostype = os.getenv( "OSTYPE" ) print( "OSTYPE,", ostype) if nil ~= string.find( ostype:lower(), "darwin", 1, true ) then PLATFORM = "mac" end end checkError( PLATFORM, "Could not determine platform." ) --]] -- Location of CoronaEnterprise directory checkError( PLATFORM, "Could not determine the OS this script is running on." ) checkError( CORONA_ROOT, "Could not determine path to 'Native' directory." ) local BIN_DIR = CORONA_ROOT .. "/Corona/" .. PLATFORM .. "/bin" if PLATFORM == "win" then BIN_DIR = CORONA_ROOT .. "\\Corona\\" .. PLATFORM .. "\\bin" end local BUILDER_PATH = BIN_DIR .. "/CoronaBuilder.app/Contents/MacOS/CoronaBuilder" if PLATFORM == "win" then BUILDER_PATH = BIN_DIR .. "\\CoronaBuilder.exe" end checkError( fileExists( BUILDER_PATH ), "Required CoronaBuilder tool not found at (" .. BUILDER_PATH .. ")" ) -------------------------------------------------------------------------------- -- Environment variables -------------------------------------------------------------------------------- -- [Required] TARGET_PLATFORM = os.getenv( "TARGET_PLATFORM" ) checkError( TARGET_PLATFORM, "Missing target device platform." ) -- [Required] Optional on iOS/Mac PROJECT_DIR = os.getenv( "PROJECT_DIR" ) checkError( PROJECT_DIR, "Missing environment variable 'PROJECT_DIR'." ) -- [Required] Optional on iOS/Mac CONFIGURATION = os.getenv( "CONFIGURATION" ) if not CONFIGURATION then CONFIGURATION = "debug" print( "WARNING: Defaulting to 'debug' configuration." ) end checkError( CONFIGURATION ) -- [Optional] Assuming you're okay with defaults CORONA_ASSETS_DIR = os.getenv( "CORONA_ASSETS_DIR" ) if not CORONA_ASSETS_DIR then CORONA_ASSETS_DIR = PROJECT_DIR .. "/../Corona" if PLATFORM == "win" then CORONA_ASSETS_DIR = PROJECT_DIR .. "\\..\\Corona" end end -- [Required] Optional on iOS/Mac CORONA_TARGET_RESOURCES_DIR = os.getenv( "CORONA_TARGET_RESOURCES_DIR" ) if not CORONA_TARGET_RESOURCES_DIR then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then -- $TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH TARGET_BUILD_DIR = os.getenv( "TARGET_BUILD_DIR" ) UNLOCALIZED_RESOURCES_FOLDER_PATH = os.getenv( "UNLOCALIZED_RESOURCES_FOLDER_PATH" ) if TARGET_BUILD_DIR and UNLOCALIZED_RESOURCES_FOLDER_PATH then CORONA_TARGET_RESOURCES_DIR = TARGET_BUILD_DIR .. '/' .. UNLOCALIZED_RESOURCES_FOLDER_PATH end end end checkError( CORONA_TARGET_RESOURCES_DIR, "Missing target build resources directory." ) -- [Required] Optional on iOS/Mac CORONA_TARGET_EXECUTABLE_DIR = os.getenv( "CORONA_TARGET_EXECUTABLE_DIR" ) if not CORONA_TARGET_EXECUTABLE_DIR then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then -- $TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH TARGET_BUILD_DIR = os.getenv( "TARGET_BUILD_DIR" ) EXECUTABLE_FOLDER_PATH = os.getenv( "EXECUTABLE_FOLDER_PATH" ) if TARGET_BUILD_DIR and EXECUTABLE_FOLDER_PATH then CORONA_TARGET_EXECUTABLE_DIR = TARGET_BUILD_DIR .. '/' .. EXECUTABLE_FOLDER_PATH end end end checkError( CORONA_TARGET_EXECUTABLE_DIR, "Missing target build executable directory." ) -- [Required] Optional on iOS/Mac BUNDLE_ID = os.getenv( "BUNDLE_ID" ) if not BUNDLE_ID then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then -- local cmd = '/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$TARGET_BUILD_DIR/$INFOPLIST_PATH"' BUNDLE_ID = execute( cmd ) end end -- Remove trailing whitespace (including newline) if BUNDLE_ID then BUNDLE_ID = BUNDLE_ID:gsub( '%s', "" ) end -- [Required] Optional on iOS/Mac local APP_ID = os.getenv( "APP_ID" ) if not APP_ID then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then local cmd = '/usr/libexec/PlistBuddy -c "Print :CoronaAppId" "$TARGET_BUILD_DIR/$INFOPLIST_PATH" 2>/dev/null' APP_ID = execute( cmd ) end end -- Assign if all else fails if "" == APP_ID or not APP_ID then if BUNDLE_ID then APP_ID = BUNDLE_ID end end -- Remove trailing whitespace (including newline) if APP_ID then APP_ID = APP_ID:gsub( '%s', "" ) end -- Ignore the given Bundle ID and App ID for Android Enterprise builds. -- This is because most enterprise users do not know to set the package name in the "build.xml" file. if "android" == TARGET_PLATFORM then BUNDLE_ID = nil APP_ID = nil end local RESOURCE_EXT = ".car" if "ios" == TARGET_PLATFORM then RESOURCE_EXT = ".corona-archive" end -- [Optional] USER_ID = os.getenv( "USER_ID" ) if not USER_ID then USER_ID = '345' end if BUNDLE_ID then print( "Using Bundle Id: (" .. BUNDLE_ID .. ")" ) end if APP_ID then print( "Using AppId: (" .. APP_ID .. ")" ) end -------------------------------------------------------------------------------- -- Main -------------------------------------------------------------------------------- -- Copy project resources, compile Lua scripts, etc -- "$BIN_DIR/CopyResources.sh" $CONFIGURATION "$CORONA_ASSETS_DIR" "$CORONA_TARGET_RESOURCES_DIR" "$BIN_DIR" local CopyResourcesScript = escape( BIN_DIR .. "/CopyResources.sh" ) if PLATFORM == "win" then CopyResourcesScript = 'cmd /Q/C "' .. escape( BIN_DIR .. "\\CopyResources.bat" ) .. ' ' .. CONFIGURATION .. ' ' .. escape( CORONA_ASSETS_DIR ) .. ' ' .. escape( CORONA_TARGET_RESOURCES_DIR ) .. ' ' .. escape( BIN_DIR ) .. '"' local result = os_execute(CopyResourcesScript) checkError( 0 == tonumber( result ) ) else local result = os_execute( CopyResourcesScript, CONFIGURATION, escape( CORONA_ASSETS_DIR ), escape( CORONA_TARGET_RESOURCES_DIR ), escape( BIN_DIR ) ) checkError( 0 == tonumber( result ) ) end -- Config.lua TMP_FILE = os.tmpname() if PLATFORM == "win" then TMP_FILE = os.getenv('TMP')..TMP_FILE end CONFIG_META = TMP_FILE -- "$TARGET_BUILD_DIR/config.metadata.lua" local pl = require "pl" local pl_dir = require "pl.dir" local pl_path = require "pl.path" local pl_file = require "pl.file" PROJECT_NAME = pl_path.basename( PROJECT_DIR ) -- `basename "$PROJECT_DIR"` MODE="distribution" if nil ~= string.find( CONFIGURATION:lower(), "Debug", 1, true ) then MODE="developer" end print("Creating application.metadata ...") local config_meta_format = [[ -- Ensure existence of "application" table if not application or type( application ) ~= "table" then application = {} end application.metadata = { appName = "%s", appVersion = "1.0", %s %s userId = "%s", mode = "%s", } ]] local bundleIdTableEntry = "" if BUNDLE_ID then bundleIdTableEntry = 'appPackageId = "' .. tostring(BUNDLE_ID) .. '",' end local appIdTableEntry = "" if APP_ID then appIdTableEntry = 'appId = "' .. tostring(APP_ID) .. '",' end local config_meta = string.format( config_meta_format, PROJECT_NAME, bundleIdTableEntry, appIdTableEntry, USER_ID, MODE ) local config_meta_file = io.open( CONFIG_META, "w+" ) print("CONFIG_META=", CONFIG_META, "config_meta_file=", config_meta_file, config_meta) config_meta_file:write( config_meta ) config_meta_file:close() -- Concatenate config.metadata.lua into config.lu overwriting original config.lu CONFIG_DST = CORONA_TARGET_EXECUTABLE_DIR .. "/config.lu" CONFIG_SRC = CORONA_TARGET_EXECUTABLE_DIR .. "/config.orig.lu" if not fileExists( CONFIG_DST ) then touch( CONFIG_SRC ) else pl_file.move( CONFIG_DST, CONFIG_SRC ) end -- "$LUAC" -s -o "$CONFIG_DST" "$CONFIG_SRC" "$CONFIG_META" if PLATFORM == "win" then LUAC = 'cmd /Q/C "' .. escape( BIN_DIR .. "\\luac.exe" ) .. ' ' .. '-s -o' .. ' ' .. escape( CONFIG_DST ) .. ' ' .. escape( CONFIG_SRC ) .. ' ' .. escape( CONFIG_META ) .. '"' local result = os_execute(LUAC) checkError( 0 == result, "Failed to compile Lua files." ) else LUAC = BIN_DIR .. "/luac" local result = os_execute( escape(LUAC), '-s -o', escape( CONFIG_DST ), escape( CONFIG_SRC ), escape( CONFIG_META ) ) checkError( 0 == result, "Failed to compile Lua files." ) end pl_file.delete( CONFIG_SRC ) pl_file.delete( CONFIG_META ) -- Create resource.{car,corona-archive} from *.lu -- "$BUILDER_PATH" car "$CORONA_TARGET_EXECUTABLE_DIR/resource.corona-archive" "$CORONA_TARGET_EXECUTABLE_DIR"/*.lu print( 'Archiving ' .. CORONA_TARGET_EXECUTABLE_DIR ..'/*.lu into ' .. CORONA_TARGET_EXECUTABLE_DIR .. '/resource' .. RESOURCE_EXT ) if PLATFORM == "win" then local result = os_execute( 'cmd /Q/C "dir /s/b', escape( CORONA_TARGET_EXECUTABLE_DIR .. "\\*.lu"), '|', escape( BUILDER_PATH ), 'car', '-f -', -- read file list from stdin escape( CORONA_TARGET_EXECUTABLE_DIR .. "/resource" .. RESOURCE_EXT ), '"') checkError( 0 == result, "Failed to generate resource" .. RESOURCE_EXT ) else local result = os_execute( 'find -H', escape( CORONA_TARGET_EXECUTABLE_DIR ), '-maxdepth 1 -name "*.lu" -print', -- avoid cmd line length issues with "*.lu" '|', escape( BUILDER_PATH ), 'car', '-f -', -- read file list from stdin escape( CORONA_TARGET_EXECUTABLE_DIR .. "/resource" .. RESOURCE_EXT ) ) checkError( 0 == result, "Failed to generate resource" .. RESOURCE_EXT ) end -- rm -f "$CORONA_TARGET_EXECUTABLE_DIR"/*.lu if PLATFORM == "win" then print( 'Removing: ' .. CORONA_TARGET_EXECUTABLE_DIR .. '\\*.lu' ) local result = os_execute('del', CORONA_TARGET_EXECUTABLE_DIR .. "\\*.lu") else print( 'Removing: ' .. CORONA_TARGET_EXECUTABLE_DIR .. '/*.lu' ) local result = os_execute( 'find -H', escape( CORONA_TARGET_EXECUTABLE_DIR ), '-maxdepth 1 -name "*.lu" -exec rm -f {} \\;') end
29.120419
132
0.651115
d309076e9f58067af3272a1c4d9fabbc75ac4326
1,557
cs
C#
MassTransit.Season1/1_InMemory_Mediator/src/Sample.API/Controllers/OrderController.cs
AdamGrzonkowski/MassTransit_SampleProject
c52b7c86f0216f2af95c81a150456673cec5ef1b
[ "Apache-2.0" ]
null
null
null
MassTransit.Season1/1_InMemory_Mediator/src/Sample.API/Controllers/OrderController.cs
AdamGrzonkowski/MassTransit_SampleProject
c52b7c86f0216f2af95c81a150456673cec5ef1b
[ "Apache-2.0" ]
null
null
null
MassTransit.Season1/1_InMemory_Mediator/src/Sample.API/Controllers/OrderController.cs
AdamGrzonkowski/MassTransit_SampleProject
c52b7c86f0216f2af95c81a150456673cec5ef1b
[ "Apache-2.0" ]
null
null
null
using System.Net; using MassTransit; using Microsoft.AspNetCore.Mvc; using Sample.Contracts; namespace Twitch.Controllers { [ApiController] [Route("[controller]")] public class OrderController : ControllerBase { private readonly ILogger<OrderController> _logger; private readonly IRequestClient<SubmitOrder> _submitOrderRequestClient; public OrderController(ILogger<OrderController> logger, IRequestClient<SubmitOrder> submitOrderRequestClient) { _logger = logger; _submitOrderRequestClient = submitOrderRequestClient; } [HttpPost] [ProducesResponseType(((int)HttpStatusCode.Accepted), Type = typeof(OrderSubmissionAccepted))] [ProducesResponseType(((int)HttpStatusCode.BadRequest), Type = typeof(OrderSubmissionRejected))] public async Task<IActionResult> Post(string id, string customerNumber) { var (accepted, rejected) = await _submitOrderRequestClient.GetResponse<OrderSubmissionAccepted, OrderSubmissionRejected>(new { OrderId = id, Timestamp = DateTimeOffset.UtcNow, CustomerNumber = customerNumber }); if (accepted.IsCompletedSuccessfully) { var response = await accepted; return Accepted(response.Message); } else { var response = await rejected; return BadRequest(response.Message); } } } }
34.6
136
0.633269
634405b900b2ae55bba575909994c0f80563d911
1,515
rs
Rust
src/models/tweet.rs
magurotuna/kuon
9409e21910e305aefbe5b60d6244997856fe66a7
[ "MIT" ]
1
2020-06-15T06:20:17.000Z
2020-06-15T06:20:17.000Z
src/models/tweet.rs
magurotuna/kuon
9409e21910e305aefbe5b60d6244997856fe66a7
[ "MIT" ]
null
null
null
src/models/tweet.rs
magurotuna/kuon
9409e21910e305aefbe5b60d6244997856fe66a7
[ "MIT" ]
null
null
null
// #[derive(Debug, Clone, Deserialize)] // pub(crate) struct RawTweet { // pub coordinates: Option<RawCoordinates>, // #[serde(deserialize_with = "deserialize_datetime")] // pub created_at: chrono::DateTime<chrono::Utc>, // pub current_user_retweet: Option<CurrentUserRetweet>, // pub display_text_range: Option<(usize, usize)>, // pub entities: TweetEntities, // pub extended_entities: Option<ExtendedTweetEntities>, // pub extended_tweet: Option<RawExtendedTweet>, // pub favorite_count: i32, // pub favorited: Option<bool>, // pub filter_level: Option<FilterLevel>, // pub id: u64, // pub in_reply_to_user_id: Option<u64>, // pub in_reply_to_screen_name: Option<String>, // pub in_reply_to_status_id: Option<u64>, // pub lang: Option<String>, // pub place: Option<place::Place>, // pub possibly_sensitive: Option<bool>, // pub quoted_status_id: Option<u64>, // pub quoted_status: Option<Box<Tweet>>, // pub retweet_count: i32, // pub retweeted: Option<bool>, // pub retweeted_status: Option<Box<Tweet>>, // #[serde(deserialize_with = "deserialize_tweet_source")] // pub source: Option<TweetSource>, // pub text: Option<String>, // pub full_text: Option<String>, // pub truncated: bool, // pub user: Option<Box<user::TwitterUser>>, // #[serde(default)] // pub withheld_copyright: bool, // pub withheld_in_countries: Option<Vec<String>>, // pub withheld_scope: Option<String>, // }
40.945946
62
0.666667
eb202b8b31deb3dd2510d5f7538ed8e06cdf4b36
1,575
css
CSS
Esercizi-CSS/04 Grid/start/style.css
Edoardo-Longo/Esercizi-CSS
baac95b7619b8fcb5508c3bc435063c2242104ab
[ "MIT" ]
null
null
null
Esercizi-CSS/04 Grid/start/style.css
Edoardo-Longo/Esercizi-CSS
baac95b7619b8fcb5508c3bc435063c2242104ab
[ "MIT" ]
null
null
null
Esercizi-CSS/04 Grid/start/style.css
Edoardo-Longo/Esercizi-CSS
baac95b7619b8fcb5508c3bc435063c2242104ab
[ "MIT" ]
null
null
null
*{ padding: 0; margin: 0; box-sizing: border-box; } body{ display: flex; justify-content: center; align-items: center; } .calculator{ font-size: 5rem; width: 700px; height: 700px; border: 1px solid black; display: grid; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(6, 1fr); align-items: center; justify-items: center; border-radius: 1rem; } .result{ grid-column: 1/ span 4; grid-row: 1; height: 100%; width: 100%; color: white; background-color: #424c52; display: flex; justify-content: flex-end; padding-right: 1rem; align-items: center; border: 1px solid black; border-top-left-radius: 1rem; border-top-right-radius: 1rem; } .operator{ border: 1px solid black; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; background-color: #d2dce3; } .num, .point, .reset{ border: 1px solid black; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; background-color: #eff2f5; } .equal{ grid-column: 4; grid-row: 3/span 4; height: 100%; width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: #f77077; border: 1px solid black; border-bottom-right-radius: 1rem; } .calculator>:nth-child(21){ border-bottom-left-radius: 1rem; }
20.192308
43
0.586667
b359169bb6abe7d9dc8abc629c722ce2193a4db7
680
py
Python
botclean/Strategies/random_walk.py
Kabix1/HackerRank
1570fd451a06f68f78268c02096fd28d39ee3df0
[ "Apache-2.0" ]
null
null
null
botclean/Strategies/random_walk.py
Kabix1/HackerRank
1570fd451a06f68f78268c02096fd28d39ee3df0
[ "Apache-2.0" ]
null
null
null
botclean/Strategies/random_walk.py
Kabix1/HackerRank
1570fd451a06f68f78268c02096fd28d39ee3df0
[ "Apache-2.0" ]
null
null
null
import numpy as np import random def is_valid(pos, board): try: board[pos[0]][pos[1]] except IndexError: return False if min(pos) < 0: return False return True def _next_move(pos, board): moves = { "RIGHT": np.array((0, 1)), "UP": np.array((-1, 0)), "LEFT": np.array((0, -1)), "DOWN": np.array((1, 0)), } dirs = ["UP", "LEFT", "DOWN", "RIGHT"] # if "b" not in board: if board[pos[0]][pos[1]] == "d": return "CLEAN" new_pos = (-1, -1) while not is_valid(new_pos, board): dir = dirs[random.randint(0, 3)] new_pos = tuple(pos + moves[dir]) return dir
21.935484
42
0.508824
b224bb878b19bbe1b3c712ae27891f8be80cf01c
724
rb
Ruby
ee/spec/factories/users.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
2
2020-11-23T17:03:26.000Z
2021-08-18T02:56:43.000Z
ee/spec/factories/users.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
26
2020-12-08T02:47:19.000Z
2022-02-26T02:18:34.000Z
ee/spec/factories/users.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
4
2020-09-23T08:06:56.000Z
2020-11-06T04:49:12.000Z
# frozen_string_literal: true FactoryBot.modify do factory :user do trait :auditor do auditor { true } end trait :group_managed do association :managing_group, factory: :group_with_managed_accounts after(:create) do |user, evaluator| create(:group_saml_identity, user: user, saml_provider: user.managing_group.saml_provider ) end end trait :service_user do user_type { :service_user } end end factory :omniauth_user do transient do saml_provider { nil } end end end FactoryBot.define do factory :auditor, parent: :user, traits: [:auditor] factory :external_user, parent: :user, traits: [:external] end
20.111111
72
0.660221
e27920ba4e7397c05cd823240f07f346c810a3a2
843
py
Python
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/mb_20011019.py
aleasims/Peach
bb56841e943d719d5101fee0a503ed34308eda04
[ "MIT" ]
null
null
null
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/mb_20011019.py
aleasims/Peach
bb56841e943d719d5101fee0a503ed34308eda04
[ "MIT" ]
null
null
null
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/mb_20011019.py
aleasims/Peach
bb56841e943d719d5101fee0a503ed34308eda04
[ "MIT" ]
1
2020-07-26T03:57:45.000Z
2020-07-26T03:57:45.000Z
# expat2domlette.c seems to get confused about xmlns attributes, # like which part is the localName and which part is the prefix. from Xml.Xslt import test_harness source_1 = """\ <?xml version="1.0"?> <foobar/>""" sheet_1 = """\ <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ss="urn:wonky" > <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <results/> </xsl:template> </xsl:stylesheet>""" expected_1 = """<?xml version='1.0' encoding='UTF-8'?> <results xmlns:ss="urn:wonky"/>""" def Test(tester): source = test_harness.FileInfo(string=source_1) sheet = test_harness.FileInfo(string=sheet_1) test_harness.XsltTest(tester, source, [sheet], expected_1, title='namespace copy-through') return
25.545455
64
0.66548
fea6925ca2280703ccf3e29d0c57cbf1095b659c
1,631
swift
Swift
Examples/Watch Extension/InterfaceController.swift
tozny/swift-sodium
a060b1301d87db1a48f4d3ed07bdffff8eaab987
[ "ISC" ]
474
2015-01-02T17:53:31.000Z
2022-03-31T06:22:55.000Z
Examples/Watch Extension/InterfaceController.swift
tozny/swift-sodium
a060b1301d87db1a48f4d3ed07bdffff8eaab987
[ "ISC" ]
234
2015-01-06T06:53:02.000Z
2022-02-16T16:04:18.000Z
Examples/Watch Extension/InterfaceController.swift
tozny/swift-sodium
a060b1301d87db1a48f4d3ed07bdffff8eaab987
[ "ISC" ]
215
2015-01-06T05:57:48.000Z
2022-03-25T22:29:15.000Z
// // InterfaceController.swift // Example Watch Extension // // Created by Joseph Ross on 10/2/18. // Copyright © 2018 Frank Denis. All rights reserved. // import WatchKit import Foundation import Sodium class InterfaceController: WKInterfaceController { override func awake(withContext context: Any?) { super.awake(withContext: context) let sodium = Sodium() let aliceKeyPair = sodium.box.keyPair()! let bobKeyPair = sodium.box.keyPair()! let message = "My Test Message".bytes print("Original Message:\(message.utf8String!)") let encryptedMessageFromAliceToBob: Bytes = sodium.box.seal( message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! print("Encrypted Message:\(encryptedMessageFromAliceToBob)") let messageVerifiedAndDecryptedByBob = sodium.box.open( nonceAndAuthenticatedCipherText: encryptedMessageFromAliceToBob, senderPublicKey: bobKeyPair.publicKey, recipientSecretKey: aliceKeyPair.secretKey) print("Decrypted Message:\(messageVerifiedAndDecryptedByBob!.utf8String!)") } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
30.203704
90
0.640711
2a5248192ec52f58c0428a48bb3bb5890e9ab445
857
css
CSS
blindspotapp/static/blindspotapp/getinfo.css
LucyWilcox/VIEW-site
b49dd7800688cf3ffae785b59025e035e94d0231
[ "MIT" ]
null
null
null
blindspotapp/static/blindspotapp/getinfo.css
LucyWilcox/VIEW-site
b49dd7800688cf3ffae785b59025e035e94d0231
[ "MIT" ]
9
2020-06-05T16:49:15.000Z
2022-01-06T00:51:57.000Z
blindspotapp/static/blindspotapp/getinfo.css
LucyWilcox/VIEW-site
b49dd7800688cf3ffae785b59025e035e94d0231
[ "MIT" ]
1
2020-03-27T13:30:22.000Z
2020-03-27T13:30:22.000Z
.container { margin: 0 auto; display: block; } .grid-container-1 { display: grid; grid-template-columns: auto; padding: 10px; margin: auto; } .grid-item-1 { background-color: rgba(255, 255, 255, 0.8); border: 1px solid rgba(0, 0, 0, 0.8); padding: 10px; font-size: 20px; text-align: center; } .grid-container-2 { display: grid; grid-template-columns: auto auto; padding: 10px; margin: auto; } .grid-item-2 { background-color: rgba(255, 255, 255, 0.8); border: 1px solid rgba(0, 0, 0, 0.8); padding: 10px; font-size: 20px; text-align: center; } .grid-container-4 { display: grid; grid-template-columns: auto auto; padding: 10px; margin: auto; } .grid-item-4 { background-color: rgba(255, 255, 255, 0.8); border: 1px solid rgba(0, 0, 0, 0.8); padding: 10px; font-size: 20px; text-align: center; }
17.854167
45
0.638273
93c44bab6df3c72b283ac243427652c2cb809ce3
962
cs
C#
SortingLibrary/SortingLibrary/SortingMethod/BubbleSort.cs
artgl42/Algorithms
0d24d6774b35b3d070ed3c50c8b52ffe0b4e5714
[ "MIT" ]
null
null
null
SortingLibrary/SortingLibrary/SortingMethod/BubbleSort.cs
artgl42/Algorithms
0d24d6774b35b3d070ed3c50c8b52ffe0b4e5714
[ "MIT" ]
null
null
null
SortingLibrary/SortingLibrary/SortingMethod/BubbleSort.cs
artgl42/Algorithms
0d24d6774b35b3d070ed3c50c8b52ffe0b4e5714
[ "MIT" ]
null
null
null
using System; namespace SortingLibrary { public class BubbleSort : ISortingMethod { public ulong Sort<T>(T[] arrayForSort) where T : IComparable<T> { T _temp; ulong _count = 0; bool _swap; for (int i = 0; i < arrayForSort.Length; i++) { _swap = false; for (int j = 0; j < arrayForSort.Length - i - 1; j++) { if (arrayForSort[j].CompareTo(arrayForSort[j + 1]) > 0) { _temp = arrayForSort[j + 1]; arrayForSort[j + 1] = arrayForSort[j]; arrayForSort[j] = _temp; _count++; _swap = true; } } if (!_swap) return _count; } return _count; } } }
27.485714
75
0.37422
0cc4792c8814caa8ea610024a630891574faea57
5,658
dart
Dart
lib/domain/entity/RankingUserInfo.dart
yzhui/sailmi-mifere-app
9f43d401cff9e2d05a099f2fce0e3287dd9a7618
[ "MIT" ]
154
2019-10-08T05:44:00.000Z
2022-03-21T03:11:51.000Z
lib/domain/entity/RankingUserInfo.dart
yzhui/sailmi-mifere-app
9f43d401cff9e2d05a099f2fce0e3287dd9a7618
[ "MIT" ]
148
2019-10-07T01:39:09.000Z
2021-12-03T15:26:31.000Z
lib/domain/entity/RankingUserInfo.dart
yzhui/sailmi-mifere-app
9f43d401cff9e2d05a099f2fce0e3287dd9a7618
[ "MIT" ]
38
2019-10-08T07:45:31.000Z
2021-12-03T15:05:04.000Z
import 'package:todo_app/domain/entity/Pet.dart'; import 'package:todo_app/domain/entity/Pets.dart'; import 'package:todo_app/domain/repository/DateRepository.dart'; class RankingUserInfo { static const KEY_UID = 'uid'; static const KEY_NAME = 'name'; static const KEY_COMPLETION_RATIO = 'completion_ratio'; static const KEY_LATEST_STREAK = 'latest_streak'; static const KEY_LATEST_STREAK_END_MILLIS = 'latest_streak_end_millis'; static const KEY_LONGEST_STREAK = 'longest_streak'; static const KEY_LONGEST_STREAK_END_MILLIS = 'longest_streak_end_millis'; static const KEY_THUMB_UP_COUNT = 'thumbs_up'; static const KEY_LAST_UPDATED_MILLIS = 'last_updated_millis'; static const KEY_PET_KEY = 'pet_key'; static const KEY_PET_PHASE_INDEX = 'pet_phase_index'; static const KEY_FIRST_LAUNCH_DATE_MILLIS = 'first_launch_date_millis'; static const KEY_COMPLETED_DAYS_COUNT = 'completed_days_count'; static const INVALID = const RankingUserInfo(); static RankingUserInfo fromMap(Map<String, dynamic> map) { return RankingUserInfo( uid: map[KEY_UID] ?? '', name: map[KEY_NAME] ?? '', completionRatio: map[KEY_COMPLETION_RATIO] * 1.0 ?? 0.0, // need this to convert to double.. latestStreak: map[KEY_LATEST_STREAK] ?? 0, latestStreakEndMillis: map[KEY_LATEST_STREAK_END_MILLIS] ?? 0, longestStreak: map[KEY_LONGEST_STREAK] ?? 0, longestStreakEndMillis: map[KEY_LONGEST_STREAK_END_MILLIS] ?? 0, thumbUpCount: map[KEY_THUMB_UP_COUNT] ?? 0, lastUpdatedMillis: map[KEY_LAST_UPDATED_MILLIS] ?? 0, petKey: map[KEY_PET_KEY] ?? '', petPhaseIndex: map[KEY_PET_PHASE_INDEX] ?? Pet.PHASE_INDEX_INACTIVE, firstLaunchDateMillis: map[KEY_FIRST_LAUNCH_DATE_MILLIS] ?? 0, completedDaysCount: map[KEY_COMPLETED_DAYS_COUNT] ?? 0, ); } final String uid; final String name; final double completionRatio; final int latestStreak; final int latestStreakEndMillis; final int longestStreak; final int longestStreakEndMillis; final int thumbUpCount; final int lastUpdatedMillis; final String petKey; final int petPhaseIndex; final int firstLaunchDateMillis; final int completedDaysCount; final int rank; PetPhase get petPhase { final pet = Pets.getPetPrototype(petKey); if (!pet.isValid) { return PetPhase.INVALID; } else { return petPhaseIndex == Pet.PHASE_INDEX_INACTIVE ? PetPhase.INVALID : petPhaseIndex == Pet.PHASE_INDEX_EGG ? pet.eggPhase : pet.bornPhases[petPhaseIndex]; } } DateTime get latestStreakStartDate { if (latestStreakEndMillis == 0) { return DateRepository.INVALID_DATE; } else { return DateTime.fromMillisecondsSinceEpoch(latestStreakEndMillis).subtract(Duration(days: latestStreak - 1)); } } DateTime get latestStreakEndDate { if (latestStreakEndMillis == 0) { return DateRepository.INVALID_DATE; } else { return DateTime.fromMillisecondsSinceEpoch(latestStreakEndMillis); } } DateTime get longestStreakStartDate { if (longestStreakEndMillis == 0) { return DateRepository.INVALID_DATE; } else { return DateTime.fromMillisecondsSinceEpoch(longestStreakEndMillis).subtract(Duration(days: longestStreak - 1)); } } DateTime get longestStreakEndDate { if (longestStreakEndMillis == 0) { return DateRepository.INVALID_DATE; } else { return DateTime.fromMillisecondsSinceEpoch(longestStreakEndMillis); } } String get completionRatioPercentageString { return (completionRatio * 100).toStringAsFixed(1).padLeft(4, '0'); } bool get isValid => uid.isNotEmpty; const RankingUserInfo({ this.uid = '', this.name = '', this.completionRatio = 0, this.latestStreak = 0, this.latestStreakEndMillis = 0, this.longestStreak = 0, this.longestStreakEndMillis = 0, this.thumbUpCount = 0, this.lastUpdatedMillis = 0, this.petKey = '', this.petPhaseIndex = Pet.PHASE_INDEX_INACTIVE, this.firstLaunchDateMillis = 0, this.completedDaysCount = 0, this.rank = 0, }); RankingUserInfo buildNew({ double completionRatio, int thumbUpCount, int rank, }) { return RankingUserInfo( uid: this.uid, name: this.name, completionRatio: completionRatio ?? this.completionRatio, latestStreak: this.latestStreak, latestStreakEndMillis: this.latestStreakEndMillis, longestStreak: this.longestStreak, longestStreakEndMillis: this.longestStreakEndMillis, thumbUpCount: thumbUpCount ?? this.thumbUpCount, lastUpdatedMillis: this.lastUpdatedMillis, petKey: this.petKey, petPhaseIndex: this.petPhaseIndex, firstLaunchDateMillis: this.firstLaunchDateMillis, completedDaysCount: this.completedDaysCount, rank: rank ?? this.rank, ); } Map<String, dynamic> toMyRankingUserInfoUpdateMap() { return { KEY_UID: uid, KEY_NAME: name, KEY_COMPLETION_RATIO: completionRatio, KEY_LATEST_STREAK: latestStreak, KEY_LATEST_STREAK_END_MILLIS: latestStreakEndMillis, KEY_LONGEST_STREAK: longestStreak, KEY_LONGEST_STREAK_END_MILLIS: longestStreakEndMillis, KEY_PET_KEY: petKey, KEY_PET_PHASE_INDEX: petPhaseIndex, KEY_FIRST_LAUNCH_DATE_MILLIS: firstLaunchDateMillis, KEY_COMPLETED_DAYS_COUNT: completedDaysCount, }; } Map<String, dynamic> toThumbUpCountUpdateMap() { return { KEY_THUMB_UP_COUNT: thumbUpCount, }; } Map<String, dynamic> toCompletionRatioUpdateMap() { return { KEY_COMPLETION_RATIO: completionRatio, }; } }
32.705202
117
0.72128
07e58a98475796b9d3a6e82d34b83b071fee3cb0
1,259
css
CSS
css/styles.css
alexandraholcombe/pig-dice
e4c3a55e3baf832dc9ca66f8d24d60fdf74cd71d
[ "MIT" ]
null
null
null
css/styles.css
alexandraholcombe/pig-dice
e4c3a55e3baf832dc9ca66f8d24d60fdf74cd71d
[ "MIT" ]
null
null
null
css/styles.css
alexandraholcombe/pig-dice
e4c3a55e3baf832dc9ca66f8d24d60fdf74cd71d
[ "MIT" ]
null
null
null
@font-face { font-family: 'dPoly Block Dice'; src: url('../resources/dPoly-Block-Dice.ttf.eot'); /* IE9 Compat Modes */ src: url('../resources/dPoly-Block-Dice?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('../resources/dPoly-Block-Dice.ttf.woff') format('woff'), /* Pretty Modern Browsers */ url('../resources/dPoly-Block-Dice.ttf') format('truetype'), /* Safari, Android, iOS */ url('../resources/dPoly-Block-Dice.svg#dPoly-Block-Dice') format('svg'); /* Legacy iOS */ } .dice { font-family: 'dPoly Block Dice', fantasy; font-size: 150px; } .player-boxes { text-align: center; } .button-container button { margin: 20px auto; display: block; } .overlay { background-color: rgba(96, 93, 97, 0.6); z-index: 1000; height: 100%; width: 100%; position: absolute; display: none; } #screen-overlay { position: fixed; z-index: 100; background-color: rgba(0, 0, 0, 0.44); width: 100%; height: 100%; display: none; } #winner, #player-mode { font-size: 30px; margin-left: 30%; margin-right: 30%; margin-top: 25%; background-color: #ffffff; text-align: center; border-radius: 5px; padding: 20px; z-index: 1001; } #player-mode button { margin: 1em 0 1em; } #winner { display: none; }
20.639344
93
0.639396
20ba123f041ad5c8982b0844a125980ee9a462c0
1,952
cs
C#
KilyCore.DataEntity/RequestMapper/Repast/RequestRepastArticleInStock.cs
EmilyEdna/KilyCore
3dda9b733f5a654f2b4b62f86183c065b4699155
[ "Apache-2.0" ]
4
2017-09-29T08:13:13.000Z
2021-02-22T17:39:35.000Z
KilyCore.DataEntity/RequestMapper/Repast/RequestRepastArticleInStock.cs
EmilyEdna/KilyCore
3dda9b733f5a654f2b4b62f86183c065b4699155
[ "Apache-2.0" ]
null
null
null
KilyCore.DataEntity/RequestMapper/Repast/RequestRepastArticleInStock.cs
EmilyEdna/KilyCore
3dda9b733f5a654f2b4b62f86183c065b4699155
[ "Apache-2.0" ]
1
2017-09-29T08:40:06.000Z
2017-09-29T08:40:06.000Z
using System; using System.Collections.Generic; using System.Text; #region << 版 本 注 释 >> /*---------------------------------------------------------------- * 类 名 称 :RequestRepastArticleInStock * 类 描 述 : * 命名空间 :KilyCore.DataEntity.RequestMapper.Repast * 机器名称 :EMILY * CLR 版本 :4.0.30319.42000 * 作 者 :$刘泽华$ * 创建时间 :2018/8/9 11:55:17 ******************************************************************* * Copyright @ $刘泽华$ 2018. All rights reserved. ******************************************************************* //----------------------------------------------------------------*/ #endregion namespace KilyCore.DataEntity.RequestMapper.Repast { public class RequestRepastArticleInStock { public Guid Id { get; set; } public Guid InfoId { get; set; } /// <summary> /// 类型Id /// </summary> public Guid? NameId { get; set; } /// <summary> /// 批次号 /// </summary> public string BatchNo { get; set; } /// <summary> /// 物品名称 /// </summary> public string ArticleName { get; set; } /// <summary> /// 入库数量 /// </summary> public int InStockNum { get; set; } /// <summary> /// 单价 /// </summary> public decimal? PrePrice { get; set; } /// <summary> /// 总价 /// </summary> public decimal? ToPrice { get; set; } /// <summary> /// 供应商 /// </summary> public string Supplier { get; set; } /// <summary> /// 生产地址 /// </summary> public string Address { get; set; } /// <summary> /// 电话 /// </summary> public string Phone { get; set; } /// <summary> /// 备注 /// </summary> public string Remark { get; set; } /// <summary> /// 采购负责人 /// </summary> public string BuyUser { get; set; } } }
27.492958
68
0.419057
d4aca08a7bb00c3cde91e0aad6f9a2352bef16d6
20,515
dart
Dart
ColourPattern/lib/study_src/Survey/consent_form.dart
geddesc/CHI-2022-Improving-Colour-Patterns
761b34a72c6b79ce498a11941a2076d71fcf5429
[ "MIT" ]
null
null
null
ColourPattern/lib/study_src/Survey/consent_form.dart
geddesc/CHI-2022-Improving-Colour-Patterns
761b34a72c6b79ce498a11941a2076d71fcf5429
[ "MIT" ]
null
null
null
ColourPattern/lib/study_src/Survey/consent_form.dart
geddesc/CHI-2022-Improving-Colour-Patterns
761b34a72c6b79ce498a11941a2076d71fcf5429
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:observationStudyScaffold/pages/custom_route.dart'; import 'package:observationStudyScaffold/theme/design_theme.dart'; class ConsentForm extends StatelessWidget { final Function onNext; ConsentForm({ @required this.onNext, }); @override Widget build(BuildContext context) { AppBar appBar = AppBar( centerTitle: true, elevation: 0, title: FittedBox( child: Text( "Consent Form", textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: DesignTheme.headerFontSize, ), ), ), backgroundColor: Colors.transparent, ); double height = MediaQuery.of(context).size.height - appBar.preferredSize.height; return Scaffold( appBar: appBar, body: Container( height: height, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Center( child: ConstrainedBox( constraints: BoxConstraints( maxWidth: 1000, minWidth: 300, ), child: Card( child: ListView( children: [ Container( height: 100, child: Image.asset( "/images/guelphLogo.png", ), // child: Image.network( // "https://www.ontariouniversitiesinfo.ca/assets/files/images/universityLogoLarge_logo%20for%20ouinfo-01.png", // ), ), Padding( padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0), child: RichText( textAlign: TextAlign.center, text: TextSpan( style: TextStyle( color: Colors.black, fontSize: 30, fontWeight: FontWeight.bold, ), text: """ INFORMED CONSENT/Information Letter Using Colour Patterns to Assist People with Colour Vision Deficiency """), ), ), Padding( padding: const EdgeInsets.only( bottom: 8.0, left: 8.0, right: 8.0), child: RichText( //textAlign: TextAlign.center, text: TextSpan( style: TextStyle( color: Colors.black, fontSize: 20, ), children: [ TextSpan(text: """ You are invited to participate in a research project. This information letter is to help you decide if you want to be involved in the project. You are invited to take part in a research project to explore the effectiveness of using patterns in order to communicate colour information. The purpose of this letter is to provide you with the information you require to make an informed decision on participating in this research. """), TextSpan( text: "Who is conducting this research study?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ This research study is being conducted by Connor Geddes ([email protected]), Masters Student; under the supervision of Dr. David Flatla ([email protected]), Associate Professor, in the School of Computer Science at the University of Guelph in Guelph, Ontario, Canada. This research is not funded by any third party.\n """), TextSpan( text: "Who do I contact if I have concerns or need more information?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ Please feel free to contact Connor Geddes ([email protected]) with any questions you might have about the project. Any questions about the research study may also be directed to Dr. David Flatla, Associate Professor ([email protected]). """), TextSpan( text: "Are there any conflicts of interest involved?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ No member of the research team has a conflict of interest related to this study. The results found in this study will not be commercialized. Any product or service made via the results of this study will be made in the form of a free product/service available via a device (e.g., phone application via camera or desktop application that will overlay patterns across the screen). """), TextSpan( text: "What is this research study about?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ The purpose of this research is to determine suitable patterns for conveying colour information. """), TextSpan( text: "Why am I being invited to participate in this research study?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ You are invited to take part in this study if: • You are an individual with colour blindness (colour vision deficiency) • You are at least 18 years of age • You are able to read/write in English • You have not already participated in this study """), TextSpan( text: "What will I be asked to do?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ You are invited to participate in a 20-25-minute online session that consists of: • a pre-study questionnaire - where we will ask you background information about yourself and details about the environment you are taking the study in. • an orientation on three different colour identification patterns • performing colour identification tasks (by selecting coloured squares) while unassisted and while using the three colour identification patterns • performing colour sorting tasks (by rearranging coloured squares) while unassisted and while using the three colour identification patterns • a post-study questionnaire - where you will answer questions related to your opinions on each of the colour patterns used through the study. The entire study will be hosted on Google’s Firebase service. We will record your responses to the questionnaires as well as the accuracy and completion time for each trial. We will not record any personally identifiable information. """), TextSpan( text: "How long will it take?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ The study session will take approximately 15-20 minutes. """), TextSpan( text: "What are my responsibilities?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ It is important that you keep in mind that we are evaluating our colour identification patterns – we are not evaluating you. Please try your best but keep in mind that the tasks have been made purposefully difficult. Your participation in this study is completely voluntary. If you feel you no longer wish to take part, you may quit the study at any point by closing the study browser window. Your responses and data will not be recorded if you quit prior to completion. """), TextSpan( text: "Are there any risks or possible negative outcomes for me if I participate?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ As a result of the study, you may discover details about your colour vision that you may not have been aware of previously. If you do, we encourage you to contact your optometrist or a vision expert in order to investigate the problems you may have encountered in greater detail. """), TextSpan( text: "What are the benefits of the research project?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • Although this research may not benefit you directly, it will help researchers understand the potential usefulness in utilizing patterns to communicate colour to people with colour vision deficiency. """), TextSpan( text: "After I agree to participate and sign the Info/consent letter, can I change my mind?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • Participation in this study is voluntary, you can change your mind at any time. • You may refuse to participate, refuse to answer any questions or withdraw from the study with no effect on your future (care/academic/employment status, etc.). • If you choose to withdraw before study session completion, all data collected up to that point will be destroyed and not used as part of this project. • After the completion of the study, data cannot be withdrawn as we are not collecting any personally identifiable information, so we will be unable to identify your data. """), TextSpan( text: "Who will know what I said or did in the study?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • Your IP address will be collected by Firebase in order to provide security to the website. The research team will in no way collect or have access to the IP address. So, no personally identifiable information will be collected by the research team. • Your anonymized information (type of colour blindness, session results, and questionnaire responses) will be linked to a unique participant ID number for data processing purposes. The data you provide will be associated only with this participant ID number. While the study is running, all study data will be stored on Google’s Firebase service. After the study has completed, we will transfer the study data on to a University of Guelph secure file storage service, only accessible by the research team. • Your anonymized information will be available through open access via the ACM digital library. """), TextSpan( text: "How will you protect the information I provide?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • Data collected will be stored on a Google’s Firebase service while the study is running and will be transferred to a University of Guelph secure file storage service after the completion of the study. The data stored on both Firebase and the secure file store service will only accessible by the research team. """), TextSpan( text: "What will you use the information you collect for?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • The data you provide will be used in our current study and may be used in future studies to answer similar research questions. • The anonymous data collected will be shared in academic journals and conferences. """), TextSpan( text: "Will I receive any incentives for my participation?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • You will not receive any incentives for participation in this study """), TextSpan( text: "Will I be given new information about participation throughout the course of the project?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • The study comprises a single session, so no new information will be provided during the course of this project. """), TextSpan( text: "Will the study be published or otherwise disseminated?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • The research team will undertake to publish the results of the project in a conference proceeding and peer-reviewed journal • Each participant’s anonymous data will only be associated with an anonymous participant ID. This participant ID will be associated with your responses and data. """), TextSpan( text: "Will I receive information about the results of this research?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • After the paper has been accepted a version of the paper will be posted on the social media sites used for recruitment for all potential participants to read. """), TextSpan( text: "What are my rights as a research participant?\n", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), TextSpan(text: """ • You do not waive any legal rights by agreeing to take part in this study. • This project has been reviewed by the Research Ethics Board for compliance with federal guidelines for research involving human participants • you have questions regarding your rights and welfare as a research participant in this study (REB# 21-03-003), please contact: Manager, Research Ethics; University of Guelph; [email protected]; (519) 824-4120 (ext. 56606). By clicking the below “I agree” button, you are confirming that you have read and understood everything above and agree to take part in this research study. Please keep in mind that your participation is voluntary, and you may withdraw at any point by closing this study in your web-browser. Make sure to print this page in order to keep it for your own records. """), ], ), ), ), Padding( padding: const EdgeInsets.all(15.0), child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( DesignTheme.defaultRadiusVal), ), color: DesignTheme.primaryColor, onPressed: () { Navigator.of(context).pushReplacement( CustomRoute(builder: (context) { return onNext(); })); }, child: Padding( padding: EdgeInsets.only( bottom: DesignTheme.mediumPadding), child: Padding( padding: const EdgeInsets.all(6.0), child: FittedBox( child: Text( 'I Agree', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: DesignTheme.titleFontSize, ), ), ), ), ), ), ), ], ), ), ), ), ), ], ), ), ); } }
58.28125
506
0.473556
0662d8cf7753c736ff0cb2d02881654ab5428106
326
sql
SQL
Filtered users and their courses.sql
hn-88/ad-hoc-moodle-database-queries
dca20ef720803d2279a2cda31b081de93ead92a8
[ "MIT" ]
null
null
null
Filtered users and their courses.sql
hn-88/ad-hoc-moodle-database-queries
dca20ef720803d2279a2cda31b081de93ead92a8
[ "MIT" ]
null
null
null
Filtered users and their courses.sql
hn-88/ad-hoc-moodle-database-queries
dca20ef720803d2279a2cda31b081de93ead92a8
[ "MIT" ]
null
null
null
SELECT u.id, u.idnumber, u.username, u.firstname, u.lastname, u.email, u.institution, c.fullname as "Courses enrolled" FROM prefix_course AS c JOIN prefix_context AS ctx ON c.id = ctx.instanceid JOIN prefix_role_assignments AS ra ON ra.contextid = ctx.id JOIN prefix_user AS u ON u.id = ra.userid WHERE u.idnumber like :idnum
46.571429
118
0.779141
b657b59826ca23cb4706d0a959f38e07ad4a1f53
13,193
html
HTML
src/assets/Category Sets/History/History178.html
Holy-Spirit-Scholar-Bowl/practice
898c2e15ddb3eb859a1d38332b9a99a7954b80ce
[ "Unlicense" ]
null
null
null
src/assets/Category Sets/History/History178.html
Holy-Spirit-Scholar-Bowl/practice
898c2e15ddb3eb859a1d38332b9a99a7954b80ce
[ "Unlicense" ]
null
null
null
src/assets/Category Sets/History/History178.html
Holy-Spirit-Scholar-Bowl/practice
898c2e15ddb3eb859a1d38332b9a99a7954b80ce
[ "Unlicense" ]
null
null
null
1. History/American (PACE NSC 2015)<br><strong>The Committee of 25 was an influential group of businessmen in this city that engineered the campaign of Norris Poulson for mayor. Harrison Gray Otis founded the Merchants and Manufacturers Association to keep unions out of this city and published its major newspaper. He was succeeded as publisher by Harry Chandler, and together Otis and Chandler bought up land surrounding this city while another friend bought water rights in the </strong> Owens Valley. Buildings in Chavez Ravine were razed initially for public housing here, but the land was sold to Walter O'Malley to build a stadium instead. William Mulholland oversaw the construction of an aqueduct through the San Fernando Valley to this city where the Brooklyn Dodgers moved in 1958. For 10 points, name this largest city in California.<br>ANSWER: Los Angeles, California [or L.A., California]<br><br>2. History/All (HSAPQ National History Bowl 2011)<br><strong>During this Presidential election, one side used the slogan "We'll give 'em Jessie!", referring to their nominee's wife, who was the daughter of the powerful Senator Thomas Hart Benton. Another party's nominee for Vice President was (+) Andrew Donelson, the adopted son of Andrew Jackson. That party won only Maryland, despite having a former Whig President as their nominee. The winner of this Presidential election had served as Secretary of State under James K. Polk, and his victory is sometimes credited to him having been out of the country during the previous four years. The losing candidates included </strong> Millard Fillmore, running as a know-nothing, and the first Republican nominee, John C. Fremont. For 10 points, name this Presidential election won by James Buchanan.<br>ANSWER: Presidential Election of <u>1856</u><br><br>3. History/American (Maggie Walker GSAC 2013)<br>This man responded to a revolution in Hungary by writing the Hülsemann Letter. He successfully argued that private contracts, including royal charters from the colonial era, cannot be legally overturned by a state in the case Dartmouth College v. Woodward. In addition to defending the Second Bank of the United States, this man promoted the Compromise of 1850, for which he was criticized by abolitionists, and he also negotiated a treaty with Baron Ashburton that defined Maine's border with Canada. For 10 points, name this Massachusetts senator who famously declared, "Liberty and Union, now and forever, one and inseparable!"<br>ANSWER: Daniel Webster<br><br>4. History/All (Prison Bowl 2009)<br>The assassination of General René Schneider cleared this man's way to power, and his Vuskovic Plan was Keynesian in principle. Early in his term, his government nationalized copper mining, precipitating a retaliatory US-led economic embargo. He created the Juntas de Abastecimientos y Precios to combat consumer shortages, but by that time his Popular Unity party was already facing stiff opposition from the Christian Democrat Party and fascist groups such as the Fatherland and Liberty party, armed and funded by the CIA. A September 1973 coup resulted in the death of, for 10 points, what socialist leader of Chile, deposed and replaced with Augusto Pinochet?<br>ANSWER: Salvador <u>Allende</u><br><br>5. History/All (Prison Bowl 2011)<br>This man's official biography was written by Abu al-Fazl. He named his eldest son after a renowned mystic, Salim Chishti, and moved his capital to Fatehpur Sikri before suddenly moving it to Lahore. This ruler established the dahsala, a flat tax on agriculture. His general Bairam Khan won a decisive victory after an arrow to the eye knocked out the opposing leader, Hemu, at the Second Battle of Panipat. He married a Rajput princess and twice abolished the jizya tax. He also founded the Din-i-Ilahi or "divine faith."  For 10 points, name this grandson of Babur who ruled over the height of the Mughal Empire.<br>ANSWER: Jalaluddin Muhammad <u>Akbar</u> the Great<br><br>6. History/All (HSAPQ ACF 2 2008)<br>Ibrahim ibn Ya'kub claimed this state ruled by the Piast dynasty was the most powerful of a particular Eastern European ethnic group. The first bishopric here was at Poznan, and Boleslaw the Second fought with bishop Stanislaus, who developed a cult here. Its union with Lithuania occurred during the Jagiellonian dynasty that ruled here, and their combined forces defeated the Teutonic Knights at Tannenburg. Partitioned by Catherine the Great, for 10 points, name this nation that was invaded by the Nazis to spark World War Two, home to the Warsaw Ghetto.<br>ANSWER: Republic of Poland [or Rzeczpospolita Polska]<br><br>7. History/All (Illinois Earlybird 2006)<br>Early on, this being displaced Dione, patroness of the oracle of Dodona in Epirus. Given the epithet Eileithyia as the easer of childbirth, this deity was the subject of the Shield celebration at Samos, of which she was the patron. Homer describes this goddess as “ox-eyed,” and animals associated with her include the coocoo, the cow and especially the peacock. FTP, name this goddess, the Greco-Roman queen of heaven, best known as the angry wife of Zeus or Jupiter.<br>ANSWER: Hera (or Juno)<br><br>8. History/All (PACE NSC 2003)<br>A man in a blue shirt and black pants is hopping the fence that separates the foreground from the village and red tree lined hills in the background. At the front, three nuns are kneeling around the title figure of this painting, marked by unnatural colors and a primitive style. For 10 points—name this 1889 Paul Gauguin painting of a crucified Jesus.<br>ANSWER: The <u>Yellow Christ</u> [or Le <u>Christ Jaune</u>]<br><br>9. History/All (SCOP Novice 2010)<br><strong>News of this battle may have caused rejection of the Olive Branch Petition and its winner's decision to hire mercenaries. Joseph Warren was killed during this battle while fighting for a force led by Israel Putnam and William Prescott. That force repelled two attacks before running out of ammunition during this attempt by British troops to break the Siege of </strong> Boston. Name this battle early in the American Revolution which saw Colonial militia hold Breed's Hill instead of the namesake location.<br>ANSWER: Battle of <u>Bunker Hill</u> [accept Battle of <u>Breed's Hill</u> until mentioned]<br><br>10. History/American (Maggie Walker GSAC 2011)<br>Prior to this event, James McLaughlin overturned an idea to use Buffalo Bill to prevent violence. A contributing factor to this event was the prophet Wovoka and his visions of the end of white expansionism, and violence during this event was partially caused by difficulties encountered when attempting to disarm Black Coyote. The Ghost Dance was interpreted as preparation for an attack, and the location of this event was occupied in 1973 by AIM members. For 10 points, name this 1890 event in which many Lakota Sioux were killed, one of the last conflicts of the Indian Wars.<br>ANSWER: Wounded Knee Massacre [accept Battle of Wounded Knee]<br><br>11. History/All (HSAPQ VHSL Regular Season 2011)<br>This action passed the Senate 37-2, thanks in part to a speech in support of it by Charles Sumner. The funds for this action ended up totaling 7.2 million dollars even though a foreign minister to the U.S. named Eduard de Stoeckl would probably have accepted considerably less. De Stoeckl’s boss, Czar Alexander II, was eager to get rid of the territory purchased. Known as "Seward's Folly" after the Secretary of State who negotiated it, for 10 points, name this territorial acquisition made by the U.S. that eventually became a northern state.<br>ANSWER: <u>purchase</u> of <u>Alaska</u> [accept equivalents]<br><br>12. History/All (Maryland Spring 2012)<br>One incident in this country’s history saw a group chaired by Timothy Hayes help organize a rebellion that was in part prompted by the murder of James Scobie. Another rebellion in this country’s history saw Lachlan Macquarie replace a governor unseated by a group led by George Johnston. This country, home to the Eureka Stockade and a revolt that unseated William Bligh, the Rum Rebellion, also saw explorer Abel Tasman discover an island off the mainland of this country. For 10 points, name this country whose history is full of mistreatment of aborigines, a former British penal colony that is also a continent.<br>ANSWER: <u>Australia</u><br><br>13. History/All (HSAPQ 4Q2 2009)<br>One of these conflicts was incited by the surprise at Meaux, which followed the Edict of St. Germain. One of the namesake figures of one war in this series was the Duke of Guise, one of the "Three Henrys." Catherine de Medici ordered one brutal occurrence during this series of conflicts. These conflicts were ended by Henry IV's conversion to Catholicism. For 10 points, name this series of 16th-century wars, which included the St. Barthlomew's Day Massacre, between Huguenots and Catholics.<br>ANSWER: French Wars of <u>Religion</u><br><br>14. History/All (PACE NSC 2002)<br>In this country’s north, the Tenne back the All People’s Congress, while the southern Mende support the People’s Party of president Ahmad Tejan Kabbah. The former Revolutionary United Front is attempting to become a legitimate political party as founder Foday Sankoh faces potential war crimes charges. For 10 points—name this West African nation whose decade-long civil war was fueled by its diamond wealth.<br>ANSWER: Republic of <u>Sierra Leone</u><br><br>15. History/All (PACE NSC 2006)<br>One of the many who is contrasted to the “daivas,” his son Atar battled the great dragon Azhi Dahaka, and he himself was a son of Zurvan. Symbolized by a winged disc, this deity’s mother was Angra Mainyu. This leader of the Amesha Spentas is opposed by a being who is a cause of all suffering and grief. For 10 points, name this deity whose praises are sung in the Avesta, the chief “good” god of Zoroastrianism.<br>ANSWER: Ahura <u>Mazda</u> [or <u>Ormuzd</u>]<br><br>16. History/All (Prison Bowl 2012)<br>The fall of Qashliq (“kash-lik”) occurred in this region following the Battle of Chuvash Cape, a victory for Yermak Timofeyevich, and later the Czechoslovak Legion was forced to cross it. This region saw conflicts at the fortress of Albazin leading to a treaty with the Qing Dynasty. Migration to this region was supported by Pyotr Stolypin, and Sergei Witte built a railway that crossed it. This place served as a place of exile for people like the Decembrists and Stalin, and it is home to enormous oil and natural gas deposits. For 10 points, identify this region east of the Urals, the Asian part of Russia.<br>ANSWER: <u>Siberia</u> [accept <u>Tyumen</u> Oblast until “Czechoslovak Legion” is read; prompt on “<u>Russia</u>” before it is read]<br><br>17. History/All (HSAPQ ACF 3 2008)<br><strong>This man lost his 1980 gubernatorial reelection bid to Frank White, and he signed the Family and Medical Leave Act into law. His commerce secretary Ron Brown died in a plane crash. This president launched Operation Desert Fox due to Iraq's interference with United Nations inspectors, and signed </strong> NAFTA into law, though his presidency was plagued by the Whitewater affair. For 10 points, name this man who defeated Ross Perot and George H.W. Bush to win the presidential election of 1992.<br>ANSWER: William Jefferson "Bill" Clinton<br><br>18. History/All (HSAPQ ACF 2 2008)<br>In 1967, Roman Herzog apologized for this event, whose casualties were exacerbated by the fact that Mondays are typically market days for the city in question. Incidentally sparing the Casa de Jontas and an ancient oak stump and carried out by Junker and Heikel bombers, it was a joint operation by the Italian air force and the Luftwaffe. For 10 points, name this Franco-endorsed attack on a Basque town, commemorated by a Picasso painting.<br>ANSWER: bombing of Guernica [or obvious equivalents]<br><br>19. History/All (HSAPQ VHSL Regular Season 2011)<br>The mayoral race in a city in this state was the 2002 documentary Street Fight, which focused on Cory Booker’s insurgent campaign against Sharpe James. Al Gore’s chief rival for the 2000 Democratic Presidential nomination was Bill Bradley, a former senator from this state. This state’s current governor received criticism in August when this state lost $400 million in federal Race to the Top education grants due to clerical errors, and that governor defeated former-governor John Corzine. For 10 points, name this northeastern state that is currently governed by Chris Christie.<br>ANSWER: <u>New Jersey</u><br><br>20. History/All (HSAPQ 4Q1 2009)<br>One attack against this group involved using "Hell Burners" as designed by Giambelli in an attempt to break its crescent formation. One action in Cadiz meant to stop this group was described as "singeing the king's beard" and was done by Francis Drake. This group was commanded by the Duke of Medina Sedonia. This group was scattered by a great storm known as the Protestant Wind. For 10 points, name this group organized to transport troops for the overthrow of Elizabeth I, a large and unsuccessful naval force organized by Philip II of Spain.<br>ANSWER: Spanish <u>Armada</u> [or <u>Invincible Armada</u>]<br><br>
13,193
13,193
0.795573
db9daf132b409637cb45b2ced10baef3e28f913d
30,307
php
PHP
test/suite/Mock/Builder/MockBuilderTest.php
eloquent/phony
4ff70c4b787fe51754d41913005e6fa532bfd9a1
[ "MIT" ]
202
2015-04-16T22:28:39.000Z
2022-03-21T12:23:01.000Z
test/suite/Mock/Builder/MockBuilderTest.php
eloquent/phony
4ff70c4b787fe51754d41913005e6fa532bfd9a1
[ "MIT" ]
199
2015-01-06T05:00:09.000Z
2022-03-06T02:13:39.000Z
test/suite/Mock/Builder/MockBuilderTest.php
eloquent/phony
4ff70c4b787fe51754d41913005e6fa532bfd9a1
[ "MIT" ]
12
2015-10-18T02:28:51.000Z
2021-07-07T13:32:23.000Z
<?php declare(strict_types=1); namespace Eloquent\Phony\Mock\Builder; use ArrayIterator; use ArrayObject; use Countable; use DateTime; use DateTimeImmutable; use DateTimeInterface; use Eloquent\Phony\Invocation\InvocableInspector; use Eloquent\Phony\Mock\Exception\ClassExistsException; use Eloquent\Phony\Mock\Exception\FinalClassException; use Eloquent\Phony\Mock\Exception\FinalizedMockException; use Eloquent\Phony\Mock\Exception\InvalidClassNameException; use Eloquent\Phony\Mock\Exception\InvalidDefinitionException; use Eloquent\Phony\Mock\Exception\InvalidTypeException; use Eloquent\Phony\Mock\Exception\MultipleInheritanceException; use Eloquent\Phony\Mock\Handle\HandleFactory; use Eloquent\Phony\Mock\Mock; use Eloquent\Phony\Mock\MockFactory; use Eloquent\Phony\Mock\MockGenerator; use Eloquent\Phony\Reflection\FeatureDetector; use Eloquent\Phony\Sequencer\Sequencer; use Eloquent\Phony\Test\TestClassA; use Eloquent\Phony\Test\TestClassB; use Eloquent\Phony\Test\TestClassI; use Eloquent\Phony\Test\TestFinalClass; use Eloquent\Phony\Test\TestInterfaceA; use Eloquent\Phony\Test\TestInterfaceC; use Eloquent\Phony\Test\TestInterfaceF; use Eloquent\Phony\Test\TestInterfaceH; use Eloquent\Phony\Test\TestTraitA; use Eloquent\Phony\Test\TestTraitB; use Error; use Exception; use Iterator; use IteratorAggregate; use Nonexistent; use PHPUnit\Framework\TestCase; use ReflectionClass; use ReflectionFunction; use Reflector; use Serializable; use Throwable; use Traversable; class MockBuilderTest extends TestCase { protected function setUp(): void { $this->invocableInspector = new InvocableInspector(); $this->featureDetector = new FeatureDetector(); $this->typeNames = [ TestClassB::class, TestInterfaceA::class, Iterator::class, Countable::class, ]; $this->typeNamesTraits = [ TestClassB::class, TestInterfaceA::class, Iterator::class, Countable::class, TestTraitA::class, TestTraitB::class, ]; $this->callbackA = function () {}; $this->callbackB = function () {}; $this->callbackC = function () {}; $this->callbackD = function () {}; $this->callbackE = function () {}; $this->callbackReflectorA = new ReflectionFunction($this->callbackA); $this->callbackReflectorB = new ReflectionFunction($this->callbackB); $this->callbackReflectorC = new ReflectionFunction($this->callbackC); $this->callbackReflectorD = new ReflectionFunction($this->callbackD); $this->callbackReflectorE = new ReflectionFunction($this->callbackE); $this->definition = [ 'static methodA' => $this->callbackA, 'static methodB' => $this->callbackB, 'static propertyA' => 'valueA', 'static propertyB' => 'valueB', 'methodC' => $this->callbackC, 'methodD' => $this->callbackD, 'propertyC' => 'valueC', 'propertyD' => 'valueD', 'const constantA' => 'constantValueA', 'const constantB' => 'constantValueB', ]; } protected function setUpWith($typeNames) { $this->handleFactory = HandleFactory::instance(); $this->factory = new MockFactory( new Sequencer(), MockGenerator::instance(), $this->handleFactory, $this->featureDetector ); return $this->subject = new MockBuilder( $typeNames, $this->factory, $this->handleFactory, $this->invocableInspector ); } protected function typesFor($typeNames) { $types = []; foreach ($typeNames as $typeName) { $types[strtolower($typeName)] = new ReflectionClass($typeName); } return $types; } protected function assertTypes(array $expectedTypes, array $expectedNonTypes, MockBuilder $actual) { $class = $actual->build(); $actualRendered = implode('&', array_keys($actual->types())); foreach ($expectedTypes as $type) { if (interface_exists($type)) { $this->assertTrue( $class->implementsInterface($type), sprintf( 'Expected %s to implement interface %s.', var_export($actualRendered, true), var_export($type, true) ) ); } else { $this->assertTrue( $class->isSubclassOf($type), sprintf( 'Expected %s to be a sub-class of %s.', var_export($actualRendered, true), var_export($type, true) ) ); } } foreach ($expectedNonTypes as $type) { if (interface_exists($type)) { $this->assertFalse( $class->implementsInterface($type), sprintf( 'Expected %s to not implement %s.', var_export($actualRendered, true), var_export($type, true) ) ); } else { $this->assertFalse( $class->isSubclassOf($type), sprintf( 'Expected %s to not be a sub-class of %s.', var_export($actualRendered, true), var_export($type, true) ) ); } } } public function testConstructor() { $this->setUpWith($this->typeNames); $this->assertEquals($this->typesFor($this->typeNames), $this->subject->types()); $this->assertSame($this->factory, $this->subject->factory()); $this->assertSame($this->handleFactory, $this->subject->handleFactory()); $this->assertSame($this->invocableInspector, $this->subject->invocableInspector()); $this->assertFalse($this->subject->isFinalized()); $this->assertFalse($this->subject->isBuilt()); } public function testConstructorWithDuplicateTypes() { $this->setUpWith( [ TestClassB::class, TestInterfaceA::class, Iterator::class, Countable::class, TestClassB::class, TestInterfaceA::class, Iterator::class, Countable::class, ] ); $this->assertEquals($this->typesFor($this->typeNames), $this->subject->types()); } public function testConstructorWithTraits() { $this->setUpWith( [ TestClassB::class, TestInterfaceA::class, Iterator::class, Countable::class, TestTraitA::class, TestTraitB::class, TestClassB::class, Iterator::class, Countable::class, TestTraitA::class, TestTraitB::class, ] ); $this->assertEquals($this->typesFor($this->typeNamesTraits), $this->subject->types()); $this->assertSame($this->factory, $this->subject->factory()); $this->assertSame($this->handleFactory, $this->subject->handleFactory()); $this->assertFalse($this->subject->isFinalized()); $this->assertFalse($this->subject->isBuilt()); } public function testConstructorFailureUndefinedClass() { $this->expectException(InvalidTypeException::class); $this->setUpWith([Nonexistent::class]); } public function testConstructorFailureFinalClass() { $this->expectException(FinalClassException::class); $this->setUpWith([TestFinalClass::class]); } public function testConstructorFailureMultipleInheritance() { $this->expectException(MultipleInheritanceException::class); $this->setUpWith([TestClassB::class, ArrayIterator::class]); } public function testConstructorFailureInvalidType() { $this->expectException(InvalidTypeException::class); $this->setUpWith([1]); } public function testClone() { $builder = $this->setUpWith([]); $builder->addMethod('methodA'); $mockA = $builder->get(); $copy = clone $builder; $copy->addMethod('methodB'); $this->assertTrue($builder->isFinalized()); $this->assertTrue($builder->isBuilt()); $this->assertFalse($copy->isFinalized()); $this->assertFalse($copy->isBuilt()); $mockB = $copy->get(); $this->assertNotSame($mockA, $mockB); $this->assertFalse($mockA instanceof $mockB); $this->assertFalse($mockB instanceof $mockA); $this->assertTrue(method_exists($mockA, 'methodA')); $this->assertTrue(method_exists($mockB, 'methodA')); $this->assertTrue(method_exists($mockB, 'methodB')); } public function testLikeWithString() { $builder = $this->setUpWith([]); $typeNames = [Iterator::class, Countable::class, Serializable::class]; $this->assertSame($builder, $builder->like(Iterator::class, [Countable::class, Serializable::class])); $this->assertEquals($this->typesFor($typeNames), $builder->types()); } public function testLikeFailureUndefinedClass() { $this->setUpWith([]); $this->expectException(InvalidTypeException::class); $this->subject->like(Nonexistent::class); } public function testLikeFailureFinalClass() { $this->setUpWith([]); $this->expectException(FinalClassException::class); $this->subject->like(TestFinalClass::class); } public function testLikeFailureMultipleInheritance() { $this->setUpWith([]); $this->expectException(MultipleInheritanceException::class); $this->subject->like(TestClassB::class, ArrayIterator::class); } public function testLikeFailureMultipleInheritanceOnSubsequentCall() { $this->setUpWith(TestClassA::class); $this->expectException(MultipleInheritanceException::class); $this->subject->like(TestClassB::class, ArrayIterator::class); } public function testLikeFailureInvalidType() { $this->setUpWith([]); $this->expectException(InvalidTypeException::class); $this->subject->like(1); } public function testLikeFailureInvalidObject() { $this->setUpWith([]); $this->expectException(InvalidTypeException::class); $this->subject->like(new ArrayIterator()); } public function testLikeFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->like('ClassName'); } public function testLikeWithAdHocDefinitions() { $this->setUpWith([]); $this->definition = [ 'static methodA' => $this->callbackA, 'static methodB' => $this->callbackB, 'static propertyA' => 'valueA', 'static propertyB' => 'valueB', 'methodC' => $this->callbackC, 'methodD' => $this->callbackD, 'propertyC' => 'valueC', 'var propertyD' => $this->callbackE, 'const constantA' => 'constantValueA', 'const constantB' => 'constantValueB', ]; $this->assertSame($this->subject, $this->subject->like($this->definition)); $definition = $this->subject->definition(); $this->assertEquals( [ 'methodA' => [$this->callbackA, $this->callbackReflectorA], 'methodB' => [$this->callbackB, $this->callbackReflectorB], ], $definition->customStaticMethods() ); $this->assertEquals( [ 'methodC' => [$this->callbackC, $this->callbackReflectorC], 'methodD' => [$this->callbackD, $this->callbackReflectorD], ], $definition->customMethods() ); $this->assertSame( [ 'propertyA' => [null, 'valueA'], 'propertyB' => [null, 'valueB'], ], $definition->customStaticProperties() ); $this->assertSame( [ 'propertyC' => [null, 'valueC'], 'propertyD' => [null, $this->callbackE], ], $definition->customProperties() ); $this->assertSame( ['constantA' => 'constantValueA', 'constantB' => 'constantValueB'], $definition->customConstants() ); } public function testLikeWithAdHocDefinitionsFailureInvalid() { $this->setUpWith([]); $this->expectException(InvalidDefinitionException::class); $this->subject->like([1 => 'propertyA', 2 => 'valueA']); } public function testAddMethod() { $this->setUpWith([]); $callback = function () {}; $callbackReflector = new ReflectionFunction($callback); $this->assertSame($this->subject, $this->subject->addMethod('methodA', $callback)); $this->assertSame($this->subject, $this->subject->addMethod('methodB')); $definition = $this->subject->definition(); $this->assertEquals( ['methodA' => [$callback, $callbackReflector], 'methodB' => [$callback, $callbackReflector]], $definition->customMethods() ); } public function testAddMethodFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->addMethod('methodA', function () {}); } public function testAddStaticMethod() { $this->setUpWith([]); $callback = function () {}; $callbackReflector = new ReflectionFunction($callback); $this->assertSame($this->subject, $this->subject->addStaticMethod('methodA', $callback)); $this->assertSame($this->subject, $this->subject->addStaticMethod('methodB')); $definition = $this->subject->definition(); $this->assertEquals( ['methodA' => [$callback, $callbackReflector], 'methodB' => [$callback, $callbackReflector]], $definition->customStaticMethods() ); } public function testAddStaticMethodFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->addStaticMethod('methodA', function () {}); } public function testAddProperty() { $this->setUpWith([]); $value = 'value'; $this->assertSame($this->subject, $this->subject->addProperty('propertyA', $value)); $this->assertSame($this->subject, $this->subject->addProperty('propertyB')); $definition = $this->subject->definition(); $this->assertSame([ 'propertyA' => [null, $value], 'propertyB' => [null, null], ], $definition->customProperties()); } public function testAddPropertyFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->addProperty('propertyA'); } public function testAddStaticProperty() { $this->setUpWith([]); $value = 'value'; $this->assertSame($this->subject, $this->subject->addStaticProperty('propertyA', $value)); $this->assertSame($this->subject, $this->subject->addStaticProperty('propertyB')); $definition = $this->subject->definition(); $this->assertSame([ 'propertyA' => [null, $value], 'propertyB' => [null, null], ], $definition->customStaticProperties()); } public function testAddStaticPropertyFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->addStaticProperty('propertyA'); } public function testAddConstant() { $this->setUpWith([]); $value = 'value'; $this->assertSame($this->subject, $this->subject->addConstant('CONSTANT_NAME', $value)); $definition = $this->subject->definition(); $this->assertSame(['CONSTANT_NAME' => $value], $definition->customConstants()); } public function testAddConstantFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->addConstant('CONSTANT_NAME', 'value'); } public function testNamed() { $this->setUpWith([]); $this->className = 'AnotherClassName'; $this->assertSame($this->subject, $this->subject->named($this->className)); $definition = $this->subject->definition(); $this->assertSame($this->className, $definition->className()); } public function testNamedFailureInvalid() { $this->setUpWith([]); $this->expectException(InvalidClassNameException::class); $this->subject->named('1'); } public function testNamedFailureInvalidPostPhp71() { $this->setUpWith([]); $this->expectException(InvalidClassNameException::class); $this->subject->named("abc\x7fdef"); } public function testNamedFailureFinalized() { $this->setUpWith([]); $this->subject->finalize(); $this->expectException(FinalizedMockException::class); $this->subject->named('AnotherClassName'); } public function testFinalize() { $this->setUpWith([]); $this->assertFalse($this->subject->isFinalized()); $this->assertSame($this->subject, $this->subject->finalize()); $this->assertTrue($this->subject->isFinalized()); $this->assertSame($this->subject, $this->subject->finalize()); $this->assertTrue($this->subject->isFinalized()); } public function testBuild() { $this->setUpWith($this->typeNames); $actual = $this->subject->build(); $this->assertTrue($this->subject->isFinalized()); $this->assertTrue($this->subject->isBuilt()); $this->assertInstanceOf(ReflectionClass::class, $actual); $this->assertTrue($actual->implementsInterface(Mock::class)); $this->assertTrue($actual->isSubclassOf(TestClassB::class)); $this->assertSame($actual, $this->subject->build()); } public function buildIterablesData() { return [ 'Traversable' => [ Traversable::class, [Traversable::class, Iterator::class], [IteratorAggregate::class], ], 'Iterator' => [ Iterator::class, [Traversable::class, Iterator::class], [IteratorAggregate::class], ], 'IteratorAggregate' => [ IteratorAggregate::class, [Traversable::class, IteratorAggregate::class], [Iterator::class], ], 'Traversable + Iterator' => [ [Traversable::class, Iterator::class], [Traversable::class, Iterator::class], [IteratorAggregate::class], ], 'Traversable + IteratorAggregate' => [ [Traversable::class, IteratorAggregate::class], [Traversable::class, IteratorAggregate::class], [Iterator::class], ], 'Traversable child' => [ TestInterfaceC::class, [Traversable::class, Iterator::class], [IteratorAggregate::class], ], 'Traversable child + Iterator' => [ [Iterator::class, TestInterfaceC::class], [Traversable::class, Iterator::class], [IteratorAggregate::class], ], 'Traversable child + IteratorAggregate' => [ [IteratorAggregate::class, TestInterfaceC::class], [Traversable::class, IteratorAggregate::class], [Iterator::class], ], 'ArrayObject' => [ ArrayObject::class, [Traversable::class, IteratorAggregate::class], [Iterator::class], ], ]; } /** * @dataProvider buildIterablesData */ public function testBuildIterables($typeNames, $expectedTypes, $expectedNonTypes) { $this->setUpWith($typeNames); $this->assertTypes($expectedTypes, $expectedNonTypes, $this->subject); } public function buildThrowablesData() { return [ 'Throwable' => [ Throwable::class, [Throwable::class, Exception::class], [Error::class], ], 'Exception' => [ Exception::class, [Throwable::class, Exception::class], [Error::class], ], 'Error' => [ Error::class, [Throwable::class, Error::class], [Exception::class], ], 'Throwable + Exception' => [ [Throwable::class, Exception::class], [Throwable::class, Exception::class], [Error::class], ], 'Throwable + Error' => [ [Throwable::class, Error::class], [Throwable::class, Error::class], [Exception::class], ], 'Throwable child' => [ TestInterfaceF::class, [Throwable::class, Exception::class], [Error::class], ], 'Throwable child + Exception' => [ [Exception::class, TestInterfaceF::class], [Throwable::class, Exception::class], [Error::class], ], 'Throwable child + Error' => [ [Error::class, TestInterfaceF::class], [Throwable::class, Error::class], [Exception::class], ], ]; } /** * @dataProvider buildThrowablesData */ public function testBuildThrowables($typeNames, $expectedTypes, $expectedNonTypes) { $this->setUpWith($typeNames); $this->assertTypes($expectedTypes, $expectedNonTypes, $this->subject); } public function buildDateTimesData() { return [ 'DateTimeInterface' => [ DateTimeInterface::class, [DateTimeInterface::class, DateTimeImmutable::class], [DateTime::class], ], 'DateTimeImmutable' => [ DateTimeImmutable::class, [DateTimeInterface::class, DateTimeImmutable::class], [DateTime::class], ], 'DateTime' => [ DateTime::class, [DateTimeInterface::class, DateTime::class], [DateTimeImmutable::class], ], 'DateTimeInterface + DateTimeImmutable' => [ [DateTimeInterface::class, DateTimeImmutable::class], [DateTimeInterface::class, DateTimeImmutable::class], [DateTime::class], ], 'DateTimeInterface + DateTime' => [ [DateTimeInterface::class, DateTime::class], [DateTimeInterface::class, DateTime::class], [DateTimeImmutable::class], ], 'DateTimeInterface child' => [ TestInterfaceH::class, [DateTimeInterface::class, DateTimeImmutable::class], [DateTime::class], ], 'DateTimeInterface child + DateTimeImmutable' => [ [DateTimeImmutable::class, TestInterfaceH::class], [DateTimeInterface::class, DateTimeImmutable::class], [DateTime::class], ], 'DateTimeInterface child + DateTime' => [ [DateTime::class, TestInterfaceH::class], [DateTimeInterface::class, DateTime::class], [DateTimeImmutable::class], ], ]; } /** * @dataProvider buildDateTimesData */ public function testBuildDateTimes($typeNames, $expectedTypes, $expectedNonTypes) { $this->setUpWith($typeNames); $this->assertTypes($expectedTypes, $expectedNonTypes, $this->subject); } public function testBuildWithReflectorInterface() { $this->setUpWith(Reflector::class); $actual = $this->subject->build(); $this->assertTrue($actual->implementsInterface(Reflector::class)); } public function testBuildWithFinalConstructor() { $this->setUpWith(TestClassI::class); $actual = $this->subject->build(); $this->assertTrue($actual->isSubclassOf(TestClassI::class)); } public function testBuildFailureClassExists() { $builder = $this->setUpWith([]); $builder->named(__CLASS__); $exception = null; try { $builder->build(); } catch (ClassExistsException $exception) { } $this->assertNotNull($exception); $this->assertTrue($builder->isFinalized()); $this->assertFalse($builder->isBuilt()); } public function testClassName() { $this->setUpWith($this->typeNames); $actual = $this->subject->className(); $this->assertMatchesRegularExpression('/^PhonyMock_TestClassB_\d+$/', $actual); $this->assertTrue($this->subject->isFinalized()); $this->assertTrue($this->subject->isBuilt()); $this->assertSame($actual, $this->subject->className()); } public function testGet() { $this->setUpWith($this->typeNames); $actual = $this->subject->get(); $this->assertTrue($this->subject->isFinalized()); $this->assertTrue($this->subject->isBuilt()); $this->assertInstanceOf(Mock::class, $actual); $this->assertInstanceOf(TestClassB::class, $actual); $this->assertSame($actual, $this->subject->get()); } public function testPartial() { $this->setUpWith($this->typeNames); $first = $this->subject->partial('a', 'b'); $this->assertTrue($this->subject->isFinalized()); $this->assertTrue($this->subject->isBuilt()); $this->assertInstanceOf(Mock::class, $first); $this->assertInstanceOf(TestClassB::class, $first); $this->assertSame(['a', 'b'], $first->constructorArguments); $this->assertSame($first, $this->subject->get()); $second = $this->subject->partial(); $this->assertNotSame($first, $second); $this->assertSame([], $second->constructorArguments); $this->assertSame($second, $this->subject->get()); } public function testPartialWith() { $this->setUpWith($this->typeNames); $first = $this->subject->partialWith(['a', 'b']); $this->assertTrue($this->subject->isFinalized()); $this->assertTrue($this->subject->isBuilt()); $this->assertInstanceOf(Mock::class, $first); $this->assertInstanceOf(TestClassB::class, $first); $this->assertSame(['a', 'b'], $first->constructorArguments); $this->assertSame($first, $this->subject->get()); $second = $this->subject->partialWith([]); $this->assertNotSame($first, $second); $this->assertSame([], $second->constructorArguments); $this->assertSame($second, $this->subject->get()); $third = $this->subject->partialWith(); $this->assertNotSame($first, $third); $this->assertNotSame($second, $third); $this->assertSame([], $second->constructorArguments); $this->assertSame($third, $this->subject->get()); $third = $this->subject->partialWith(null); $this->assertNotSame($first, $third); $this->assertNotSame($second, $third); $this->assertNull($third->constructorArguments); $this->assertSame($third, $this->subject->get()); } public function testFull() { $this->setUpWith($this->typeNames); $first = $this->subject->full(); $this->assertTrue($this->subject->isFinalized()); $this->assertTrue($this->subject->isBuilt()); $this->assertInstanceOf(Mock::class, $first); $this->assertInstanceOf(TestClassB::class, $first); $this->assertNull($first->constructorArguments); $this->assertSame($first, $this->subject->get()); $second = $this->subject->full(); $this->assertNotSame($first, $second); $this->assertNull($second->constructorArguments); $this->assertSame($second, $this->subject->get()); } public function testSource() { $this->setUpWith([]); $this->subject->named('PhonyMockBuilderTestSourceMethod'); $expected = <<<'EOD' class PhonyMockBuilderTestSourceMethod implements \Eloquent\Phony\Mock\Mock { private static $_uncallableMethods = []; private static $_traitMethods = []; private static $_customMethods = []; private static $_staticHandle; private $_handle; } EOD; $expected = str_replace("\n", PHP_EOL, $expected); $this->assertSame($expected, $this->subject->source()); $this->assertTrue($this->subject->isFinalized()); } public function testMockedConstructorWithReferenceParameters() { $first = null; $second = null; $builder = $this->setUpWith(TestClassA::class); $builder->partialWith([&$first, &$second]); $this->assertSame('first', $first); $this->assertSame('second', $second); } }
32.870933
110
0.566008
de0499f019d0a8be18b7c38b5602d26f53f2e97c
2,136
swift
Swift
ImageDocker/UI.Controls/StackView/StackBodyViewController.swift
kelvinjjwong/ImageDocker
aa5a5ea08881d11acc15846a6b650755d54457dd
[ "MIT" ]
5
2019-03-09T02:26:18.000Z
2020-04-06T17:35:39.000Z
ImageDocker/UI.Controls/StackView/StackBodyViewController.swift
kelvinjjwong/ImageDocker
aa5a5ea08881d11acc15846a6b650755d54457dd
[ "MIT" ]
1
2019-07-21T06:50:54.000Z
2019-07-21T06:53:20.000Z
ImageDocker/UI.Controls/StackView/StackBodyViewController.swift
kelvinjjwong/ImageDocker
aa5a5ea08881d11acc15846a6b650755d54457dd
[ "MIT" ]
2
2019-05-10T09:58:25.000Z
2020-01-03T05:56:42.000Z
// // BaseViewController.swift // TreeView // // Created by Kelvin Wong on 2019/12/14. // Copyright © 2019 nonamecat. All rights reserved. // import Cocoa class CustomStackView : NSStackView { override var isFlipped: Bool { return true } } class StackBodyViewController : NSViewController, StackItemBody { static let StackItemBackgroundColor = Colors.DarkGray // NSColor(calibratedRed: 244/255, green:244/255, blue:244/255, alpha:1) @IBOutlet var heightConstraint: NSLayoutConstraint! @IBOutlet var widthConstraint: NSLayoutConstraint! var initialWidth:CGFloat = 0 var initialHeight:CGFloat = 0 var savedDefaultHeight: CGFloat = 0 var disclosureState: StackItemContainer.DisclosureState = .open // Subclasses determine the header title. func headerTitle() -> String { return "" } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() if initialWidth > 0 { self.view.setWidth(initialWidth) } if initialHeight > 0 { self.view.setHeight(initialHeight) } savedDefaultHeight = view.bounds.height view.wantsLayer = true view.layer?.backgroundColor = StackBodyViewController.StackItemBackgroundColor.cgColor } // MARK: - StackItemBody lazy var stackItemContainer: StackItemContainer? = { let storyboard = NSStoryboard(name: "StackHeaderViewController", bundle: nil) guard let header = storyboard.instantiateController(withIdentifier: "HeaderTriangleViewController") as? StackHeaderViewController else { return .none } header.title = self.headerTitle() return StackItemContainer(header: header, body: self, state: self.disclosureState) }() func restoreInitialWidth() { self.view.setWidth(self.initialWidth) } func setWidth(_ value:CGFloat){ self.view.setWidth(value) } func setHeight(_ value:CGFloat){ self.view.setHeight(value) } }
28.105263
144
0.651217
cdef8f4257a2497ae30b3103ee8cf4efce469177
5,668
cs
C#
04.MultidimensionalArrays-Exercise/07.KnightGame/Program.cs
stefani-karaustova/03.C-Sharp-Advanced
b3aa8b6835d7e4d15a71b6057915cf4660923278
[ "MIT" ]
null
null
null
04.MultidimensionalArrays-Exercise/07.KnightGame/Program.cs
stefani-karaustova/03.C-Sharp-Advanced
b3aa8b6835d7e4d15a71b6057915cf4660923278
[ "MIT" ]
null
null
null
04.MultidimensionalArrays-Exercise/07.KnightGame/Program.cs
stefani-karaustova/03.C-Sharp-Advanced
b3aa8b6835d7e4d15a71b6057915cf4660923278
[ "MIT" ]
null
null
null
using System; namespace _07.KnightGame { class Program { static void Main(string[] args) { var size = int.Parse(Console.ReadLine()); char[,] matrix = new char[size, size]; byte[,] canAtack = new byte[size, size]; byte[,] canBeAttacked = new byte[size, size]; for (int i = 0; i < matrix.GetLength(0); i++) { var row = Console.ReadLine(); for (int j = 0; j < matrix.GetLength(1); j++) { matrix[i, j] = row[j]; } } var counter = 0; int[] maxCoordinates = UpdateMatrices(matrix, canAtack, canBeAttacked); while (maxCoordinates != null) { matrix[maxCoordinates[0], maxCoordinates[1]] = '0'; canAtack = new byte[size, size]; canBeAttacked = new byte[size, size]; maxCoordinates = UpdateMatrices(matrix, canAtack, canBeAttacked); counter++; } Console.WriteLine(counter); } private static int[] UpdateMatrices(char[,] matrix, byte[,] canAtack, byte[,] canBeAttacked) { var size = matrix.GetLength(0); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (matrix[i, j] == 'K') { if (i > 1) { if (j > 0) { if (matrix[i - 2, j - 1] == 'K') { canAtack[i, j]++; canBeAttacked[i - 2, j - 1]++; } } if (j < size - 1) { if (matrix[i - 2, j + 1] == 'K') { canAtack[i, j]++; canBeAttacked[i - 2, j + 1]++; } } } if (i < size - 2) { if (j > 0) { if (matrix[i + 2, j - 1] == 'K') { canAtack[i, j]++; canBeAttacked[i + 2, j - 1]++; } } if (j < size - 1) { if (matrix[i + 2, j + 1] == 'K') { canAtack[i, j]++; canBeAttacked[i + 2, j + 1]++; } } } if (j > 1) { if (i > 0) { if (matrix[i - 1, j - 2] == 'K') { canAtack[i, j]++; canBeAttacked[i - 1, j - 2]++; } } if (i < size - 1) { if (matrix[i + 1, j - 2] == 'K') { canAtack[i, j]++; canBeAttacked[i + 1, j - 2]++; } } } if (j < size - 2) { if (i > 0) { if (matrix[i - 1, j + 2] == 'K') { canAtack[i, j]++; canBeAttacked[i - 1, j + 2]++; } } if (i < size - 1) { if (matrix[i + 1, j + 2] == 'K') { canAtack[i, j]++; canBeAttacked[i + 1, j + 2]++; } } } } } } int[] maxCoordinates = null; var maxSum = 0; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { var sum = (byte)(canAtack[i, j] + canBeAttacked[i, j]); if (sum > maxSum) { maxCoordinates = new int[] { i, j }; maxSum = sum; } } } return maxCoordinates; } private static void PrintMatrix(byte[,] matrix) { for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { Console.Write(matrix[i, j] + " "); } Console.WriteLine(); } } } }
33.146199
100
0.240296
350f085281c71d58a24486b30e7513bdf4e71f11
463
dart
Dart
lib/views/global_music_player_page/components/global_player_buttonsbar_component/reducer.dart
1906374092/FRDX_NeteaseMusic
161a700507ce146a9ed1b4b20d60b34877814ab1
[ "MIT" ]
1
2020-12-04T09:44:50.000Z
2020-12-04T09:44:50.000Z
lib/views/global_music_player_page/components/global_player_buttonsbar_component/reducer.dart
1906374092/FRDX_NeteaseMusic
161a700507ce146a9ed1b4b20d60b34877814ab1
[ "MIT" ]
null
null
null
lib/views/global_music_player_page/components/global_player_buttonsbar_component/reducer.dart
1906374092/FRDX_NeteaseMusic
161a700507ce146a9ed1b4b20d60b34877814ab1
[ "MIT" ]
null
null
null
import 'package:fish_redux/fish_redux.dart'; import 'action.dart'; import 'state.dart'; Reducer<GlobalPlayerButtonsbarState> buildReducer() { return asReducer( <Object, Reducer<GlobalPlayerButtonsbarState>>{ GlobalPlayerButtonsbarAction.action: _onAction, }, ); } GlobalPlayerButtonsbarState _onAction( GlobalPlayerButtonsbarState state, Action action) { final GlobalPlayerButtonsbarState newState = state.clone(); return newState; }
24.368421
61
0.768898
e2b840809b699ab185450306eb2e4ed2ad9a4e95
342
py
Python
blog/admin.py
Benz-Solutions/MyWebsite
d60601f7f390c9d8a4b4394b321cf3b2cdc4b26a
[ "MIT" ]
null
null
null
blog/admin.py
Benz-Solutions/MyWebsite
d60601f7f390c9d8a4b4394b321cf3b2cdc4b26a
[ "MIT" ]
null
null
null
blog/admin.py
Benz-Solutions/MyWebsite
d60601f7f390c9d8a4b4394b321cf3b2cdc4b26a
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import * # Register your models here. class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} admin.site.register(Category, CategoryAdmin) admin.site.register(Article, ArticleAdmin)
34.2
46
0.760234
c0159671c3c7ac16164732f87be6f913fe9400a1
1,252
rs
Rust
src/utils/facade.rs
savaki/oura
05527037c8ba2e2810554684f492339487b14a19
[ "Apache-2.0" ]
124
2021-12-04T11:13:09.000Z
2022-03-26T10:51:19.000Z
src/utils/facade.rs
savaki/oura
05527037c8ba2e2810554684f492339487b14a19
[ "Apache-2.0" ]
95
2021-12-14T05:44:16.000Z
2022-03-31T22:38:28.000Z
src/utils/facade.rs
savaki/oura
05527037c8ba2e2810554684f492339487b14a19
[ "Apache-2.0" ]
16
2021-12-09T19:07:55.000Z
2022-03-28T16:01:05.000Z
use super::*; ///! A friendly facade to simplify access to common utils procedures impl Utils { // To be used by source stages to access the cursor, if any pub fn get_cursor_if_any(&self) -> Option<cursor::PointArg> { match &self.cursor { Some(provider) => provider.get_cursor(), _ => None, } } /// To be used by sink stages to track progress pub fn track_source_progress(&self, event: &Event) { if let Some(metrics) = &self.metrics { metrics.on_source_event(event); } } /// To be used by sink stages to track progress pub fn track_sink_progress(&self, event: &Event) { let point = match (event.context.slot, &event.context.block_hash) { (Some(slot), Some(hash)) => cursor::PointArg(slot, hash.to_owned()), _ => return, }; if let Some(cursor) = &self.cursor { cursor.set_cursor(point).ok_or_warn("failed to set cursor") } if let Some(metrics) = &self.metrics { metrics.on_sink_event(event); } } pub fn track_chain_tip(&self, tip: u64) { if let Some(metrics) = &self.metrics { metrics.on_chain_tip(tip); } } }
29.116279
80
0.575879
f8fdb8f91d8b0ab17832f710421b06e8b6141c7e
1,903
cc
C++
chrome/common/privacy_budget/privacy_budget_settings_provider.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/common/privacy_budget/privacy_budget_settings_provider.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/common/privacy_budget/privacy_budget_settings_provider.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 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 "chrome/common/privacy_budget/privacy_budget_settings_provider.h" #include <memory> #include "base/containers/contains.h" #include "base/ranges/algorithm.h" #include "chrome/common/privacy_budget/field_trial_param_conversions.h" #include "chrome/common/privacy_budget/privacy_budget_features.h" #include "third_party/blink/public/common/privacy_budget/identifiable_surface.h" PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider() : blocked_surfaces_( DecodeIdentifiabilityFieldTrialParam<IdentifiableSurfaceSet>( features::kIdentifiabilityStudyBlockedMetrics.Get())), blocked_types_( DecodeIdentifiabilityFieldTrialParam<IdentifiableSurfaceTypeSet>( features::kIdentifiabilityStudyBlockedTypes.Get())), enabled_(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy)) {} PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider( const PrivacyBudgetSettingsProvider&) = default; PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider( PrivacyBudgetSettingsProvider&&) = default; PrivacyBudgetSettingsProvider::~PrivacyBudgetSettingsProvider() = default; bool PrivacyBudgetSettingsProvider::IsActive() const { return enabled_; } bool PrivacyBudgetSettingsProvider::IsAnyTypeOrSurfaceBlocked() const { return !blocked_surfaces_.empty() || !blocked_types_.empty(); } bool PrivacyBudgetSettingsProvider::IsSurfaceAllowed( blink::IdentifiableSurface surface) const { return !base::Contains(blocked_surfaces_, surface) && IsTypeAllowed(surface.GetType()); } bool PrivacyBudgetSettingsProvider::IsTypeAllowed( blink::IdentifiableSurface::Type type) const { return !base::Contains(blocked_types_, type); }
39.645833
80
0.794535
c6ac16548b8e8dbd03c7dd828b2f08dd5d9bd025
1,593
py
Python
authentication/forms.py
klevamane/zuriboard-blog
ad73802923611c8c55aa4fe4855aa263fe179620
[ "MIT" ]
null
null
null
authentication/forms.py
klevamane/zuriboard-blog
ad73802923611c8c55aa4fe4855aa263fe179620
[ "MIT" ]
null
null
null
authentication/forms.py
klevamane/zuriboard-blog
ad73802923611c8c55aa4fe4855aa263fe179620
[ "MIT" ]
null
null
null
from django.contrib.auth import authenticate from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django import forms from authentication.models import User class SignupForm(UserCreationForm): email = forms.EmailField(required=True) firstname = forms.CharField(max_length=100, required=True) lastname = forms.CharField(max_length=100, required=True) class Meta: model = User fields = ("firstname", "lastname", "email", "password1", "password2") def save(self, commit=True): user = super(SignupForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user class LoginForm(AuthenticationForm): username = forms.EmailField( label="Email address", max_length=254, widget=forms.EmailInput(attrs={'autofocus': True}), ) # # def clean(self): # email = self.cleaned_data.get('email') # password = self.cleaned_data.get('password') # # if email is not None and password: # self.user_cache = authenticate(self.request, email=email, password=password) # if self.user_cache is None: # raise forms.ValidationError( # self.error_messages['invalid_login'], # code='invalid_login', # params={'username': self.username_field.verbose_name}, # ) # else: # self.confirm_login_allowed(self.user_cache) # # return self.cleaned_data
32.510204
90
0.622097
3c7cbe67fc90502cc3f1681643a6321d4cabbd0f
773
swift
Swift
Classes/ UIImageView+Chain.swift
MnkGitBox/MNkSupportUtilities
69b17c4491efc39eabb1fa00455d7258a473e587
[ "MIT" ]
null
null
null
Classes/ UIImageView+Chain.swift
MnkGitBox/MNkSupportUtilities
69b17c4491efc39eabb1fa00455d7258a473e587
[ "MIT" ]
null
null
null
Classes/ UIImageView+Chain.swift
MnkGitBox/MNkSupportUtilities
69b17c4491efc39eabb1fa00455d7258a473e587
[ "MIT" ]
null
null
null
// // UIImageView+Chain.swift // iDak // // Created by Malith Nadeeshan on 4/5/20. // Copyright © 2020 Malith Nadeeshan. All rights reserved. // import UIKit extension UIKitChain where Component: UIImageView { ///Generic property set with -> clipsToBounds = true & contentMode = .scaleAspectFill public var general:Self{ component.contentMode = .scaleAspectFill component.clipsToBounds = true return self } ///Set image to image view public func image(_ image: UIImage?) -> Self { component.image = image return self } ///Set image using image URL public func image(fromURL url: URL?) -> Self { component.sd_setImage(with: url, completed: nil) return self } }
24.15625
89
0.637775
da730857f5cd4734d9d023a2d2f5081857e1d8f0
112
dart
Dart
my_serial_list/lib/features/account/domain/entities/user/edit_user.dart
misiek231/My-serial-list
deb97636b75c0602164d46a7538c77e3cd42edbc
[ "MIT" ]
2
2020-02-16T22:37:23.000Z
2020-03-02T16:34:14.000Z
my_serial_list/lib/features/account/domain/entities/user/edit_user.dart
misiek231/My-serial-list
deb97636b75c0602164d46a7538c77e3cd42edbc
[ "MIT" ]
null
null
null
my_serial_list/lib/features/account/domain/entities/user/edit_user.dart
misiek231/My-serial-list
deb97636b75c0602164d46a7538c77e3cd42edbc
[ "MIT" ]
1
2020-03-02T16:37:11.000Z
2020-03-02T16:37:11.000Z
class EditUserModel { String userName; String password; String name; String surname; String email; }
14
22
0.714286
b08bd16f9d454b1946573ba606d8c15f6761f117
206
py
Python
OccurenceProbability.py
AnmolSethi/Python---Challenges-
83cce9334f58a91bee6ed08f34eea19b0139472f
[ "MIT" ]
null
null
null
OccurenceProbability.py
AnmolSethi/Python---Challenges-
83cce9334f58a91bee6ed08f34eea19b0139472f
[ "MIT" ]
null
null
null
OccurenceProbability.py
AnmolSethi/Python---Challenges-
83cce9334f58a91bee6ed08f34eea19b0139472f
[ "MIT" ]
null
null
null
from itertools import combinations N = int(input()) DATA = input().split() M = int(input()) C = list(combinations(DATA, M)) F = filter(lambda c: 'a' in c, C) print('{0:.3f}'.format(len(list(F)) / len(C)))
22.888889
46
0.631068
397ca5dfea095d7b3c4e9de5f1775e307f07915b
2,386
ps1
PowerShell
Posh-ACME/Public/Unpublish-Challenge.ps1
torbjornlandin/Posh-ACME
95ba84a3c9a218c3ff2dd859637bbb9cf4631629
[ "MIT" ]
556
2018-04-28T07:17:01.000Z
2022-03-21T21:11:48.000Z
Posh-ACME/Public/Unpublish-Challenge.ps1
torbjornlandin/Posh-ACME
95ba84a3c9a218c3ff2dd859637bbb9cf4631629
[ "MIT" ]
376
2018-04-26T23:49:30.000Z
2022-03-30T03:35:00.000Z
Posh-ACME/Public/Unpublish-Challenge.ps1
torbjornlandin/Posh-ACME
95ba84a3c9a218c3ff2dd859637bbb9cf4631629
[ "MIT" ]
210
2018-04-30T21:43:50.000Z
2022-03-19T21:51:58.000Z
function Unpublish-Challenge { [CmdletBinding()] param( [Parameter(Mandatory,Position=0)] [string]$Domain, [Parameter(Mandatory,Position=1)] [PSTypeName('PoshACME.PAAccount')]$Account, [Parameter(Mandatory,Position=2)] [string]$Token, [Parameter(Mandatory,Position=3)] [ValidateScript({Test-ValidPlugin $_ -ThrowOnFail})] [string]$Plugin, [Parameter(Position=4)] [hashtable]$PluginArgs, [string]$DnsAlias ) # dot source the plugin file $pluginDetail = $script:Plugins.$Plugin . $pluginDetail.Path # All plugins in $script:Plugins should have been validated during module # load. So we're not going to do much plugin-specific validation here. Write-Verbose "Unpublishing challenge for Domain $Domain with Token $Token using Plugin $Plugin and DnsAlias '$DnsAlias'." # sanitize the $Domain if it was passed in as a wildcard on accident if ($Domain -and $Domain.StartsWith('*.')) { Write-Warning "Stripping wildcard characters from domain name. Not required for publishing." $Domain = $Domain.Substring(2) } # do stuff appropriate for the challenge type if ('dns-01' -eq $pluginDetail.ChallengeType) { # determine the appropriate record name if (-not [String]::IsNullOrWhiteSpace($DnsAlias)) { # always use the alias if it was specified $recordName = $DnsAlias } else { # use Domain $recordName = "_acme-challenge.$($Domain)" } $txtValue = Get-KeyAuthorization $Token $Account -ForDNS # call the function with the required parameters and splatting the rest Write-Debug "Calling $Plugin plugin to remove $recordName TXT with value $txtValue" Remove-DnsTxt -RecordName $recordName -TxtValue $txtValue @PluginArgs } else { # http-01 is the only other challenge type we support at the moment $keyAuth = Get-KeyAuthorization $Token $Account # call the function with the required parameters and splatting the rest Write-Debug "Calling $Plugin plugin to remove challenge for $Domain with token $Token and key auth $keyAuth" Remove-HttpChallenge -Domain $Domain -Token $Token -Body $keyAuth @PluginArgs } }
39.766667
127
0.645013
2aa42a133e9a563317e17d1d180f7c2bd91b69ad
4,002
rs
Rust
libs/debugger/src/minidump.rs
pacbypass/og_mesos_fuzzer
ad932fe477b04b6083d69034be9d8879a8f8da1a
[ "MIT" ]
39
2019-10-12T14:57:28.000Z
2022-02-08T14:46:29.000Z
libs/debugger/src/minidump.rs
pacbypass/og_mesos_fuzzer
ad932fe477b04b6083d69034be9d8879a8f8da1a
[ "MIT" ]
null
null
null
libs/debugger/src/minidump.rs
pacbypass/og_mesos_fuzzer
ad932fe477b04b6083d69034be9d8879a8f8da1a
[ "MIT" ]
11
2019-10-17T22:13:59.000Z
2020-10-05T09:14:04.000Z
/// Module containing utilities to create full minidumps of processes use winapi::um::winnt::EXCEPTION_POINTERS; use winapi::um::winnt::GENERIC_READ; use winapi::um::winnt::GENERIC_WRITE; use winapi::um::winnt::EXCEPTION_RECORD; use winapi::um::fileapi::CREATE_NEW; use winapi::um::winnt::HANDLE; use winapi::um::fileapi::CreateFileW; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::errhandlingapi::GetLastError; use winapi::um::winnt::CONTEXT; use std::path::Path; use crate::handles::Handle; use crate::ffi_helpers::win32_string; #[repr(C)] #[allow(dead_code)] pub enum MinidumpType { MiniDumpNormal = 0x00000000, MiniDumpWithDataSegs = 0x00000001, MiniDumpWithFullMemory = 0x00000002, MiniDumpWithHandleData = 0x00000004, MiniDumpFilterMemory = 0x00000008, MiniDumpScanMemory = 0x00000010, MiniDumpWithUnloadedModules = 0x00000020, MiniDumpWithIndirectlyReferencedMemory = 0x00000040, MiniDumpFilterModulePaths = 0x00000080, MiniDumpWithProcessThreadData = 0x00000100, MiniDumpWithPrivateReadWriteMemory = 0x00000200, MiniDumpWithoutOptionalData = 0x00000400, MiniDumpWithFullMemoryInfo = 0x00000800, MiniDumpWithThreadInfo = 0x00001000, MiniDumpWithCodeSegs = 0x00002000, MiniDumpWithoutAuxiliaryState = 0x00004000, MiniDumpWithFullAuxiliaryState = 0x00008000, MiniDumpWithPrivateWriteCopyMemory = 0x00010000, MiniDumpIgnoreInaccessibleMemory = 0x00020000, MiniDumpWithTokenInformation = 0x00040000, MiniDumpWithModuleHeaders = 0x00080000, MiniDumpFilterTriage = 0x00100000, MiniDumpWithAvxXStateContext = 0x00200000, MiniDumpWithIptTrace = 0x00400000, MiniDumpValidTypeFlags = 0x007fffff, } #[link(name = "dbghelp")] extern "system" { pub fn MiniDumpWriteDump(hProcess: HANDLE, processId: u32, hFile: HANDLE, DumpType: u32, exception: *const MinidumpExceptionInformation, userstreamparam: usize, callbackParam: usize) -> i32; } #[repr(C, packed)] #[derive(Clone, Copy, Debug)] pub struct MinidumpExceptionInformation { thread_id: u32, exception: *const EXCEPTION_POINTERS, client_pointers: u32, } /// Create a full minidump of a given process pub fn dump(filename: &str, pid: u32, tid: u32, process: HANDLE, exception: &mut EXCEPTION_RECORD, context: &mut CONTEXT) { // Don't overwrite existing dumps if Path::new(filename).is_file() { print!("Ignoring duplicate crash {}\n", filename); return; } unsafe { let filename = win32_string(filename); let ep = EXCEPTION_POINTERS { ExceptionRecord: exception, ContextRecord: context, }; // Create the minidump file let fd = CreateFileW(filename.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, std::ptr::null_mut(), CREATE_NEW, 0, std::ptr::null_mut()); assert!(fd != INVALID_HANDLE_VALUE, "Failed to create dump file"); // Wrap up the HANDLE for drop tracking let fd = Handle::new(fd).expect("Failed to get handle to minidump"); let mei = MinidumpExceptionInformation { thread_id: tid, exception: &ep, client_pointers: 0, }; // Take a minidump! let res = MiniDumpWriteDump(process, pid, fd.raw(), MinidumpType::MiniDumpWithFullMemory as u32 | MinidumpType::MiniDumpWithHandleData as u32, &mei, 0, 0); assert!(res != 0, "MiniDumpWriteDump error: {}\n", GetLastError()); } }
38.114286
76
0.617691
c3feee9aaaf4a2aff33a0f63f72bc6edbd61829e
9,209
cs
C#
test/Sphere10.FrameworkTester/VisualInheritanceFixerBase.Designer.cs
Sphere10/Framework
5f6d9ed67dd6ec3b938d9d24223aa92ca21d9e2e
[ "MIT" ]
1
2020-05-22T00:02:56.000Z
2020-05-22T00:02:56.000Z
test/Sphere10.FrameworkTester/VisualInheritanceFixerBase.Designer.cs
Sphere10/Framework
5f6d9ed67dd6ec3b938d9d24223aa92ca21d9e2e
[ "MIT" ]
null
null
null
test/Sphere10.FrameworkTester/VisualInheritanceFixerBase.Designer.cs
Sphere10/Framework
5f6d9ed67dd6ec3b938d9d24223aa92ca21d9e2e
[ "MIT" ]
1
2020-12-22T02:37:51.000Z
2020-12-22T02:37:51.000Z
//----------------------------------------------------------------------- // <copyright file="VisualInheritanceFixerBase.Designer.cs" company="Sphere 10 Software"> // // Copyright (c) Sphere 10 Software. All rights reserved. (http://www.sphere10.com) // // Distributed under the MIT software license, see the accompanying file // LICENSE or visit http://www.opensource.org/licenses/mit-license.php. // // <author>Herman Schoenfeld</author> // <date>2018</date> // </copyright> //----------------------------------------------------------------------- namespace Sphere10.FrameworkTester { partial class VisualInheritanceFixerBase { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.aToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.aAToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.bToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.menuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aToolStripMenuItem, this.aAToolStripMenuItem, this.bToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(531, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // aToolStripMenuItem // this.aToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem2, this.toolStripMenuItem3, this.toolStripMenuItem4, this.toolStripMenuItem5}); this.aToolStripMenuItem.Name = "aToolStripMenuItem"; this.aToolStripMenuItem.Size = new System.Drawing.Size(27, 20); this.aToolStripMenuItem.Text = "A"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(86, 22); this.toolStripMenuItem2.Text = "1"; // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(86, 22); this.toolStripMenuItem3.Text = "2"; // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(86, 22); this.toolStripMenuItem4.Text = "22"; // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(86, 22); this.toolStripMenuItem5.Text = "3"; // // aAToolStripMenuItem // this.aAToolStripMenuItem.Name = "aAToolStripMenuItem"; this.aAToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.aAToolStripMenuItem.Text = "AA"; // // bToolStripMenuItem // this.bToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem6, this.toolStripMenuItem7}); this.bToolStripMenuItem.Name = "bToolStripMenuItem"; this.bToolStripMenuItem.Size = new System.Drawing.Size(26, 20); this.bToolStripMenuItem.Text = "B"; // // toolStripMenuItem6 // this.toolStripMenuItem6.Name = "toolStripMenuItem6"; this.toolStripMenuItem6.Size = new System.Drawing.Size(80, 22); this.toolStripMenuItem6.Text = "1"; // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(80, 22); this.toolStripMenuItem7.Text = "3"; // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.toolStripLabel2, this.toolStripTextBox1}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(531, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(13, 22); this.toolStripLabel1.Text = "1"; // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(19, 22); this.toolStripLabel2.Text = "11"; // // toolStripTextBox1 // this.toolStripTextBox1.Name = "toolStripTextBox1"; this.toolStripTextBox1.Size = new System.Drawing.Size(100, 25); this.toolStripTextBox1.Text = "3"; // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripStatusLabel2}); this.statusStrip1.Location = new System.Drawing.Point(0, 256); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(531, 22); this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(13, 17); this.toolStripStatusLabel1.Text = "2"; // // toolStripStatusLabel2 // this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; this.toolStripStatusLabel2.Size = new System.Drawing.Size(13, 17); this.toolStripStatusLabel2.Text = "3"; // // VisualInheritanceFixerBase // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(531, 278); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "VisualInheritanceFixerBase"; this.Text = "VisualInheritanceFixerBase"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStripMenuItem aToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem aAToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem bToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripTextBox toolStripTextBox1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; protected System.Windows.Forms.MenuStrip menuStrip1; protected System.Windows.Forms.ToolStrip toolStrip1; protected System.Windows.Forms.StatusStrip statusStrip1; } }
39.865801
101
0.719188
f4afbbde0668c1817d463e36b20fa7b13f246c21
1,855
ts
TypeScript
test/node/preprocess/encoder.ts
imgcook/datacook
b88d298d77d8f35422455f6e75bddfafbf921820
[ "Apache-2.0" ]
33
2020-11-05T10:51:30.000Z
2022-02-10T05:23:44.000Z
test/node/preprocess/encoder.ts
imgcook/datacook
b88d298d77d8f35422455f6e75bddfafbf921820
[ "Apache-2.0" ]
44
2020-10-28T10:27:13.000Z
2022-02-09T15:15:24.000Z
test/node/preprocess/encoder.ts
imgcook/datacook
b88d298d77d8f35422455f6e75bddfafbf921820
[ "Apache-2.0" ]
5
2020-11-02T23:00:05.000Z
2021-12-29T06:30:16.000Z
import { eigenSolve } from '../../../src/linalg/eigen'; import '@tensorflow/tfjs-backend-cpu'; import * as tf from '@tensorflow/tfjs-core'; import { tensorEqual } from '../../../src/linalg/utils'; import { assert } from 'chai'; import 'mocha'; import { OneHotEncoder } from '../../../src/preprocess'; const x = ['tree', 'apple', 'banana', 'tree', 'apple', 'banana']; const xEncode = tf.tensor([ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1], ]); const xEncodeDrop = tf.tensor([ [0, 0], [1, 0], [0, 1], [0, 0], [1, 0], [0, 1], ]); const bx = ['tree', 'apple', 'tree', 'apple']; const bxEncodeDrop = tf.tensor([0, 1, 0, 1]); describe('OneHot Encoder', () => { it('encode', async () => { const encoder = new OneHotEncoder(); await encoder.init(x); const xOneHot = await encoder.encode(x); assert.deepEqual(xOneHot.dataSync(), xEncode.dataSync()); }); it('decode', async () => { const encoder = new OneHotEncoder(); await encoder.init(x); const xCate = await encoder.decode(xEncode); assert.deepEqual(xCate.dataSync() as any, x); }); it('encode drop first', async () => { const encoder = new OneHotEncoder({drop: 'first'}); await encoder.init(x); const xOneHot = await encoder.encode(x); assert.deepEqual(xOneHot.dataSync(), xEncodeDrop.dataSync()); }); it('encode binary only', async () => { const encoder = new OneHotEncoder({drop: 'binary-only'}); await encoder.init(bx); const bxOneHot = await encoder.encode(bx); assert.deepEqual(bxOneHot.dataSync(), bxEncodeDrop.dataSync()); }); it('decode binary only', async () => { const encoder = new OneHotEncoder({drop: 'binary-only'}); await encoder.init(bx); const bxCate = await encoder.decode(bxEncodeDrop); assert.deepEqual(bxCate.dataSync() as any, bx); }); });
30.409836
67
0.607547
64364d57fbf77402a81c753d147e6d8619dee81f
828
py
Python
expose.py
mzal/pysweeper
175ae570c001760d4f7a5122a5eb0b50ef36e046
[ "MIT" ]
null
null
null
expose.py
mzal/pysweeper
175ae570c001760d4f7a5122a5eb0b50ef36e046
[ "MIT" ]
null
null
null
expose.py
mzal/pysweeper
175ae570c001760d4f7a5122a5eb0b50ef36e046
[ "MIT" ]
null
null
null
def expose(board, x, y): if not board[y][x].flagged: board[y][x].exposed = True #debug print(x, y, sep='\t') if x == 0 or x == len(board[0]) - 1 or y == 0 or y == len(board) - 1 or board[y][x].mine: return 0 if board[y][x].neighbours == 0: if board[y-1][x-1].exposed is False: expose(board, x-1, y-1) if board[y-1][x].exposed is False: expose(board, x, y-1) if board[y-1][x+1].exposed is False: expose(board, x+1, y-1) if board[y][x-1].exposed is False: expose(board, x-1, y) if board[y][x+1].exposed is False: expose(board, x+1, y) if board[y+1][x-1].exposed is False: expose(board, x-1, y+1) if board[y+1][x].exposed is False: expose(board, x, y+1) if board[y+1][x+1].exposed is False: expose(board, x+1, y+1) return 0
43.578947
93
0.556763
14bf34736f76c9de522490749e04815897fc6b38
1,909
ts
TypeScript
fashionretail-frontend/src/app/supplierviewprofile/supplierviewprofile.component.ts
NilakshiS/BackupRepo
56e29b80de47622000606465f6e52572ffc49d9a
[ "Apache-2.0" ]
null
null
null
fashionretail-frontend/src/app/supplierviewprofile/supplierviewprofile.component.ts
NilakshiS/BackupRepo
56e29b80de47622000606465f6e52572ffc49d9a
[ "Apache-2.0" ]
9
2020-03-04T22:15:30.000Z
2022-03-02T05:36:40.000Z
fashionretail-frontend/src/app/supplierviewprofile/supplierviewprofile.component.ts
NilakshiS/BackupRepo
56e29b80de47622000606465f6e52572ffc49d9a
[ "Apache-2.0" ]
null
null
null
import { Component, OnInit, Inject} from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { Supplier } from '../models/Supplier'; import { SupplierService } from '../services/supplier.service'; export interface DialogData { city: string; contactNumber: number; } @Component({ selector: 'app-supplierviewprofile', templateUrl: './supplierviewprofile.component.html', styleUrls: ['./supplierviewprofile.component.css'] }) export class SupplierviewprofileComponent implements OnInit { constructor(private dialog: MatDialog, private supplierService: SupplierService ) { } supplier: Supplier; city: string; contactNumber: number; data; ngOnInit() { this.supplierService.getSupplier().subscribe((data) => { this.supplier = data; console.log(this.supplier); }); } updateSupplier(supplier: Supplier) { console.log(supplier); this.supplierService.updateSupplier( supplier, supplier.id).subscribe((data) => { console.log('result is', data); this.supplierService.getSupplier().subscribe((data) => {this.supplier = data; }); }); } openDialog(supplier: Supplier) { const dialogRef = this.dialog.open(SupplierEditDialogue, { width: '350px', data: {} }); dialogRef.afterClosed().subscribe(result => { this.data = result; console.log(result); this.updateSupplier(result); }); } } @Component({ selector: 'supplierEdit-dialogue', templateUrl: 'supplierEdit-dialogue.html', }) export class SupplierEditDialogue { supplier: Supplier; city: string; contactNumber: number; constructor( public dialogRef: MatDialogRef<SupplierEditDialogue>, @Inject(MAT_DIALOG_DATA) public data: Supplier, private supplierService: SupplierService) { } onNoClick(): void { this.dialogRef.close(); } }
24.474359
99
0.686747
e2507efb5c8a74272e08a571751c000192311e80
1,229
asm
Assembly
solutions/39-re coordinator/standard division.asm
Ernesto-Alvarez/HRM-Puzzles
2ec938341dbf67cd186a1d7f1e794a3acd63155f
[ "Unlicense" ]
null
null
null
solutions/39-re coordinator/standard division.asm
Ernesto-Alvarez/HRM-Puzzles
2ec938341dbf67cd186a1d7f1e794a3acd63155f
[ "Unlicense" ]
null
null
null
solutions/39-re coordinator/standard division.asm
Ernesto-Alvarez/HRM-Puzzles
2ec938341dbf67cd186a1d7f1e794a3acd63155f
[ "Unlicense" ]
null
null
null
-- HUMAN RESOURCE MACHINE PROGRAM -- a: COPYFROM 14 COPYTO 13 INBOX b: SUB 15 JUMPN c COPYTO 10 BUMPUP 13 COPYFROM 10 JUMP b COMMENT 0 c: ADD 15 OUTBOX COPYFROM 13 OUTBOX JUMP a DEFINE COMMENT 0 eJzTZ2BgkJDWtJ4kNs1pn5CjnxLP0QwlnobSTZwVbZs4TbalciXvTOXasO81X/bpb/zZp13EVW9MlmO7 1qkqe2yVRvLOg1or1khpey+T0i4o4deSin2kKuStosLkFaO41YVZsc3xoaymNdAKBgGryJZz1tu7btqs n21rd26up73M4sNOnav+uM9Y3eurs4QjcMLMo0FPe48G9ZeB1G8qWKIwIffevAm5C/e25lx4zJ37/z9I /HhSROLsvOmpfuXTUxlGwSgYBRQDAG+0Sck; DEFINE LABEL 13 eJzTZmBgkNL+pNqlO7/8p/762T/1nbdnGh3Yn2n07lCsoeyxWMN3h9z1k3e665tsU9WJWn5G+9zcbZrG kwM1WCYUKbNMUJFJmlYo/W6+ikznKiu55J1v1W5cqtN5fjnI4MRFoNEMCZ7LOxM8J+6R9fY5CeJ/cBPy /uDm6Adi34lJmuYYl7XiX/y3jaJJ/w6LJu24UJksdv1/uu7xE1n3DypmJ++cnRe1fHaezpJNBffmMYyC UTAKqA4AU2hK0A; DEFINE LABEL 14 eJyzY2BgWCHQKmet9kgl06jXIE3KqMBSzKv5qkjlys2CG/ZN4ss+fU2G7+hjXd3jQKUMEsJGBXxKgUUg NrtnYNGGhCdZGxLeRC6NTwhwjHP0Wx+h5DMzLMA/MbA+SMjrTSSb47Z0I9u3Neo2X/vUbYKmTrNbP7vM +e+C9QG8ixzj1s8GmbO3kHXz3sJ785zy3ta8zL2a+bq2PYW3sT2lsGl6qnLz0Qyr1quZIHV1k40KJCc5 Fc7vO1s1v8+ruaPHePK17h1rrXpFt6RPXLj3xuyJe6bOVdkat+Dbxu0LdqxVWyyz+MkS5yndS/7U1i9+ klU/mztm2wzuGLdp7SkMo2AUjAIwAADdv2pu;
29.261905
80
0.830757
1053ae2995a6091d73eda170dc567e54b0a0d714
2,814
lua
Lua
usb-device.lua
pgrabas/ljusb
a00dd3d11f3ef808a3e454f82c0be550e360fa9a
[ "MIT" ]
null
null
null
usb-device.lua
pgrabas/ljusb
a00dd3d11f3ef808a3e454f82c0be550e360fa9a
[ "MIT" ]
null
null
null
usb-device.lua
pgrabas/ljusb
a00dd3d11f3ef808a3e454f82c0be550e360fa9a
[ "MIT" ]
null
null
null
local core = require'ljusb/ljusb_ffi_core' local ffi = require'ffi' local bit = require'bit' local usb_device_handle = require "ljusb/usb-device-handle" ffi.cdef[[ typedef struct ljusb_device { struct libusb_device *handle; } ljusb_device; ]] ffi.metatype('struct ljusb_device', { __gc = function(t) if t.handle ~= nil then core.libusb_unref_device(t.handle) t.handle = nil end end }) local usb_device = {} usb_device.__index = usb_device function usb_device:__tostring() return "usb_device" end function usb_device.__new(context, device) local dev = { ljusb_device = ffi.new("ljusb_device") , context = context, } dev.ljusb_device.handle = core.libusb_ref_device(device) if dev.ljusb_device.handle ~= nil then return setmetatable(dev, usb_device) else return nil end end function usb_device:get_device_port_numbers() local max_len = 8 -- libusb doc says limit is 7 local memory = ffi.gc(ffi.C.malloc(max_len), ffi.C.free) local buffer = ffi.cast("uint8_t*", memory) local r = core.libusb_get_port_numbers(self:get_raw_handle(), buffer, max_len) if r < ffi.C.LIBUSB_SUCCESS then return nil, r end local path = {} for i=0,r-1 do table.insert(path, buffer[i]) end return path end function usb_device:get_device_port_numbers_string(dev) local path, err = self:get_device_port_numbers(dev) if not path then return nil, err end return table.concat(path, ".") end function usb_device:get_raw_handle() local h = self.ljusb_device.handle assert(h ~= nil) return h end function usb_device:open() --TODO store as weak return usb_device_handle.__open_device(self.context, self) end function usb_device:get_descriptor() if not self.descriptor then local desc = ffi.new("struct libusb_device_descriptor ") local r = core.libusb_get_device_descriptor(self:get_raw_handle(), desc) if r == ffi.C.LIBUSB_SUCCESS then self.descriptor = desc return desc end error("Failed to get device descriptor: " .. error_str(r)) end return self.descriptor end function usb_device:get_vid_pid() local d = self:get_descriptor() return { vid=d.idVendor, pid=d.idProduct } end function usb_device:get_product_manufacturer_serial() local d = self:get_descriptor() local h, c = self:open() if not h then return nil, c end local product = h:get_string_descriptor_ascii(d.iProduct) local manufacturer = h:get_string_descriptor_ascii(d.iManufacturer) local serial = h:get_string_descriptor_ascii(d.iSerialNumber) return { product=product, manufacturer=manufacturer, serial=serial } end return usb_device
26.299065
82
0.688344
2f273455cd56840d77cccd795879a75d61dba3b6
2,957
js
JavaScript
Api/src/UserController.js
Paul-Dwamena/vue-project
e492b4bf94e068ea338d169d6e14176166ecf12f
[ "MIT" ]
null
null
null
Api/src/UserController.js
Paul-Dwamena/vue-project
e492b4bf94e068ea338d169d6e14176166ecf12f
[ "MIT" ]
null
null
null
Api/src/UserController.js
Paul-Dwamena/vue-project
e492b4bf94e068ea338d169d6e14176166ecf12f
[ "MIT" ]
null
null
null
const User = require('../database/user') const express=require('express') const router=express.Router() const auth=require('../src/helper') //register route router.all('/register', (req, res)=>{ if (req.method != "POST"){ console.log(req.method) res.status('405').send('Method not allowed') } else User.create({ username:req.body.username, email:req.body.email, contact:req.body.contact, password:req.body.password },(err,user)=>{ if(err){ console.log("There was a problem registering the user.") User.findOne({username:req.body.username},(err,doc)=>{ if(doc){ res.status(400).send({ error:'Username already exists' }) } else{ User.findOne({email:req.body.email},(err,doc)=>{ if(doc){ res.status(400).send({ error:'email already exists' }) } }) } }) }else{ var token= auth.generate_token(user._id,user.password,user.email) res.status(200).send({ success:'User registered successfully', auth:true, token:token }) } })} ) //login route router.all('/login',(req,res)=>{ if (req.method != "POST"){ console.log(req.method) res.status('405').send('Method not allowed') } User.findOne({$or:[{username:req.body.username},{email:req.body.email}]},(err,doc)=>{ if (err) res.status(500).send("Error on the server ") else{ if(doc){ var ispasswordvalid=doc.password==req.body.password if(ispasswordvalid){ res.json({ id:doc.id, username:doc.username, contact:doc.contact, email:doc.email, token: auth.generate_token(doc.id,doc.password,doc.email) }) }else{ res.status(401).send({ error:"Wrong username or Password", auth:false, token:null}) } } else{ res.status(400).send({ error:"Wrong username or Password"}) } } }) }) router.put('/editUser',auth.checkToken,(req, res) => { User.findById(req.userId, 'username,contact ', function (error, user) { if (error) { return res.status(404).send("Account not found") } user.username=req.body.username user.contact=req.body.contact user.save(function(error){ if(error){ console.error(error) } res.send({ msg:'You have updated the your profile successfully' }) }) }) }) module.exports =router
26.401786
85
0.486642
8dc5d5c7780682eb01ef89001cbca5c6facdde2b
88,205
js
JavaScript
public/js/Graph/holder.js
VijaySBoobalan/cbe_class
1d292a6ada7f1aefe4a781a4fd41889e097b0b9c
[ "MIT" ]
null
null
null
public/js/Graph/holder.js
VijaySBoobalan/cbe_class
1d292a6ada7f1aefe4a781a4fd41889e097b0b9c
[ "MIT" ]
null
null
null
public/js/Graph/holder.js
VijaySBoobalan/cbe_class
1d292a6ada7f1aefe4a781a4fd41889e097b0b9c
[ "MIT" ]
null
null
null
if (typeof fontsToLoad == 'undefined') fontsToLoad = ['Hobo', 'smileyMonster', 'segoePrint']; for (var i = 0; i < fontsToLoad.length; i++) { var div = document.createElement("div"); div.id = 'hideMe'; div.style.fontFamily = fontsToLoad[i]; div.innerHTML = '.'; document.body.insertBefore(div, document.body.firstChild); } var oldConsoleLog = null; var log = function on() { var obj = {}; obj.on = function () { if (oldConsoleLog == null) return; window['console']['log'] = oldConsoleLog; }; obj.off = function off() { oldConsoleLog = console.log; window['console']['log'] = function () {}; }; return obj; } (); function un(variable) { if (typeof variable == 'undefined') { return true; } else { return false; } } function def(arr) { for (var d = 0; d < arr.length; d++) { if (typeof arr[d] !== 'undefined') { return arr[d]; } } return undefined; } function boolean(testVar, def) { if (typeof testVar == 'boolean') { return testVar; } else { return def; } } function clone(obj) { var copy; if (null == obj || "object" != typeof obj) return obj; if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } if (!Array.prototype.last){ Array.prototype.last = function(){ return this[this.length - 1]; }; }; var mainCanvasWidth = mainCanvasWidth || 1200; var mainCanvasHeight = mainCanvasHeight || 700; var mainCanvasBorderWidth = 2; var mainCanvasMode = mainCanvasMode || 'full'; var mainCanvasOrientationChangeMode = false; var mainCanvasOrientation = 0; var mainCanvasOrientationDims = [[1200, 700], [616, 700]]; var mainCanvasOrientationChangeFunc = function () {}; var mainCanvasFillStyle = mainCanvasFillStyle || '#e3dee8'; var mainCanvasLeft = mainCanvasLeft || 0; var mainCanvasTop = mainCanvasTop || 0; var logging = []; function logMe(string, variable, logType) { if (!logType) logType = logging; if (string == 'br' && logging.indexOf(logType) > -1) { console.log('-------------------------------'); } else if (logging.indexOf(logType) > -1 && typeof variable !== 'undefined') { console.log(string, variable, typeof variable, variable.length); } else if (logging.indexOf(logType) > -1 && typeof variable == 'undefined') { console.log(string, 'undefined'); } } function logMeG(varNameAsString, logType) { // for logging global variables if (!logType) logType = logging; if (logging.indexOf(logType) > -1) { console.log(varNameAsString, eval(varNameAsString), typeof eval(varNameAsString), eval(varNameAsString).length); } } /* log event listeners // Speed up calls to hasOwnProperty var hasOwnProperty = Object.prototype.hasOwnProperty; function isEmpty(obj) { // null and undefined are "empty" if (obj == null) return true; // Assume if it has a length property with a non-zero value // that that property is correct. if (obj.length > 0) return false; if (obj.length === 0) return true; // If it isn't an object at this point // it is empty, but it can't be anything *but* empty // Is it empty? Depends on your application. if (typeof obj !== "object") return true; // Otherwise, does it have any properties of its own? // Note that this doesn't handle // toString and valueOf enumeration bugs in IE < 9 for (var key in obj) { if (hasOwnProperty.call(obj, key)) return false; } return true; } function logListeners(type) { var all = document.getElementsByTagName("*"); for (var i = 0, max = all.length; i < max; i++) { var list = getEventListeners(all[i]); if (typeof type == 'undefined') { if (!isEmpty(list)) { list.obj = all[i]; console.log(list); } } else if (typeof list[type] !== 'undefined') { list[type].unshift(all[i]); console.log(list[type]); } } }/*/ // if (typeof scriptsToLoad == 'undefined') { var scriptsToLoad = ['/drawMathsText.js', '/mathsInput.js', '/timeme.min.js', '/login.js', '/grid2.js', '/video.js', '/keyboard.js', '/text.js', '/draw.js', '/draw2.js', '/miscFuncs.js', '/drawLines.js', '/Notifier.js']; // } var loadedScriptCount = 0; var totalScriptCount = scriptsToLoad.length; var loadedScriptLogin = true; if (scriptsToLoad.indexOf('../login.js') > -1) { var loadedScriptLogin = false; totalScriptCount--; //scriptsToLoad = scriptsToLoad.splice(scriptsToLoad.indexOf('../login.js'),1); } loadScripts2(); function loadScripts2() { if (scriptsToLoad.length == 0) { scriptLoaded(); } else { while (scriptsToLoad.length > 0) { var script = scriptsToLoad.shift(); if (script !== '../login.js') loadScript(script, scriptLoaded); } } } function loadScript(url, callback, errorCallback) { url = public_path+'/public/js/Graph/'+url; if (un(errorCallback)) errorCallback = function() {}; var head = document.getElementsByTagName('head')[0]; if (url.indexOf('css') > -1) { var elem = document.createElement('link'); elem.rel = 'stylesheet'; elem.type = 'text/css'; elem.callback = callback; eleme.errorCallback = errorCallback; elem.onload = callback; elem.onerror = errorCallback; elem.href = url; head.appendChild(elem); } else { var script = document.createElement('script'); script.type = 'text/javascript'; script.callback = callback; script.errorCallback = errorCallback; script.onerror = errorCallback; script.onload = script.onreadystatechange = function() { if (typeof this.callback == 'function') callback(); } script.src = url; head.appendChild(script); } } function scriptLoaded() { loadedScriptCount++; if (loadedScriptCount >= totalScriptCount) { if (loadedScriptLogin == false) { loadedScriptLogin = true; loadScript('../login.js', scriptLoaded); } else if (task.length > 0) { loadScript(task[0] + '.js', scriptsLoaded); } else { holderLoadHandler(); } } } function scriptsLoaded() { pageLoaded[0] = true; holderLoadHandler(); } var makePDFLoaded = false; function loadMakePDF(callback) { if (makePDFLoaded == false) { makePDFLoaded = true; window.callback = callback; loadScript('../pdfmake.min.js',loadMakePDF2); } else { callback(); } } function loadMakePDF2() { var callback = window.callback; delete window.callback; loadScript('../vfs_fonts.js',callback); } var pi = String.fromCharCode(0x03C0); var times = String.fromCharCode(0x00D7); var divide = String.fromCharCode(0x00F7); var degrees = String.fromCharCode(0x00B0); var infinity = String.fromCharCode(0x221E); var lessThanEq = String.fromCharCode(0x2264); var moreThanEq = String.fromCharCode(0x2265); var notEqual = String.fromCharCode(0x2260); var theta = String.fromCharCode(0x03B8); var plusMinus = String.fromCharCode(0x00B1); var minusPlus = String.fromCharCode(0x2213); var logPointerEvents = false; window.addEventListener("touchstart", function (e) { e.preventDefault(); if (logPointerEvents) console.log('touchstart', e.target); }, true); window.addEventListener("touchmove", function (e) { e.preventDefault(); if (logPointerEvents) console.log('touchmove', e.target); }, true); window.addEventListener("touchend", function (e) { e.preventDefault(); if (logPointerEvents) console.log('touchend', e.target); }, true); window.addEventListener("pointerstart", function (e) { e.preventDefault(); if (logPointerEvents) console.log('pointerstart'); }, true); window.addEventListener("pointermove", function (e) { e.preventDefault(); if (logPointerEvents) console.log('pointermove'); }, true); window.addEventListener("pointerend", function (e) { e.preventDefault(); if (logPointerEvents) console.log('pointerend'); }, true); window.addEventListener("mousedown", function (e) { e.preventDefault(); if (logPointerEvents) console.log('mousedown'); }, true); window.addEventListener("mousemove", function (e) { e.preventDefault(); if (logPointerEvents) console.log('mousemove'); }, true); window.addEventListener("mouseup", function (e) { e.preventDefault(); if (logPointerEvents) console.log('mouseup'); }, true); var taskObject = []; var taskObjectData = []; var pageLoaded = []; var taskState = []; for (var t = 0; t < task.length; t++) { pageLoaded[t] = false; taskState[t] = 0; } var questions = []; var isMobile = { Android: function () { return navigator.userAgent.match(/Android/i); }, BlackBerry: function () { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function () { return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i); }, any: function () { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } } if (isMobile.any()) { document.getElementsByTagName("head")[0].innerHTML += '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">' document.ontouchmove = function (event) { event.preventDefault() } } function stopDefaultBackspaceBehaviour(e) { if (e.keyCode == 8) { e.preventDefault ? e.preventDefault() : e.returnValue = false; } } function horizCanvasToWindow(horizLength) { return (horizLength / mainCanvasWidth) * canvasDisplayWidth; } function vertCanvasToWindow(vertLength) { return (vertLength / mainCanvasHeight) * canvasDisplayHeight; } function horizWindowToCanvas(horizLength) { return (horizLength * mainCanvasWidth) / canvasDisplayWidth; } function vertWindowToCanvas(vertLength) { return (vertLength * mainCanvasHeight) / canvasDisplayHeight; } function xWindowToCanvas(xCoord) { return mainCanvasWidth * ((xCoord - canvasMetrics.left) / (canvasDisplayWidth)); } function xCanvasToWindow(xCoord) { return canvasMetrics.left + (xCoord / mainCanvasWidth) * canvasDisplayWidth; } function yWindowToCanvas(yCoord) { return mainCanvasHeight * ((yCoord - canvasMetrics.top) / canvasDisplayHeight); } function yCanvasToWindow(yCoord) { return canvasMetrics.top + (yCoord / mainCanvasHeight) * canvasDisplayHeight; } function addListener(toButton, yourFunction) { toButton.addEventListener("touchend", yourFunction, false) toButton.addEventListener("mouseup", yourFunction, false) } function removeListener(toButton, yourFunction) { toButton.removeEventListener("touchend", yourFunction, false) toButton.removeEventListener("mouseup", yourFunction, false) } function addListenerStart(toButton, yourFunction) { toButton.addEventListener("touchstart", yourFunction, false) toButton.addEventListener("mousedown", yourFunction, false); } function removeListenerStart(toButton, yourFunction) { toButton.removeEventListener("touchstart", yourFunction, false) toButton.removeEventListener("mousedown", yourFunction, false); } function addListenerMove(toButton, yourFunction) { toButton.addEventListener("touchmove", yourFunction, false) toButton.addEventListener("mousemove", yourFunction, false) } function removeListenerMove(toButton, yourFunction) { toButton.removeEventListener("touchmove", yourFunction, false) toButton.removeEventListener("mousemove", yourFunction, false) } function addListenerEnd(toButton, yourFunction) { toButton.addEventListener("touchend", yourFunction, false) toButton.addEventListener("mouseup", yourFunction, false); } function removeListenerEnd(toButton, yourFunction) { toButton.removeEventListener("touchend", yourFunction, false) toButton.removeEventListener("mouseup", yourFunction, false); } function get_browser_info() { var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { tem = /\brv[ :]+(\d+)/g.exec(ua) || []; return { name: 'IE', version: (tem[1] || '') }; } if (M[1] === 'Chrome') { tem = ua.match(/\bOPR\/(\d+)/) if (tem != null) { return { name: 'Opera', version: tem[1] }; } } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); } return { name: M[0], version: M[1] }; } var browser = get_browser_info(); switch (browser.name) { case 'Chrome': break; case 'Firefox': break; case 'MSIE': if (browser.version < 11) { alert('You do not have the latest version of Internet Explorer. Some elements on the task may not work unless you update your browser.') } break; case 'Safari': break; case 'Opera': break; } var blinking = false; window.addEventListener('focus', function () { if (blinking == true) { setTimeout(function () { mathsInputCursorBlinkInterval = setCorrectingInterval(function () { mathsInputCursorBlink() }, 600); }, 100); } }); window.addEventListener('blur', function () { if (blinking == true) { clearCorrectingInterval(mathsInputCursorBlinkInterval); inputCursorState = false; drawMathsInputText(currMathsInput); } if (typeof currMathsInput !== 'undefined') endMathsInput(); }); var taskTag; var taskTagArray = []; var taskId; var taskState = []; window.pageLoading = false; var taskNum = 0; if (taskOrTool == 'Task' || taskOrTool == 'task') { taskOrTool = 'Task' } var taskCompleteMessage = []; for (var i = 0; i < task.length; i++) { taskCompleteMessage[i] = 0 }; var taskCompleteMessageCanvas = []; var taskCompleteMessageCanvasctx = []; var taskCompleteMessageCanvasData = []; var taskCompleteMessageInterval = []; var starYellow = new Image; var starYellowPointy = new Image; var starWhite6points = new Image; var yellowStar = new Image; yellowStar.src = '../images/yellowStar.png' var backgroundLoadHandler = []; var loadHandler = []; var taskReset = []; var penColour = -1; var keyboard = []; var keyboardData = []; var key1 = []; var key1Data = []; var showKeys = []; var hideKeys = []; var keyboardVis = []; var textCanvas = []; var textCanvasData = []; var mouse = { x: 0, y: 0 }; function updateMouse(e) { if (un(e)) return; if (e.touches) { if (un(e.touches[0])) return; var x = e.touches[0].pageX; var y = e.touches[0].pageY; } else { var x = e.clientX || e.pageX; var y = e.clientY || e.pageY; } mouse.x = xWindowToCanvas(x); mouse.y = yWindowToCanvas(y); } var path = { x: 0, y: 0 }; var dragObject = []; var dragObjectData = []; var currentDragId; var dragOffset = { x: 0, y: 0 }; var dragArea = { xMin: 0, xMax: 0, yMin: 0, yMax: 0 }; var zIndexFront = 100; var firstPlay = []; var textCanvas = []; var currMathsInput; var currMathsInputId; var currMathsInputType; var currMathsInputWidth; var mathsInputCursorBlinkInterval; var mathsInputCursorState; var mathsInput = []; var mathsInputCursor = {x:0, top:0, bottom:0} var charMap = [[42,215,215], [48,48,41], [49,49,33], [50,50,34], [51,51,163], [52,52,36], [53,53,37], [54,54,94], [55,55,38], [56,56,215], [57,57,40], [96,48,48], [97,49,49], [98,50,50], [99,51,51], [100,52,52], [101,53,53], [102,54,54], [103,55,55], [104,56,56], [105,57,57], [106,215,215], [107,43,43], [109,189,189], [110,190,190], [111,191,191], [186,59,58], [187,61,43], [188,44,60], [189,45,95], [190,46,62], [191,247,63], [192,39,64], [219,91,123], [220,92,124], [221,93,125], [222,35,126]]; var endInputExceptions = []; var currSlider; var slider = []; var draw = []; var container = document.getElementById('canvascontainer'); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var canvasDisplayRect; var canvasDisplayWidth; var canvasDisplayHeight; var canvasMetrics = canvas.getBoundingClientRect(); var openhand = 'url("../images/cursors/openhand.cur"), auto'; var closedhand = 'url("../images/cursors/closedhand.cur"), auto'; //var openhand = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAhUlEQVQ4T62S0RIAIQQA+f+P1uhiUKiZu7cu1iKE+qN1jVlYvLAJRPQdEV1YetgSLCDAFGJprwDW824A4CCFAQfO1rYZZEnZfwEch3eaPFe1MAakvTcr1hYUICuTChVgrVaH6CBdZfM23BaeINGAodcASZ4mQfcKUgFaE5t8MhCh1OR3wADGb2cNb+0DlAAAAABJRU5ErkJggg==';; //var closedhand = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAbUlEQVQ4T92SQQ4AIQgD6f8fzUa0xiioCXvSixzsUIqQ5EFSL48CtOVSxovqHt2cgapWDQCJ6qHBEmIHRNshuNzWx3l4hNChBzD/tL77I56Dq86EpgAU2yiTzSsXO0CLgOtfUxjFngMqQie/Az6XuzQRt0ZDFgAAAABJRU5ErkJggg=='; if (document.getElementById("holderHomeButton") !== null) { var homeImage = new Image; homeImage.src = "../images/logoSmall.PNG"; } if (document.getElementById("userInfoText") !== null) { var userInfoText = document.getElementById('userInfoText'); var userInfoTextctx = userInfoText.getContext('2d'); userInfoText.style.zIndex = 799999; } if (document.getElementById("holderPrevButton") !== null) { var button00 = document.getElementById('holderPrevButton'); var button00ctx = button00.getContext('2d'); var button01 = document.getElementById('holderReloadButton'); var button01ctx = button01.getContext('2d'); var button02 = document.getElementById('holderNextButton'); var button02ctx = button02.getContext('2d'); var button03 = document.getElementById('holderHomeButton'); var button03ctx = button03.getContext('2d'); var button04 = document.getElementById('holderQuestionNum'); var button04ctx = button04.getContext('2d'); var holderButton = []; holderButton.push(button00, button01, button02, button03, button04); var holderButtonctx = []; holderButtonctx.push(button00ctx, button01ctx, button02ctx, button03ctx, button04ctx); if (taskOrTool == 'tool') { var holderButtonData = [[75, 20, 50, 50, ""], [1020, 20, 50, 50, ""], [1075, 20, 50, 50, ""], [1130, 20, 50, 50, ""], [20, 20, 50, 50, taskNum + 1]]; for (var i = 0, iLim = holderButton.length; i < iLim; i++) { holderButton[i].width = 50; holderButton[i].height = 50; } if (task.length == 1) { container.removeChild(holderButton[0]); container.removeChild(holderButton[2]); container.removeChild(holderButton[4]); holderButtonData[1] = [1075, 20, 50, 50, ""]; } } else { var holderButtonData = [[96, 24, 210, 68, "Previous Page"], [680, 24, 190, 68, "Reload Page"], [883, 24, 210, 68, "Next Page"], [1102, 24, 74, 68, ""], [22, 24, 66, 68, taskNum + 1]]; } } if (document.getElementById("penColourBlack") !== null) { container.removeChild(document.getElementById('penColourBlack')); container.removeChild(document.getElementById('penColourBlue')); container.removeChild(document.getElementById('penColourRed')); container.removeChild(document.getElementById('penColourGreen')); container.removeChild(document.getElementById('penClear')); container.removeChild(document.getElementById('penOff')); } if (document.getElementById("inactiveBox") !== null) { var inactiveBox = document.getElementById('inactiveBox'); var inactiveBoxctx = inactiveBox.getContext('2d'); } window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false); window.addEventListener('keydown', stopDefaultBackspaceBehaviour, false); window.addEventListener('mousemove', updateMouse, false); window.addEventListener('touchstart', updateMouse, false); window.addEventListener('touchmove', updateMouse, false); function holderLoadHandler() { if (taskOrTool == 'Task') { getSessionOnPageLoad() } clearCanvas(); if (typeof holderButton !== 'undefined') { holderButton[0].style.opacity = "0.5"; holderButton[0].style.filter = 'alpha(opacity = 50)'; holderButton[0].style.cursor = "auto"; holderButton[0].style.pointerEvents = "none"; if (taskNum == task.length - 1) { holderButton[2].style.opacity = "0.5"; holderButton[2].style.filter = 'alpha(opacity = 50)'; holderButton[2].style.cursor = "auto"; holderButton[2].style.pointerEvents = "none"; } for (var i = 0; i < holderButtonData.length; i++) { drawHolderButton(i); holderButton[i].addEventListener('mousedown', clickHolderButton, false); holderButton[i].addEventListener('touchstart', clickHolderButton, false); holderButton[i].style.zIndex = 800000; } if (taskOrTool == 'tool') { homeImage.onload = function () { holderButtonctx[3].drawImage(homeImage, 6, 5.5, 40, 40) }; // holderButtonctx[3].drawImage(homeImage, 6, 5.5, 40, 40); } else { homeImage.onload = function () { holderButtonctx[3].drawImage(homeImage, 10, 8, 56, 54) }; holderButtonctx[3].drawImage(homeImage, 10, 8, 56, 54); } } for (i = 0; i < loadHandler.length; i++) { taskNum = i; loadHandler[i](); } for (var i = 0; i < task.length; i++) { taskState[i] = 0; } taskNum = 0; taskId = 0; taskTag = taskTagArray[0]; if (typeof backgroundLoadHandler[0] === 'function') backgroundLoadHandler[0](); if (typeof userInfoText !== 'undefined') userInfoTextUpdate(); if (typeof inactiveBox !== 'undefined') drawInactiveBox(); if (taskOrTool == 'Task' || taskOrTool == 'task') { drawSmallTaskCompleteMessage(); loadTaskCompleteMessages(); } for (j = 0; j < taskObject.length; j++) { for (i = 0; i < taskObject[j].length; i++) { if (j == 0) { if (taskObjectData[j][i][4] == true) { container.appendChild(taskObject[j][i]) }; } else { if (taskObject[j][i].parentNode == container) { container.removeChild(taskObject[j][i]) }; } } } resize(); } function resize() { if (mainCanvasOrientationChangeMode == true) { if (window.innerWidth > window.innerHeight && mainCanvasOrientation == 1) { mainCanvasOrientation = 0; mainCanvasWidth = mainCanvasOrientationDims[0][0]; mainCanvasHeight = mainCanvasOrientationDims[0][1]; mainCanvasBorderWidth = 16; canvas.width = mainCanvasWidth; canvas.height = mainCanvasHeight; clearCanvas(); mainCanvasOrientationChangeFunc.apply(); } else if (window.innerWidth < window.innerHeight && mainCanvasOrientation == 0) { mainCanvasOrientation = 1; mainCanvasWidth = mainCanvasOrientationDims[1][0]; mainCanvasHeight = mainCanvasOrientationDims[1][1]; mainCanvasBorderWidth = 12; canvas.width = mainCanvasWidth; canvas.height = mainCanvasHeight; clearCanvas(); mainCanvasOrientationChangeFunc.apply(); } } if (mainCanvasMode == 'full') { canvasDisplayWidth = window.innerWidth; canvasDisplayHeight = window.innerHeight; if ((canvasDisplayWidth / canvasDisplayHeight) > (mainCanvasWidth / mainCanvasHeight)) { canvasDisplayWidth = canvasDisplayHeight * (mainCanvasWidth / mainCanvasHeight); } else { canvasDisplayHeight = canvasDisplayWidth / (mainCanvasWidth / mainCanvasHeight); } } else if (mainCanvasMode == 'width') { canvasDisplayWidth = window.innerWidth - 400; canvasDisplayHeight = canvasDisplayWidth / (mainCanvasWidth / mainCanvasHeight); } else if (mainCanvasMode == 'height') { canvasDisplayWidth = window.innerHeight; canvasDisplayHeight = canvasDisplayHeight * (mainCanvasWidth / mainCanvasHeight); } canvas.style.left = String(mainCanvasLeft) + 'px'; canvas.style.top = String(mainCanvasTop) + 'px'; canvas.style.width = canvasDisplayWidth + 'px'; canvas.style.height = canvasDisplayHeight + 'px'; canvasDisplayRect = canvas.getBoundingClientRect(); if (typeof holderButton !== 'undefined') { for (i = 0; i < holderButton.length; i++) { resizeCanvas(holderButton[i], holderButtonData[i][0], holderButtonData[i][1], holderButtonData[i][2], holderButtonData[i][3]); } } if (typeof userInfoText !== 'undefined') resizeCanvas(userInfoText, 321, 24, 343, 68); if (typeof inactiveBox !== 'undefined') resizeCanvas(inactiveBox, 400, 290, 400, 120); if (typeof taskVideo !== 'undefined' && typeof taskVideoData !== 'undefined' && typeof taskVideoData[taskId] !== 'undefined') { resizeCanvas(iframe[taskId], taskVideoData[taskId][0], taskVideoData[taskId][1], taskVideoData[taskId][2], taskVideoData[taskId][3]); } for (var j = 0; j < taskObject.length; j++) { for (i = 0; i < taskObject[j].length; i++) { if (typeof taskObject[j][i].data == 'undefined') { resizeCanvas(taskObject[j][i], taskObjectData[j][i][100], taskObjectData[j][i][101], taskObjectData[j][i][102], taskObjectData[j][i][103]); } else { resizeCanvas(taskObject[j][i], taskObject[j][i].data[100], taskObject[j][i].data[101], taskObject[j][i].data[102], taskObject[j][i].data[103]); } } } for (var j = 0; j < task.length; j++) { if (typeof keyboard[j] !== 'undefined') { resizeCanvas(keyboard[j], keyboardData[j][100], keyboardData[j][101], keyboardData[j][2], keyboardData[j][3]); for (var i = 0; i <key1[j].length; i++) { resizeCanvas(key1[j][i], key1Data[j][i][100], key1Data[j][i][101], key1Data[j][i][2], key1Data[j][i][3]); } } } canvasMetrics = canvas.getBoundingClientRect(); } function resizeCanvas(canvasToResize, left, top, width, height) { if (typeof canvasToResize !== 'object') return; if (canvasToResize.isStaticMenuCanvas == true) { var l = 0.5 * (window.innerWidth - Number(String(canvas.style.width).slice(0, -2))) + canvasDisplayWidth * (left / mainCanvasWidth); var t = canvasDisplayHeight * (top / mainCanvasHeight); } else { var l = 0.5 * (window.innerWidth - Number(String(canvas.style.width).slice(0, -2))) + canvasDisplayWidth * (left / mainCanvasWidth) + mainCanvasLeft; var t = canvasDisplayHeight * (top / mainCanvasHeight) + mainCanvasTop; } var w = canvasDisplayWidth * (width / mainCanvasWidth); var h = canvasDisplayHeight * (height / mainCanvasHeight); canvasToResize.style.left = l + "px"; canvasToResize.style.top = t + "px"; canvasToResize.style.width = w + "px"; canvasToResize.style.height = h + "px"; } function resizeCanvas2(canvasToResize, left, top) { if (un(canvasToResize)) return; if (canvasToResize.isStaticMenuCanvas == true) { var l = 0.5 * (window.innerWidth - Number(String(canvas.style.width).slice(0, -2))) + canvasDisplayWidth * (left / mainCanvasWidth); var t = canvasDisplayHeight * (top / mainCanvasHeight); } else { var l = 0.5 * (window.innerWidth - Number(String(canvas.style.width).slice(0, -2))) + canvasDisplayWidth * (left / mainCanvasWidth) + mainCanvasLeft; var t = canvasDisplayHeight * (top / mainCanvasHeight) + mainCanvasTop; } canvasToResize.style.left = l + "px"; canvasToResize.style.top = t + "px"; } function resizeCanvas3(canvasToResize) { if (typeof canvasToResize.data == 'undefined') return; var left = canvasToResize.data[100]; var top = canvasToResize.data[101]; var width = canvasToResize.data[102]; var height = canvasToResize.data[103]; if (canvasToResize.isStaticMenuCanvas == true) { var l = 0.5 * (window.innerWidth - Number(String(canvas.style.width).slice(0, -2))) + canvasDisplayWidth * (left / mainCanvasWidth); var t = canvasDisplayHeight * (top / mainCanvasHeight); } else { var l = 0.5 * (window.innerWidth - Number(String(canvas.style.width).slice(0, -2))) + canvasDisplayWidth * (left / mainCanvasWidth) + mainCanvasLeft; var t = canvasDisplayHeight * (top / mainCanvasHeight) + mainCanvasTop; } var w = canvasDisplayWidth * (width / mainCanvasWidth); var h = canvasDisplayHeight * (height / mainCanvasHeight); canvasToResize.style.left = l + "px"; canvasToResize.style.top = t + "px"; canvasToResize.style.width = w + "px"; canvasToResize.style.height = h + "px"; } function initialiseTaskVariables() { for (i = 0; i < task.length; i++) { var taskTagRegExp = new RegExp(taskTag); if (taskTagRegExp.test(task[i]) == true) { taskId = i; taskTagArray[taskId] = taskTag; } } taskObject[taskId] = []; taskObjectData[taskId] = []; if (typeof taskVideo !== 'undefined') taskVideo[taskId] = false; window[taskTag + 'button'] = []; window[taskTag + 'buttonctx'] = []; window[taskTag + 'buttonData'] = []; window[taskTag + 'imageCanvas'] = []; window[taskTag + 'imageCanvasctx'] = []; window[taskTag + 'imageCanvasData'] = []; window[taskTag + 'mathsInput'] = []; window[taskTag + 'imageLoadArray'] = []; window[taskTag + 'imagesLoaded'] = true; slider[taskId] = []; firstPlay[taskId] = true; mathsInput[taskId] = []; textCanvas[taskId] = []; } function clearCanvas() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.strokeStyle = "#000"; ctx.lineWidth = mainCanvasBorderWidth; ctx.beginPath(); ctx.moveTo(mainCanvasBorderWidth / 2, mainCanvasBorderWidth / 2); ctx.lineTo(mainCanvasWidth - mainCanvasBorderWidth / 2, mainCanvasBorderWidth / 2); ctx.lineTo(mainCanvasWidth - mainCanvasBorderWidth / 2, mainCanvasHeight - mainCanvasBorderWidth / 2); ctx.lineTo(mainCanvasBorderWidth / 2, mainCanvasHeight - mainCanvasBorderWidth / 2); ctx.lineTo(mainCanvasBorderWidth / 2, mainCanvasBorderWidth / 2); ctx.closePath(); ctx.fillStyle = mainCanvasFillStyle; ctx.fill(); ctx.stroke(); } function drawInactiveBox() { inactiveBoxctx.lineCap = "round"; inactiveBoxctx.lineJoin = "round"; inactiveBoxctx.clearRect(0, 0, 400, 120); inactiveBoxctx.fillStyle = "#FFF"; inactiveBoxctx.strokeStyle = "#000"; inactiveBoxctx.lineWidth = 6; inactiveBoxctx.beginPath(); inactiveBoxctx.moveTo(3, 3); inactiveBoxctx.lineTo(397, 3); inactiveBoxctx.lineTo(397, 117); inactiveBoxctx.lineTo(3, 117); inactiveBoxctx.lineTo(3, 3); inactiveBoxctx.closePath(); inactiveBoxctx.fill(); inactiveBoxctx.stroke(); inactiveBoxctx.font = "80px Hobo"; inactiveBoxctx.textAlign = "center"; inactiveBoxctx.textBaseline = "middle"; inactiveBoxctx.fillStyle = "#000"; inactiveBoxctx.fillText('Inactive', 200, 66); inactiveBox.style.pointerEvents = 'none'; inactiveBox.style.zIndex = 900000; if (inactiveBox.parentElement == container) container.removeChild(inactiveBox); } function newcanvas(obj) { if (typeof obj == 'undefined') obj = {}; if (typeof obj.rect !== 'undefined') { obj.l = obj.rect[0]; obj.t = obj.rect[1]; obj.w = obj.rect[2]; obj.h = obj.rect[3]; } var l = obj.l || obj.left || 0; var t = obj.t || obj.top || 0; var w = obj.w || obj.width || 1200; var h = obj.h || obj.height || 700; var vis = true; if (obj.visible === false || obj.vis === false) vis = false; var drag = false; if (obj.draggable === true || obj.drag === true) drag = true; var point = false; if (obj.pointerEvents === true || obj.pEvents === true || obj.pE === true || obj.point === true) point = true; var z = obj.zIndex || obj.z || 2; var cnv = createButton(0, l, t, w, h, vis, drag, point, z); resizeCanvas(cnv, cnv.data[100], cnv.data[101], cnv.data[102], cnv.data[103]); return cnv; } function newctx(obj) { var cnv = newcanvas(obj); var ctx = cnv.ctx; ctx.canvas = cnv; ctx.data = cnv.data; return ctx; } function createButton(id, left, top, width, height, visible, draggable, pointerEvents, zIndex, opt_verticesArray, opt_polygonClickFunc) { taskTag = taskTagArray[taskId]; var buttonInstance = document.createElement('canvas'); buttonInstance.width = width; buttonInstance.height = height; buttonInstance.setAttribute('id', taskTag + 'button' + id); buttonInstance.setAttribute('position', 'absolute'); buttonInstance.setAttribute('cursor', 'auto'); buttonInstance.setAttribute('draggable', 'false'); buttonInstance.setAttribute('class', 'buttonClass'); var buttonInstanceData = [left, top, width, height, visible, draggable, pointerEvents, zIndex]; if (visible == true) { container.appendChild(buttonInstance); buttonInstanceData[130] = true; } else { if (buttonInstance.parentNode == container) { container.removeChild(buttonInstance) } buttonInstanceData[130] = false; } eval(taskTag + 'button.push(buttonInstance)'); taskObject[taskId].push(buttonInstance); var buttonInstancectx = buttonInstance.getContext('2d'); eval(taskTag + 'buttonctx.push(buttonInstancectx)'); if (!zIndex) (zIndex = 2); buttonInstanceData[100] = left; buttonInstanceData[101] = top; buttonInstanceData[102] = width; buttonInstanceData[103] = height; buttonInstanceData[104] = visible; buttonInstanceData[105] = draggable; buttonInstanceData[106] = pointerEvents; buttonInstanceData[107] = zIndex; if (opt_verticesArray && opt_verticesArray.length > 2) { buttonInstanceData[41] = opt_verticesArray; if (typeof opt_polygonClickFunc !== 'undefined') buttonInstanceData[43] = opt_polygonClickFunc; pointerEventsFix(buttonInstance, buttonInstanceData); pointerEventsFixTouch(buttonInstance, buttonInstanceData); } else if (draggable == true) { makeDraggable(buttonInstance, buttonInstanceData); } eval(taskTag + 'buttonData.push(buttonInstanceData)'); taskObjectData[taskId].push(buttonInstanceData); buttonInstance.style.zIndex = zIndex; buttonInstance.ctx = buttonInstancectx; buttonInstance.data = buttonInstanceData; if (pointerEvents == false) { buttonInstance.style.pointerEvents = 'none'; } else { buttonInstance.style.pointerEvents = 'auto'; } if (typeof buttonInstancectx.getLineDash !== 'function') buttonInstancectx.getLineDash = function () { return [] }; if (typeof buttonInstancectx.setLineDash !== 'function') buttonInstancectx.setLineDash = function () {}; buttonInstancectx.fillStyle = 'none'; /*buttonInstancectx.setStroke = function (obj) { var lineWidth = obj.lineWidth || obj.width || obj.w || obj.thickness || this.lineWidth; var strokeStyle = obj.color || obj.strokeStyle || obj.style || this.strokeStyle; var dash = obj.dash || obj.lineDash || this.getLineDash(); var lineCap = obj.lineCap || obj.cap || 'round'; var lineJoin = obj.lineJoin || obj.join || obj.cap || 'round'; this.lineWidth = lineWidth; this.strokeStyle = strokeStyle; this.setLineDash(dash); this.lineCap = lineCap; this.lineJoin = lineJoin; } buttonInstancectx.setFill = function (obj) { var color = obj.color || this.fillStyle; this.fillStyle = obj.color; } buttonInstancectx.path = function (pathArray, close, obj) { if (typeof obj == 'undefined') obj = {}; this.beginPath(); this.moveTo(pathArray[0][0], pathArray[0][1]); for (var i = 1; i < pathArray.length; i++) { this.lineTo(pathArray[i][0], pathArray[i][1]); } if (boolean(close, false) === true) { this.lineTo(pathArray[0][0], pathArray[0][1]); } if (typeof obj.fill !== 'undefined') { this.setFill(obj.fill); this.fill(); } if (typeof obj.lineDec !== 'undefined') {} if (typeof obj.intAngles !== 'undefined') { if (typeof obj.intAngles.show == 'undefined') { obj.intAngles.show = []; for (var i = 0; i < pathArray.length; i++) obj.intAngles.show.push(true); } var angle = { ctx: this }; angle.radius = obj.intAngles.radius || obj.intAngles.r || undefined; angle.squareForRight = boolean(obj.intAngles.squareForRight, true); angle.labelIfRight = boolean(obj.intAngles.labelIfRight, false); angle.drawLines = boolean(obj.intAngles.drawLines, false); angle.lineWidth = obj.intAngles.lineWidth || obj.intAngles.width || obj.intAngles.w || undefined; angle.lineColor = obj.intAngles.lineColor || obj.intAngles.color || undefined; angle.drawCurve = boolean(obj.intAngles.drawCurve, true); angle.curveWidth = obj.intAngles.curveWidth || angle.lineWidth; angle.curveColor = obj.intAngles.curveColor || angle.lineColor; if (typeof obj.intAngles.fill == 'string') { angle.fill = true; angle.fillColor = obj.intAngles.fill; } else { angle.fill = boolean(obj.intAngles.fill, false); angle.fillColor = obj.intAngles.fillColor || undefined; } angle.label = obj.intAngles.label || obj.intAngles.text || undefined; angle.labelFont = obj.intAngles.labelFont || obj.intAngles.font || undefined; angle.labelFontSize = obj.intAngles.labelFontSize || obj.intAngles.fontSize || undefined; angle.labelColor = obj.intAngles.labelColor || angle.lineColor || undefined; angle.labelRadius = obj.intAngles.labelRadius || undefined; angle.labelMeasure = boolean(obj.intAngles.labelMeasure, false); angle.measureRoundTo = obj.intAngles.measureRoundTo || obj.intAngles.roundTo || undefined; angle.angleType = obj.intAngles.angleType || undefined; for (var i = 0; i < pathArray.length; i++) { if (obj.intAngles.show[i] === true) { if (i === 0) { angle.a = pathArray[pathArray.length - 1] } else { angle.a = pathArray[i - 1] }; angle.b = pathArray[i]; if (i === pathArray.length - 1) { angle.c = pathArray[0] } else { angle.c = pathArray[i + 1] }; if (typeof obj.intAngles.r == 'object') angle.radius = obj.intAngles.r[i]; if (typeof obj.intAngles.radius == 'object') angle.radius = obj.intAngles.radius[i]; if (typeof obj.intAngles.squareForRight == 'object') angle.squareForRight = boolean(obj.intAngles.squareForRight[i], true); if (typeof obj.intAngles.labelIfRight == 'object') angle.labelIfRight = boolean(obj.intAngles.labelIfRight[i], false); if (typeof obj.intAngles.drawLines == 'object') angle.drawLines = boolean(obj.intAngles.drawLines[i], false); if (typeof obj.intAngles.lineWidth == 'object') angle.lineWidth = obj.intAngles.lineWidth[i]; if (typeof obj.intAngles.width == 'object') angle.lineWidth = obj.intAngles.width[i]; if (typeof obj.intAngles.w == 'object') angle.lineWidth = obj.intAngles.w[i]; if (typeof obj.intAngles.lineColor == 'object') angle.lineColor = obj.intAngles.lineColor[i]; if (typeof obj.intAngles.color == 'object') angle.lineWidth = obj.intAngles.color[i]; if (typeof obj.intAngles.drawCurve == 'object') angle.drawCurve = boolean(obj.intAngles.drawCurve[i], true); if (typeof obj.intAngles.lineWidth == 'object') angle.curveWidth = obj.intAngles.lineWidth[i]; if (typeof obj.intAngles.curveWidth == 'object') angle.curveWidth = obj.intAngles.curveWidth[i]; if (typeof obj.intAngles.curveColor == 'object') angle.curveColor = obj.intAngles.curveColor[i]; if (typeof obj.intAngles.fill == 'object') { if (typeof obj.intAngles.fill[i] == 'string') { angle.fill = true; angle.fillColor = obj.intAngles.fill[i]; } else { angle.fill = boolean(obj.intAngles.fill[i], false); if (typeof obj.intAngles.fillColor == 'object') angle.fillColor = obj.intAngles.fillColor[i]; } } if (typeof obj.intAngles.label == 'object') angle.label = obj.intAngles.label[i]; if (typeof obj.intAngles.text == 'object') angle.label = obj.intAngles.text[i]; if (typeof obj.intAngles.labelFont == 'object') angle.labelFont = obj.intAngles.curveColor[i]; if (typeof obj.intAngles.font == 'object') angle.labelFont = obj.intAngles.font[i]; if (typeof obj.intAngles.labelFontSize == 'object') angle.labelFontSize = obj.intAngles.labelFontSize[i]; if (typeof obj.intAngles.fontSize == 'object') angle.labelFontSize = obj.intAngles.fontSize[i]; if (typeof obj.intAngles.lineColor == 'object') angle.labelColor = obj.intAngles.lineColor[i]; if (typeof obj.intAngles.labelColor == 'object') angle.labelColor = obj.intAngles.labelColor[i]; if (typeof obj.intAngles.labelRadius == 'object') angle.labelRadius = obj.intAngles.labelRadius[i]; if (typeof obj.intAngles.labelMeasure == 'object') angle.labelMeasure = boolean(obj.intAngles.labelMeasure[i], false); if (typeof obj.intAngles.measureRoundTo == 'object') angle.measureRoundTo = obj.intAngles.measureRoundTo[i]; if (typeof obj.intAngles.roundTo == 'object') angle.measureRoundTo = obj.intAngles.roundTo[i]; drawAngle(angle); } } } if (typeof obj.vertexLabels !== 'undefined') { if (typeof obj.vertexLabels.show == 'undefined') { obj.vertexLabels.show = []; for (var i = 0; i < pathArray.length; i++) obj.vertexLabels.show.push(true); } var angle = { ctx: this }; angle.labelIfRight = true; angle.drawLines = false; angle.drawCurve = false; angle.fill = false; angle.label = obj.vertexLabels.label || obj.vertexLabels.text || undefined; angle.labelFont = obj.vertexLabels.labelFont || obj.vertexLabels.font || undefined; angle.labelFontSize = obj.vertexLabels.labelFontSize || obj.vertexLabels.fontSize || undefined; angle.labelColor = obj.vertexLabels.labelColor || angle.lineColor || undefined; angle.labelRadius = obj.vertexLabels.labelRadius || obj.vertexLabels.radius || obj.vertexLabels.r || undefined; angle.labelMeasure = false; for (var i = 0; i < pathArray.length; i++) { if (obj.vertexLabels.show[i] === true) { if (i === 0) { angle.c = pathArray[pathArray.length - 1] } else { angle.c = pathArray[i - 1] }; angle.b = pathArray[i]; if (i === pathArray.length - 1) { angle.a = pathArray[0] } else { angle.a = pathArray[i + 1] }; if (typeof obj.vertexLabels.label == 'object') angle.label = obj.vertexLabels.label[i]; if (typeof obj.vertexLabels.text == 'object') angle.label = obj.vertexLabels.text[i]; if (typeof obj.vertexLabels.labelFont == 'object') angle.labelFont = obj.vertexLabels.curveColor[i]; if (typeof obj.vertexLabels.font == 'object') angle.labelFont = obj.vertexLabels.font[i]; if (typeof obj.vertexLabels.labelFontSize == 'object') angle.labelFontSize = obj.vertexLabels.labelFontSize[i]; if (typeof obj.vertexLabels.fontSize == 'object') angle.labelFontSize = obj.vertexLabels.fontSize[i]; if (typeof obj.vertexLabels.lineColor == 'object') angle.labelColor = obj.vertexLabels.lineColor[i]; if (typeof obj.vertexLabels.labelColor == 'object') angle.labelColor = obj.vertexLabels.labelColor[i]; if (typeof obj.vertexLabels.radius == 'object') angle.labelRadius = obj.vertexLabels.radius[i]; if (typeof obj.vertexLabels.r == 'object') angle.labelRadius = obj.vertexLabels.r[i]; if (typeof obj.vertexLabels.labelRadius == 'object') angle.labelRadius = obj.vertexLabels.labelRadius[i]; drawAngle(angle); } } } if (typeof obj.edgeLabels !== 'undefined') { if (typeof obj.edgeLabels.show == 'undefined') { obj.edgeLabels.show = []; for (var i = 0; i < pathArray.length; i++) obj.edgeLabels.show.push(true); } var label = { ctx: this }; label.font = obj.edgeLabels.font || undefined; label.fontSize = obj.edgeLabels.fontSize || undefined; label.width = 1200; for (var i = 0; i < pathArray.length; i++) { if (obj.edgeLabels.show[i] === true) { var a = pathArray[i]; var b = pathArray[(i + 1) % pathArray.length]; label.textArray = obj.edgeLabels.text[i]; labelLine(a, b, label); } } } if (typeof obj.stroke !== 'undefined') { this.beginPath(); this.moveTo(pathArray[0][0], pathArray[0][1]); for (var i = 1; i < pathArray.length; i++) { this.lineTo(pathArray[i][0], pathArray[i][1]); } if (boolean(close, false) === true) { this.lineTo(pathArray[0][0], pathArray[0][1]); } this.setStroke(obj.stroke); this.stroke(); } } buttonInstancectx.clear = function () { this.clearRect(0, 0, this.data[102], this.data[103]); } buttonInstance.setLeft = function (left) { this.data[100] = left; resizeCanvas2(this, this.data[100], this.data[101]); } buttonInstance.setTop = function (top) { this.data[101] = top; resizeCanvas2(this, this.data[100], this.data[101]); } buttonInstance.setPos = function (left, top) { this.data[100] = left; this.data[101] = top; resizeCanvas2(this, this.data[100], this.data[101]); } buttonInstance.setWidth = function (width) { this.data[102] = width; resizeCanvas(this, this.data[100], this.data[101], this.data[102], this.data[103]); } buttonInstance.setHeight = function (height) { this.data[103] = height; resizeCanvas(this, this.data[100], this.data[101], this.data[102], this.data[103]); } buttonInstance.setDims = function (width, height) { this.data[102] = width; this.data[103] = height; resizeCanvas(this, this.data[100], this.data[101], this.data[102], this.data[103]); } buttonInstance.setVis = function (vis) { if (typeof vis == 'undefined') { this.data[104] = !this.data[104]; } else { this.data[104] = vis; } if (this.data[104] == true) { showObj(this); } else { hideObj(this); } } buttonInstance.setPE = function (point) { if (typeof point == 'undefined') { this.data[106] = !this.data[106]; } else { this.data[106] = point; } if (this.data[106] == true) { this.style.pointerEvents = 'auto'; } else { this.style.pointerEvents = 'none'; } } buttonInstance.setZ = function (z) { this.data[107] = z; this.style.zIndex = z; } buttonInstance.setCursor = function (cursor) { this.style.cursor = cursor || 'pointer'; } buttonInstance.setOpacity = function (opacity) { this.style.opacity = opacity; }*/ return buttonInstance; } function createCanvas(left, top, width, height, visible, draggable, pointerEvents, zIndex) { var canvasInstance = document.createElement('canvas'); canvasInstance.width = width; canvasInstance.height = height; canvasInstance.setAttribute('position', 'absolute'); canvasInstance.setAttribute('cursor', 'auto'); canvasInstance.setAttribute('draggable', 'false'); canvasInstance.setAttribute('class', 'buttonClass'); var canvasInstanceData = [left, top, width, height, visible, draggable, pointerEvents, zIndex]; if (visible == true) { container.appendChild(canvasInstance); canvasInstanceData[130] = true; } else { if (canvasInstance.parentNode == container) container.removeChild(canvasInstance); canvasInstanceData[130] = false; } for (var i = 0; i < 8; i++) { canvasInstanceData[100 + i] = canvasInstanceData[i]; } canvasInstance.style.zIndex = zIndex; if (pointerEvents == false) canvasInstance.style.pointerEvents = 'none'; if (draggable == true) { makeDraggable(canvasInstance, canvasInstanceData) } taskObject[taskId].push(canvasInstance); taskObjectData[taskId].push(canvasInstanceData); canvasInstance.data = canvasInstanceData; canvasInstance.ctx = canvasInstance.getContext('2d'); return canvasInstance; } function createTextCanvas(object) { var left = object.left; var top = object.top; var text = object.text || ""; var id = object.id || textCanvas[taskId].length; var width = object.width || 300; var spacing = object.spacing || 30; var visible; if (typeof object.visible == 'boolean') { visible = object.visible } else { visible = true }; var draggable; if (typeof object.draggable == 'boolean') { draggable = object.draggable } else { draggable = false }; var pointerEvents; if (typeof object.pointerEvents == 'boolean') { pointerEvents = object.pointerEvents } else { pointerEvents = false }; var zIndex = object.zIndex || 2; var font = object.font || '24px Arial'; var textColor = object.textColor || '#000'; var textAlign = object.textAlign || 'left'; createTextCanvas2(id, left, top, width, spacing, visible, draggable, pointerEvents, zIndex, font, textColor, textAlign, text) } function createTextCanvas2(id, left, top, width, spacing, visible, draggable, pointerEvents, zIndex, font, textColor, textAlign, text) { var canvasInstance = document.createElement('canvas'); canvasInstance.width = width; canvasInstance.height = spacing; canvasInstance.setAttribute('position', 'absolute'); canvasInstance.setAttribute('cursor', 'auto'); canvasInstance.setAttribute('draggable', 'false'); canvasInstance.setAttribute('class', 'buttonClass'); var canvasInstanceData = [left, top, width, spacing, visible, draggable, pointerEvents, zIndex]; if (visible == true) { container.appendChild(canvasInstance); canvasInstanceData[130] = true; } else { if (canvasInstance.parentNode == container) { container.removeChild(canvasInstance) } canvasInstanceData[130] = false; } taskObject[taskId].push(canvasInstance); var canvasInstancectx = canvasInstance.getContext('2d'); canvasInstanceData[100] = left; canvasInstanceData[101] = top; canvasInstanceData[102] = width; canvasInstanceData[103] = spacing; canvasInstanceData[104] = visible; canvasInstanceData[105] = draggable; canvasInstanceData[106] = pointerEvents; canvasInstanceData[107] = zIndex; taskObjectData[taskId].push(canvasInstanceData); canvasInstance.style.zIndex = zIndex; if (pointerEvents == false) { canvasInstance.style.pointerEvents = 'none'; canvasInstance.style.cursor = 'auto'; } else { canvasInstance.style.pointerEvents = 'auto'; } if (draggable == true) { makeDraggable(canvasInstance, canvasInstanceData) } var obj = { id: id, canvas: canvasInstance, ctx: canvasInstancectx, data: canvasInstanceData, spacing: spacing, font: font, textColor: textColor, textAlign: textAlign, text: text, lineCount: 1 }; textCanvas[taskId][id] = obj; drawTextCanvas(taskId, id); } function drawTextCanvas(taskNum2, textCanvasId) { var width = Number(textCanvas[taskNum2][textCanvasId].data[102]); textCanvas[taskNum2][textCanvasId].canvas.width = width; textCanvas[taskNum2][textCanvasId].canvas.style.width = canvasDisplayWidth * width / mainCanvasWidth + 'px'; var ctx = textCanvas[taskNum2][textCanvasId].ctx; var x = 0; if (textCanvas[taskNum2][textCanvasId].textAlign == 'center') { x = 0.5 * textCanvas[taskNum2][textCanvasId].canvas.width }; if (textCanvas[taskNum2][textCanvasId].textAlign == 'right') { x = textCanvas[taskNum2][textCanvasId].canvas.width }; var lineCount; wrapText2(); function wrapText2() { ctx.textBaseline = 'middle'; ctx.textAlign = textCanvas[taskNum2][textCanvasId].textAlign; ctx.font = textCanvas[taskNum2][textCanvasId].font; ctx.fillStyle = textCanvas[taskNum2][textCanvasId].textColor; var y = 0.5 * textCanvas[taskNum2][textCanvasId].spacing; lineCount = 1; var words = textCanvas[taskNum2][textCanvasId].text.split(' '); var line = ''; for (var n = 0; n < words.length; n++) { var testLine = line + words[n] + ' '; var metrics = ctx.measureText(testLine); var testWidth = metrics.width; if (testWidth > width && n > 0) { ctx.fillText(line, x, y); line = words[n] + ' '; y += textCanvas[taskNum2][textCanvasId].spacing; lineCount++; } else { line = testLine; } } ctx.fillText(line, x, y); } textCanvas[taskNum2][textCanvasId].lineCount = lineCount; var height = textCanvas[taskNum2][textCanvasId].spacing * lineCount; textCanvas[taskNum2][textCanvasId].height = height; textCanvas[taskNum2][textCanvasId].canvas.height = height; textCanvas[taskNum2][textCanvasId].canvas.style.height = canvasDisplayHeight * height / mainCanvasWidth + 'px'; textCanvas[taskNum2][textCanvasId].data[3] = height; textCanvas[taskNum2][textCanvasId].data[103] = height; wrapText2(); resize(); } function createImageCanvas(id, taskTag, taskId, filename, left, top, visible, draggable, pointerEvents, zIndex, scaleFactor, opacity, verticesArray, onload) { var imageInstanceURL = '../images/' + filename; var imageInstance = new Image; imageInstance.src = imageInstanceURL; if (!verticesArray) { var verticesArray = [] }; var imageCanvasInstance = document.createElement('canvas'); eval(taskTag + 'imageCanvas[' + id + ']=imageCanvasInstance'); taskObject[taskId].push(imageCanvasInstance); imageCanvasInstance.setAttribute('id', taskTag + 'imageCanvas' + id); imageCanvasInstance.setAttribute('position', 'absolute'); imageCanvasInstance.setAttribute('class', 'buttonClass'); if (!scaleFactor) { scaleFactor = 1 }; if (!opacity) { var opacity = 1 }; if (!zIndex) (zIndex = 2); imageCanvasInstance.style.zIndex = zIndex; if (pointerEvents == false) { imageCanvasInstance.style.pointerEvents = 'none'; } else { imageCanvasInstance.style.pointerEvents = 'auto'; } var imageCanvasInstancectx = imageCanvasInstance.getContext('2d'); eval(taskTag + 'imageCanvasctx[' + id + ']=imageCanvasInstancectx'); var leftPos = left; if (left == 'center') leftPos = 550 var imageCanvasInstanceData = [leftPos, top, 100, 100, visible, draggable, pointerEvents, zIndex]; if (visible == true && taskId == taskNum) { imageCanvasInstanceData[130] = true; container.appendChild(imageCanvasInstance); } else { imageCanvasInstanceData[130] = false; if (imageCanvasInstance.parentNode == container) { container.removeChild(imageCanvasInstance) } } imageCanvasInstanceData[100] = leftPos; imageCanvasInstanceData[101] = top; imageCanvasInstanceData[102] = 100; imageCanvasInstanceData[103] = 100; imageCanvasInstanceData[104] = visible; imageCanvasInstanceData[105] = draggable; imageCanvasInstanceData[106] = pointerEvents; imageCanvasInstanceData[107] = zIndex; imageCanvasInstanceData[40] = opacity; imageCanvasInstance.data = imageCanvasInstanceData; if (verticesArray && verticesArray.length > 2) { imageCanvasInstanceData[41] = verticesArray; pointerEventsFix(imageCanvasInstance, imageCanvasInstanceData, 'drag'); pointerEventsFixTouch(imageCanvasInstance, imageCanvasInstanceData, 'drag'); } else if (draggable == true) { makeDraggable(imageCanvasInstance, imageCanvasInstanceData); } eval(taskTag + 'imageCanvasData[' + id + ']=imageCanvasInstanceData'); taskObjectData[taskId].push(imageCanvasInstanceData); eval(taskTag + 'imageLoadArray[' + id + '] = false'); eval(taskTag + 'imagesLoaded = false'); imageInstance.onload = function () { createImageCanvas2(imageInstance, imageCanvasInstance, imageCanvasInstancectx, imageCanvasInstanceData, id, taskTag, taskId, left, scaleFactor, onload) } return imageCanvasInstance; } function createImageCanvas2(imageInstance, imageCanvasInstance, imageCanvasInstancectx, imageCanvasInstanceData, id, taskTag, taskId, left, scaleFactor, onload) { var width = imageInstance.naturalWidth * scaleFactor; var height = imageInstance.naturalHeight * scaleFactor; imageCanvasInstance.width = width; imageCanvasInstance.height = height; imageCanvasInstancectx.drawImage(imageInstance, 0, 0, width, height); if (left == 'center') { imageCanvasInstanceData[0] = 600 - 0.5 * width; imageCanvasInstanceData[100] = 600 - 0.5 * width; } imageCanvasInstanceData[2] = width; imageCanvasInstanceData[3] = height; imageCanvasInstanceData[102] = width; imageCanvasInstanceData[103] = height; eval(taskTag + 'imageLoadArray[' + id + '] = true'); var allImagesLoaded = true; for (var iii = 0; iii < eval(taskTag + 'imageLoadArray.length'); iii++) { if (eval(taskTag + 'imageLoadArray[' + iii + '] == false')) allImagesLoaded = false; } if (allImagesLoaded == true) { eval(taskTag + 'imagesLoaded = true'); } if (typeof onload === 'function') onload(imageCanvasInstance); resize(); } function drawHolderButton(i) { if (typeof holderButton == 'undefined' || typeof holderButton[i] == 'undefined') return; holderButtonctx[i].lineCap = "round"; holderButtonctx[i].lineJoin = "round"; holderButtonctx[i].clearRect(0, 0, holderButtonData[i][2], holderButtonData[i][3]); if (i === 0 || i === 2) { holderButtonctx[i].fillStyle = "#6F9"; } else if (i === 1) { holderButtonctx[i].fillStyle = "#C9F"; } else if (i === 3) { holderButtonctx[i].fillStyle = "#6CF"; } else if (i === 4) { holderButtonctx[i].fillStyle = "#99F"; holderButton[i].style.cursor = "auto"; } holderButtonctx[i].strokeStyle = "#000"; if (taskOrTool == 'tool') { holderButtonctx[i].lineWidth = 4; holderButtonctx[i].beginPath(); holderButtonctx[i].moveTo(2, 2); holderButtonctx[i].lineTo(holderButtonData[i][2] - 2, 2); holderButtonctx[i].lineTo(holderButtonData[i][2] - 2, holderButtonData[i][3] - 2); holderButtonctx[i].lineTo(3, holderButtonData[i][3] - 2); holderButtonctx[i].lineTo(2, 2); holderButtonctx[i].closePath(); holderButtonctx[i].fill(); holderButtonctx[i].stroke(); switch (i) { case 0: drawPath({ ctx: holderButtonctx[i], path: [[33, 15], [33, 35], [17, 25]], lineColor: '#000', fillColor: '#000', lineWidth: 2 }); break; case 1: holderButtonctx[i].beginPath(); holderButtonctx[i].lineWidth = 5; holderButtonctx[i].arc(25, 25, 10, 0.2 * Math.PI, 1.8 * Math.PI) holderButtonctx[i].lineWidth = 4; holderButtonctx[i].moveTo(35, 20); holderButtonctx[i].lineTo(33, 10); holderButtonctx[i].moveTo(35, 19); holderButtonctx[i].lineTo(28, 24); holderButtonctx[i].stroke(); break; case 2: drawPath({ ctx: holderButtonctx[i], path: [[17, 15], [17, 35], [33, 25]], lineColor: '#000', fillColor: '#000', lineWidth: 2 }); break; case 3: break; case 4: holderButtonctx[i].font = "30px Hobo"; holderButtonctx[i].textAlign = "center"; holderButtonctx[i].textBaseline = "middle"; holderButtonctx[i].fillStyle = "#000"; holderButtonctx[i].fillText(holderButtonData[i][4], holderButtonData[i][2] / 2, holderButtonData[i][3] / 2); break; } } else { holderButtonctx[i].lineWidth = 6; holderButtonctx[i].beginPath(); holderButtonctx[i].moveTo(3, 3); holderButtonctx[i].lineTo(holderButtonData[i][2] - 3, 3); holderButtonctx[i].lineTo(holderButtonData[i][2] - 3, holderButtonData[i][3] - 3); holderButtonctx[i].lineTo(3, holderButtonData[i][3] - 3); holderButtonctx[i].lineTo(3, 3); holderButtonctx[i].closePath(); holderButtonctx[i].fill(); holderButtonctx[i].stroke(); holderButtonctx[i].font = "30px Hobo"; holderButtonctx[i].textAlign = "center"; holderButtonctx[i].textBaseline = "middle"; holderButtonctx[i].fillStyle = "#000"; holderButtonctx[i].fillText(holderButtonData[i][4], holderButtonData[i][2] / 2, holderButtonData[i][3] / 2); } } function userInfoTextUpdate() { if (typeof userInfoText == 'undefined') return; if (taskOrTool == 'Task') { userInfoTextctx.clearRect(0, 0, 343, 62); userInfoTextctx.strokeStyle = "#000"; userInfoTextctx.lineWidth = 4; userInfoTextctx.beginPath(); userInfoTextctx.moveTo(0, 60); userInfoTextctx.lineTo(343, 60); userInfoTextctx.stroke(); userInfoTextctx.font = "24px Verdana, Geneva, sans-serif"; userInfoTextctx.textAlign = "left"; userInfoTextctx.textBaseline = "middle"; userInfoTextctx.fillStyle = "#000"; if (userName) { var welcomeText = "Welcome " + userName; userInfoTextctx.fillText(welcomeText, 2, 15); } var completionText = getArrayCount(taskState, 1) + ' out of ' + (task.length) + ' pages completed'; userInfoTextctx.fillText(completionText, 2, 42); } } function clickHolderButton(event) { event.preventDefault(); var buttonClicked = holderButton.indexOf(event.currentTarget); dismissTaskCompleteMessage(); dismissSmallTaskCompleteMessage(); switch (buttonClicked) { case 0: changeTask(-1); break; case 1: for (i = 0; i < taskObject[taskNum].length; i++) { for (j = 0; j < 8; j++) { taskObjectData[taskNum][i][j + 100] = taskObjectData[taskNum][i][j]; } if (taskObjectData[taskNum][i][4] == true) { showObj(taskObject[taskNum][i], taskObjectData[taskNum][i]); } else { hideObj(taskObject[taskNum][i], taskObjectData[taskNum][i]); } if (taskObjectData[taskNum][i][5] == true) { makeDraggable(taskObject[taskNum][i], taskObjectData[taskNum][i]); } else { makeNotDraggable(taskObject[taskNum][i], taskObjectData[taskNum][i]); } if (taskObjectData[taskNum][i][6] == true) { taskObject[taskNum][i].style.pointerEvents = 'auto'; } else { taskObject[taskNum][i].style.pointerEvents = 'none'; } if (taskObjectData[taskNum][i][7]) { taskObject[taskNum][i].style.zIndex = taskObjectData[taskNum][i][7]; } } if (keyboard[taskNum]) { hideKeyboard2(); keyboardData[taskNum][100] = keyboardData[taskNum][0]; keyboardData[taskNum][101] = keyboardData[taskNum][1]; for (var i = 0; i < key1Data[taskNum].length; i++) { key1Data[taskNum][i][100] = key1Data[taskNum][i][0]; key1Data[taskNum][i][101] = key1Data[taskNum][i][1]; } } for (var i = 0; i < mathsInput[taskNum].length; i++) { setMathsInputText(mathsInput[taskNum][i], mathsInput[taskNum][i].startText.slice(0)); } if (eval(taskTag + 'mathsInput')) { for (var i = 0; i < eval(taskTag + 'mathsInput.length'); i++) { eval(taskTag + 'mathsInput[i].active = true;'); } } resetDrawTools(); clearCanvas(); if (typeof backgroundLoadHandler[taskNum] === 'function') backgroundLoadHandler[taskNum](); loadHandler[taskNum](); if (taskReset[taskNum]) { taskReset[taskNum]() }; unfadePage(); clearInterval(videoPlaying); replayVideoTime = 0; if (typeof player[taskId] !== 'undefined' && firstPlay[taskId] == false) { player[taskId].seekTo(0, true); player[taskId].pauseVideo() } firstPlay[taskNum] = true; resize(); break; case 2: changeTask(1); break; case 3: window.location.href = '../../myProfile.php'; break; } } function changeTask(diff) { if (window.pageLoading == true) return; if (taskNum+diff < 0 || taskNum+diff > task.length-1) return; if (keyboard[taskNum] && keyboard[taskNum].parentNode == container) { container.removeChild(keyboard[taskNum]); for (var i = 0; i < key1[taskNum].length; i++) { container.removeChild(key1[taskNum][i]); if (i < key1[taskNum].length - 1) { key1[taskNum][i].style.opacity = 0.7; key1[taskNum][i].style.pointerEvents = 'none'; } } } if (typeof player[taskNum] !== 'undefined' && firstPlay[taskNum] == false) { player[taskNum].pauseVideo(); } window.diff = diff; taskNum = taskNum+diff; taskId = taskNum; clearInterval(videoPlaying); currMathsInputId = 0; penColour = -1; taskId = taskNum; if (pageLoaded[taskId] == false) { window.pageLoading = true; loadScript(task[taskId] + '.js', pageScriptLoaded, pageScriptLoadError); } else { pageScriptLoaded2(); } function pageScriptLoadError() { window.pageLoading = false; changeTask(-window.diff); Notifier.error('Error connecting to the server. The page cannot be loaded.'); } function pageScriptLoaded() { window.pageLoading = false; pageLoaded[taskId] = true; if (typeof backgroundLoadHandler[taskNum] === 'function') backgroundLoadHandler[taskNum](); loadHandler[taskNum](); pageScriptLoaded2(); } function pageScriptLoaded2() { taskTag = taskTagArray[taskNum]; for (j = 0; j < taskObject.length; j++) { for (i = 0; i < taskObject[j].length; i++) { if (taskNum == j) { if (taskObjectData[j][i][130] == true) { container.appendChild(taskObject[j][i]) } } else { if (taskObject[j][i].parentNode == container) { container.removeChild(taskObject[j][i]) } } } if (taskVideo[j]) { if (j == taskNum) { iframe[j].style.zIndex = 500; iframe[j].style.opacity = 1; } else { iframe[j].style.zIndex = 0; iframe[j].style.opacity = 0 } } } for (i = 0; i < taskObject[taskNum].length; i++) { if (taskObjectData[taskNum][i][104] && taskObjectData[taskNum][i][104] == true) { showObj(taskObject[taskNum][i], taskObjectData[taskNum][i]); } else { hideObj(taskObject[taskNum][i], taskObjectData[taskNum][i]); } } unfadePage(); if (taskState[taskNum] == 1) { fadePage(); container.appendChild(holderButton[5]); container.appendChild(holderButton[6]); } if (keyboard[taskNum]) { if (keyboardVis[taskNum] == true) { container.appendChild(hideKeys[taskNum]); if (showKeys[taskNum].parentNode == container) { container.removeChild(showKeys[taskNum]) }; container.appendChild(keyboard[taskNum]); for (var i = 0; i < key1[taskNum].length; i++) { container.appendChild(key1[taskNum][i]); if (i < key1[taskNum].length - 1) { key1[taskNum][i].style.opacity = 0.7; key1[taskNum][i].style.pointerEvents = 'none'; } } } else { container.appendChild(showKeys[taskNum]); if (hideKeys[taskNum].parentNode == container) { container.removeChild(hideKeys[taskNum]) }; for (var i = 0; i < key1[taskNum].length; i++) { if (i < key1[taskNum].length - 1) { key1[taskNum][i].style.opacity = 0.7; key1[taskNum][i].style.pointerEvents = 'none'; } } } } clearCanvas(); if (typeof backgroundLoadHandler[taskNum] === 'function') backgroundLoadHandler[taskNum](); resize(); } holderButtonData[4][4] = taskNum + 1; drawHolderButton(4); if (taskNum == 0) { holderButton[0].style.opacity = "0.5"; holderButton[0].style.filter = 'alpha(opacity = 50)'; holderButton[0].style.cursor = "auto"; holderButton[0].style.pointerEvents = "none"; } else { holderButton[0].style.opacity = "1"; holderButton[0].style.filter = 'alpha(opacity = 100)'; holderButton[0].style.cursor = "pointer"; holderButton[0].style.pointerEvents = "auto"; } if (taskNum == task.length - 1) { holderButton[2].style.opacity = "0.5"; holderButton[2].style.filter = 'alpha(opacity = 50)'; holderButton[2].style.cursor = "auto"; holderButton[2].style.pointerEvents = "none"; } else { holderButton[2].style.opacity = "1"; holderButton[2].style.filter = 'alpha(opacity = 100)'; holderButton[2].style.cursor = "pointer"; holderButton[2].style.pointerEvents = "auto"; } } function fadePage() { unfadePage(); canvas.style.opacity = 0.6; for (i = 0; i < taskObject[taskNum].length; i++) { taskObject[taskNum][i].style.opacity = 0.5; } if (keyboard[taskNum]) keyboard[taskNum].style.opacity = 0.5; if (key1[taskNum]) { for (var i = 0; i < key1[taskNum].length; i++) { key1[taskNum][i].style.opacity = 0.5; } } } function unfadePage() { canvas.style.opacity = 1; if (typeof userInfoText !== 'undefined') userInfoText.style.opacity = 1; if (typeof inactiveBox !== 'undefined' && inactiveBox.parentNode == container) { container.removeChild(inactiveBox) }; if (typeof holderButton !== 'undefined') { if (!un(holderButton[5]) && holderButton[5].parentNode == container) { container.removeChild(holderButton[5]) }; if (!un(holderButton[6]) && holderButton[6].parentNode == container) { container.removeChild(holderButton[6]) }; for (var i = 0; i < holderButton.length; i++) { holderButton[i].style.opacity = 1; } if (taskNum == 0 && !un(holderButton[0])) { holderButton[0].style.opacity = "0.5"; holderButton[0].style.filter = 'alpha(opacity = 50)'; holderButton[0].style.cursor = "auto"; holderButton[0].style.pointerEvents = "none"; } if (taskNum == task.length - 1 && !un(holderButton[2])) { holderButton[2].style.opacity = "0.5"; holderButton[2].style.filter = 'alpha(opacity = 50)'; holderButton[2].style.cursor = "auto"; holderButton[2].style.pointerEvents = "none"; } } var startAt = 0; if (!un(taskObject[taskNum])) { for (var i = startAt; i < taskObject[taskNum].length; i++) { if (typeof taskObjectData[taskNum][i][40] == 'number') { taskObject[taskNum][i].style.opacity = taskObjectData[taskNum][i][40]; } else { taskObject[taskNum][i].style.opacity = 1; } } } if (keyboard[taskNum]) keyboard[taskNum].style.opacity = 1; if (key1[taskNum]) { for (var i = 0; i < key1[taskNum].length; i++) { key1[taskNum][i].style.opacity = 0.75; } key1[taskNum][key1[taskNum].length - 1].style.opacity = 1 } } function makeDraggable(object, objectData, left, top, horizSpacing, vertSpacing, vertLines, horizLines, toFront) { addListenerStart(object,dragStart); if (dragObject.indexOf(object) == -1) { object.style.cursor = openhand; dragObject.push(object); objectData[100] = objectData[0]; objectData[101] = objectData[1]; for (i = 0; i < taskObject.length; i++) { if (taskObject[i].indexOf(object) > -1) { objectData[109] = i; } } if (typeof left !== 'undefined') { objectData[110] = left; objectData[111] = top; objectData[112] = horizSpacing; objectData[113] = vertSpacing; objectData[114] = vertLines; objectData[115] = horizLines; objectData[116] = true; } else { objectData[116] = false; } if (toFront) { objectData[117] = toFront; } else { objectData[117] = true; } dragObjectData.push(objectData); } } function makeNotDraggable(object, objectData, taskId) { removeListenerStart(object,dragStart); object.style.cursor = 'default'; } function dragStart(e) { try { if (typeof eval(taskTag + 'dragStart') == 'function') { eval(taskTag + 'dragStart(e);'); } } catch (err) {} e.preventDefault(); currentDragId = dragObject.indexOf(e.target); if (dragObjectData[currentDragId][117] == true) { dragObject[currentDragId].style.zIndex = zIndexFront; zIndexFront++; } if (e.touches) { var x = e.touches[0].pageX; var y = e.touches[0].pageY; } else { var x = e.clientX || e.pageX; var y = e.clientY || e.pageY; } var dragObjectBoundingRect = dragObject[currentDragId].getBoundingClientRect(); dragOffset.x = x - dragObjectBoundingRect.left; dragOffset.y = y - dragObjectBoundingRect.top; if (dragObjectData[currentDragId][116] == true) { dragArea.xMin = canvasDisplayRect.left + ((dragObjectData[currentDragId][110] - event.currentTarget.width / 2) / mainCanvasWidth) * canvasDisplayWidth; dragArea.xMax = canvasDisplayRect.left + ((dragObjectData[currentDragId][110] + dragObjectData[currentDragId][112] * dragObjectData[currentDragId][114] - event.currentTarget.width / 2) / mainCanvasWidth) * canvasDisplayWidth; dragArea.yMin = canvasDisplayRect.top + ((dragObjectData[currentDragId][111] - event.currentTarget.height / 2) / mainCanvasHeight) * canvasDisplayHeight; dragArea.yMax = canvasDisplayRect.top + ((dragObjectData[currentDragId][111] + dragObjectData[currentDragId][113] * dragObjectData[currentDragId][115] - event.currentTarget.height / 2) / mainCanvasHeight) * canvasDisplayHeight; } else { dragArea.xMin = canvasDisplayRect.left + (15 / mainCanvasWidth) * canvasDisplayWidth; dragArea.xMax = canvasDisplayRect.right - (15 / mainCanvasWidth) * canvasDisplayWidth - (dragObjectBoundingRect.right - dragObjectBoundingRect.left); dragArea.yMin = canvasDisplayRect.top + (100 / mainCanvasHeight) * canvasDisplayHeight; dragArea.yMax = canvasDisplayRect.bottom - (15 / mainCanvasHeight) * canvasDisplayHeight - (dragObjectBoundingRect.bottom - dragObjectBoundingRect.top); } addListenerMove(window,dragMove); addListenerEnd(window,dragStop); e.target.style.cursor = closedhand; try { if (typeof eval(taskTag + 'dragStart2') == 'function') { eval(taskTag + 'dragStart2(e);'); } } catch (err) {} } function dragMove(e) { try { if (typeof eval(taskTag + 'dragMove') == 'function') { eval(taskTag + 'dragMove(e);'); } } catch (err) {} e.preventDefault(); if (e.touches) { var x = e.touches[0].pageX; var y = e.touches[0].pageY; } else { var x = e.clientX || e.pageX; var y = e.clientY || e.pageY; } var l = x - dragOffset.x; l = Math.max(l, dragArea.xMin); l = Math.min(l, dragArea.xMax); var t = y - dragOffset.y; t = Math.max(t, dragArea.yMin); t = Math.min(t, dragArea.yMax); dragObject[currentDragId].style.left = l + 'px'; dragObjectData[currentDragId][100] = xWindowToCanvas(l); dragObject[currentDragId].style.top = (t - (window.innerHeight - canvasDisplayHeight) / 2) + 'px'; dragObjectData[currentDragId][101] = yWindowToCanvas(t); try { if (typeof eval(taskTag + 'dragMove2') == 'function') { eval(taskTag + 'dragMove2(e);'); } } catch (err) {} } function dragStop(e) { e.preventDefault(); updateMouse(e); removeListenerMove(window,dragMove); removeListenerEnd(window,dragStop); e.target.style.cursor = openhand; var objX; var objY; if (dragObjectData[currentDragId][116] == true) { if (mouse.x < xWindowToCanvas(dragArea.xMin)) { objX = xWindowToCanvas(dragArea.xMin); } else { if (mouse.x > xWindowToCanvas(dragArea.xMax)) { objX = xWindowToCanvas(dragArea.xMax); } else { objX = mouse.x; } } objX = (objX - dragObjectData[currentDragId][110]) / dragObjectData[currentDragId][112]; objX = Math.round(objX); objX = objX * dragObjectData[currentDragId][112] + dragObjectData[currentDragId][110] - (dragObject[currentDragId].width / 2); objX = xCanvasToWindow(objX); dragObject[currentDragId].style.left = objX + 'px'; dragObjectData[currentDragId][100] = xWindowToCanvas(objX); if (mouse.y < yWindowToCanvas(dragArea.yMin)) { objY = yWindowToCanvas(dragArea.yMin); } else { if (mouse.y > yWindowToCanvas(dragArea.yMax)) { objY = yWindowToCanvas(dragArea.yMax); } else { objY = mouse.y; } } objY = (objY - dragObjectData[currentDragId][111]) / dragObjectData[currentDragId][113]; objY = Math.round(objY); objY = objY * dragObjectData[currentDragId][113] + dragObjectData[currentDragId][111] - (dragObject[currentDragId].height / 2); objY = yCanvasToWindow(objY); dragObject[currentDragId].style.top = (objY - canvasMetrics.top) + 'px'; dragObjectData[currentDragId][101] = yWindowToCanvas(objY); } try { if (typeof eval(taskTag + 'dragStop') == 'function') { eval(taskTag + 'dragStop(e);'); } } catch (err) {} } function createHolderCanvas(left, top, width, height, visible) { var canvasInstance = document.createElement('canvas'); canvasInstance.width = width; canvasInstance.height = height; canvasInstance.setAttribute('position', 'absolute'); canvasInstance.setAttribute('z-index', '99999'); canvasInstance.setAttribute('cursor', 'auto'); canvasInstance.setAttribute('class', 'buttonClass'); if (visible == true) { container.appendChild(canvasInstance); } else { if (canvasInstance.parentNode == container) { container.removeChild(canvasInstance) } } holderButton.push(canvasInstance); var canvasInstancectx = canvasInstance.getContext('2d'); holderButtonctx.push(canvasInstancectx); var canvasInstanceData = [left, top, width, height, visible, ""]; holderButtonData.push(canvasInstanceData); } function drawSmallTaskCompleteMessage() { createHolderCanvas(350, 200, 500, 110, false); holderButton[5].style.backgroundColor = "#6CC"; holderButton[5].style.borderRadius = "5px"; holderButton[5].style.border = "4px solid black" holderButton[5].style.cursor = "auto"; holderButton[5].style.zIndex = 900000; holderButtonctx[5].font = "50px Hobo"; holderButtonctx[5].fillStyle = "#000"; holderButtonctx[5].textAlign = "center"; holderButtonctx[5].textBaseline = "middle"; holderButtonctx[5].fillText("Page Completed!", 290, 57); yellowStar.onload = function () { holderButtonctx[5].drawImage(yellowStar, 7, 7, 104, 98) }; holderButtonctx[5].drawImage(yellowStar, 7, 7, 104, 98); createHolderCanvas(758, 205, 110, 26, false); holderButton[6].style.zIndex = 900000; holderButtonctx[6].font = "20px Arial"; holderButtonctx[6].fillStyle = "#000"; holderButtonctx[6].textAlign = "center"; holderButtonctx[6].textBaseline = "middle"; holderButtonctx[6].fillText("Dismiss", 55, 13); addListener(holderButton[6], dismissSmallTaskCompleteMessage) addListener(holderButton[5], dismissSmallTaskCompleteMessage) } function dismissSmallTaskCompleteMessage() { if (!un(holderButton[5]) && holderButton[5].parentNode == container) { container.removeChild(holderButton[5]) } if (!un(holderButton[6]) && holderButton[6].parentNode == container) { container.removeChild(holderButton[6]) } unfadePage(); } function showObj(canvas, canvasData, hideAfter) { if (canvas) { if (canvas.canvas) { canvasData = canvas.data; canvas = canvas.canvas; } if (typeof canvasData == 'undefined' && typeof canvas.data == 'object') { canvasData = canvas.data; } var canvasTask; for (var ii = 0; ii < taskObject.length; ii++) { if (taskObject[ii].indexOf(canvas) > -1) { canvasTask = ii }; } if (typeof mathsInput[taskId] !== 'undefined') { for (var i = 0; i < mathsInput[taskId].length; i++) { if (mathsInput[taskId][i].canvas == canvas) { if (taskId == canvasTask) container.appendChild(mathsInput[taskId][i].canvas); mathsInput[taskId][i].data[130] = true; mathsInput[taskId][i].data[104] = true; if (typeof mathsInput[taskId][i].cursorCanvas !== 'undefined') { if (taskId == canvasTask) container.appendChild(mathsInput[taskId][i].cursorCanvas); mathsInput[taskId][i].cursorData[130] = true; mathsInput[taskId][i].cursorData[104] = true; } if (typeof mathsInput[taskId][i].leftRightTextCanvas !== 'undefined') { if (taskId == canvasTask) container.appendChild(mathsInput[taskId][i].leftRightTextCanvas); mathsInput[taskId][i].leftRightTextCanvas.data[130] = true; mathsInput[taskId][i].leftRightTextCanvas.data[104] = true; } return; } } } if (taskNum == canvasTask) { container.appendChild(canvas) }; canvasData[130] = true; canvasData[104] = true; if (hideAfter) { setTimeout(function () { hideObj(canvas, canvasData) }, hideAfter); } } } function hideObj(canvas, canvasData, showAfter) { if (canvas) { if (canvas.canvas) { canvasData = canvas.data; canvas = canvas.canvas; } if (typeof canvasData == 'undefined' && typeof canvas.data == 'object') { canvasData = canvas.data; } if (typeof mathsInput[taskId] !== 'undefined') { for (var i = 0; i < mathsInput[taskId].length; i++) { if (mathsInput[taskId][i].canvas == canvas) { if (mathsInput[taskId][i].canvas.parentNode == container) container.removeChild(mathsInput[taskId][i].canvas); mathsInput[taskId][i].data[130] = false; mathsInput[taskId][i].data[104] = false; if (typeof mathsInput[taskId][i].cursorCanvas !== 'undefined') { if (mathsInput[taskId][i].cursorCanvas.parentNode == container) container.removeChild(mathsInput[taskId][i].cursorCanvas); mathsInput[taskId][i].cursorData[130] = false; mathsInput[taskId][i].cursorData[104] = false; } if (typeof mathsInput[taskId][i].leftRightTextCanvas !== 'undefined') { if (mathsInput[taskId][i].leftRightTextCanvas.parentNode == container) container.removeChild(mathsInput[taskId][i].leftRightTextCanvas); mathsInput[taskId][i].leftRightTextCanvas.data[130] = false; mathsInput[taskId][i].leftRightTextCanvas.data[104] = false; } if (typeof mathsInput[taskId][i].tick !== 'undefined') { if (mathsInput[taskId][i].tick.parentNode == container) container.removeChild(mathsInput[taskId][i].tick); mathsInput[taskId][i].tick.data[130] = false; mathsInput[taskId][i].tick.data[104] = false; } if (typeof mathsInput[taskId][i].cross !== 'undefined') { if (mathsInput[taskId][i].cross.parentNode == container) container.removeChild(mathsInput[taskId][i].cross); mathsInput[taskId][i].cross.data[130] = false; mathsInput[taskId][i].cross.data[104] = false; } return; } } } if (canvas.parentNode == container) { container.removeChild(canvas) }; canvasData[130] = false; canvasData[104] = false; if (showAfter) { setTimeout(function () { showObj(canvas, canvasData) }, showAfter); } } } function pointerEventsFix(canvas2, data2, opt_type) { if (data2[5] == true && dragObject.indexOf(canvas2) == -1) { dragObject.push(canvas2); data2[100] = data2[0]; data2[101] = data2[1]; for (i = 0; i < taskObject.length; i++) { if (taskObject[i].indexOf(canvas2) > -1) { data2[109] = i; } } data2[116] = false; data2[117] = true; dragObjectData.push(data2); } window.addEventListener('mousemove', function () { pointerEventsListen(canvas2, opt_type) }, false); } function pointerEventsListen(canvas2, opt_type) { if (hitTestMouseOver(canvas2) == true) { canvas2.style.pointerEvents = 'auto'; canvas2.addEventListener('mousemove', updateMouse, false); canvas2.addEventListener('touchmove', updateMouse, false); } else { canvas2.style.pointerEvents = 'none'; canvas2.removeEventListener('mousemove', updateMouse, false); canvas2.removeEventListener('touchmove', updateMouse, false); } if (opt_type && opt_type == 'drag') { if (hitTestMouseOver(canvas2) == true) { canvas2.addEventListener('mousedown', dragStart, false); canvas2.addEventListener('touchstart', dragStart, false); } else { canvas2.removeEventListener('mousedown', dragStart, false); canvas2.removeEventListener('touchstart', dragStart, false); } } } var touchListenerAdded = false; function pointerEventsFixTouch(canvas2, data2, opt_type) { if (data2[5] == true && dragObject.indexOf(canvas2) == -1) { dragObject.push(canvas2); data2[100] = data2[0]; data2[101] = data2[1]; for (i = 0; i < taskObject.length; i++) { if (taskObject[i].indexOf(canvas2) > -1) { data2[109] = i; } } data2[116] = false; data2[117] = true; dragObjectData.push(data2); } if (touchListenerAdded == false) { if (typeof opt_type !== 'undefined' && opt_type == 'drag') { window.addEventListener('touchstart', pointerEventsListenTouch, false); } else { window.addEventListener('touchend', pointerEventsListenTouch, false); } } touchListenerAdded = true; } function pointerEventsListenTouch(e) { e.preventDefault(); var x = e.touches[0].pageX; var y = e.touches[0].pageY; mouse.x = xWindowToCanvas(x); mouse.y = yWindowToCanvas(y); var obj1 = []; var maxZ = 0; for (var i = 0; i < taskObject[taskNum].length; i++) { if (taskObjectData[taskNum][i][4] == true && taskObjectData[taskNum][i][6] == true && hitTestMouseOver(taskObject[taskNum][i]) == true) { maxZ = Math.max(maxZ, taskObjectData[taskNum][i][7]); obj1.push(i); } } if (obj1.length == 0) return; for (i = obj1.length - 1; i >= 0; i--) { if (taskObjectData[taskNum][i][7] < maxZ) { obj1 = obj1.splice(0, -1); } } if (obj1.length == 0) return; obj1 = obj1.pop(); if (dragObject.indexOf(taskObject[taskNum][obj1]) > -1) forceDragStart(taskObject[taskNum][obj1]); if (typeof taskObjectData[taskNum][obj1][43] !== 'undefined') { //console.log('Event call,', taskObjectData[taskNum][obj1][43], taskObject[taskNum][obj1]); eval(taskObjectData[taskNum][obj1][43] + "(taskObject[taskNum][obj1]);"); } } function getCanvasesAtMousePos() { var canvasArray = []; var dataArray = []; var pointerArray = []; for (var i = 0; i < taskObject[taskNum].length; i++) { if (taskObject[taskNum][i].parentNode == container) { if (hitTestMouseOver(taskObject[taskNum][i]) == true) { canvasArray.push(taskObject[taskNum][i]); dataArray.push(taskObjectData[taskNum][i]); } } } return { canvasArray: canvasArray, dataArray: dataArray }; } function forceDragStart(canvas) { if (dragObject.indexOf(canvas) == -1) { return }; currentDragId = dragObject.indexOf(canvas); dragObject[currentDragId].style.zIndex = zIndexFront; zIndexFront++; var dragObjectBoundingRect = dragObject[currentDragId].getBoundingClientRect(); dragOffset.x = xCanvasToWindow(mouse.x) - dragObjectBoundingRect.left; dragOffset.y = yCanvasToWindow(mouse.y) - dragObjectBoundingRect.top; if (dragObjectData[currentDragId][116] == true) { dragArea.xMin = canvasDisplayRect.left + ((dragObjectData[currentDragId][110] - dragObject[currentDragId].width / 2) / mainCanvasWidth) * canvasDisplayWidth; dragArea.xMax = canvasDisplayRect.left + ((dragObjectData[currentDragId][110] + dragObjectData[currentDragId][112] * dragObjectData[currentDragId][114] - dragObject[currentDragId].width / 2) / mainCanvasWidth) * canvasDisplayWidth; dragArea.yMin = ((dragObjectData[currentDragId][111] - dragObject[currentDragId].height / 2) / mainCanvasHeight) * canvasDisplayHeight; dragArea.yMax = ((dragObjectData[currentDragId][111] + dragObjectData[currentDragId][113] * dragObjectData[currentDragId][115] - dragObject[currentDragId].height / 2) / mainCanvasHeight) * canvasDisplayHeight; } else { dragArea.xMin = canvasDisplayRect.left + (15 / mainCanvasWidth) * canvasDisplayWidth; dragArea.xMax = canvasDisplayRect.right - (15 / mainCanvasWidth) * canvasDisplayWidth - (dragObjectBoundingRect.right - dragObjectBoundingRect.left); dragArea.yMin = canvasDisplayRect.top + (100 / mainCanvasHeight) * canvasDisplayHeight; dragArea.yMax = canvasDisplayRect.bottom - (15 / mainCanvasHeight) * canvasDisplayHeight - (dragObjectBoundingRect.bottom - dragObjectBoundingRect.top); } window.addEventListener('mousemove', dragMove, false); window.addEventListener('touchmove', dragMove, false); window.addEventListener('mouseup', dragStop, false); window.addEventListener('touchend', dragStop, false); } function createGridOfButtons(startingButNum, numRows, numColumns, startingX, startingY, butWidth, butHeight, gapX, gapY, draggable) { for (var n242j = 0; n242j < numRows; n242j++) { for (var n242i = 0; n242i < numColumns; n242i++) { createButton(startingButNum + n242j * numColumns + n242i, startingX + (butWidth - 3) * n242i + gapX * n242i, gapY * n242j + startingY + (butHeight - 3) * n242j, butWidth, butHeight, true, draggable, true, 2); } } } function removeTags(string) { for (var i = string.length - 1; i >= 0; i--) { if (string.slice(i).indexOf('>>') == 0) { for (var j = i - 1; j >= 0; j--) { if (string.slice(j).indexOf('<<') == 0) { string = string.slice(0, j) + string.slice(i + 2); i = j; break; } } } } return string; } function canvasPaste(toctx, fromctx, x, y) { toctx.clearRect(0, 0, toctx.canvas.data[102], toctx.canvas.data[103]); toctx.drawImage(fromctx.canvas, -x, -y); } function saveCanvasAsPNG(canvas, filename, l, t, w, h) { if (typeof filename == 'undefined') filename = 'download.png'; if (filename.slice(-4).toLowerCase() !== '.png') filename += '.png'; var imgURL = canvasToPNG(canvas, filename, l, t, w, h); var dlLink = document.createElement('a'); dlLink.download = filename; dlLink.href = imgURL; dlLink.dataset.downloadurl = ["image/png", dlLink.download, dlLink.href].join(':'); document.body.appendChild(dlLink); dlLink.click(); document.body.removeChild(dlLink); } function printCanvasAsPNG(canvas, filename, l, t, w, h) { if (typeof filename == 'undefined') filename = 'print.png'; if (filename.slice(-4).toLowerCase() !== '.png') filename += '.png'; var imgURL = canvasToPNG(canvas, filename, l, t, w, h); var win = window.open(); win.document.write('<head></head><body><img src="' + imgURL + '" style="width:100%"></body>'); win.print(); } function canvasToPNG(canvas, filename, l, t, w, h) { var width = mainCanvasWidth; var height = mainCanvasHeight; if (isElement(canvas)) { width = canvas.width; height = canvas.height; } var canvas2 = document.createElement('canvas'); canvas2.width = width; canvas2.height = height; var ctx2 = canvas2.getContext('2d'); if (isElement(canvas)) { ctx2.drawImage(canvas, 0, 0); } else if (typeof canvas == 'object') { for (var i = 0; i < canvas.length; i++) { ctx2.drawImage(canvas[i], canvas[i].data[100], canvas[i].data[101]); } } var left = l || 0; var top = t || 0; var w2 = w || width; var h2 = h || height; var canvas3 = document.createElement('canvas'); canvas3.width = w2; canvas3.height = h2; var ctx3 = canvas3.getContext('2d'); ctx3.drawImage(canvas2, -left, -top); var imgURL = canvas3.toDataURL("image/png"); return imgURL; } function croppedCanvasToPNG(canvas, left, top, width, height, filename) { var can = document.createElement('canvas'); can.width = width; can.height = height; var ctx = can.getContext('2d'); ctx.drawImage(canvas, -left, -top); return canvasToPNG(can, filename); } function flattenCanvases(canvas1, canvas2, offsetLeft, offsetTop) { if (typeof offsetLeft !== 'number') { if (typeof canvas1.data == 'object' && typeof canvas2.data == 'object') { var offsetLeft = canvas2.data[100] - canvas1.data[100]; } else { var offsetLeft = 0; } } if (typeof offsetTop !== 'number') { if (typeof canvas1.data == 'object' && typeof canvas2.data == 'object') { var offsetTop = canvas2.data[101] - canvas1.data[101]; } else { var offsetTop = 0; } } var ctx = canvas1.getContext('2d'); ctx.drawImage(canvas2, offsetLeft, offsetTop); }
35.782961
498
0.687727
0d9dc2471d126f5568ed909668b1ec5f2487c453
2,212
cs
C#
Assets/MazeCreation.cs
poeticmatter/mindbender
f5b4afb8131eb193d2655afcfdb8a15cdbbbdde5
[ "CC0-1.0" ]
null
null
null
Assets/MazeCreation.cs
poeticmatter/mindbender
f5b4afb8131eb193d2655afcfdb8a15cdbbbdde5
[ "CC0-1.0" ]
null
null
null
Assets/MazeCreation.cs
poeticmatter/mindbender
f5b4afb8131eb193d2655afcfdb8a15cdbbbdde5
[ "CC0-1.0" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MazeCreation { public static MazeLocation CreateMaze(int size) { if (size <1) { Debug.LogError("Cannot create a maze smaller than 1."); } List<MazeLocation> mazeLocations = new List<MazeLocation>(); MazeLocation root = new MazeLocation(0); mazeLocations.Add(root); for (int i = 1; i < size; i++) { MazeLocation newLocation = new MazeLocation(i); bool added = false; while (!added) { MazeLocation connectTo = mazeLocations[Random.Range(0, mazeLocations.Count)]; int addedDirection = connectTo.Add(newLocation); added = addedDirection >= 0; if (added) { newLocation.SetConnected(connectTo, OppositeDirection(addedDirection)); mazeLocations.Add(newLocation); } } } int connectionsAdded = 0; int iterations = 0; while (connectionsAdded < size && iterations < size*2) { iterations++; Shuffle(mazeLocations); MazeLocation current = mazeLocations[0]; bool connected = false; for (int addIndex = 0; addIndex < 4 && !connected; addIndex++) { if (current.connected[addIndex] != null) { if (addIndex == 3) { mazeLocations.RemoveAt(0); // Fully connected; } continue; } int direction = current.GetIndexDirection(addIndex); for (int i = 1; i < mazeLocations.Count && !connected; i++) { MazeLocation connectTo = mazeLocations[i]; int oppositeDirection = OppositeDirection(direction); if (connectTo.GetConnected(oppositeDirection) == null) { connectTo.SetConnected(current, oppositeDirection); current.SetConnected(connectTo, direction); connected = true; } } } if (connected) { connectionsAdded++; } } return root; } private static int OppositeDirection(int direction) { return (direction + 2) % 4; } private static void Shuffle(List<MazeLocation> list) { for (int t = 0; t < list.Count; t++) { MazeLocation tmp = list[t]; int r = Random.Range(t, list.Count); list[t] = list[r]; list[r] = tmp; } } }
25.72093
82
0.62613
f48a379296a5491d10991bc3e025c84c5f8f01c8
2,328
ts
TypeScript
front-redux/src/pods/player/player.reducers.ts
jsagardoy/planning-poker-example
409b18fc7cef71525f5faf7e2bdfc8964df825e0
[ "Unlicense", "MIT" ]
23
2020-10-29T07:05:31.000Z
2021-01-25T19:18:46.000Z
front-redux/src/pods/player/player.reducers.ts
jsagardoy/planning-poker-example
409b18fc7cef71525f5faf7e2bdfc8964df825e0
[ "Unlicense", "MIT" ]
66
2020-08-23T21:25:52.000Z
2021-02-26T07:41:23.000Z
front-redux/src/pods/player/player.reducers.ts
jsagardoy/planning-poker-example
409b18fc7cef71525f5faf7e2bdfc8964df825e0
[ "Unlicense", "MIT" ]
7
2020-08-24T10:45:12.000Z
2021-01-24T19:06:25.000Z
import { PlayerStatus } from './player.const'; import { ActionBase, SocketOuputMessageTypes } from 'core'; import { actionIds } from 'core/actions'; import { podPlayerActionIds, playerVotesAction } from './player.actions'; import { combineReducers } from 'redux'; export interface PlayerPlanningPokerState { status: PlayerStatus; nicknameInUse: boolean; } const createDefaultMasterPlanningPokerState = (): PlayerPlanningPokerState => ({ status: PlayerStatus.NOT_CONNECTED, nicknameInUse: false, }); export const playerPlanningPokerReducer = ( state: PlayerPlanningPokerState = createDefaultMasterPlanningPokerState(), action: ActionBase ): PlayerPlanningPokerState => { switch (action.type) { case podPlayerActionIds.CONNECT_PLAYER: return { ...state, status: PlayerStatus.CONNECTION_IN_PROGRESS }; case podPlayerActionIds.PLAYER_SUCCESSFULLY_CONNECTED: return { ...state, status: PlayerStatus.WAITING_FOR_STORY }; case actionIds.SET_STORY_TITLE: return { ...state, status: PlayerStatus.VOTING_IN_PROGRESS }; case podPlayerActionIds.SEND_MESSAGE_PLAYER: return handleSendMessagePlayer(state, action.payload); case actionIds.SHOW_VOTING_RESULTS: return { ...state, status: PlayerStatus.SHOW_RESULTS }; case podPlayerActionIds.DISCONNECT_PLAYER: return { ...state, status: PlayerStatus.NOT_CONNECTED }; case podPlayerActionIds.NOTIFY_NICKNAME_IN_USE: return { ...state, nicknameInUse: true }; case podPlayerActionIds.HIDE_NICKNAME_INUSE_NOTIFICATION: return { ...state, nicknameInUse: false }; } return state; }; // TODO: Type this const handleSendMessagePlayer = ( state: PlayerPlanningPokerState, message: any ): PlayerPlanningPokerState => { // TODO: consider using lodash get here if (message && message.type) { switch (message.type) { case SocketOuputMessageTypes.USER_VOTED: return { ...state, status: PlayerStatus.VOTING_CLOSED }; case SocketOuputMessageTypes.END_VOTE_TIME: return { ...state, status: PlayerStatus.SHOW_RESULTS }; } } return state; }; export interface PlayerPodState { playerPlanningPokerState: PlayerPlanningPokerState; } export const playerPodReducers = combineReducers<PlayerPodState>({ playerPlanningPokerState: playerPlanningPokerReducer, });
34.235294
80
0.747852
446476724535a244c0db21090cef1c8d7d43ad61
1,663
py
Python
lanim/pil_machinery.py
brad90four/lanim
7af5aa23d53007624a00b2460c49e94bf3c43eac
[ "MIT" ]
6
2021-09-14T22:07:55.000Z
2021-11-08T20:56:52.000Z
lanim/pil_machinery.py
brad90four/lanim
7af5aa23d53007624a00b2460c49e94bf3c43eac
[ "MIT" ]
1
2021-10-07T00:01:46.000Z
2021-10-07T00:01:46.000Z
lanim/pil_machinery.py
brad90four/lanim
7af5aa23d53007624a00b2460c49e94bf3c43eac
[ "MIT" ]
2
2021-09-30T17:56:41.000Z
2021-10-31T21:18:51.000Z
from __future__ import annotations from typing import Iterable from pathlib import Path from threading import Thread import time from lanim.core import Animation, frames from lanim.pil_types import PilRenderable, PilSettings def render_pil( width: int, height: int, animation: Animation[PilRenderable], path: Path, fps: float, workers: int ): path.mkdir(parents=True, exist_ok=True) settings = PilSettings( width=width, height=height, center_x=width//2, center_y=height//2, unit=width//16 ) print(f"Size: {width}x{height}, duration: {animation.duration}s @{fps}FPS") print(f"Launching {workers} threads") jobs = [[] for _ in range(workers)] for (i, frame) in enumerate(frames(animation, fps)): jobs[i % workers].append((i, frame)) frame_rendering_threads: list[Thread] = [] t1 = time.time() for (n, job) in enumerate(jobs): print(f"Starting job {n} with {len(job)} frames...") thread = Thread(target=_render_frames, args=(job, settings, path)) thread.start() frame_rendering_threads.append(thread) for (n, thread) in enumerate(frame_rendering_threads): print(f"Waiting for frame-job {n}...") thread.join() t2 = time.time() return t2 - t1 def _render_frames(frames: Iterable[tuple[int, PilRenderable]], settings: PilSettings, path: Path): ctx = settings.make_ctx() for (position, frame) in frames: ctx.draw.rectangle((0, 0) + ctx.img.size, fill=(0, 0, 0, 255)) # type: ignore -- bad PIL stubs frame.render_pil(ctx) ctx.img.save(path / f"frame_{position}.png")
27.716667
103
0.653037
d9185e5351f25a2b3273cfd9e58e55fdaca216e8
168
cpp
C++
old/AtCoder/abc074/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
old/AtCoder/abc074/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
old/AtCoder/abc074/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "vector.hpp" int main() { int n(in), k(in); Vector<int> x(n, in); for (int &i : x) { i = min(i, k - i); } cout << 2 * x.accumulate() << endl; }
15.272727
37
0.47619
0ad876cd4a29cdaf89d5b4e72c0b14552c2c1f18
3,917
cs
C#
source/LokerIT.LibUsb/LokerIT.LibUsb/LibUsb/Interop/Linux/Native.cs
aloker/LokerIT.LibUsb
264236f5e8b9ee87df3753da9de1c38d811c3279
[ "MIT" ]
1
2020-10-20T00:35:50.000Z
2020-10-20T00:35:50.000Z
source/LokerIT.LibUsb/LokerIT.LibUsb/LibUsb/Interop/Linux/Native.cs
aloker/LokerIT.LibUsb
264236f5e8b9ee87df3753da9de1c38d811c3279
[ "MIT" ]
null
null
null
source/LokerIT.LibUsb/LokerIT.LibUsb/LibUsb/Interop/Linux/Native.cs
aloker/LokerIT.LibUsb
264236f5e8b9ee87df3753da9de1c38d811c3279
[ "MIT" ]
null
null
null
using System; using System.Runtime.InteropServices; using System.Text; namespace LokerIT.LibUsb.Interop.LinuxArm { public static class Native { private const string Dll = "libusb-1.0.so.0"; [DllImport(Dll)] public static extern IntPtr libusb_get_version(); [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern Result libusb_set_option(IntPtr context, Option option, int value); [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern Result libusb_set_option(IntPtr context, Option option); [DllImport(Dll)] public static extern Result libusb_init(out IntPtr context); [DllImport(Dll)] public static extern void libusb_exit(IntPtr context); [DllImport(Dll)] public static extern Result libusb_get_device_list(IntPtr context, out IntPtr ptrList); [DllImport(Dll)] public static extern void libusb_free_device_list(IntPtr list, int unrefDevices); [DllImport(Dll)] public static extern byte libusb_get_bus_number(IntPtr device); [DllImport(Dll)] public static extern byte libusb_get_port_number(IntPtr device); [DllImport(Dll)] public static extern Result libusb_get_port_numbers(IntPtr device, [Out] byte[] portNumbers, int portNumbersLength); [DllImport(Dll)] public static extern IntPtr libusb_get_parent(IntPtr device); [DllImport(Dll)] public static extern byte libusb_get_device_address(IntPtr device); [DllImport(Dll)] public static extern Speed libusb_get_device_speed(IntPtr device); [DllImport(Dll)] public static extern Result libusb_get_max_packet_size(IntPtr device, byte endpoint); [DllImport(Dll)] public static extern Result libusb_get_max_iso_packet_size(IntPtr device, byte endpoint); [DllImport(Dll)] public static extern IntPtr libusb_ref_device(IntPtr device); [DllImport(Dll)] public static extern void libusb_unref_device(IntPtr device); [DllImport(Dll)] public static extern Result libusb_open(IntPtr device, out IntPtr deviceHandle); [DllImport(Dll)] public static extern IntPtr libusb_open_device_with_vid_pid(IntPtr context, ushort vendorId, ushort productId); [DllImport(Dll)] public static extern void libusb_close(IntPtr deviceHandle); [DllImport(Dll)] public static extern IntPtr libusb_get_device(IntPtr deviceHandle); [DllImport(Dll)] public static extern Result libusb_get_configuration(IntPtr deviceHandle, ref int config); [DllImport(Dll)] public static extern Result libusb_set_configuration(IntPtr deviceHandle, int config); [DllImport(Dll)] public static extern Result libusb_claim_interface(IntPtr deviceHandle, int interfaceNumber); [DllImport(Dll)] public static extern Result libusb_release_interface(IntPtr deviceHandle, int interfaceNumber); [DllImport(Dll)] public static extern Result libusb_set_interface_alt_setting(IntPtr deviceHandle, int interfaceNumber, int alternateSetting); [DllImport(Dll)] public static extern Result libusb_clear_halt(IntPtr deviceHandle, byte endpoint); [DllImport(Dll)] public static extern Result libusb_reset_device(IntPtr deviceHandle); [DllImport(Dll)] public static extern Result libusb_get_device_descriptor(IntPtr device, out DeviceDescriptor descriptor); [DllImport(Dll)] public static extern Result libusb_control_transfer(IntPtr deviceHandle, byte requestType, byte request, ushort value, ushort index, IntPtr data, ushort length, int timeout); } }
38.029126
133
0.695685
a6ca95eace876a0e72dc732c0e84aa22c9bed3be
580
rb
Ruby
lib/macros/contract/extract_params.rb
artur79/ff-tbl-macros
2dd3a4ddc6559eaf50621e927ba66c273269f173
[ "MIT" ]
null
null
null
lib/macros/contract/extract_params.rb
artur79/ff-tbl-macros
2dd3a4ddc6559eaf50621e927ba66c273269f173
[ "MIT" ]
1
2020-06-25T06:09:22.000Z
2020-06-25T06:09:22.000Z
lib/macros/contract/extract_params.rb
firefield/ff-tbl-macros
2dd3a4ddc6559eaf50621e927ba66c273269f173
[ "MIT" ]
null
null
null
# frozen_string_literal: true module Macros class Contract class ExtractParams < Macros::Base # @return [Macros::Contract::ExtractParams] step macro instance # @param from [Hash] key in params # @example scope not passed # Macros::Contract::ExtractParams(from: :scope) def initialize(from:) @from = from end def call(ctx, **) return false unless ctx[:params] scope = ctx[@from] return false unless scope ctx['contract.default.params'] = ctx[:params][scope] end end end end
22.307692
69
0.615517
7af0e531a92cdb0534eeefb10da053bc27f1dbdf
1,237
cs
C#
Epam.Task1/Epam.Task1.Sequence/Program.cs
Polikutkin/Epam_XT-2018Q4
316be5f0150de95af26784ece7711197be5427f9
[ "MIT" ]
null
null
null
Epam.Task1/Epam.Task1.Sequence/Program.cs
Polikutkin/Epam_XT-2018Q4
316be5f0150de95af26784ece7711197be5427f9
[ "MIT" ]
null
null
null
Epam.Task1/Epam.Task1.Sequence/Program.cs
Polikutkin/Epam_XT-2018Q4
316be5f0150de95af26784ece7711197be5427f9
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Epam.Task1.Sequence { internal class Program { internal static void Sequence(int n) { try { if (n < 1) { throw new ArgumentOutOfRangeException(nameof(n), "The number less than 0."); } } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); return; } for (var i = 1; i < n; i++) { Console.Write($"{i}, "); } Console.WriteLine(n); } internal static void Main(string[] args) { while (true) { Console.WriteLine("Enter a positive integer."); bool isDigit = int.TryParse(Console.ReadLine(), out var data); if (!isDigit || data < 1) { Console.WriteLine("Please, enter the correct data."); continue; } Sequence(data); } } } }
23.339623
96
0.438157
0e66a452ef4928ea81e0158dc5c7cc0620bb949a
3,845
kt
Kotlin
idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/RunScratchAction.kt
evgzakharov/kotlin
1d0d801744e74c0d4a07f2b3592ed23103fb0925
[ "Apache-2.0" ]
null
null
null
idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/RunScratchAction.kt
evgzakharov/kotlin
1d0d801744e74c0d4a07f2b3592ed23103fb0925
[ "Apache-2.0" ]
null
null
null
idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/RunScratchAction.kt
evgzakharov/kotlin
1d0d801744e74c0d4a07f2b3592ed23103fb0925
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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. */ package org.jetbrains.kotlin.idea.scratch.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.compiler.CompilerManager import com.intellij.openapi.project.DumbService import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.scratch.ScratchFileLanguageProvider import org.jetbrains.kotlin.idea.scratch.output.ScratchOutputHandlerAdapter import org.jetbrains.kotlin.idea.scratch.printDebugMessage import org.jetbrains.kotlin.idea.scratch.ui.ScratchTopPanel import org.jetbrains.kotlin.idea.scratch.LOG as log class RunScratchAction(private val scratchPanel: ScratchTopPanel) : AnAction( KotlinBundle.message("scratch.run.button"), KotlinBundle.message("scratch.run.button"), AllIcons.Actions.Execute ) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val scratchFile = scratchPanel.scratchFile val psiFile = scratchFile.getPsiFile() ?: return val isMakeBeforeRun = scratchPanel.isMakeBeforeRun() val isRepl = scratchPanel.isRepl() val provider = ScratchFileLanguageProvider.get(psiFile.language) ?: return val handler = provider.getOutputHandler() log.printDebugMessage("Run Action: isMakeBeforeRun = $isMakeBeforeRun, isRepl = $isRepl") val module = scratchPanel.getModule() if (module == null) { handler.error(scratchFile, "Module should be selected") handler.onFinish(scratchFile) return } val runnable = r@{ val executor = if (isRepl) provider.createReplExecutor(scratchFile) else provider.createCompilingExecutor(scratchFile) if (executor == null) { handler.error(scratchFile, "Couldn't run ${psiFile.name}") handler.onFinish(scratchFile) return@r } e.presentation.isEnabled = false executor.addOutputHandler(handler) executor.addOutputHandler(object : ScratchOutputHandlerAdapter() { override fun onFinish(file: ScratchFile) { e.presentation.isEnabled = true } }) try { executor.execute() } catch (ex: Throwable) { handler.error(scratchFile, "Exception occurs during Run Scratch Action") handler.onFinish(scratchFile) e.presentation.isEnabled = true log.error(ex) return@r } } if (isMakeBeforeRun) { CompilerManager.getInstance(project).make(module) { aborted, errors, _, _ -> if (!aborted && errors == 0) { if (DumbService.isDumb(project)) { DumbService.getInstance(project).smartInvokeLater { runnable() } } else { runnable() } } } } else { runnable() } } }
35.934579
130
0.638231
798cda1b302841f504fc6b01d8e44604f352fd2b
899
php
PHP
resources/views/articles.blade.php
khandaniel/windowsite
1e565f29c9f3cf4cbf096b46d8cc333041bb8345
[ "MIT" ]
null
null
null
resources/views/articles.blade.php
khandaniel/windowsite
1e565f29c9f3cf4cbf096b46d8cc333041bb8345
[ "MIT" ]
null
null
null
resources/views/articles.blade.php
khandaniel/windowsite
1e565f29c9f3cf4cbf096b46d8cc333041bb8345
[ "MIT" ]
null
null
null
@extends('layouts.main') @section('content') <div class="fh5co-slider"> <div class="container"> <img src="{{ asset('/storage/slider/articles/default.jpg') }}"> </div> </div> <!-- Slider --> <div id="fh5co-intro" class="fh5co-section"> <div class="container"> <div class="row row-bottom-padded-md"> <div class="col-md-8 col-md-offset-2 text-center ts-intro"> <h1>{{ $articles_desc->title }}</h1> <p class="fh5co-lead">{{ $articles_desc->excerpt }}</p> </div> </div> <div class="row row-bottom-padded-sm"> @foreach($categories as $category) @include('partials.category_badge') @endforeach </div> @include('partials.important') </div> </div> @endsection
34.576923
75
0.49277
44828f4275502f6154e75ccea3d4a829500f6cad
1,218
py
Python
June21/small_inventory/inventory.py
pythonbykhaja/intesivepython
d3074f35bf36a04d4d1d9b4ff4631733d40b5817
[ "Apache-2.0" ]
2
2021-05-29T18:21:50.000Z
2021-07-24T13:03:30.000Z
June21/small_inventory/inventory.py
pythonbykhaja/intesivepython
d3074f35bf36a04d4d1d9b4ff4631733d40b5817
[ "Apache-2.0" ]
null
null
null
June21/small_inventory/inventory.py
pythonbykhaja/intesivepython
d3074f35bf36a04d4d1d9b4ff4631733d40b5817
[ "Apache-2.0" ]
2
2021-05-25T10:19:54.000Z
2021-09-21T12:20:48.000Z
from dataclasses import dataclass import csv from os import write @dataclass class Inventory: id: int name: str price: float quantity: int field_names = ['id', 'name', 'price', 'quantity'] def to_dict(self): inv_dict = dict() inv_dict['id'] = self.id inv_dict['name'] = self.name inv_dict['price'] = self.price inv_dict['quantity'] = self.quantity return inv_dict @staticmethod def get_inventory_from_cli(): id = int(input('Enter the id: ')) name = input('Enter the product name: ') price = float(input('Enter the product price: ')) quantity = int(input('Enter the quanity available: ')) return Inventory(id,name, price, quantity) def add_inventory_item(inventory, filename='data/inventory.csv'): with open(filename, 'at') as inv_obj: writer = csv.DictWriter(inv_obj, inventory.field_names) writer.writerow(inventory.to_dict()) if __name__ == '__main__': while True: inventory = Inventory.get_inventory_from_cli() add_inventory_item(inventory) choice = input('Do you want to continue? y or n ') if choice == 'n': break
26.478261
65
0.624795
390775d760bfdfec84e8cca4605d942407766e3a
2,208
py
Python
services/auth/authdb.py
NguyenVanVu0499/baitap_bigdata
bab1359e63264d9dfad90c62babff541ad3a2bd5
[ "MIT" ]
null
null
null
services/auth/authdb.py
NguyenVanVu0499/baitap_bigdata
bab1359e63264d9dfad90c62babff541ad3a2bd5
[ "MIT" ]
null
null
null
services/auth/authdb.py
NguyenVanVu0499/baitap_bigdata
bab1359e63264d9dfad90c62babff541ad3a2bd5
[ "MIT" ]
null
null
null
from datetime import datetime, timedelta from typing import Optional from passlib.context import CryptContext from .model import UserInDB, User, TokenData from jose import JWTError, jwt from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi import Depends, FastAPI, HTTPException, status from database.mongo import database userCollection = database.get_collection("nguoi_dung") pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def get_password_hash(password): return pwd_context.hash(password) SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) def authenticate_user(username: str, password: str): user = userCollection.find_one({ 'ten_nguoi_dung' : username, 'trang_thai': True, }) if not user: return False if not verify_password(password, user['mat_khau']): return False return user def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() # print('to encode', to_encode) if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) return payload except JWTError: raise credentials_exception async def get_current_active_user(current_user: User = Depends(get_current_user)): return current_user
28.675325
82
0.740036
739c6d0602550285753a2068e311414c00eed0b6
2,710
php
PHP
resources/views/index.blade.php
goodjack/Books
608b0dbcbc86a5c5313a41b49d46bbd0a107c396
[ "MIT" ]
1
2018-04-08T16:52:29.000Z
2018-04-08T16:52:29.000Z
resources/views/index.blade.php
goodjack/Books
608b0dbcbc86a5c5313a41b49d46bbd0a107c396
[ "MIT" ]
null
null
null
resources/views/index.blade.php
goodjack/Books
608b0dbcbc86a5c5313a41b49d46bbd0a107c396
[ "MIT" ]
null
null
null
@extends('layouts.layout') @section('title', '首頁') @section('content') <div class="jumbotron jumbotron-fluid m-b-0" style="background-image: url('https://static.pexels.com/photos/48126/books-education-school-literature-48126-large.jpeg'); background-size: cover; padding: 8em;"> <div class="container"> <h1 class="display-2">看書,從這裡開始</h1> <div class="input-group "> <input type="text" class="form-control" aria-label="Text input with dropdown button"> <div class="input-group-btn"> <button type="button" class="btn btn-lg btn-secondary"> <i class="material-icons">search</i> </button> </div> </div> </div> </div> <div class="jumbotron jumbotron-fluid m-b-0" style="color:white; background-color: #0277BD;"> <div class="container"> <h1>今日選句</h1> <p> <blockquote class="blockquote"> <p class="m-b-0"> 一個人至少擁有一個夢想,有一個理由去堅強。<br>心若沒有棲息的地方,到哪裡都是在流浪。 </p> <footer class="blockquote-footer" style="color:rgba(255,255,255,.26);"> 三毛 </footer> </blockquote> </p> </div> </div> <div class="jumbotron jumbotron-fluid" style="color:white; background-color: #77aa43;"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="card card-block"> <div class="input-group "> <button type="button" class="btn btn-lg btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> 篩選工具 </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Action</a> </div> <input type="text" class="form-control" aria-label="Text input with dropdown button"> <div class="input-group-btn"> <button type="button" class="btn btn-lg btn-secondary"> <i class="material-icons">search</i> </button> <button type="button" class="btn btn-lg btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> <div role="separator" class="dropdown-divider"></div> <a class="dropdown-item" href="#">Separated link</a> </div> </div> </div> </div> </div> </div> </div> </div> @stop
38.169014
208
0.572325
2575cbf1210c46538253f7fb2270948f5d17668a
147
js
JavaScript
src/app/store/reducers/rootReducer.js
kuldeepkeshwar/preact-pwa
0aa6cab883190b95437aee6d990022b4ea61d6ed
[ "MIT" ]
571
2016-12-30T02:43:04.000Z
2022-03-23T22:28:30.000Z
src/app/store/reducers/rootReducer.js
kuldeepkeshwar/preact-pwa
0aa6cab883190b95437aee6d990022b4ea61d6ed
[ "MIT" ]
14
2017-02-10T12:00:40.000Z
2018-05-16T22:05:01.000Z
src/app/store/reducers/rootReducer.js
kuldeepkeshwar/preact-pwa
0aa6cab883190b95437aee6d990022b4ea61d6ed
[ "MIT" ]
68
2016-12-30T17:55:52.000Z
2021-12-03T15:40:02.000Z
import { combineReducers } from 'redux' import meta from './meta' import posts from './posts' export default combineReducers({ meta, posts })
16.333333
39
0.714286
59ee771c9819cb869e628032caf4cf835b8ca19a
1,405
sql
SQL
src/main/resources/database/oracle/alter_12_4_0_to_12_4_1.sql
GeorgeKirev/OpenOLAT
ac0618163dc9965b6779e2c0c998247dc2a9d1ea
[ "Apache-2.0" ]
191
2018-03-29T09:55:44.000Z
2022-03-23T06:42:12.000Z
src/main/resources/database/oracle/alter_12_4_0_to_12_4_1.sql
KuricynAlexx/OpenOLAT
4ac8fbce54a41f61e1fd61adce5bf4ec36bcef68
[ "Apache-2.0" ]
68
2018-05-11T06:19:00.000Z
2022-01-25T18:03:26.000Z
src/main/resources/database/oracle/alter_12_4_0_to_12_4_1.sql
KuricynAlexx/OpenOLAT
4ac8fbce54a41f61e1fd61adce5bf4ec36bcef68
[ "Apache-2.0" ]
139
2018-04-27T09:46:11.000Z
2022-03-27T08:52:50.000Z
alter table o_qti_assessment_response modify q_responseidentifier varchar2(255 char); alter table o_bs_authentication add lastmodified date; update o_bs_authentication set lastmodified=creationdate; alter table o_bs_authentication modify lastmodified date not null; create table o_bs_authentication_history ( id number(20) generated always as identity, creationdate date, provider varchar(8), authusername varchar(255), credential varchar(255), salt varchar(255) default null, hashalgorithm varchar(16) default null, fk_identity number(20) not null, primary key (id) ); alter table o_bs_authentication_history add constraint auth_hist_to_ident_idx foreign key (fk_identity) references o_bs_identity (id); create index idx_auth_hist_to_ident_idx on o_bs_authentication_history (fk_identity); create table o_csp_log ( id number(20) generated always as identity, creationdate date, l_blocked_uri varchar(1024), l_disposition varchar(32), l_document_uri varchar(1024), l_effective_directive CLOB, l_original_policy CLOB, l_referrer varchar(1024), l_script_sample CLOB, l_status_code varchar(1024), l_violated_directive varchar(1024), l_source_file varchar(1024), l_line_number number(20), l_column_number number(20), fk_identity number(20), primary key (id) ); create index idx_csp_log_to_ident_idx on o_csp_log (fk_identity);
31.931818
134
0.790747
6c3f49e5c40875dd9d4b3fa2f3961c8c80721a0f
2,021
psm1
PowerShell
Twitter/Twitter.psm1
jwmoss/Twitter
f6b5160832ce17f1104d2bc3e0f1f8a27a04779f
[ "MIT" ]
1
2020-10-09T03:06:50.000Z
2020-10-09T03:06:50.000Z
Twitter/Twitter.psm1
jwmoss/Twitter
f6b5160832ce17f1104d2bc3e0f1f8a27a04779f
[ "MIT" ]
null
null
null
Twitter/Twitter.psm1
jwmoss/Twitter
f6b5160832ce17f1104d2bc3e0f1f8a27a04779f
[ "MIT" ]
null
null
null
using module .\classes\OAuthParameters.Class.psm1 using namespace System.Management.Automation using namespace Collections.ObjectModel using namespace System.Collections #Requires -Version 7.0 # load the twittererrorcodes and httpresponsecodes #region info <# The following members are exported via the module's data file (.psd1) Functions TypeData FormatData #> #endregion info #region discover module name $ScriptPath = Split-Path $MyInvocation.MyCommand.Path $ModuleName = $ExecutionContext.SessionState.Module Write-Verbose -Message "Loading module $ModuleName" #endregion discover module name #region load module variables Write-Verbose -Message "Creating modules variables" $ErrorMappingPath = Join-Path -Path $PSScriptRoot -ChildPath 'resources' -AdditionalChildPath 'TwitterErrorCodeExceptions.json' [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ErrorMapping = Get-Content -Path $ErrorMappingPath -Raw | ConvertFrom-Json [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $RateLimitWarning = $false #endregion load module variables #region Handle Module Removal $OnRemoveScript = { # } $ExecutionContext.SessionState.Module.OnRemove += $OnRemoveScript Register-EngineEvent -SourceIdentifier ([System.Management.Automation.PsEngineEvent]::Exiting) -Action $OnRemoveScript #endregion Handle Module Removal #region dot source public and private function definition files, export publich functions try { foreach ($Scope in 'Public','Private') { Get-ChildItem (Join-Path -Path $ScriptPath -ChildPath $Scope) -Filter *.ps1 | ForEach-Object { . $_.FullName if ($Scope -eq 'Public') { Export-ModuleMember -Function $_.BaseName -ErrorAction Stop } } } } catch { Write-Error ("{0}: {1}" -f $_.BaseName,$_.Exception.Message) exit 1 } #endregion dot source public and private function definition files, export publich functions
32.596774
127
0.761999
b85affb87e1d1dfbdbbf4441dc0c4b84134b464b
232
sql
SQL
target/run/jaffel_shop/models/staging/jaffle_shop/src_jaffle_shop.yml/source_not_null_jaffle_shop_customers_id.sql
Pachinchin/gbt-repo
383cdd36c7031e4ee70df90a0b051d3cdc257b94
[ "MIT" ]
2
2022-01-05T18:28:55.000Z
2022-01-07T13:50:16.000Z
target/run/jaffel_shop/models/staging/jaffle_shop/src_jaffle_shop.yml/source_not_null_jaffle_shop_customers_id.sql
Pachinchin/dbt-repo
383cdd36c7031e4ee70df90a0b051d3cdc257b94
[ "MIT" ]
null
null
null
target/run/jaffel_shop/models/staging/jaffle_shop/src_jaffle_shop.yml/source_not_null_jaffle_shop_customers_id.sql
Pachinchin/dbt-repo
383cdd36c7031e4ee70df90a0b051d3cdc257b94
[ "MIT" ]
null
null
null
select count(*) as failures, count(*) != 0 as should_warn, count(*) != 0 as should_error from ( select * from "dev"."jaffle_shop"."customers" where id is null ) dbt_internal_test
13.647059
36
0.547414
a354d54a9914c3604c0c14dbe5e9cbcbe462af85
389
ts
TypeScript
src/cli/lib/non-configurable/backgrounds.ts
imrishabh18/tailwindcss-classnames
7988e9c67165de09f24af810c901303f773c0728
[ "MIT" ]
1
2022-01-04T04:46:45.000Z
2022-01-04T04:46:45.000Z
src/cli/lib/non-configurable/backgrounds.ts
imrishabh18/tailwindcss-classnames
7988e9c67165de09f24af810c901303f773c0728
[ "MIT" ]
null
null
null
src/cli/lib/non-configurable/backgrounds.ts
imrishabh18/tailwindcss-classnames
7988e9c67165de09f24af810c901303f773c0728
[ "MIT" ]
null
null
null
const backgroundAttachment = ['bg-fixed', 'bg-local', 'bg-scroll']; const backgroundClip = ['bg-clip-border', 'bg-clip-padding', 'bg-clip-content', 'bg-clip-text']; const backgroundRepeat = [ 'bg-repeat', 'bg-no-repeat', 'bg-repeat-x', 'bg-repeat-y', 'bg-repeat-round', 'bg-repeat-space', ]; export default { backgroundAttachment, backgroundClip, backgroundRepeat, };
20.473684
96
0.66838
434f635d9f78b7fe0709ced75e817329c025a854
4,028
tsx
TypeScript
src/renderer/components/config/CacheGroup.tsx
f3lin3/flipflip
75a830fa1b125cb075709550a94a687f8f2cf14d
[ "MIT" ]
4
2019-01-19T05:02:31.000Z
2019-07-18T18:16:12.000Z
src/renderer/components/config/CacheGroup.tsx
f3lin3/flipflip
75a830fa1b125cb075709550a94a687f8f2cf14d
[ "MIT" ]
null
null
null
src/renderer/components/config/CacheGroup.tsx
f3lin3/flipflip
75a830fa1b125cb075709550a94a687f8f2cf14d
[ "MIT" ]
null
null
null
import {remote} from "electron"; import * as React from 'react'; import {existsSync} from "fs"; import rimraf from "rimraf"; import getFolderSize from 'get-folder-size'; import {getCachePath} from "../../data/utils"; import Config, {CacheSettings} from "../../data/Config"; import ControlGroup from "../sceneDetail/ControlGroup"; import SimpleCheckbox from "../ui/SimpleCheckbox"; import SimpleNumberInput from "../ui/SimpleNumberInput"; import SimpleTextInput from "../ui/SimpleTextInput"; export default class CacheGroup extends React.Component { readonly props: { config: Config, onUpdateSettings(settings: CacheSettings, fn: (settings: CacheSettings) => void): void, }; readonly state = { cacheSize: "--", }; render() { return ( <ControlGroup title="Caching" isNarrow={true}> <SimpleCheckbox text="Enable Caching" isOn={this.props.config.caching.enabled} onChange={this.changeKey.bind(this, 'enabled').bind(this)}> <button className={this.props.config.caching.enabled ? '' : 'u-disabled'} onClick={this.props.config.caching.enabled ? this.clearCache.bind(this) : this.nop}>ClearCache </button> </SimpleCheckbox> <div className="ControlSubgroup m-inline"> <SimpleTextInput isEnabled={this.props.config.caching.enabled} label="Caching Directory" value={this.props.config.caching.directory} onChange={this.changeKey.bind(this, 'directory').bind(this)}> <div> {" "} <button className={this.props.config.caching.enabled ? '' : 'u-disabled'} onClick={this.props.config.caching.enabled ? this.pickDirectory.bind(this) : this.nop}>Browse </button> {" "} <button className={this.props.config.caching.enabled ? '' : 'u-disabled'} onClick={this.props.config.caching.enabled ? this.paste.bind(this) : this.nop}>Paste </button> {" "} </div> {this.props.config.caching.directory == "" && ( <span>You are using the default directory</span> )} </SimpleTextInput> </div> <div className="ControlSubgroup m-inline"> <span>Cache Dir size: {this.state.cacheSize}</span> <SimpleNumberInput label="Caching Directory Max Size (MB):" min={0} value={this.props.config.caching.maxSize} isEnabled={this.props.config.caching.enabled} onChange={this.changeKey.bind(this, 'maxSize').bind(this)}/> <span>Set to 0 for Unlimited</span> </div> </ControlGroup> ); } nop() {} componentDidMount() { this.calculateCacheSize(); } calculateCacheSize() { if (this.props.config.caching.maxSize != 0) { const cachePath = getCachePath(null, this.props.config); if (existsSync(cachePath)) { getFolderSize(getCachePath(null, this.props.config), (err: string, size: number) => { if (err) { throw err; } const mbSize = (size / 1024 / 1024); this.setState({cacheSize: mbSize.toFixed(2) + "MB"}); }); } } } pickDirectory() { let result = remote.dialog.showOpenDialog(remote.getCurrentWindow(), {properties: ['openDirectory']}); if (!result) return; this.changeKey('directory', result[0]); } paste() { (navigator as any).clipboard.readText().then((pastedText: string) => { this.changeKey('directory', pastedText); }); } update(fn: (settings: any) => void) { this.props.onUpdateSettings(this.props.config.caching, fn); } changeKey(key: string, value: any) { this.update((s) => s[key] = value); } clearCache() { const cachePath = getCachePath(null, this.props.config); if (!confirm("Are you SURE you want to delete " + cachePath + "?")) return; rimraf.sync(cachePath); this.setState({cacheSize: "--"}); } }
34.724138
113
0.605015
66148cb9223c8b7fc9637bef4bdaade367fee468
2,939
py
Python
Python/plotSurfaceMachContour.py
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
1
2019-02-11T00:45:37.000Z
2019-02-11T00:45:37.000Z
Python/plotSurfaceMachContour.py
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
null
null
null
Python/plotSurfaceMachContour.py
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
null
null
null
import tecplot import numpy as np import math import string from tecplot.exception import * from tecplot.constant import * class plotSurfaceMachContour(object): def __init__(self, mySurfaceFlowFile, Type): print("plotMachContour................................................."); self.mySurfaceFlowFile_ = mySurfaceFlowFile; self.type_ = Type; if self.type_ == 0: #EULER dataset = tecplot.data.load_tecplot_szl(self.mySurfaceFlowFile_, read_data_option=2); elif self.type_ == 1: #SU2 dataset = tecplot.data.load_tecplot(self.mySurfaceFlowFile_, read_data_option=2); frame = tecplot.active_frame(); plot = frame.plot(PlotType.Cartesian3D) plot.activate() plot.show_contour = True; if self.type_ == 0: # EULER plot.contour(0).variable = dataset.variable(9); elif self.type_ == 1: # SU2 plot.contour(0).variable = dataset.variable(11); # Set Rainbow plot.contour(0).colormap_name = 'Small Rainbow'; # Set View plot.view.width = 1.91291; plot.view.alpha = -47.73; plot.view.theta = 137.32; plot.view.psi = 136.51; plot.view.position = (-6.57402, 7.48889, -10.3657); # Save layout for Tecplot print("Save MachContour_fullbody.lay..................................."); tecplot.save_layout('../Python/lay/MachContour_fullbody.lay'); print("Save MachContour_fullbody.lay...............................DONE"); # export image of full body print("Save MachContour_fullbody.png..................................."); tecplot.export.save_png('../Python/png/MachContour_fullbody.png', 2000, supersample=3); print("Save MachContour_fullbody.png...............................DONE"); plot = frame.plot(PlotType.Cartesian2D) plot.activate() plot.show_contour = True; if self.type_ == 0: # EULER plot.contour(0).variable = dataset.variable(9); elif self.type_ == 1: # SU2 plot.contour(0).variable = dataset.variable(11); plot.axes.x_axis.show = False; plot.axes.y_axis.show = False; # Save layout for Tecplot print("Save MachContour_wing.lay......................................."); tecplot.save_layout('../Python/lay/MachContour_wing.lay'); print("Save MachContour_wing.lay...................................DONE"); # export image of wing print("Save MachContour_wing.png......................................."); tecplot.export.save_png('../Python/png/MachContour_wing.png', 2000, supersample=3); print("Save MachContour_wing.png...................................DONE"); print("plotMachContour.............................................DONE");
40.260274
98
0.536237
c353ec357e1e14cb1f7c13007b1fa01766345826
3,863
cs
C#
LCL_Controls/Controls/PageTitleBar/NavigationTitleBar.Designer.cs
landriesnidis/LCL_UI
e6c4c4d4a2078be9acc19b81c70b27d6006cc2d3
[ "MIT" ]
6
2019-07-08T07:59:35.000Z
2022-03-28T08:35:48.000Z
LCL_Controls/Controls/PageTitleBar/NavigationTitleBar.Designer.cs
landriesnidis/LCL_UI
e6c4c4d4a2078be9acc19b81c70b27d6006cc2d3
[ "MIT" ]
null
null
null
LCL_Controls/Controls/PageTitleBar/NavigationTitleBar.Designer.cs
landriesnidis/LCL_UI
e6c4c4d4a2078be9acc19b81c70b27d6006cc2d3
[ "MIT" ]
1
2020-03-23T03:55:20.000Z
2020-03-23T03:55:20.000Z
using System.Windows.Forms; namespace Landriesnidis.LCL_Controls.Controls.PageTitleBar { partial class NavigationTitleBar { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 组件设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.LeftButton = new Landriesnidis.LCL_Controls.Controls.Button.MiniImageButton(); this.RightButton = new Landriesnidis.LCL_Controls.Controls.Button.MiniImageButton(); this.TitleLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); this.TitleLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.TitleLabel.Font = new System.Drawing.Font("微软雅黑", 9F); this.TitleLabel.Location = new System.Drawing.Point(0, 0); this.TitleLabel.Name = "TitleLabel"; this.TitleLabel.Size = new System.Drawing.Size(400, 35); this.TitleLabel.TabIndex = 0; this.TitleLabel.Text = "Title"; this.TitleLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.LeftButton.AllowNoFocusResponseMouseEvent = true; this.LeftButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(122)))), ((int)(((byte)(204))))); this.LeftButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.LeftButton.Dock = System.Windows.Forms.DockStyle.Left; this.LeftButton.Image = global::Landriesnidis.LCL_Controls.Properties.Resources.android_title_bar_arrow; this.LeftButton.Location = new System.Drawing.Point(0, 0); this.LeftButton.Name = "LeftButton"; this.LeftButton.Size = new System.Drawing.Size(Height, Height); this.LeftButton.TabIndex = 1; this.RightButton.AllowNoFocusResponseMouseEvent = true; this.RightButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(122)))), ((int)(((byte)(204))))); this.RightButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.RightButton.Dock = System.Windows.Forms.DockStyle.Right; this.RightButton.Image = global::Landriesnidis.LCL_Controls.Properties.Resources.android_title_bar_arrow_right; this.RightButton.Location = new System.Drawing.Point(465, 0); this.RightButton.Name = "RightButton"; this.RightButton.Size = new System.Drawing.Size(Height, Height); this.RightButton.TabIndex = 2; // // AndroidTitleBar // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.TitleLabel); this.Controls.Add(this.RightButton); this.Controls.Add(this.LeftButton); this.Name = "NavigationTitleBar"; this.Size = new System.Drawing.Size(400, 35); this.Resize += new System.EventHandler(this.NavigationTitleBar_Resize); this.ResumeLayout(false); } #endregion protected Button.MiniImageButton LeftButton; protected Button.MiniImageButton RightButton; public Label TitleLabel; } }
43.897727
141
0.619984
e0468d7ef13d77f99085cb6175cf8ea0e74c5634
4,837
c
C
attic/sht.c
dmgerman/ntpsec
28dde8422e1a949e50663ae965d58c2fdbc782b9
[ "CC-BY-4.0", "BSD-2-Clause", "NTP", "MIT", "BSD-3-Clause" ]
null
null
null
attic/sht.c
dmgerman/ntpsec
28dde8422e1a949e50663ae965d58c2fdbc782b9
[ "CC-BY-4.0", "BSD-2-Clause", "NTP", "MIT", "BSD-3-Clause" ]
null
null
null
attic/sht.c
dmgerman/ntpsec
28dde8422e1a949e50663ae965d58c2fdbc782b9
[ "CC-BY-4.0", "BSD-2-Clause", "NTP", "MIT", "BSD-3-Clause" ]
null
null
null
/* * sht.c - Testprogram for shared memory refclock * read/write shared memory segment; see usage */ #include "config.h" #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <assert.h> #include "ntp.h" #include "ntp_stdlib.h" char *progname; struct shmTime { int mode; /* 0 - if valid set * use values, * clear valid * 1 - if valid set * if count before and after read of values is equal, * use values * clear valid */ volatile int count; time_t clockTimeStampSec; int clockTimeStampUSec; time_t receiveTimeStampSec; int receiveTimeStampUSec; int leap; int precision; int nsamples; volatile int valid; unsigned clockTimeStampNSec; /* Unsigned ns timestamps */ unsigned receiveTimeStampNSec; /* Unsigned ns timestamps */ }; static struct shmTime * getShmTime ( int unit ) { int shmid=shmget (0x4e545030+unit, sizeof (struct shmTime), IPC_CREAT|0777); if (shmid==-1) { perror ("shmget"); exit (1); } else { struct shmTime *p=(struct shmTime *)shmat (shmid, 0, 0); if ((int)(long)p==-1) { perror ("shmat"); p=0; } assert (p!=0); return p; } } int main ( int argc, char *argv[] ) { volatile struct shmTime *p; int unit; char *argp; progname = argv[0]; if (argc<=1) { usage: printf ("usage: %s [uu:]{r[c][l]|w|snnn}\n",argv[0]); printf (" uu use clock unit uu (default: 2)\n"); printf (" r read shared memory\n"); printf (" c clear valid-flag\n"); printf (" l loop (so, rcl will read and clear in a loop\n"); printf (" w write shared memory with current time\n"); printf (" snnnn set nsamples to nnn\n"); printf (" lnnnn set leap to nnn\n"); printf (" pnnnn set precision to -nnn\n"); exit (0); } unit = (int)strtoul(argv[1], &argp, 10); if (argp == argv[1]) unit = 2; else if (*argp == ':') argp++; else goto usage; p=getShmTime(unit); switch (*argp) { case 's': p->nsamples=atoi(argp+1); break; case 'l': p->leap=atoi(argp+1); break; case 'p': p->precision=-atoi(argp+1); break; case 'r': { int clear=0; int loop=0; printf ("reader\n"); while (*++argp) { switch (*argp) { case 'l': loop=1; break; case 'c': clear=1; break; default : goto usage; } } again: printf ("mode=%d, count=%d, clock=%ld.%09u, rec=%ld.%09u,\n", p->mode,p->count, (long)p->clockTimeStampSec,p->clockTimeStampNSec, (long)p->receiveTimeStampSec,p->receiveTimeStampNSec); printf (" leap=%d, precision=%d, nsamples=%d, valid=%d\n", p->leap, p->precision, p->nsamples, p->valid); if (!p->valid) printf ("***\n"); if (clear) { p->valid=0; printf ("cleared\n"); } if (loop) { sleep (1); goto again; } break; } case 'w': { /* To show some life action, we read the system * clock and use a bit of fuzz from 'ntp_random()' to get a * bit of wobbling into the values (so we can observe a * certain jitter!) */ time_t clk_sec, rcv_sec; unsigned int clk_frc, rcv_frc; /* Here we have a high-resolution system clock, and * we're not afraid to use it! */ struct timespec tmptime; if (0 == clock_gettime(CLOCK_REALTIME, &tmptime)) { rcv_sec = tmptime.tv_sec; rcv_frc = (unsigned int)tmptime.tv_nsec; } else { time(&rcv_sec); rcv_frc = (unsigned int)ntp_random() % 1000000000u; } /* add a wobble of ~3.5msec to the clock time */ clk_sec = rcv_sec; clk_frc = rcv_frc + (unsigned int)(ntp_random()%7094713 - 3547356); /* normalise result -- the SHM driver is picky! */ while ((int)clk_frc < 0) { clk_frc += 1000000000; clk_sec -= 1; } while ((int)clk_frc >= 1000000000) { clk_frc -= 1000000000; clk_sec += 1; } /* Most 'real' time sources would create a clock * (reference) time stamp where the fraction is zero, * but that's not an actual requirement. So we show how * to deal with the time stamps in general; changing the * behaviour for cases where the fraction of the * clock time is zero should be trivial. */ printf ("writer\n"); p->mode=0; if (!p->valid) { p->clockTimeStampSec = clk_sec; p->clockTimeStampUSec = (int)(clk_frc / 1000); /* truncate! */ p->clockTimeStampNSec = clk_frc; p->receiveTimeStampSec = rcv_sec; p->receiveTimeStampUSec = (int)(rcv_frc / 1000); /* truncate! */ p->receiveTimeStampNSec = rcv_frc; printf ("%ld.%09u %ld.%09u\n", (long)p->clockTimeStampSec , p->clockTimeStampNSec , (long)p->receiveTimeStampSec, p->receiveTimeStampNSec); p->valid=1; } else { printf ("p->valid still set\n"); /* not an error! */ } break; } default: break; } return 0; }
23.033333
77
0.610296
d15e080d09c578bbcf74a3c0844fdaa8ccf4a332
2,692
dart
Dart
lib/src/model/event_insights.g.dart
jr1221/tba_api_dart_dio_client
622051c4cc4007d6ff43193db41fdbb3aeb70504
[ "MIT" ]
3
2021-04-14T02:42:57.000Z
2021-12-26T08:27:35.000Z
lib/src/model/event_insights.g.dart
jr1221/tba_api_dart_dio_client
622051c4cc4007d6ff43193db41fdbb3aeb70504
[ "MIT" ]
null
null
null
lib/src/model/event_insights.g.dart
jr1221/tba_api_dart_dio_client
622051c4cc4007d6ff43193db41fdbb3aeb70504
[ "MIT" ]
1
2021-12-26T08:27:41.000Z
2021-12-26T08:27:41.000Z
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'event_insights.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** class _$EventInsights extends EventInsights { @override final JsonObject? qual; @override final JsonObject? playoff; factory _$EventInsights([void Function(EventInsightsBuilder)? updates]) => (new EventInsightsBuilder()..update(updates)).build(); _$EventInsights._({this.qual, this.playoff}) : super._(); @override EventInsights rebuild(void Function(EventInsightsBuilder) updates) => (toBuilder()..update(updates)).build(); @override EventInsightsBuilder toBuilder() => new EventInsightsBuilder()..replace(this); @override bool operator ==(Object other) { if (identical(other, this)) return true; return other is EventInsights && qual == other.qual && playoff == other.playoff; } @override int get hashCode { return $jf($jc($jc(0, qual.hashCode), playoff.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('EventInsights') ..add('qual', qual) ..add('playoff', playoff)) .toString(); } } class EventInsightsBuilder implements Builder<EventInsights, EventInsightsBuilder> { _$EventInsights? _$v; JsonObject? _qual; JsonObject? get qual => _$this._qual; set qual(JsonObject? qual) => _$this._qual = qual; JsonObject? _playoff; JsonObject? get playoff => _$this._playoff; set playoff(JsonObject? playoff) => _$this._playoff = playoff; EventInsightsBuilder() { EventInsights._initializeBuilder(this); } EventInsightsBuilder get _$this { final $v = _$v; if ($v != null) { _qual = $v.qual; _playoff = $v.playoff; _$v = null; } return this; } @override void replace(EventInsights other) { ArgumentError.checkNotNull(other, 'other'); _$v = other as _$EventInsights; } @override void update(void Function(EventInsightsBuilder)? updates) { if (updates != null) updates(this); } @override _$EventInsights build() { final _$result = _$v ?? new _$EventInsights._(qual: qual, playoff: playoff); replace(_$result); return _$result; } } // ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
28.336842
354
0.663447
df822d0bfdbffd763ec0c38c3b76281285404207
629
cs
C#
photoAddIn/photoAddIn/photo.cs
SurgicalSteel/dotNEThacks
e1f5ad1168e51dcf3189dc20e8a9a67c79c6ee48
[ "MIT" ]
null
null
null
photoAddIn/photoAddIn/photo.cs
SurgicalSteel/dotNEThacks
e1f5ad1168e51dcf3189dc20e8a9a67c79c6ee48
[ "MIT" ]
null
null
null
photoAddIn/photoAddIn/photo.cs
SurgicalSteel/dotNEThacks
e1f5ad1168e51dcf3189dc20e8a9a67c79c6ee48
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace photoAddIn { class photo { public int width, height; public string filename; public Image gambar; public void reset() { width = 0; height = 0; filename = ""; gambar = null; } public photo(int w, int h, string f, Image i) { this.filename = f; this.width = w; this.height = h; this.gambar = i; } } }
20.966667
54
0.511924
851b77f3061333f4203da5a69eb4b5a2a9387587
1,366
cs
C#
DFC.App.Account/Controllers/YourDetailsController.cs
SkillsFundingAgency/dfc-app-account
83169fd7fe4e233ff543004d858c6e03922703e3
[ "MIT" ]
1
2021-06-23T09:31:26.000Z
2021-06-23T09:31:26.000Z
DFC.App.Account/Controllers/YourDetailsController.cs
SkillsFundingAgency/dfc-app-account
83169fd7fe4e233ff543004d858c6e03922703e3
[ "MIT" ]
176
2020-04-17T10:07:54.000Z
2022-03-14T11:01:09.000Z
DFC.App.Account/Controllers/YourDetailsController.cs
SkillsFundingAgency/dfc-app-account
83169fd7fe4e233ff543004d858c6e03922703e3
[ "MIT" ]
1
2021-04-11T08:37:14.000Z
2021-04-11T08:37:14.000Z
using DFC.App.Account.Models; using DFC.App.Account.Services; using DFC.App.Account.Services.DSS.Interfaces; using DFC.App.Account.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System.Threading.Tasks; using DFC.APP.Account.Data.Models; using DFC.Compui.Cosmos.Contracts; using Microsoft.Extensions.Configuration; namespace DFC.App.Account.Controllers { [Authorize] public class YourDetailsController : CompositeSessionController<YourDetailsCompositeViewModel> { private readonly IDssReader _dssService; public YourDetailsController(ILogger<YourDetailsController> logger, IOptions<CompositeSettings> compositeSettings, IDssReader dssService, IAuthService authService, IDocumentService<CmsApiSharedContentModel> documentService, IConfiguration config) : base(compositeSettings, authService, documentService, config) { _dssService = dssService; } [Route("/body/your-details")] public override async Task<IActionResult> Body() { var customer = await GetCustomerDetails(); ViewModel.CustomerDetails = await _dssService.GetCustomerData(customer.CustomerId.ToString()); return await base.Body(); } } }
35.947368
254
0.743777
e74b2aac97e0219c9ee39d942f24aad183dbe2d4
741
php
PHP
src/Traits/Jsonable.php
andrey-helldar/helpers
7c1b3d8e24228ded997780f3ecc2eedf73f8a38c
[ "MIT" ]
2
2019-01-09T07:45:06.000Z
2021-07-27T23:31:06.000Z
src/Traits/Jsonable.php
andrey-helldar/helpers
7c1b3d8e24228ded997780f3ecc2eedf73f8a38c
[ "MIT" ]
16
2017-09-20T08:14:55.000Z
2018-09-18T08:34:41.000Z
src/Traits/Jsonable.php
andrey-helldar/helpers
7c1b3d8e24228ded997780f3ecc2eedf73f8a38c
[ "MIT" ]
null
null
null
<?php namespace Helldar\Helpers\Traits; use Illuminate\Contracts\Support\Jsonable as JsonableSupport; /** * Class Jsonable * * @see https://gist.github.com/Ellrion/2c7648d3ebdef2cd8ed24ffa78cf1d3d */ class Jsonable implements JsonableSupport { /** * @var mixed */ protected $dataToJson; /** * Set a value; * * @param $data * * @return $this */ protected function setData($data) { $this->dataToJson = $data; return $this; } /** * Convert the object to its JSON representation. * * @param int $options * * @return mixed|string */ public function toJson($options = 0) { return $this->dataToJson; } }
16.466667
72
0.576248
b5f14d1d37b6d7ed276352246f50dc3d40d0ab24
138
rb
Ruby
Ruby/CodeAbbey/Sum A+B.rb
dvt32/cpp-journey
afd7db7a1ad106c41601fb09e963902187ae36e6
[ "MIT" ]
1
2018-05-24T11:30:05.000Z
2018-05-24T11:30:05.000Z
Ruby/CodeAbbey/Sum A+B.rb
dvt32/cpp-journey
afd7db7a1ad106c41601fb09e963902187ae36e6
[ "MIT" ]
null
null
null
Ruby/CodeAbbey/Sum A+B.rb
dvt32/cpp-journey
afd7db7a1ad106c41601fb09e963902187ae36e6
[ "MIT" ]
2
2017-08-11T06:53:30.000Z
2017-08-29T12:07:52.000Z
# http://www.codeabbey.com/index/task_view/sum-of-two def sum(a, b) return a + b end a = gets.to_i b = gets.to_i puts sum(a, b)
12.545455
53
0.630435
9716ea342a0f149e36901efd06c9ca5d3494928d
1,281
ts
TypeScript
src/interface-segregation/solution.ts
andreygio-adl/solid-principles
0f853a896ec23b1e8d1d7c32b8f98eaf7f7307fc
[ "Apache-2.0" ]
null
null
null
src/interface-segregation/solution.ts
andreygio-adl/solid-principles
0f853a896ec23b1e8d1d7c32b8f98eaf7f7307fc
[ "Apache-2.0" ]
null
null
null
src/interface-segregation/solution.ts
andreygio-adl/solid-principles
0f853a896ec23b1e8d1d7c32b8f98eaf7f7307fc
[ "Apache-2.0" ]
null
null
null
interface PaymentProvider { validate: () => boolean; getPaymentCommission: () => number; processPayment: () => string; verifyPayment: () => boolean; } class CreditCardPaymentProvider implements PaymentProvider { validate() { // Payment is validated console.log("Payment Card Validated"); return true; } getPaymentCommission() { // Commission is returned return 10; } processPayment() { // Payment processed console.log("Payment Processed"); return "Payment Fingerprint"; } verifyPayment() { // No verify Payment API exist // Return false to just implement the Payment Provider return false; } } class WalletPaymentProvider implements PaymentProvider { validate() { // No validate method exists // Just for sake of implementation return false return false; } getPaymentCommission() { // Commission is returned return 5; } processPayment() { // Payment processed console.log("Payment Processed"); return "Payment Fingerprint"; } verifyPayment() { // Payment verification does exist on Wallet Payment Provider console.log("Payment Verified"); return false; } }
25.62
67
0.626073
bb3951712be81ff37f3f274310b8f636fe611c45
3,279
cs
C#
Unity2020Test/Assets/QFramework/Framework/Plugins/Editor/PackageKit/PackageMaker/Service/UploadPackage.cs
JiYangJi/QFramework
5fca44ad8f93f1d90a9c9cc23a32260b86bf2786
[ "MIT" ]
1
2021-09-22T05:45:40.000Z
2021-09-22T05:45:40.000Z
Unity2020Test/Assets/QFramework/Framework/Plugins/Editor/PackageKit/PackageMaker/Service/UploadPackage.cs
JiYangJi/QFramework
5fca44ad8f93f1d90a9c9cc23a32260b86bf2786
[ "MIT" ]
null
null
null
Unity2020Test/Assets/QFramework/Framework/Plugins/Editor/PackageKit/PackageMaker/Service/UploadPackage.cs
JiYangJi/QFramework
5fca44ad8f93f1d90a9c9cc23a32260b86bf2786
[ "MIT" ]
null
null
null
using System.IO; using UnityEditor; using UnityEngine; namespace QFramework { public static class UploadPackage { private static string UPLOAD_URL { get { return "https://api.liangxiegame.com/qf/v4/package/add"; } } public static void DoUpload(PackageVersion packageVersion, System.Action succeed) { EditorUtility.DisplayProgressBar("插件上传", "打包中...", 0.1f); var fileName = packageVersion.Name + "_" + packageVersion.Version + ".unitypackage"; var fullpath = ExportPaths(fileName, packageVersion.IncludeFileOrFolders.ToArray()); var file = File.ReadAllBytes(fullpath); var form = new WWWForm(); form.AddField("username", User.Username.Value); form.AddField("password", User.Password.Value); form.AddField("name", packageVersion.Name); form.AddField("version", packageVersion.Version); form.AddBinaryData("file", file); form.AddField("releaseNote", packageVersion.Readme.content); form.AddField("installPath", packageVersion.InstallPath); form.AddField("accessRight", packageVersion.AccessRight.ToString().ToLower()); form.AddField("docUrl", packageVersion.DocUrl); if (packageVersion.Type == PackageType.FrameworkModule) { form.AddField("type", "fm"); } else if (packageVersion.Type == PackageType.Shader) { form.AddField("type", "s"); } else if (packageVersion.Type == PackageType.AppOrGameDemoOrTemplate) { form.AddField("type", "agt"); } else if (packageVersion.Type == PackageType.Plugin) { form.AddField("type", "p"); } else if (packageVersion.Type == PackageType.Master) { form.AddField("type", "master"); } Log.I(fullpath); EditorUtility.DisplayProgressBar("插件上传", "上传中...", 0.2f); EditorHttp.Post(UPLOAD_URL, form, (response) => { if (response.Type == ResponseType.SUCCEED) { EditorUtility.ClearProgressBar(); Log.I(response.Text); if (succeed != null) { succeed(); } File.Delete(fullpath); } else { EditorUtility.ClearProgressBar(); EditorUtility.DisplayDialog("插件上传", string.Format("上传失败!{0}", response.Error), "确定"); File.Delete(fullpath); } }); } private static readonly string EXPORT_ROOT_DIR = Path.Combine(Application.dataPath, "../"); public static string ExportPaths(string exportPackageName, params string[] paths) { var filePath = Path.Combine(EXPORT_ROOT_DIR, exportPackageName); AssetDatabase.ExportPackage(paths, filePath, ExportPackageOptions.Recurse); AssetDatabase.Refresh(); return filePath; } } }
36.032967
105
0.539189
8da864a5f09dd141d9fce28ce71f888d1364158b
1,688
js
JavaScript
Gulpfile.js
thegurucompany/clicktocall-widget
90203a1abe6451ba2e8ac79a35c37fd0aa4ec87a
[ "MIT" ]
null
null
null
Gulpfile.js
thegurucompany/clicktocall-widget
90203a1abe6451ba2e8ac79a35c37fd0aa4ec87a
[ "MIT" ]
2
2021-03-09T09:55:48.000Z
2022-03-02T04:35:18.000Z
Gulpfile.js
thegurucompany/clicktocall-widget
90203a1abe6451ba2e8ac79a35c37fd0aa4ec87a
[ "MIT" ]
null
null
null
const gulp = require('gulp') const babel = require('gulp-babel') const notify = require('gulp-notify') const concat = require('gulp-concat') const uglify = require('gulp-uglify') const standard = require('gulp-standard') const sourcemaps = require('gulp-sourcemaps') const stylish = require('jshint-stylish') const webpack = require('webpack-stream') const del = require('del') const argv = require('yargs').argv const pckg = require('./package.json') const modulePath = './node_modules' const distFolder = 'dist' const srcFilesPattern = './src/**/*.js' const testFilesPattern = './test/**/*.js' let isProduction = (argv.production === undefined) ? false : true; gulp.task('lint', () => { gulp.src([ srcFilesPattern, testFilesPattern ]) .pipe(standard()) .pipe(standard.reporter('default', { breakOnError: false, quiet: true, showRuleNames: true })) }) gulp.task('build', () => { let jsPipe = gulp.src('./src/widget.js') .pipe(webpack()) .pipe(babel({ presets: ['es2015'] })) if (!isProduction) { jsPipe = jsPipe.pipe(sourcemaps.init()) } jsPipe = jsPipe.pipe(concat(`widget-${pckg.version}.js`)) if (isProduction) { jsPipe = jsPipe.pipe(uglify()) } else{ jsPipe = jsPipe.pipe(sourcemaps.write()) } return jsPipe.pipe(gulp.dest(`./${distFolder}/js`)) .pipe(notify('JS processed')) }) gulp.task('watch', ['lint', 'build'], () => { gulp.watch(srcFilesPattern, ['build']) gulp.watch([srcFilesPattern, testFilesPattern], ['lint']) }) gulp.task('clean', () => { return del([`./${distFolder}`]) }) gulp.task('default', ['clean'], () =>{ gulp.start('lint') gulp.start('build') })
25.969231
66
0.633294
79ad34560920610adfede6c9dd622cc43161d161
515
php
PHP
resources/views/confirm.blade.php
nupagachi/trainning_para
d9a6a935fb27fc962d0ccc506b9ae823a821106d
[ "MIT" ]
null
null
null
resources/views/confirm.blade.php
nupagachi/trainning_para
d9a6a935fb27fc962d0ccc506b9ae823a821106d
[ "MIT" ]
5
2021-03-09T15:35:50.000Z
2022-02-26T16:51:29.000Z
resources/views/confirm.blade.php
nupagachi/trainning_para
d9a6a935fb27fc962d0ccc506b9ae823a821106d
[ "MIT" ]
null
null
null
<p>Click the button to demonstrate line-breaks in a confirm box.</p> <a onclick="myFunction()">Try it</a> <p id="demo"></p> <script> function myFunction() { var txt; var r = confirm("Press a button!\nEither OK or Cancel.\nThe button you pressed will be displayed in the result window."); if (r == true) { txt = "You pressed OK!"; } else { txt = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = txt; } </script>
25.75
129
0.572816
48afb63de42ed55b2c8ce994226849284bfbad83
1,112
sql
SQL
AspNetCoreMVCExample.DB/dbo/Tables/AspNetUsers.sql
truedeity/AspNetCoreMVCExample
6bd0a0fac3edcb3aa8204638b5ff7bbe221f3068
[ "MIT" ]
1
2017-09-11T14:30:37.000Z
2017-09-11T14:30:37.000Z
AspNetCoreMVCExample.DB/dbo/Tables/AspNetUsers.sql
truedeity/AspNetCoreMVCExample
6bd0a0fac3edcb3aa8204638b5ff7bbe221f3068
[ "MIT" ]
null
null
null
AspNetCoreMVCExample.DB/dbo/Tables/AspNetUsers.sql
truedeity/AspNetCoreMVCExample
6bd0a0fac3edcb3aa8204638b5ff7bbe221f3068
[ "MIT" ]
null
null
null
CREATE TABLE [dbo].[AspNetUsers] ( [Id] NVARCHAR (450) NOT NULL, [AccessFailedCount] INT NOT NULL, [ConcurrencyStamp] NVARCHAR (MAX) NULL, [Email] NVARCHAR (256) NULL, [EmailConfirmed] BIT NOT NULL, [LockoutEnabled] BIT NOT NULL, [LockoutEnd] DATETIMEOFFSET (7) NULL, [NormalizedEmail] NVARCHAR (256) NULL, [NormalizedUserName] NVARCHAR (256) NULL, [PasswordHash] NVARCHAR (MAX) NULL, [PhoneNumber] NVARCHAR (MAX) NULL, [PhoneNumberConfirmed] BIT NOT NULL, [SecurityStamp] NVARCHAR (MAX) NULL, [TwoFactorEnabled] BIT NOT NULL, [UserName] NVARCHAR (256) NULL, CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC) ); GO CREATE NONCLUSTERED INDEX [EmailIndex] ON [dbo].[AspNetUsers]([NormalizedEmail] ASC); GO CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex] ON [dbo].[AspNetUsers]([NormalizedUserName] ASC);
37.066667
64
0.558453
4d0511bc073909fe88d0bfc9adfed8a1e7628967
2,643
cs
C#
PDTools.Compression/PDIZIP.cs
Nenkai/PDTools
2235af1f01b7aa2424c3113b41cbd60eff52dbca
[ "MIT" ]
3
2021-06-26T17:57:46.000Z
2021-11-08T20:05:01.000Z
PDTools.Compression/PDIZIP.cs
Nenkai/PDTools
2235af1f01b7aa2424c3113b41cbd60eff52dbca
[ "MIT" ]
null
null
null
PDTools.Compression/PDIZIP.cs
Nenkai/PDTools
2235af1f01b7aa2424c3113b41cbd60eff52dbca
[ "MIT" ]
null
null
null
using Syroot.BinaryData; using System; using System.Buffers; using System.IO; using System.IO.Compression; using System.Numerics; using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Zip.Compression; namespace PDTools.Compression { public class PDIZIP { public const uint PDIZIP_MAGIC = 0xFF_F7_F3_2F; public static bool Inflate(Stream input, Stream output, bool skipMagic = false) { if (!skipMagic && input.ReadUInt32() == PDIZIP_MAGIC) return false; // Read PDIZIP Header uint expand_size = input.ReadUInt32(); uint compressed_size = input.ReadUInt32(); uint fragment_size = input.ReadUInt32(); int method = input.ReadInt32(); input.ReadInt32s(3); // Calculate the fragment (or chunk) count for the file uint fragmentCount = (compressed_size + fragment_size - 1) / fragment_size; // Set up inflater and buffers Inflater inflater = new Inflater(true); byte[] fragment_buffer = ArrayPool<byte>.Shared.Rent((int)fragment_size); byte[] expand_buffer = ArrayPool<byte>.Shared.Rent(0x20000); for (uint i = 0; i < fragmentCount; i++) { if (input.ReadUInt32() != PDIZIP_MAGIC) throw new Exception("PDIZip Fragment magic did not match expected magic."); // Read Fragment header uint fragmentExpandSize = input.ReadUInt32(); uint fragmentCompressedSize = input.ReadUInt32(); uint Unk = input.ReadUInt32(); // Only way to do it properly apparently, inflate streams read too much data input.Read(fragment_buffer, 0, (int)fragmentCompressedSize); inflater.SetInput(fragment_buffer, 0, (int)fragmentCompressedSize); while (!inflater.IsFinished) { int inflated = inflater.Inflate(expand_buffer); output.Write(expand_buffer, 0, inflated); } // Crypto stream can't seek, so just manually move.. int left = (int)(fragment_size - fragmentCompressedSize) - 0x10; if (i == 0) left -= 0x20; while (left-- > 0) input.ReadByte(); inflater.Reset(); // Prepare for next chunk } ArrayPool<byte>.Shared.Return(fragment_buffer); ArrayPool<byte>.Shared.Return(expand_buffer); return output.Length == expand_size; } } }
36.205479
95
0.582671
0d75b6629430ec61ecdb20df707e66295d057fa2
10,456
h
C
napoca/include/boot/vmstate.h
fengjixuchui/napoca
ed26609ab9a3ea12d12882b311dcb332dc759d32
[ "Apache-2.0" ]
170
2020-07-30T15:04:59.000Z
2022-03-24T10:59:29.000Z
napoca/include/boot/vmstate.h
a-cristi/napoca
ed6691125bf703366581e47a1fe789167009c24a
[ "Apache-2.0" ]
3
2020-08-10T09:16:56.000Z
2022-02-18T21:40:43.000Z
napoca/include/boot/vmstate.h
a-cristi/napoca
ed6691125bf703366581e47a1fe789167009c24a
[ "Apache-2.0" ]
44
2020-07-30T15:06:55.000Z
2022-02-25T08:55:55.000Z
/* * Copyright (c) 2020 Bitdefender * SPDX-License-Identifier: Apache-2.0 */ /** @file vmstate.h * @brief VMCS configuration APIs * * A mechanism for handling the configuration of a VMCS. It ensures the integrity of the VMCS state. * The api configures the VMCS structure in 3 independent stages: * - VMCS Guest state configuration * - VMCS Control Fields state configuration * - VMCS Host state configuration * * Each stage can be bypassed/customized by setting the appropriate option * in the VMCS_CONFIGURE_SETTINGS structure supplied to the interface. * */ /// \defgroup vmcs VMCS handling support /// @{ #ifndef __VMSTATE_H__ #define __VMSTATE_H__ #include "core.h" typedef struct _VCPU VCPU; /** @name Structures and definitions used to drive the vmcs configuration logic */ ///@{ /// @brief Bypasses/configures the way the vmcs guest fields should be set. typedef enum _VMCS_GUEST_STATE_OPTIONS { VMCS_GUEST_NO_UPDATE, ///< The guest state in the vmcs is not modified. VMCS_GUEST_BOOT_STATE, ///< The guest state in the vmcs is set according to the boot option. For UEFI the boot state is retrieved for ech CPU for Legacy boot the bsp is placed in 16 bit real mode with the rip pointing to the first boot sector and APs are in wait for sipi state. VMCS_GUEST_REAL_MODE ///< The guest state in the vmcs is set to real mode. Cs, Ip, Ss, Sp and the active state are loaded from the supplied VMCS_GUEST_REAL_MODE_PARAMETERS structure. } VMCS_GUEST_OPTIONS; /// @brief Bypasses/configures the way the vmcs control fields should be set. typedef enum _VMCS_CONTROLS_STATE_OPTIONS { VMCS_CONTROLS_NO_UPDATE, ///< The control fields in the vmcs are not modified. VMCS_CONTROLS_APPLY_CHANGES_ONLY, ///< The control fields are updated with the requested features VMCS_CONTROLS_RESET_ONLY, ///< The control fields are reset to default values VMCS_CONTROLS_RESET_AND_CHANGES, ///< The control fields are set to default and requested features are applied VMCS_CONTROLS_CUSTOM ///< The control fields in the vmcs are set according to the custom state supplied } VMCS_CONTROLS_OPTIONS; /// @brief Bypasses/configures the way the vmcs host fields should be set. typedef enum _VMCS_HOST_STATE_OPTIONS { VMCS_HOST_NO_UPDATE, ///< The host state in the vmcs is not modified. VMCS_HOST_DEFAULT ///< The host state in the vmcs is set to the current values of the HV. } VMCS_HOST_OPTIONS; /// @brief Identifies the logical processor's activity state. typedef enum _VMCS_GUEST_ACTIVITY_STATE_VALUE { VMCS_GUEST_ACTIVITY_STATE_ACTIVE = 0, ///< The logical processor is executing instructions normally. VMCS_GUEST_ACTIVITY_STATE_HLT = 1, ///< The logical processor is inactive because it executed the HLT instruction. VMCS_GUEST_ACTIVITY_STATE_SHUTDOWN = 2, ///< The logical processor is inactive because it incurred a triple fault or some other serious error. VMCS_GUEST_ACTIVITY_STATE_WAIT_FOR_SIPI = 3 ///< The logical processor is inactive because it is waiting for a startup-IPI (SIPI). } VMCS_GUEST_ACTIVITY_STATE_VALUE; /** * @brief For VMCS_GUEST_REAL_MODE this structure determines the CS:IP address at which the * guest will run, the SS:SP address for the guest stack and the guest activity state. */ typedef struct _VMCS_GUEST_REAL_MODE_STATE { // The CS:IP address for the guest CX_UINT16 Cs; CX_UINT16 Ip; // The SS:SP address for the guest's stack CX_UINT16 Ss; CX_UINT16 Sp; VMCS_GUEST_ACTIVITY_STATE_VALUE ActivityState; } VMCS_GUEST_REAL_MODE_STATE; /// @brief The requested state for a particular control field feature typedef enum _VMCS_CONTROL_FEATURE_STATE { VMCS_CONTROL_FEATURE_NO_UPDATE, ///< No action needed VMCS_CONTROL_FEATURE_ENABLE, ///< Enable the specified features VMCS_CONTROL_FEATURE_DISABLE ///< Disable the specified features } VMCS_CONTROL_FEATURE_STATE; /** * @brief If the #VMCS_CONTROLS_CUSTOM option is set, * the Control Field state is configured according to the required features */ typedef struct _VMCS_CONTROL_FEATURE_CONFIGURATION { struct FeaturePreemptionTimer { VMCS_CONTROL_FEATURE_STATE PreemptionTimerEnableState; VMCS_CONTROL_FEATURE_STATE PreemptionTimerSaveState; }; VMCS_CONTROL_FEATURE_STATE FeatureCr3LoadExit; VMCS_CONTROL_FEATURE_STATE FeatureDescriptorExit; VMCS_CONTROL_FEATURE_STATE FeatureExitOnHalt; VMCS_CONTROL_FEATURE_STATE FeatureExitAllIoPorts; VMCS_CONTROL_FEATURE_STATE FeatureExitAllMsrs; VMCS_CONTROL_FEATURE_STATE FeatureSpptp; VMCS_CONTROL_FEATURE_STATE FeatureBreakpointExit; VMCS_CONTROL_FEATURE_STATE FeatureVeInfoPageSet; CX_UINT64 FeatureVeInfoPageHpa; } VMCS_CONTROL_FEATURE_CONFIGURATION; /// @brief Used to differentiate between VMCS_GUEST_CUSTOM custom state and VMCS_GUEST_REAL_MODE custom state. typedef union _VMCS_GUEST_CONFIGURATION { VMCS_GUEST_REAL_MODE_STATE RealModeState; ///< Used with VMCS_GUEST_REAL_MODE option. Describes the guest's real mode state. } VMCS_GUEST_CONFIGURATION; /// @brief Structure used for customizing the resulting VMCS state typedef struct _VMCS_CONFIGURE_SETTINGS { union { struct { CX_UINT8 InitVmcs : 1; ///< Determines the clearing of the Vmcs structure and related cached information in the corresponding vcpu structure CX_UINT8 ActivateGuestDomain : 1; ///< Determines the setting of ept domain CX_UINT8 ClearVmcsFromCpu : 1; ///< Apply vmclear if set CX_UINT8 SetNewVmcs : 1; ///< Apply vmptrld on the VCPU specific vmcs area }; CX_UINT8 VmcsRawUpdateOptions; }; struct VmcsGuestSettings { VMCS_GUEST_OPTIONS GuestOptions; ///< Determines the way in which the vmcs guest state is set VMCS_GUEST_CONFIGURATION GuestConfig; }; struct VmcsControlSettings { VMCS_CONTROLS_OPTIONS ControlsOptions; VMCS_CONTROL_FEATURE_CONFIGURATION ControlsConfigState; }; VMCS_HOST_OPTIONS HostOptions; } VMCS_CONFIGURE_SETTINGS; ///@} /** @name Presets for VMCS_CONFIGURE_SETTINGS structure */ ///@{ /// @brief Default value for creating the boot vmcs structure #define VMCS_CONFIGURE_SETTINGS_BOOT &(VMCS_CONFIGURE_SETTINGS){ \ .InitVmcs = CX_TRUE, \ .ActivateGuestDomain = CX_TRUE, \ .GuestOptions = VMCS_GUEST_BOOT_STATE, \ .ControlsOptions = VMCS_CONTROLS_RESET_ONLY, \ .HostOptions = VMCS_HOST_DEFAULT, \ .ClearVmcsFromCpu = CX_TRUE, \ .SetNewVmcs = CX_TRUE \ } /// @brief Update only the host state in the given Vcpu, everything else stays the same #define VMCS_CONFIGURE_SETTINGS_INIT_HOST_STATE &(VMCS_CONFIGURE_SETTINGS){ \ .InitVmcs = CX_FALSE, \ .ActivateGuestDomain = CX_FALSE, \ .GuestOptions = VMCS_GUEST_NO_UPDATE, \ .ControlsOptions = VMCS_CONTROLS_NO_UPDATE, \ .HostOptions = VMCS_HOST_DEFAULT, \ .ClearVmcsFromCpu = CX_FALSE, \ .SetNewVmcs = CX_TRUE \ } ///@} /** * @brief Interface exposed by the algorithm for managing the configuration of a vmcs structure. * * @param[in] Vcpu Pointer to a VCPU structure. * @param[in] Options Pointer to a VMCS_CONFIGURE_SETTINGS structure. Used to guide the vmcs creation logic. * * @retval CX_STATUS_SUCCESS The control fields have successfully been flushed to vmcs. * @retval CX_STATUS_INVALID_PARAMETER_1 The given Vcpu pointer is invalid. * @retval CX_STATUS_INVALID_PARAMETER_2 The given Options pointer is invalid. * @retval CX_STATUS_INVALID_DATA_STATE Vmclear or vmptrld instructions failed. * @retval otherwise The algorithm failed internally. */ CX_STATUS VmstateConfigureVmcs( _In_ VCPU* Vcpu, _In_ VMCS_CONFIGURE_SETTINGS *Options ); /** * @brief Controls the activating of the NMI window exiting VMCS feature. Used for injection of pending NMIs. * * @param[in] Enable TRUE to enable NMI window exiting, FALSE otherwise */ VOID VmstateControlNMIWindowExiting( _In_ BOOLEAN Enable ); /** * @brief Routine that update vmcs according to the requirements of the Introspection Engine * * Introspection may have some preferences on how to configure the vmcs. * For example: they may want exits on CR3 changes, exits on breakpoints, activated \c \#VE feature, etc. * * @param[in] Vcpu Pointer to a VCPU structure. * @param[in] Force If TRUE, apply the changes on the selected VCPU even if in the bitmask where the VCPUs to which the intro requests are to be applied are specified, this vcpu is not selected * @param[in] LoadAndClearVmcsFromCpu Set to TRUE if VMCS is to be cleared from and loaded in the current VCPU, FALSE otherwise * * @retval CX_STATUS_SUCCESS Update performed without errors * @retval other error statuses that may come from the VmstateConfigureVmcs function call */ CX_STATUS VmstateUpdateVmcsForIntrospection( _In_ VCPU* Vcpu, _In_ CX_BOOL Force, _In_ CX_BOOL LoadAndClearVmcsFromCpu ); /// @} #endif //__VMSTATE_H__
43.932773
292
0.653405
dbb21684e7d9e0cbf8d31eddd9442ca044a60703
7,497
php
PHP
resources/views/layouts/nav.blade.php
BaenaMaria/Matricula
4a1b418df9661c91dcd9c923ef787496732006ea
[ "MIT" ]
null
null
null
resources/views/layouts/nav.blade.php
BaenaMaria/Matricula
4a1b418df9661c91dcd9c923ef787496732006ea
[ "MIT" ]
null
null
null
resources/views/layouts/nav.blade.php
BaenaMaria/Matricula
4a1b418df9661c91dcd9c923ef787496732006ea
[ "MIT" ]
null
null
null
<nav id="nav"> <div class="--nav_primary"> <div class="--logo"> <a href="{{route('home')}}"> <img src="{{ URL::to('/') }}/images/svg/edase.svg" alt=""> </a> </div> <div class="--menu"> <ul class="--menu_list"> <li class="--menu_list_item --menu_list_item_desp" data="1" data-order="1">titulaciones</li> <li class="--menu_list_item --menu_list_item_desp" data="2" data-order="2">la escuela</li> {{-- <li class="--menu_list_item --menu_list_item_desp" data="3" data-order="3">plan de carrera</li> --}} <li class="--menu_list_item" data-order="4"><a href="{{route('becas')}}">becas y admisión</a></li> </ul> <p class="--phone_tablet"><a href="tel:900 866 336">900 866 336</a></p> <p class="--acceder_mobile"><a href="">Acceder</a></p> </div> <div class="--submenu"> <ul class="--submenu_list"> <li class="--submenu_list_item"><a href=""><b>acceder</b></a></li> <li class="--submenu_list_item --menu_list_item_desp" data="rrss">redes sociales</li> <li class="--submenu_list_item"><a href="tel:900 866 336"><b>900 866 336</b></a></li> </ul> </div> <div class="--icon_menu"> <div class="--icon_menu_line"></div> <div class="--icon_menu_line"></div> <div class="--icon_menu_line"></div> </div> </div> <div class="--desplegable"> <div class="--mascara"></div> <ul class="--deplegable_list --visible" data="1"> <a href="{{route('master')}}"> <li class="--desplegable_list_item"> Master Asesor Experto </li> </a> <a href="{{route('mba')}}"> <li class="--desplegable_list_item"> MBA </li> </a> <a href="{{route('tecnico')}}"> <li class="--desplegable_list_item"> Técnico Asesoría </li> </a> </ul> <ul class="--deplegable_list" data="2"> <a href="{{route('conocenos')}}"> <li class="--desplegable_list_item"> Conócenos </li> </a> <a href="{{route('metodologia')}}"> <li class="--desplegable_list_item"> Metodología </li> </a> </ul> <ul class="--deplegable_list" data="3"> <li class="--desplegable_list_item">Lorem ipsum 3</li> <li class="--desplegable_list_item">Lorem ipsum</li> <li class="--desplegable_list_item">Lorem ipsum</li> </ul> <ul class="--deplegable_list" data="rrss"> <a href="https://www.instagram.com/escueladeasesores_/" target="_blank"> <li class="--desplegable_list_item">Instagram</li> </a> <a href="https://www.linkedin.com/company/edase-escuela-de-asesores-de-ayuda-t-pymes" target="_blank"> <li class="--desplegable_list_item">LinkedIn</li> </a> <a href="https://www.tiktok.com/@edase_escuela" target="_blank"> <li class="--desplegable_list_item">Tik tok</li> </a> <a href="https://www.facebook.com/escueladeasesores/" target="_blank"> <li class="--desplegable_list_item">Facebook</li> </a> <a href="https://wa.link/zgjqi0" target="_blank"> <li class="--desplegable_list_item">Whatsapp</li> </a> </ul> </div> <div class="--content_menu"> <ul class="--links --open_menu --left_menu" data-select="1"> <li> HOME </li> <li class="--content_menu_link" data-link="2"> TITULACIONES </li> <li class="--content_menu_link" data-link="3"> LA ESCUELA </li> {{-- <li class="--content_menu_link" data-link="4"> PLANES DE CARRERA </li> --}} <li class="--content_menu_link"> <a href="{{route('becas')}}"> BECAS Y ADMINISIONES </a> </li> <li class="--content_menu_link" data-link="6"> RRSS </li> </ul> <ul class="--links" data-select="2"> <li class="--return">< Volver</li> <a href="{{route('master')}}"> <li> Master Asesor Experto </li> </a> <a href="{{route('mba')}}"> <li> MBA </li> </a> <a href="{{route('tecnico')}}"> <li> Técnico Asesoría </li> </a> </ul> <ul class="--links" data-select="3"> <li class="--return">< Volver</li> <a href="{{route('conocenos')}}"> <li> Conócenos </li> </a> <a href="{{route('metodologia')}}"> <li> Metodología </li> </a> </ul> <ul class="--links" data-select="4"> <li class="--return">< Volver</li> <li>Lorem ipsum</li> <li>Lorem ipsum</li> <li>Lorem ipsum</li> <li>Lorem ipsum</li> </ul> <ul class="--links" data-select="5"> <li class="--return">< Volver</li> <li>Lorem ipsum</li> <li>Lorem ipsum</li> <li>Lorem ipsum</li> <li>Lorem ipsum</li> </ul> <ul class="--links" data-select="6"> <li class="--return">< Volver</li> <a href="https://www.instagram.com/escueladeasesores_/" target="_blank"> <li>Instagram</li> </a> <a href="https://www.linkedin.com/company/edase-escuela-de-asesores-de-ayuda-t-pymes" target="_blank"> <li>LinkedIn</li> </a> <a href="https://www.tiktok.com/@edase_escuela" target="_blank"> <li>Tik tok</li> </a> <a href="https://www.facebook.com/escueladeasesores/" target="_blank"> <li>Facebook</li> </a> <a href="https://wa.link/zgjqi0" target="_blank"> <li>Whatsapp</li> </a> </ul> </div> </nav> <div class="--llamar_mobile"> <p><a href="tel:900 866 336">LLAMAR AHORA</a></p> </div>
41.882682
125
0.403762
f2b8ca16259654bb78410528a1c1242cfcc9e851
340
lua
Lua
resources/[qb]/qb-bossmenu/config.lua
p4zinee/server-data
b523650fc4b5a3465c7ffc1dde7330a16bb62d05
[ "CC0-1.0" ]
1
2022-01-05T15:17:06.000Z
2022-01-05T15:17:06.000Z
resources/[qb]/qb-bossmenu/config.lua
p4zinee/server-data
b523650fc4b5a3465c7ffc1dde7330a16bb62d05
[ "CC0-1.0" ]
null
null
null
resources/[qb]/qb-bossmenu/config.lua
p4zinee/server-data
b523650fc4b5a3465c7ffc1dde7330a16bb62d05
[ "CC0-1.0" ]
null
null
null
Config = {} Config.Jobs = { ['police'] = vector3(448.4, -973.2, 30.6), ['ambulance'] = vector3(270.5, -1363.0, 23.5), ['realestate'] = vector3(-124.786, -641.486, 167.820), ['taxi'] = vector3(903.32, -170.55, 74.0), ['cardealer'] = vector3(-32.0, -1114.2, 25.4), ['mechanic'] = vector3(-342.291, -133.370, 39.009) }
34
58
0.547059
8c4f99c3f4b32d2d47ed0a078e9505c9c2dcdd69
8,250
lua
Lua
5dim_equipment/prototypes/gen-energy-shield-equipment.lua
JuanignacioX10X/Factorio5DimMods
d5bc0fa18527aa9532608c54ed7d9f2ca5fa60e0
[ "MIT" ]
null
null
null
5dim_equipment/prototypes/gen-energy-shield-equipment.lua
JuanignacioX10X/Factorio5DimMods
d5bc0fa18527aa9532608c54ed7d9f2ca5fa60e0
[ "MIT" ]
null
null
null
5dim_equipment/prototypes/gen-energy-shield-equipment.lua
JuanignacioX10X/Factorio5DimMods
d5bc0fa18527aa9532608c54ed7d9f2ca5fa60e0
[ "MIT" ]
null
null
null
require("__5dim_core__.lib.equipment.generation-energy-shield-equipment") local bufferCapacity = 120 local energyShield = 20 local shield = 50 local input = 240 local techCount = 200 -- Beacon 01 genEnergyShields { number = "01", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = false, order = "a", ingredients = { {"advanced-circuit", 5}, {"steel-plate", 10} }, tech = nil } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 02 genEnergyShields { number = "02", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = false, order = "b", ingredients = { {"energy-shield-equipment", 10}, {"processing-unit", 5}, {"low-density-structure", 5} }, tech = nil } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 03 genEnergyShields { number = "03", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "c", ingredients = { {"energy-shield-mk2-equipment", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 1, count = techCount * 2, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1} }, prerequisites = { "energy-shield-mk2-equipment" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 04 genEnergyShields { number = "04", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "d", ingredients = { {"5d-energy-shield-equipment-03", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 2, count = techCount * 3, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-1" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 05 genEnergyShields { number = "05", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "e", ingredients = { {"5d-energy-shield-equipment-04", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 3, count = techCount * 4, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-2" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 06 genEnergyShields { number = "06", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "f", ingredients = { {"5d-energy-shield-equipment-05", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 4, count = techCount * 5, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1}, {"space-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-3" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 07 genEnergyShields { number = "07", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "g", ingredients = { {"5d-energy-shield-equipment-06", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 5, count = techCount * 6, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1}, {"space-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-4" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 08 genEnergyShields { number = "08", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "h", ingredients = { {"5d-energy-shield-equipment-07", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 6, count = techCount * 7, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1}, {"space-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-5" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 09 genEnergyShields { number = "09", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "i", ingredients = { {"5d-energy-shield-equipment-08", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 7, count = techCount * 8, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1}, {"space-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-6" } } } bufferCapacity = bufferCapacity + 60 energyShield = energyShield + 10 shield = shield * 2 input = input + 120 -- Beacon 10 genEnergyShields { number = "10", subgroup = "armor-shield", capacity = bufferCapacity, energyPerShield = energyShield, shieldCapacity = shield, inputFlow = input, new = true, order = "j", ingredients = { {"5d-energy-shield-equipment-09", 2}, {"processing-unit", 15}, {"low-density-structure", 5} }, tech = { number = 8, count = techCount * 9, packs = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"military-science-pack", 1}, {"utility-science-pack", 1}, {"space-science-pack", 1} }, prerequisites = { "5d-energy-shield-equipment-7" } } }
24.193548
73
0.545333
642b03514aa01a3fc1ab774281df2701a42ff782
427
py
Python
papier/helper.py
shiroyuki/papier
4a39c3f38419dd19f84dca7b3ccec83933501dde
[ "MIT" ]
null
null
null
papier/helper.py
shiroyuki/papier
4a39c3f38419dd19f84dca7b3ccec83933501dde
[ "MIT" ]
1
2016-08-08T02:24:23.000Z
2016-08-08T02:24:23.000Z
papier/helper.py
shiroyuki/papier
4a39c3f38419dd19f84dca7b3ccec83933501dde
[ "MIT" ]
null
null
null
import os import papier _base_path = os.path.dirname(papier.__file__) def path(*level): global _base_path primary = os.path.abspath(os.path.join(_base_path, *level)) secondary = os.path.abspath(os.path.join(_base_path, '..', *level)) local = os.path.abspath(os.path.join(*level)) return local if os.path.exists(local) else ( secondary if os.path.exists(secondary) else primary )
25.117647
71
0.672131
3a95dba3bb1956b0fa092f23dd2929e4f29b11ee
1,643
swift
Swift
Graph(DFS & BFS)/파이프 옮기기 1.swift
GeonHyeong5036/AlgoriGym
ed268ac3b90efb559b5d318f1a1389866bcdc1d5
[ "MIT" ]
5
2020-02-01T08:31:50.000Z
2020-08-10T04:17:07.000Z
Graph(DFS & BFS)/파이프 옮기기 1.swift
GeonHyeong5036/AlgoriGym
ed268ac3b90efb559b5d318f1a1389866bcdc1d5
[ "MIT" ]
null
null
null
Graph(DFS & BFS)/파이프 옮기기 1.swift
GeonHyeong5036/AlgoriGym
ed268ac3b90efb559b5d318f1a1389866bcdc1d5
[ "MIT" ]
2
2020-07-26T09:32:42.000Z
2021-08-03T10:10:43.000Z
// // 파이프 옮기기 1.swift // Question Link: https://www.acmicpc.net/problem/17070 // Primary idea: (BFS) // 1. BFS로 queue와 while을 활용한다. // 2. 위치 정보와 가로(0)/세로(1)/대각선(2)을 표시하는 방향 정보를 queue에 저장한다. // 3. queue의 앞에서 하나씩 불러오며 3가지의 방향을 진행한다. // 4. 가로(0) -> 세로(1), 세로(1) -> 가로(0)는 갈 수 없으므로 합이 1일 때는 제외한다. // 5. 대각선(2)일 때는 걸치는 부분이 모두 1이 아닌지를 체크한다. // 6. 모두 만족하면 queue에 저장한다. // // Time Complexity : O(n^n) // Space Complexity : O(n^2) // Runtime: ms // Memory Usage: MB // // Created by gunhyeong on 2020/08/07. // import Foundation let size = Int(readLine()!)! var map = [[Int]]() for _ in 0..<size { let input = readLine()!.split(separator: " ").map{Int($0)!} map.append(input) } let dirs = [[0, 1], [1, 0], [1, 1]] var answer = 0 var queue = [(Int, Int, Int)]() queue.append((0, 1, 0)) while !queue.isEmpty { let cur = queue.removeFirst() let x = cur.0 let y = cur.1 let direction = cur.2 if x == size - 1 && y == size - 1 { answer += 1 continue } for (i, dir) in dirs.enumerated() { let x = x + dir.first! let y = y + dir.last! if (direction + i) == 1 { continue } // (row -> col) or (col -> row) if x >= size || y >= size || map[x][y] == 1 { continue } if i == 2 { // cross if map[x-1][y] == 0 && map[x][y-1] == 0 { queue.append((x, y, i)) } } else { queue.append((x, y, i)) } } } print(answer)
25.276923
82
0.458917
c6d2820ae10f65c8a0c179e51bbdab63108a239a
380
rb
Ruby
db/migrate/20140106042845_create_rsvp_invitations.rb
ryanricard/rsvp
c646b9bbf8550efb67d5152518d24841ccd8ab96
[ "MIT" ]
1
2015-02-23T18:38:33.000Z
2015-02-23T18:38:33.000Z
db/migrate/20140106042845_create_rsvp_invitations.rb
ryanricard/rsvp
c646b9bbf8550efb67d5152518d24841ccd8ab96
[ "MIT" ]
null
null
null
db/migrate/20140106042845_create_rsvp_invitations.rb
ryanricard/rsvp
c646b9bbf8550efb67d5152518d24841ccd8ab96
[ "MIT" ]
null
null
null
class CreateRsvpInvitations < ActiveRecord::Migration def change create_table :rsvp_invitations do |t| t.integer :family_id t.string :salutation_type, :limit => 50 t.string :salutation t.string :rsvp_code, :limit => 20 t.integer :total_invited t.timestamps end add_index :rsvp_invitations, :rsvp_code, :unique => true end end
23.75
60
0.678947
b01006bd69fc6bb95ef9721887f70732293c617d
2,099
py
Python
sv_tracker/gui/graphs/cost_breakdown_frame.py
nekusakaki/svtxd
0956de45aee4f7c79c3e484256843c52a7d17f56
[ "MIT" ]
1
2020-10-22T14:12:12.000Z
2020-10-22T14:12:12.000Z
sv_tracker/gui/graphs/cost_breakdown_frame.py
nekusakaki/svtxd
0956de45aee4f7c79c3e484256843c52a7d17f56
[ "MIT" ]
null
null
null
sv_tracker/gui/graphs/cost_breakdown_frame.py
nekusakaki/svtxd
0956de45aee4f7c79c3e484256843c52a7d17f56
[ "MIT" ]
null
null
null
from tkinter import * import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import sv_tracker.helper_functions as hf class CostBreakdownFrame(Frame): def __init__(self, master, deck): self.cost_breakdown = deck.cost_breakdown() super().__init__(master, width=150, height=150) self.cost_chart = self.generate_graph() def generate_graph(self): follower_counts = [] amulet_counts = [] spell_counts = [] for index, cost in enumerate(self.cost_breakdown): follower_count = self.cost_breakdown[cost][0] amulet_count = self.cost_breakdown[cost][1] spell_count = self.cost_breakdown[cost][2] follower_counts.append(follower_count) amulet_counts.append(amulet_count) spell_counts.append(spell_count) fa_counts = [x + y for x, y in zip(follower_counts, amulet_counts)] labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8+'] width = 0.9 fig = plt.Figure(figsize=(2, 2), dpi=75) ax = fig.subplots() ax.bar(labels, follower_counts, width, color='#333399', label='Followers') ax.bar(labels, amulet_counts, width, bottom=follower_counts, color='#339900', label='Amulets') ax.bar(labels, spell_counts, width, bottom=fa_counts, color='#990033', label='Spells') ax.yaxis.set_visible(False) ax.spines["top"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["right"].set_visible(False) background_color = hf.rgb_to_hex(self.winfo_rgb(self['bg'])) fig.legend() ax.set_facecolor(background_color) ax.set_title('Cost Breakdown') fig.patch.set_facecolor(background_color) cost_chart = FigureCanvasTkAgg(fig, self) cost_chart.get_tk_widget().pack(fill=BOTH) return cost_chart def resize(self, event): self.configure(width=event.width, height=event.width) def destroy(self): plt.close(self.cost_chart.figure) super().destroy()
37.482143
102
0.646975
8546463b3bfa273bb3c89158972658535f98762c
2,400
cshtml
C#
Elections/Views/Candidates/Comment.cshtml
Aurel/rbya_election
a7a057019435825e06419b3bf7a33aaaf144a994
[ "MIT" ]
2
2019-08-02T01:28:47.000Z
2019-08-02T01:32:49.000Z
Elections/Views/Candidates/Comment.cshtml
Aurel/rbya_election
a7a057019435825e06419b3bf7a33aaaf144a994
[ "MIT" ]
null
null
null
Elections/Views/Candidates/Comment.cshtml
Aurel/rbya_election
a7a057019435825e06419b3bf7a33aaaf144a994
[ "MIT" ]
1
2019-08-02T01:35:37.000Z
2019-08-02T01:35:37.000Z
@model Elections.Models.Comment @{ ViewData["Title"] = "Comment"; } <div class="center-block text-center container"> <div class="row" style="margin-bottom:100px;"> <img src="~/images/elections.png" style="margin:auto; width:25%;" /> </div> </div> <h2>Submit a comment for <strong>@Model.Candidate.Name</strong></h2> <p> We want to make sure that the people in the RBYA are strong believers who can be good role models for others. Please leave us a description helping us understand why @Model.Candidate.Name would be a good fit for the RBYA! </p> <p> If they are not a good fit or you believe they would be more detrimental than helpful, please leave a comment but be sure to mark it as negative so that we do not automatically approve the person. </p> <hr /> <div class="row"> <div class="col-md-4"> <form method="post" action="/comment/@Model.Candidate.Id"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Content" class="control-label"></label> <textarea asp-for="Content" class="form-control"></textarea> <span asp-validation-for="Content" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Type" class="control-label"></label> <select asp-for="Type" asp-items="@Html.GetEnumSelectList<Comment.CommentType>()" class="form-control"></select> <span asp-validation-for="Type" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Submitter" class="control-label"></label> <input asp-for="Submitter" class="form-control" /> <span asp-validation-for="Submitter" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="SubmitterEmail" class="control-label"></label> <input asp-for="SubmitterEmail" class="form-control" /> <span asp-validation-for="SubmitterEmail" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-default" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div>
41.37931
200
0.595
2d5d7980d9192567f623d454026b0f4d0b8529bf
25
css
CSS
css/composite/styleguide-80b05f72646235db07a7f693d12e795c.min.css
HexaPlant/hexaplant.github.io
3e6833887c18452bf4f785bf5fb2610a8262f4c1
[ "MIT" ]
null
null
null
css/composite/styleguide-80b05f72646235db07a7f693d12e795c.min.css
HexaPlant/hexaplant.github.io
3e6833887c18452bf4f785bf5fb2610a8262f4c1
[ "MIT" ]
null
null
null
css/composite/styleguide-80b05f72646235db07a7f693d12e795c.min.css
HexaPlant/hexaplant.github.io
3e6833887c18452bf4f785bf5fb2610a8262f4c1
[ "MIT" ]
null
null
null
.styleguide{padding:1em}
12.5
24
0.8
1a518963eef49f782e3b70a2cbe6946224a0c383
2,852
py
Python
purbeurre/database_search.py
Mathiou04/Purbeurre
abf138d79c7b35e6dc3294daaa949a63f9afc000
[ "MIT" ]
null
null
null
purbeurre/database_search.py
Mathiou04/Purbeurre
abf138d79c7b35e6dc3294daaa949a63f9afc000
[ "MIT" ]
7
2020-06-20T20:55:48.000Z
2021-09-22T19:08:56.000Z
purbeurre/database_search.py
Mathiou04/Purbeurre
abf138d79c7b35e6dc3294daaa949a63f9afc000
[ "MIT" ]
1
2020-07-29T11:38:44.000Z
2020-07-29T11:38:44.000Z
from purbeurre.models import Product from django.db.models import Q from collections import Counter class DatabaseSearch: """This class's job is to find categories concerned by the user research and return the best products (in terms of nutri-score) of each category.""" def get_substitutes_per_category(self, search): """This method gets the list of concerned categories from the get_categories_from_search() method, and if it's not empty, builds a list of dictionnaries where each one has the category's name as key and a list of the 6 best products as value.""" cat_subs_list = [] categories = self.get_categories_from_search(search) if categories is None: return None else: for i, cat in enumerate(categories.keys()): cat_subs_list.append({cat: []}) rq = Product.objects.filter( category__name=cat ).order_by('nutriscore')[:6] for r in rq: if r.nutriscore < 'd': cat_subs_list[i][cat].append(r) return cat_subs_list def get_categories_from_search(self, search): products = Product.objects.filter(Q(name__startswith=search.lower()) | Q(name__contains=search.lower())) return self.keep_only_real_categories(products) def keep_only_real_categories(self, products): """It can happen that a user's search contains a word that is in a product that has nothing to do with the intended research, so this is why this method is here : it deletes categories where the product was found too few times compared to the category where it was the most present. Actually, the decision ratio if a category is deleted or not is 10%.""" categories_list = [] # For each product, adds its category name to a list for product in products: categories_list.append(product.category.name) if len(categories_list) == 0: return None # Gets the category the most present greatest = max(Counter(categories_list).values()) keys_to_del = [] # Builds and sorts a dict from the category the most present # to the least dict = Counter(categories_list) the_dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1], reverse=True)} # Checks which categories are too few for k, v in the_dict.items(): if v < greatest*0.1: keys_to_del.append(k) # Removes them for key in keys_to_del: del(the_dict[key]) return the_dict
37.526316
79
0.598527
7af2e5c38167a995d8af05e7f83585f19484b3cb
2,665
cs
C#
CosmosEmulatorSample_Part1/Program.cs
jeremylindsayni/AzureCosmos_Part1
2900a259b8fb45c07386395e0c28e79a6b478fe0
[ "MIT" ]
1
2021-02-15T04:53:47.000Z
2021-02-15T04:53:47.000Z
CosmosEmulatorSample_Part1/Program.cs
jeremylindsayni/AzureCosmos_Part1
2900a259b8fb45c07386395e0c28e79a6b478fe0
[ "MIT" ]
null
null
null
CosmosEmulatorSample_Part1/Program.cs
jeremylindsayni/AzureCosmos_Part1
2900a259b8fb45c07386395e0c28e79a6b478fe0
[ "MIT" ]
2
2019-05-31T20:27:41.000Z
2019-08-01T20:02:55.000Z
using System; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; namespace CosmosEmulatorSample_Part1 { class Program { private static readonly string CosmosEndpoint = "https://localhost:8081"; private static readonly string EmulatorKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; private static readonly string DatabaseId = "LocalLandmarks"; private static readonly string NaturalSitesCollection = "NaturalSites"; static void Main(string[] args) { // Create the client connection var client = new DocumentClient( new Uri(CosmosEndpoint), EmulatorKey, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }); // Create a new database in Cosmos var databaseCreationResult = client.CreateDatabaseAsync(new Database { Id = DatabaseId }).Result; Console.WriteLine("The database Id created is: " + databaseCreationResult.Resource.Id); // Now initialize a new collection for our objects to live inside var collectionCreationResult = client.CreateDocumentCollectionAsync( UriFactory.CreateDatabaseUri(DatabaseId), new DocumentCollection { Id = NaturalSitesCollection }).Result; Console.WriteLine("The collection created has the ID: " + collectionCreationResult.Resource.Id); // Let's instantiate a POCO with a local landmark var giantsCauseway = new NaturalSite { Name = "Giant's Causeway" }; // Add this POCO as a document in Cosmos to our natural site collection var itemResult = client .CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri(DatabaseId, NaturalSitesCollection), giantsCauseway) .Result; Console.WriteLine("The document has been created with the ID: " + itemResult.Resource.Id); // Use the ID to retrieve the object we just created var document = client .ReadDocumentAsync( UriFactory.CreateDocumentUri(DatabaseId, NaturalSitesCollection, itemResult.Resource.Id)) .Result; // Convert the document resource returned to a NaturalSite POCO NaturalSite site = (dynamic)document.Resource; Console.WriteLine("The returned document is a natural landmark with name: " + site.Name); } } }
43.688525
144
0.642402
49790b7e217f16b62f97e5f716f334259c4f3ac8
325
asm
Assembly
oeis/021/A021581.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/021/A021581.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/021/A021581.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A021581: Decimal expansion of 1/577. ; Submitted by Jon Maiga ; 0,0,1,7,3,3,1,0,2,2,5,3,0,3,2,9,2,8,9,4,2,8,0,7,6,2,5,6,4,9,9,1,3,3,4,4,8,8,7,3,4,8,3,5,3,5,5,2,8,5,9,6,1,8,7,1,7,5,0,4,3,3,2,7,5,5,6,3,2,5,8,2,3,2,2,3,5,7,0,1,9,0,6,4,1,2,4,7,8,3,3,6,2,2,1,8,3,7,0 add $0,1 mov $2,10 pow $2,$0 div $2,577 mov $0,$2 mod $0,10
29.545455
199
0.556923
0183663011c6cc0fe1d5481511d6cf2abd93f175
164
lua
Lua
stnbdhw/init.lua
deform-lab/fast-artistic-videos
47ed2a9934c6d91a6d000c050ac3f327897a972f
[ "MIT" ]
341
2018-02-10T23:49:43.000Z
2022-03-18T16:53:00.000Z
stnbdhw/init.lua
deform-lab/fast-artistic-videos
47ed2a9934c6d91a6d000c050ac3f327897a972f
[ "MIT" ]
32
2018-02-13T23:00:56.000Z
2021-01-22T04:19:22.000Z
stnbdhw/init.lua
deform-lab/fast-artistic-videos
47ed2a9934c6d91a6d000c050ac3f327897a972f
[ "MIT" ]
49
2018-02-11T20:23:40.000Z
2022-03-20T12:26:58.000Z
require 'nn' local withCuda = pcall(require, 'cutorch') require 'libstn' if withCuda then require 'libcustn' end require('stn.BilinearSamplerBDHW') return nn
13.666667
42
0.75
da7865b9de996ce6a56cff98249a19ebaadb389d
471
php
PHP
src/Models/PostTaxonomy.php
theanhk/tad-system
21bd37b2b66ab56915398bb55420c2b09cf8b15c
[ "MIT" ]
null
null
null
src/Models/PostTaxonomy.php
theanhk/tad-system
21bd37b2b66ab56915398bb55420c2b09cf8b15c
[ "MIT" ]
null
null
null
src/Models/PostTaxonomy.php
theanhk/tad-system
21bd37b2b66ab56915398bb55420c2b09cf8b15c
[ "MIT" ]
null
null
null
<?php namespace Tadcms\System\Models; use Illuminate\Database\Eloquent\Model; /** * Tadcms\System\Models\PostTaxonomy * * @method static \Illuminate\Database\Eloquent\Builder|PostTaxonomy newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|PostTaxonomy newQuery() * @method static \Illuminate\Database\Eloquent\Builder|PostTaxonomy query() * @mixin \Eloquent */ class PostTaxonomy extends Model { protected $table = 'post_taxonomies'; }
23.55
84
0.768577
2a8269c73eeca6c05ee6720db4b4b6d0b397477b
531
dart
Dart
lib/core/constants/app_constants.dart
nbc-hub/Quiz_App
dff1243e3ecdc5e045f745f12eb8b7f4b7e83ceb
[ "MIT" ]
null
null
null
lib/core/constants/app_constants.dart
nbc-hub/Quiz_App
dff1243e3ecdc5e045f745f12eb8b7f4b7e83ceb
[ "MIT" ]
null
null
null
lib/core/constants/app_constants.dart
nbc-hub/Quiz_App
dff1243e3ecdc5e045f745f12eb8b7f4b7e83ceb
[ "MIT" ]
null
null
null
import 'package:intl/intl.dart'; class AppConstants { static AppConstants _instace; static AppConstants get instance { _instace ??= AppConstants._init(); return _instace; } AppConstants._init(); List<String> petList = [ 'Kedi', 'Köpek', 'Muhabbet Kuşu', 'Papağan', 'Hamster' ]; String convertMiliSecondToDate(String adversitementID) { var dateTime = DateTime.fromMillisecondsSinceEpoch(int.parse(adversitementID)); return DateFormat('dd-MM-yy').format(dateTime); } }
20.423077
72
0.676083
85324675dec49758867e1a5ff43df327f16d01dd
2,207
cs
C#
Tests/Editor/StratusCollectionExtensionTests.cs
Azurelol/Stratus-Core
ff86ec280eff23054cdff07e35fbbf8d113d5068
[ "MIT" ]
null
null
null
Tests/Editor/StratusCollectionExtensionTests.cs
Azurelol/Stratus-Core
ff86ec280eff23054cdff07e35fbbf8d113d5068
[ "MIT" ]
null
null
null
Tests/Editor/StratusCollectionExtensionTests.cs
Azurelol/Stratus-Core
ff86ec280eff23054cdff07e35fbbf8d113d5068
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Reflection; using NUnit.Framework; using UnityEngine; using System.Linq; namespace Stratus.Editor.Tests { public class StratusCollectionExtensionsTests { [Test] public void IsEmpty() { List<string> values = null; Assert.Throws<Exception>(() => values.Empty()); values = new List<string>(); Assert.True(values.Empty()); values.Add("Boo"); Assert.False(values.Empty()); } [Test] public void IsNotEmpty() { List<string> values = null; Assert.Throws<Exception>(() => values.NotEmpty()); Assert.False(values.NotEmpty()); values = new List<string>(); values.Add("Boo"); Assert.True(values.NotEmpty()); } [Test] public void IsNullOrEmpty() { string[] values = null; Assert.True(values.IsNullOrEmpty()); values = new string[] { }; Assert.True(values.IsNullOrEmpty()); values = new string[] { "foo", "bar" }; Assert.False(values.IsNullOrEmpty()); } [Test] public void IsValid() { string[] values = null; Assert.False(values.IsValid()); values = new string[] { }; Assert.False(values.IsValid()); values = new string[] { "foo", "bar" }; Assert.True(values.IsValid()); } [Test] public void PushRange() { Stack<int> values = new Stack<int>(); values.PushRange(1, 2, 3); Assert.AreEqual(new int[] { 3, 2, 1 }, values.ToArray()); } [Test] public void EnqueueRange() { Queue<int> values = new Queue<int>(); values.EnqueueRange(1, 2, 3); Assert.AreEqual(new int[] { 1, 2, 3 }, values.ToArray()); } [Test] public void TryContains() { IList<string> values; string value = "a"; values = new string[] { value, "b", "c" }; Assert.True(values.TryContains(value)); values = new string[] { "b", "c" }; Assert.False(values.TryContains(value)); values = null; Assert.False(values.TryContains(value)); } [Test] public void LenghOrZero() { string[] values; values = null; Assert.AreEqual(0, values.LengthOrZero()); values = new string[] { }; Assert.AreEqual(0, values.LengthOrZero()); values = new string[] { "a" }; Assert.AreEqual(1, values.LengthOrZero()); } } }
22.752577
60
0.628002