text:
Q: Converting a Python 2.7 Module to Python 3.5: It Compiles, but crashes Python Several months ago I wrote a Python debugger for Windows. It was written on Python 2.7. I am currently trying to convert it to Python 3.5. The main problem is coming from a module I need. The module is PyDasm, a wrapper to libdasm, and on 2.7 I used this source to build it. I tried building it for Python 3.5, and it returned multiple linker errors. I have since fixed them, so the module compiles without any errors on 3.5. When I try and import it into Pyhton, it crashes the Python process. Here is the code that at least compiles on 3.5. Here is the main pydasm.c file:
#include <Python.h>
#include "./libdasm/libdasm.h"

#define INSTRUCTION_STR_BUFFER_LENGTH   256

/*
    Instruction types borrowed from
    "libdasm.h"
*/
char *instruction_types[] = {
    "INSTRUCTION_TYPE_ASC",
    "INSTRUCTION_TYPE_DCL",
    "INSTRUCTION_TYPE_MOV",
    "INSTRUCTION_TYPE_MOVSR",
    "INSTRUCTION_TYPE_ADD",
    "INSTRUCTION_TYPE_XADD",
    "INSTRUCTION_TYPE_ADC",
    "INSTRUCTION_TYPE_SUB",
    "INSTRUCTION_TYPE_SBB",
    "INSTRUCTION_TYPE_INC",
    "INSTRUCTION_TYPE_DEC",
    "INSTRUCTION_TYPE_DIV",
    "INSTRUCTION_TYPE_IDIV",
    "INSTRUCTION_TYPE_NOT",
    "INSTRUCTION_TYPE_NEG",
    "INSTRUCTION_TYPE_STOS",
    "INSTRUCTION_TYPE_LODS",
    "INSTRUCTION_TYPE_SCAS",
    "INSTRUCTION_TYPE_MOVS",
    "INSTRUCTION_TYPE_MOVSX",
    "INSTRUCTION_TYPE_MOVZX",
    "INSTRUCTION_TYPE_CMPS",
    "INSTRUCTION_TYPE_SHX",
    "INSTRUCTION_TYPE_ROX",
    "INSTRUCTION_TYPE_MUL",
    "INSTRUCTION_TYPE_IMUL",
    "INSTRUCTION_TYPE_EIMUL",
    "INSTRUCTION_TYPE_XOR",
    "INSTRUCTION_TYPE_LEA",
    "INSTRUCTION_TYPE_XCHG",
    "INSTRUCTION_TYPE_CMP",
    "INSTRUCTION_TYPE_TEST",
    "INSTRUCTION_TYPE_PUSH",
    "INSTRUCTION_TYPE_AND",
    "INSTRUCTION_TYPE_OR",
    "INSTRUCTION_TYPE_POP",
    "INSTRUCTION_TYPE_JMP",
    "INSTRUCTION_TYPE_JMPC",
    "INSTRUCTION_TYPE_JECXZ",
    "INSTRUCTION_TYPE_SETC",
    "INSTRUCTION_TYPE_MOVC",
    "INSTRUCTION_TYPE_LOOP",
    "INSTRUCTION_TYPE_CALL",
    "INSTRUCTION_TYPE_RET",
    "INSTRUCTION_TYPE_ENTER",
    "INSTRUCTION_TYPE_INT",
    "INSTRUCTION_TYPE_BT",
    "INSTRUCTION_TYPE_BTS",
    "INSTRUCTION_TYPE_BTR",
    "INSTRUCTION_TYPE_BTC",
    "INSTRUCTION_TYPE_BSF",
    "INSTRUCTION_TYPE_BSR",
    "INSTRUCTION_TYPE_BSWAP",
    "INSTRUCTION_TYPE_SGDT",
    "INSTRUCTION_TYPE_SIDT",
    "INSTRUCTION_TYPE_SLDT",
    "INSTRUCTION_TYPE_LFP",
    "INSTRUCTION_TYPE_CLD",
    "INSTRUCTION_TYPE_STD",
    "INSTRUCTION_TYPE_XLAT",
    "INSTRUCTION_TYPE_FCMOVC",
    "INSTRUCTION_TYPE_FADD",
    "INSTRUCTION_TYPE_FADDP",
    "INSTRUCTION_TYPE_FIADD",
    "INSTRUCTION_TYPE_FSUB",
    "INSTRUCTION_TYPE_FSUBP",
    "INSTRUCTION_TYPE_FISUB",
    "INSTRUCTION_TYPE_FSUBR",
    "INSTRUCTION_TYPE_FSUBRP",
    "INSTRUCTION_TYPE_FISUBR",
    "INSTRUCTION_TYPE_FMUL",
    "INSTRUCTION_TYPE_FMULP",
    "INSTRUCTION_TYPE_FIMUL",
    "INSTRUCTION_TYPE_FDIV",
    "INSTRUCTION_TYPE_FDIVP",
    "INSTRUCTION_TYPE_FDIVR",
    "INSTRUCTION_TYPE_FDIVRP",
    "INSTRUCTION_TYPE_FIDIV",
    "INSTRUCTION_TYPE_FIDIVR",
    "INSTRUCTION_TYPE_FCOM",
    "INSTRUCTION_TYPE_FCOMP",
    "INSTRUCTION_TYPE_FCOMPP",
    "INSTRUCTION_TYPE_FCOMI",
    "INSTRUCTION_TYPE_FCOMIP",
    "INSTRUCTION_TYPE_FUCOM",
    "INSTRUCTION_TYPE_FUCOMP",
    "INSTRUCTION_TYPE_FUCOMPP",
    "INSTRUCTION_TYPE_FUCOMI",
    "INSTRUCTION_TYPE_FUCOMIP",
    "INSTRUCTION_TYPE_FST",
    "INSTRUCTION_TYPE_FSTP",
    "INSTRUCTION_TYPE_FIST",
    "INSTRUCTION_TYPE_FISTP",
    "INSTRUCTION_TYPE_FISTTP",
    "INSTRUCTION_TYPE_FLD",
    "INSTRUCTION_TYPE_FILD",
    "INSTRUCTION_TYPE_FICOM",
    "INSTRUCTION_TYPE_FICOMP",
    "INSTRUCTION_TYPE_FFREE",
    "INSTRUCTION_TYPE_FFREEP",
    "INSTRUCTION_TYPE_FXCH",
    "INSTRUCTION_TYPE_SYSENTER",
    "INSTRUCTION_TYPE_FPU_CTRL",
    "INSTRUCTION_TYPE_FPU",

    "INSTRUCTION_TYPE_MMX",

    "INSTRUCTION_TYPE_SSE",

    "INSTRUCTION_TYPE_OTHER",
    "INSTRUCTION_TYPE_PRIV",
    NULL };

/*
    Operand types borrowed from
    "libdasm.h"
*/
char *operand_types[] = {
    "OPERAND_TYPE_NONE",
    "OPERAND_TYPE_MEMORY",
    "OPERAND_TYPE_REGISTER",
    "OPERAND_TYPE_IMMEDIATE",
    NULL };

/*
    Registers borrowed from
    "libdasm.h"
*/
char *registers[] = {
    "REGISTER_EAX",
    "REGISTER_ECX",
    "REGISTER_EDX",
    "REGISTER_EBX",
    "REGISTER_ESP",
    "REGISTER_EBP",
    "REGISTER_ESI",
    "REGISTER_EDI",
    "REGISTER_NOP",
    NULL };

/*
    Register types borrowed from
    "libdasm.h"
*/
char *register_types[] = {
    "REGISTER_TYPE_GEN",
    "REGISTER_TYPE_SEGMENT",
    "REGISTER_TYPE_DEBUG",
    "REGISTER_TYPE_CONTROL",
    "REGISTER_TYPE_TEST",
    "REGISTER_TYPE_XMM",
    "REGISTER_TYPE_MMX",
    "REGISTER_TYPE_FPU",
    NULL };

PyObject *module;   // Main module Python object

/*
    Check whether we got a Python Object
*/
PyObject *check_object(PyObject *pObject)
{
    PyObject *pException;

    if(!pObject) {
        pException = PyErr_Occurred();
        if(pException)
            PyErr_Print();
        return NULL;
    }

    return pObject;
}

/*
    Assign an attribute "attr" named "name" to an object "obj"
*/
void assign_attribute(PyObject *obj, char *name, PyObject *attr)
{
    PyObject_SetAttrString(obj, name, attr);
    Py_DECREF(attr);
}

/*
    Get an attribute named "attr_name" from object "obj"
    The function steals the reference! note the decrement of
    the reference count.
*/
PyObject *get_attribute(PyObject *obj, char *attr_name)
{
    PyObject *pObj;

    pObj = PyObject_GetAttrString(obj, attr_name);
    if(!check_object(pObj)) {
        PyErr_SetString(PyExc_ValueError, "Can't get attribute from object");
        return NULL;
    }

    Py_DECREF(pObj);
    return pObj;
}

/*
    Get an Long attribute named "attr_name" from object "obj" and
    return it as a "long int"
*/
long int get_long_attribute(PyObject *o, char *attr_name)
{
    PyObject *pObj;

    pObj = get_attribute(o, attr_name);
    if(!pObj)
        return 0;

    return PyLong_AsLong(pObj);;
}

/*
    Create a new class and take care of decrementing references.
*/
PyObject *create_class(char *class_name)
{
    PyObject *pClass;
    PyObject *pClassDict = PyDict_New();
    PyObject *pClassName = PyBytes_FromString(class_name);

    pClass = PyCapsule_New(NULL, pClassDict, pClassName);
    if(!check_object(pClass))
        return NULL;

    Py_DECREF(pClassDict);
    Py_DECREF(pClassName);

    return pClass;
}

/*
    Create an "Inst" Python object from an INST structure.
*/
PyObject *create_inst_object(INST *pinst)
{
    PyObject *pPInst = create_class("Inst");

    if(!pPInst)
        return NULL;

    assign_attribute(pPInst, "type", PyLong_FromLong(pinst->type));
    assign_attribute(pPInst, "mnemonic", PyBytes_FromString(pinst->mnemonic));
    assign_attribute(pPInst, "flags1", PyLong_FromLong(pinst->flags1));
    assign_attribute(pPInst, "flags2", PyLong_FromLong(pinst->flags2));
    assign_attribute(pPInst, "flags3", PyLong_FromLong(pinst->flags3));
    assign_attribute(pPInst, "modrm", PyLong_FromLong(pinst->modrm));

    return pPInst;
}

/*
    Fill an INST structure from the data in an "Inst" Python object.
*/
void fill_inst_structure(PyObject *pPInst, PINST *_pinst)
{
    ssize_t mnemonic_length;
    PINST pinst;

    if(!pPInst || !_pinst)
        return;

    *_pinst = (PINST)calloc(1, sizeof(INST));
    pinst = *_pinst;
    if(!pinst) {
        PyErr_SetString(PyExc_MemoryError, "Can't allocate memory");
        return;
    }

    pinst->type = get_long_attribute(pPInst, "type");

    PyBytes_AsStringAndSize(
        get_attribute(pPInst, "mnemonic"),
        (void *)&pinst->mnemonic, &mnemonic_length);

    pinst->flags1 = get_long_attribute(pPInst, "flags1");
    pinst->flags2 = get_long_attribute(pPInst, "flags2");
    pinst->flags3 = get_long_attribute(pPInst, "flags3");
    pinst->modrm = get_long_attribute(pPInst, "modrm");
}

/*
    Create an "Operand" Python object from an OPERAND structure.
*/
PyObject *create_operand_object(OPERAND *op)
{
    PyObject *pOperand = create_class("Operand");

    if(!pOperand)
        return NULL;

    assign_attribute(pOperand, "type", PyLong_FromLong(op->type));
    assign_attribute(pOperand, "reg", PyLong_FromLong(op->reg));
    assign_attribute(pOperand, "basereg", PyLong_FromLong(op->basereg));
    assign_attribute(pOperand, "indexreg", PyLong_FromLong(op->indexreg));
    assign_attribute(pOperand, "scale", PyLong_FromLong(op->scale));
    assign_attribute(pOperand, "dispbytes", PyLong_FromLong(op->dispbytes));
    assign_attribute(pOperand, "dispoffset", PyLong_FromLong(op->dispoffset));
    assign_attribute(pOperand, "immbytes", PyLong_FromLong(op->immbytes));
    assign_attribute(pOperand, "immoffset", PyLong_FromLong(op->immoffset));
    assign_attribute(pOperand, "sectionbytes", PyLong_FromLong(op->sectionbytes));
    assign_attribute(pOperand, "section", PyLong_FromLong(op->section));
    assign_attribute(pOperand, "displacement", PyLong_FromLong(op->displacement));
    assign_attribute(pOperand, "immediate", PyLong_FromLong(op->immediate));
    assign_attribute(pOperand, "flags", PyLong_FromLong(op->flags));

    return pOperand;
}

/*
    Fill an OPERAND structure from the data in an "Operand" Python object.
*/
void fill_operand_structure(PyObject *pOperand, OPERAND *op)
{
    if(!pOperand || !op)
        return;

    op->type = get_long_attribute(pOperand, "type");
    op->reg = get_long_attribute(pOperand, "reg");
    op->basereg = get_long_attribute(pOperand, "basereg");
    op->indexreg = get_long_attribute(pOperand, "indexreg");
    op->scale = get_long_attribute(pOperand, "scale");
    op->dispbytes = get_long_attribute(pOperand, "dispbytes");
    op->dispoffset = get_long_attribute(pOperand, "dispoffset");
    op->immbytes = get_long_attribute(pOperand, "immbytes");
    op->immoffset = get_long_attribute(pOperand, "immoffset");
    op->sectionbytes = get_long_attribute(pOperand, "sectionbytes");
    op->section = get_long_attribute(pOperand, "section");
    op->displacement = get_long_attribute(pOperand, "displacement");
    op->immediate = get_long_attribute(pOperand, "immediate");
    op->flags = get_long_attribute(pOperand, "flags");
}

/*
    Create an "Instruction" Python object from an INSTRUCTION structure.
*/
PyObject *create_instruction_object(INSTRUCTION *insn)
{
    PyObject *pInstruction = create_class("Instruction");

    if(!pInstruction)
        return NULL;

    assign_attribute(pInstruction, "length", PyLong_FromLong(insn->length));
    assign_attribute(pInstruction, "type", PyLong_FromLong(insn->type));
    assign_attribute(pInstruction, "mode", PyLong_FromLong(insn->mode));
    assign_attribute(pInstruction, "opcode", PyLong_FromLong(insn->opcode));
    assign_attribute(pInstruction, "modrm", PyLong_FromLong(insn->modrm));
    assign_attribute(pInstruction, "sib", PyLong_FromLong(insn->sib));
    assign_attribute(pInstruction, "extindex", PyLong_FromLong(insn->extindex));
    assign_attribute(pInstruction, "fpuindex", PyLong_FromLong(insn->fpuindex));
    assign_attribute(pInstruction, "dispbytes", PyLong_FromLong(insn->dispbytes));
    assign_attribute(pInstruction, "immbytes", PyLong_FromLong(insn->immbytes));
    assign_attribute(pInstruction, "sectionbytes", PyLong_FromLong(insn->sectionbytes));
    assign_attribute(pInstruction, "op1", create_operand_object(&insn->op1));
    assign_attribute(pInstruction, "op2", create_operand_object(&insn->op2));
    assign_attribute(pInstruction, "op3", create_operand_object(&insn->op3));
    assign_attribute(pInstruction, "ptr", create_inst_object(insn->ptr));
    assign_attribute(pInstruction, "flags", PyLong_FromLong(insn->flags));
    assign_attribute(pInstruction, "eflags_affected", PyLong_FromLong(insn->eflags_affected));
    assign_attribute(pInstruction, "eflags_used", PyLong_FromLong(insn->eflags_used));

    return pInstruction;
}

/*
    Fill an INSTRUCTION structure from the data in an "Instruction" Python object.
*/
void fill_instruction_structure(PyObject *pInstruction, INSTRUCTION *insn)
{
    insn->length = get_long_attribute(pInstruction, "length");
    insn->type = get_long_attribute(pInstruction, "type");
    insn->mode = get_long_attribute(pInstruction, "mode");
    insn->opcode = get_long_attribute(pInstruction, "opcode");
    insn->modrm = get_long_attribute(pInstruction, "modrm");
    insn->sib = get_long_attribute(pInstruction, "sib");
    insn->extindex = get_long_attribute(pInstruction, "extindex");
    insn->fpuindex = get_long_attribute(pInstruction, "fpuindex");
    insn->dispbytes = get_long_attribute(pInstruction, "dispbytes");
    insn->immbytes = get_long_attribute(pInstruction, "immbytes");
    insn->sectionbytes = get_long_attribute(pInstruction, "sectionbytes");
    insn->flags = get_long_attribute(pInstruction, "flags");
    fill_operand_structure(get_attribute(pInstruction, "op1"), &insn->op1);
    fill_operand_structure(get_attribute(pInstruction, "op2"), &insn->op2);
    fill_operand_structure(get_attribute(pInstruction, "op3"), &insn->op3);
    fill_inst_structure(get_attribute(pInstruction, "ptr"), &insn->ptr);
}

/*
    Python counterpart of libdasm's "get_instruction"
*/
#define GET_INSTRUCTION_DOCSTRING                                               \
    "Decode an instruction from the given buffer.\n\n"                          \
    "Takes in a string containing the data to disassemble and the\nmode, "      \
    "either MODE_16 or MODE_32. Returns an Instruction object or \nNone if "    \
    "the instruction can't be disassembled."

PyObject *pydasm_get_instruction(PyObject *self, PyObject *args)
{
    PyObject *pBuffer, *pMode;
    INSTRUCTION insn;
    int size, mode;
    ssize_t data_length;
    char *data;

    if(!args || PyObject_Length(args)!=2) {
        PyErr_SetString(PyExc_TypeError,
            "Invalid number of arguments, 2 expected: (data, mode)");
        return NULL;
    }

    pBuffer = PyTuple_GetItem(args, 0);
    if(!check_object(pBuffer)) {
        PyErr_SetString(PyExc_ValueError, "Can't get buffer from arguments");
    }

    pMode = PyTuple_GetItem(args, 1);
    if(!check_object(pMode)) {
        PyErr_SetString(PyExc_ValueError, "Can't get mode from arguments");
    }
    mode = PyLong_AsLong(pMode);

    PyBytes_AsStringAndSize(pBuffer, &data, &data_length);

    size = get_instruction(&insn, (unsigned char *)data, mode);

    if(!size) {
        Py_INCREF(Py_None);
        return Py_None;
    }

    return create_instruction_object(&insn);
}

/*
    Python counterpart of libdasm's "get_instruction_string"
*/
#define GET_INSTRUCTION_STRING_DOCSTRING                                    \
    "Transform an instruction object into its string representation.\n\n"   \
    "The function takes an Instruction object; its format, either \n"       \
    "FORMAT_INTEL or FORMAT_ATT and finally an offset (refer to \n"         \
    "libdasm for meaning). Returns a string representation of the \n"       \
    "disassembled instruction."

PyObject *pydasm_get_instruction_string(PyObject *self, PyObject *args)
{
    PyObject *pInstruction, *pFormat, *pOffset, *pStr;
    INSTRUCTION insn;
    unsigned long int offset, format;
    char *data;

    if(!args || PyObject_Length(args)!=3) {
        PyErr_SetString(PyExc_TypeError,
            "Invalid number of arguments, 3 expected: (instruction, format, offset)");
        return NULL;
    }

    pInstruction = PyTuple_GetItem(args, 0);
    if(!check_object(pInstruction)) {
        PyErr_SetString(PyExc_ValueError, "Can't get instruction from arguments");
    }
    if(pInstruction == Py_None) {
        Py_INCREF(Py_None);
        return Py_None;
    }
    memset(&insn, 0, sizeof(INSTRUCTION));
    fill_instruction_structure(pInstruction, &insn);

    pFormat = PyTuple_GetItem(args, 1);
    if(!check_object(pFormat)) {
        PyErr_SetString(PyExc_ValueError, "Can't get format from arguments");
    }
    format = PyLong_AsLong(pFormat);

    pOffset = PyTuple_GetItem(args, 2);
    if(!check_object(pOffset)) {
        PyErr_SetString(PyExc_ValueError, "Can't get offset from arguments");
    }
    offset = PyLong_AsLong(pOffset);

    data = (char *)calloc(1, INSTRUCTION_STR_BUFFER_LENGTH);
    if(!data) {
        PyErr_SetString(PyExc_MemoryError, "Can't allocate memory");
        return NULL;
    }

    if(!get_instruction_string(&insn, format, offset,
        data, INSTRUCTION_STR_BUFFER_LENGTH))
    {
        Py_INCREF(Py_None);
        return Py_None;
    }

    pStr = PyBytes_FromStringAndSize(data, strlen(data));
    free(insn.ptr);
    free(data);

    return pStr;
}

/*
    Python counterpart of libdasm's "get_mnemonic_string"
*/
#define GET_MNEMONIC_STRING_DOCSTRING                                       \
    "Transform an instruction object's mnemonic into its string representation.\n\n"    \
    "The function takes an Instruction object and its format, either \n"    \
    "FORMAT_INTEL or FORMAT_ATT. Returns a string representation of the \n" \
    "mnemonic."

PyObject *pydasm_get_mnemonic_string(PyObject *self, PyObject *args)
{
    PyObject *pInstruction, *pFormat, *pStr;
    INSTRUCTION insn;
    unsigned long int format;
    char *data;

    if(!args || PyObject_Length(args)!=2) {
        PyErr_SetString(PyExc_TypeError,
            "Invalid number of arguments, 3 expected: (instruction, format)");
        return NULL;
    }

    pInstruction = PyTuple_GetItem(args, 0);
    if(!check_object(pInstruction)) {
        PyErr_SetString(PyExc_ValueError, "Can't get instruction from arguments");
    }
    fill_instruction_structure(pInstruction, &insn);

    pFormat = PyTuple_GetItem(args, 1);
    if(!check_object(pFormat)) {
        PyErr_SetString(PyExc_ValueError, "Can't get format from arguments");
    }
    format = PyLong_AsLong(pFormat);

    data = (char *)calloc(1, INSTRUCTION_STR_BUFFER_LENGTH);
    if(!data) {
        PyErr_SetString(PyExc_MemoryError, "Can't allocate memory");
        return NULL;
    }

    get_mnemonic_string(&insn, format, data, INSTRUCTION_STR_BUFFER_LENGTH);

    pStr = PyBytes_FromStringAndSize(data, strlen(data));
    free(data);

    return pStr;
}

/*
    Python counterpart of libdasm's "get_operand_string"
*/
#define GET_OPERAND_STRING_DOCSTRING                                        \
    "Transform an instruction object's operand into its string representation.\n\n"    \
    "The function takes an Instruction object; the operand index (0,1,2);\n"\
    " its format, either FORMAT_INTEL or FORMAT_ATT and finally an offset\n"\
    "(refer to libdasm for meaning). Returns a string representation of \n" \
    "the disassembled operand."

PyObject *pydasm_get_operand_string(PyObject *self, PyObject *args)
{
    PyObject *pInstruction, *pFormat, *pOffset, *pOpIndex, *pStr;
    INSTRUCTION insn;
    unsigned long int offset, format, op_idx;
    char *data;

    if(!args || PyObject_Length(args)!=4) {
        PyErr_SetString(PyExc_TypeError,
            "Invalid number of arguments, 4 expected: (instruction, operand index, format, offset)");
        return NULL;
    }

    pInstruction = PyTuple_GetItem(args, 0);
    if(!check_object(pInstruction)) {
        PyErr_SetString(PyExc_ValueError, "Can't get instruction from arguments");
    }
    memset(&insn, 0, sizeof(INSTRUCTION));
    fill_instruction_structure(pInstruction, &insn);

    pOpIndex = PyTuple_GetItem(args, 1);
    if(!check_object(pOpIndex)) {
        PyErr_SetString(PyExc_ValueError, "Can't get operand index from arguments");
    }
    op_idx = PyLong_AsLong(pOpIndex);

    pFormat = PyTuple_GetItem(args, 2);
    if(!check_object(pFormat)) {
        PyErr_SetString(PyExc_ValueError, "Can't get format from arguments");
    }
    format = PyLong_AsLong(pFormat);

    pOffset = PyTuple_GetItem(args, 3);
    if(!check_object(pOffset)) {
        PyErr_SetString(PyExc_ValueError, "Can't get offset from arguments");
    }
    offset = PyLong_AsLong(pOffset);

    data = (char *)calloc(1, INSTRUCTION_STR_BUFFER_LENGTH);
    if(!data) {
        PyErr_SetString(PyExc_MemoryError, "Can't allocate memory");
        return NULL;
    }

    if(!get_operand_string(&insn, &(insn.op1)+op_idx,
        format, offset, data, INSTRUCTION_STR_BUFFER_LENGTH))
    {
        Py_INCREF(Py_None);
        return Py_None;
    }

    pStr = PyBytes_FromStringAndSize(data, strlen(data));
    free(data);

    return pStr;
}

/*
    Python counterpart of libdasm's "get_register_type"
*/
#define GET_REGISTER_TYPE_DOCSTRING                                         \
    "Get the type of the register used by the operand.\n\n"                 \
    "The function takes an Operand object and returns a Long representing\n"\
    "the type of the register."

PyObject *pydasm_get_register_type(PyObject *self, PyObject *args)
{
    PyObject *pOperand;
    OPERAND op;

    if(!args || PyObject_Length(args)!=1) {
        PyErr_SetString(PyExc_TypeError,
            "Invalid number of arguments, 1 expected: (operand)");
        return NULL;
    }

    pOperand = PyTuple_GetItem(args, 0);
    if(!check_object(pOperand)) {
        PyErr_SetString(PyExc_ValueError, "Can't get instruction from arguments");
    }
    memset(&op, 0, sizeof(OPERAND));
    fill_operand_structure(pOperand, &op);

    return PyLong_FromLong(get_register_type(&op));
}

/*
    Map all the exported methods.
*/
static PyMethodDef pydasmMethods[] = {
    {"get_instruction", pydasm_get_instruction, METH_VARARGS,
    GET_INSTRUCTION_DOCSTRING},
    {"get_instruction_string", pydasm_get_instruction_string, METH_VARARGS,
    GET_INSTRUCTION_STRING_DOCSTRING},
    {"get_mnemonic_string", pydasm_get_mnemonic_string, METH_VARARGS,
    GET_MNEMONIC_STRING_DOCSTRING},
    {"get_operand_string", pydasm_get_operand_string, METH_VARARGS,
    GET_OPERAND_STRING_DOCSTRING},
    {"get_register_type", pydasm_get_register_type, METH_VARARGS,
    GET_REGISTER_TYPE_DOCSTRING},
    {NULL, NULL, 0, NULL}
};

/*
    Init the module, set constants.
*/
static PyObject * initpydasm(void)
{
    int i;
    PyObject *pModule;

    pModule = PyModule_Create("pydasm", pydasmMethods);

    assign_attribute(pModule, "FORMAT_ATT", PyLong_FromLong(0));
    assign_attribute(pModule, "FORMAT_INTEL", PyLong_FromLong(1));

    assign_attribute(pModule, "MODE_16", PyLong_FromLong(1));
    assign_attribute(pModule, "MODE_32", PyLong_FromLong(0));

    for(i=0; instruction_types[i]; i++)
        assign_attribute(pModule, instruction_types[i], PyLong_FromLong(i));

    for(i=0; operand_types[i]; i++)
        assign_attribute(pModule, operand_types[i], PyLong_FromLong(i));

    for(i=0; registers[i]; i++)
        assign_attribute(pModule, registers[i], PyLong_FromLong(i));

    for(i=0; register_types[i]; i++)
        assign_attribute(pModule, register_types[i], PyLong_FromLong(i+1));
    return pModule;
}

PyMODINIT_FUNC PyInit_pydasm(void)
{
    return initpydasm();
}

int main(int agrc, char *argv[])
{
    Py_SetProgramName(argv[0]);

    Py_Initialize();

    return PyInit_pydasm();

}

Why is this compiling, but crashing Python 3.5?


text:
Q: JsonSerializer and JsonDeserializer using HTTP Headers I have a requirement in which the REST consumer will be sending in the date data in the client or consumer's locale. The HTTP header will be configured to send the client locale information.
The REST server implementation needs to process the Http header and convert the date from the client locale to the UTC format and store the date into the database.
Similarly when returning back the response when there is a date field the reverse operation is expected. This will ensure the consumer sees the same date which was input by the client.
I want to know how I can access the HTTPRequest object OR pass custom parameters to the my implementated JSONSerializer and JSONDeserializer.

A: I think you can use the ThreadLocal variable to save the information of ServletRequest and then use it anywhere. For example:
In your filter to get the information you need in request
public class YourFilter implements Filter {

    private static final ThreadLocal<String> _date = new ThreadLocal<>();

    public static ThreadLocal<String> getDate() {
        return _date;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //....
        //other code
        //get the date from request
        Date date = request.xxxxxx();
        //set the date to the local thread variable
        _date.set(date);
    }
}

Use the ThreadLocal variable in your JSONSerializer
@Override
public void serialize(String resourceIdMsg,
                      JsonGenerator jsonGenerator,
                      SerializerProvider serializerProvider)
            throws IOException {
    String date = YourFilter.getDate().get();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse error cannot be resolved to a type I am trying to learn Cucumber using Maven + Eclipse. When trying to import the following I am getting the error respectively
import cucumber.org.junit.runner.RunWith;
import cucumber.api.junit.CucumberOptions;

CucumberOptions cannot be resolved to a type
RunWith cannot be resolved to a type

I have search through and read possible ways to resolved this but nothing worked for me.
POM Details:
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>4.2.0</version>
</dependency>

Version of Java/Exclipse/Maven
Eclipse IDE for Java Developers - Version: 2018-09 (4.9.0)
JAVA 11.0.1
Maven 3.6.0

Not sure what I am doing wrong if someone could help please.

A: tested some things in my IDE locally, I made a new maven project skipped the arch type selection and pasted your dependencies from the pom in your question and got the same results. I did some research and I think your pom dependencies need to be this ...
<dependencies>
     <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.1.2</version>
       <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>4.2.0</version>
   </dependency>
</dependencies>

Notice the info.cukes in groupId its different than what you have, once I did this I was able create test class like this ..
package cucumber;

import cucumber.api.junit.Cucumber.Options;
import org.junit.runner.RunWith;

 public class Test {

 public static void main(String[] args) {
    Options d;
    RunWith e;
 }
}

And it resolved the dependencies! Also if you are still having issues right click on the project select the maven submenu and select update. People who feel the need to edit my answer grammar and content have no life.


text:
Q: jquery dynamically add div and bind elements I have this piece of html in my page.

Add

            <select class="parameter" id="parameter_1" name="parameter_1">
                <option title="Keyword Anywhere" value="Anywhere">Keyword Anywhere</option>
                <option title="Author or Contributor" value="Contributor">Author or Contributor</option>
                <option title="Title" value="Title">Title</option>
                <option title="Subject" value="Subject">Subject</option>
            </select>
            <input class="keyword" id="keyword_1" name="keyword_1" type="text" />
            [-]

I want to use jquery to dynamically add/repeat the contents of query_chunk div. Below is what I have so far, which obviously is not working! I am not very familiar with the jquery functions. Any pointers where I am going wrong?
$(document).ready(function () {

    Init = new function () {
        this.construct = function () {
            Actions.bind();
        }

        query_chunks = $("div.query_chunk");
        term_count = query_chunks.size();

    }

    Actions = new function () {
        this.bind = function () {

            $("#addQueryPart").bind("click", function () {

                var query_chunk = query_chunks[0].clone().attr({ 'class': 'query_chunk', 'id': 'query_chunk_' + (++term_count) });
                var search_param_select = $("select", query_chunk).attr({ 'class': 'parameter', 'id': 'parameter_' + (++term_count) });
                var keyword = $("input", query_chunk).attr({ 'class': 'keyword', 'id': 'keyword_' + (++term_count) });
                var removebtn = $("a", query_chunk).attr({ 'class': 'remove', 'id': 'remove_' + (++term_count) });
                query_chunks[0].append(query_chunk);
                keyword.bind("click", function () {
                    alert("Click event fired");
                });

            });
        }
    }
    Init.construct();
});

PS: I am trying to use similar idea of an already existing MooTools js script, may be there is an easier way to do the same in jquery?

A: Here's the working version of your code:
http://jsfiddle.net/9MRLQ/
The problem was that you were trying to .clone() and append() on query_chunks[0], which is not a jQuery object but an HTML element. So you needed to wrap it in $() first.
One more update
http://jsfiddle.net/9MRLQ/1/
I replaced append() with an after(). Since append() adds content to query_chunks[0] next time you click "Add" you clone already modified query_chunk, so instead of adding one row you add two. Next time you click you add 4 and so on...

A: I had a similar question, here is a sample project that  Muhammad Adeel Zahid gave me that did exactly what I wanted, it sounds like what your after too. "dynamically add rows using jquery'
This solution uses MVC3 though.
http://www.esnips.com/doc/63cc65e3-0bc9-409d-a6ef-795985e58d32/Master-Detail3


text:
Q: Using albumentation's augmentation in tensorflow dataset API is giving this error : Incompatible shapes expected [?,224,224,3] but got [8,1,224,224,3] I am getting this error while trying to augment the images using the albumentations library which uses tf.numpy_function to wrap the python function for augmentation in tensorflow from this link :https://albumentations.ai/docs/examples/tensorflow-example/
I have loaded my dataset of images and target label using tensorflow dataset API.
The code :
img_paths = df['image_path'].values
target = df['target_label'].values

path_lis = tf.data.Dataset.from_tensor_slices(img_paths)
target_lis = tf.data.Dataset.from_tensor_slices(target)
list_ds = tf.data.Dataset.zip((path_lis, target_lis))

image_count = len(df)
val_size = int(image_count * 0.3)
train = list_ds.skip(val_size)
val = list_ds.take(val_size)

def process_path(file_path, target):

  # load the raw data from the file as a string
  img = tf.io.read_file(file_path)
  img = tf.image.decode_jpeg(img, channels=3)

  return img, target

# Set `num_parallel_calls` so multiple images are loaded/processed in parallel.
train_data = train.map(process_path, num_parallel_calls=AUTOTUNE)
val_data = val.map(process_path, num_parallel_calls=AUTOTUNE)

# Augmentation using albumentations library
transforms = A.Compose([
            A.Rotate(limit=40),
            A.RandomBrightness(limit=0.1),
            A.RandomContrast(limit=0.9, p=1),
            A.HorizontalFlip(),
            A.Resize(224, 224)
            ])

def aug_fn(image):

    data = {"image": image}
    aug_data = transforms(**data)
    aug_img = aug_data["image"]
    #target = aug_data["keypoints"][0]
    aug_img = tf.cast(aug_img/255.0, tf.float32)
    #aug_img = tf.image.resize(aug_img, size=[224, 224])

    return aug_img

def process_aug(img, label):

    aug_img = tf.numpy_function(func=aug_fn, inp=[img], Tout=[tf.float32])
    return aug_img, label

# create dataset
train_ds = train_data.map(process_aug, num_parallel_calls=AUTOTUNE).prefetch(AUTOTUNE)
val_ds = val_data.map(process_aug, num_parallel_calls=AUTOTUNE).prefetch(AUTOTUNE)

def set_shapes(img, label):

    img.set_shape([224, 224, 3])
    label.set_shape([])

    return img, label

train_ds = train_ds.map(set_shapes, num_parallel_calls=AUTOTUNE).batch(8).prefetch(AUTOTUNE)
val_ds = val_ds.map(set_shapes, num_parallel_calls=AUTOTUNE).batch(8).prefetch(AUTOTUNE)

def view_image(ds):

    image, label = next(iter(ds)) # extract 1 batch from the dataset
    image = image.numpy()
    label = label.numpy()

    fig = plt.figure(figsize=(22, 22))
    for i in range(20):
        ax = fig.add_subplot(4, 5, i+1, xticks=[], yticks=[])
        ax.imshow(image[i])
        ax.set_title(f"Label: {label[i]}")

view_image(train_ds)

The full error message:
Traceback (most recent call last):
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\eager\context.py", line 2102, in execution_mode
    yield
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py", line 758, in _next_internal
    output_shapes=self._flat_output_shapes)
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_dataset_ops.py", line 2610, in iterator_get_next
    _ops.raise_from_not_ok_status(e, name)
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 6843, in raise_from_not_ok_status
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes at component 0: expected [?,224,224,3] but got [4,1,224,224,3]. [Op:IteratorGetNext]

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\Arun\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-20-23a37450bee7>", line 13, in <module>
    view_image(train_ds)
  File "<ipython-input-20-23a37450bee7>", line 3, in view_image
    image, label = next(iter(ds)) # extract 1 batch from the dataset
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py", line 736, in __next__
    return self.next()
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py", line 772, in next
    return self._next_internal()
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py", line 764, in _next_internal
    return structure.from_compatible_tensor_list(self._element_spec, ret)
  File "C:\Users\Arun\Anaconda3\lib\contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\eager\context.py", line 2105, in execution_mode
    executor_new.wait()
  File "C:\Users\Arun\Anaconda3\lib\site-packages\tensorflow\python\eager\executor.py", line 67, in wait
    pywrap_tfe.TFE_ExecutorWaitForAllPendingNodes(self._handle)

tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes at component 0: expected [?,224,224,3] but got [8,1,224,224,3].

Can someone can at least tell me why this error is happening? Thanks in advance!

A: img_shape should be (224, 224, 3) not [224, 224, 3]
for example:
def set_shapes(img, label, img_shape=(120,120,3)):
    img.set_shape(img_shape)
    label.set_shape([])
    return img, label


text:
Q: Css centering boxes percentages workings How do I remove the remaining space on the right:
HTML code:

Title 1

Title 1

Title 1

CSS code:
.wrapper {
height:                                                         450px;
margin:                                                         50px;
border-radius:                                                  30px;
overflow:                                                       hidden;
background-color:                                               #F00;
border:                                                         1px solid #000;
display:block;
}
.wrapper a {
    width:                                                      33.3%;
    height:                                                     100%;
    background-color:                                           #444;
    margin:0 auto;
    float:                                                      left;
    color:                                                      #fff;
    text-decoration:                                            none;
    display:inline-block;
}
.wrapper a:nth-child(2) {
    background-color:                                           #333;
}
.wrapper a h1 {
    width:                                                      100%;
    height:                                                     70px;
    text-align:                                                 center;
    position:                                                   relative;
    bottom:                                                     0;
    text-shadow:                                                1px 1px #000;
}

http://jsfiddle.net/6bXQ9/
the 3 blocks must be 33,3 % but the rest(0,1%) wont be filled, and ive i use 33,4% there will get 1 block lost when the page is smaller
what should i use? Thanks! and sorry for my bad english

A: width: 33.33% does the magic trick.

A: Is this what you want? http://jsfiddle.net/6bXQ9/5/
width: 33.33%;

Making Width: 33.33% solves your problem.


text:
Q: What is the image of N-Pair loss function? Does it have a global minimum? In the paper "Improved Deep Metric Learning with Multi-class N-pair Loss Objective" [1] the author proposes the N-Pair loss as an efficient and effective alternative to Triplet loss [2].
Let $x$ be an input sample, $x^+$ a sample similar to $x$, and a set of $(N-1)$ samples dissimilar to $x$, the N-Pair loss is defined as:
\begin{equation}\label{n_pairs_loss}
    \mathcal{L}(\{x,x^+,x_i\}_{i=1}^{N-1}; f) = -log \frac{exp(f^T f^+)}{exp(f^T f^+) + \sum_{i=1}^{N-1}exp(f^T f_i)}
\end{equation}
where $f(·;θ)$ is an embedding kernel defined by a deep neural network, $f$ is the representation of $x$, $f_i$ is the representation of the negative samples, and $f^+$ is the representation of the positive sample. This loss is minimized when the representation of $x$ is closer to $x^+$ than to all $x^-$.
What is the image of the N-Pair loss function? Does it have a global minimum?
References
[1] Sohn, Kihyuk. "Improved deep metric learning with multi-class n-pair loss objective." Advances in neural information processing systems 29 (2016): 1857-1865.
[2] Weinberger, Kilian Q., John Blitzer, and Lawrence K. Saul. "Distance metric learning for large margin nearest neighbor classification." Advances in neural information processing systems. 2006.


text:
Q: 80s or 90s movie - Asian man jumps through large spinning fan I don't have much to go by here... but I'll give it a shot. I would have to say this movie was set in the late 80's early 90's. (May possibly be an episode of a TV show)
I remember one of the characters was an Asian guy who at one point jumps through a spinning fan/vent. The jump is in slow motion, and he lands on the other side of the spinning fan blades and kicks the fan from the other side to stop the blades from spinning, allowing the other people with him to get through.
I wanna say that the main character/hero is sort of a Robocop-type character. I even thought at one point that it WAS Robocop.. but I skimmed through the Robocop movies and couldn't find any familiar scenes. I remember that the three heroes of the movie were this potential "Robocop-like dude", the Asian dude, and a kid. There may have been a forth but I can't remember. At the very end of the movie, the "bad guy" was in some sort of air craft or space ship or laboratory or something, and he laughs just before the whole place explodes. I'm pretty sure the bad guy had a beard and mustache.

A: This is "Eliminators" (1986). He's a cyborg, she's a hottie, there's an asian dude as well.

As part of their experiments in time travel, Drs. Reeves and Takada
  construct a cyborg "Mandroid" with the body of a downed pilot. After
  the success of the initial experiments, Reeves decides to have the
  Mandroid scrapped. Not wishing to be taken apart, Mandroid flees with
  the help of Dr. Takeda, who is killed for his disobedience. Distraught
  by the death of his one friend, the Mandroid goes north to America in
  search of someone who can help him in getting revenge and stopping Dr.
  Reeves in whatever evil plan he intends to use his time machine for.

You can see the 'fan scene' at 1:21.00


text:
Q: Alert box not show when sign up has same username I am doing my a sign up using php, I want to show up an alert box that show "User already taken". However when I sign up an account that have same information like the last account, it's not show an alert box. It will go back to blank login page like I set it. The data duplicate not write to the mySQL but the alert box not show.
Thanks
<?php

session_start();
header('location:login.php');
$con = mysqli_connect('localhost','root','');

mysqli_select_db($con, 'userregistration');

$name = $_POST['user'];
$pass = $_POST ['password'];
$email = $_POST['mail'];
$phone = $_POST['phone'];

$s = " SELECT * FROM usertable WHERE name = '$name'";

$result = mysqli_query($con, $s);

$num = mysqli_num_rows($result);

if ($num == 1){
    $message="User already taken";
    echo "<script type='text/javascript'> alert('$message');</script>";
}else {
    $reg = "INSERT INTO usertable(name, password, email, phone ) values ('$name', '$pass','$email', '$phone')";/*, '$email','$phone'*/
    mysqli_query($con, $reg);
    echo"Registration successfull";
}
?>

A: You may need to check for successful connection/query first:
if($result=mysqli_query($con,$s)) {
   if(mysqli_num_rows($result)==1) {
         ... user already taken code ...
   } else {
         ... insert new user code ...
   }
}

See w3schools ref: https://www.w3schools.com/php/func_mysqli_num_rows.asp
This may also help you debug where the problem is occurring.


text:
Q: What is the best approach to inserting or updating an integer using stored procedure? I have a table called Employees.
This table is updated daily with a scheduled job from Active Directory.
We currently have the following stored procedure that checks if a particular employee exists in the Employee table.
If yes, update the rest of the employee records in that table.
If no, then insert the employee record into that Employee table.
In order to determine whether an employee exists in Employee table or not, employees are required to FIRST enter their employeeID. This is not an auto-generated ID. It is imported into the Employee table along with rest of employee records from Active Directory if that employee record exists in Active Directory.
The issue we are having is that we are not able insert a new employee record into Employee table. Neither are we able to update the record.
We kept getting the message that:
Cannot insert the value NULL into column 'employeeID', table 'Employees'; column does not allow nulls. INSERT fails.The statement has been terminated.
I suspect the issue is with my stored procedure but not sure what the issue is.
Any assistance is greatly appreciated.
Here is my stored proc and the code I am using to try to invoke it.
ALTER PROCEDURE [dbo].[usp_Employees]
 @FullName       varchar(75),
 @address     varchar(100),
 @city        varchar(50),
 @state       varchar(50),
 @zip         varchar(50),
 @eid  int = 0 OUTPUT
AS
BEGIN
  SET NOCOUNT ON;
  begin tran
  if exists (select * from Employees where employeeID = @eid)
   begin
    UPDATE Employees SET [empFullName] = @FullName
      ,[Address] = @address
      ,[City] = @city
      ,[State] = @state
      ,[Zip] = @zip where employeeID = @eid
    end
    else
    begin
  INSERT INTO [dbo].[Employees]
           ([empFullName]
           ,[Address]
           ,[City]
           ,[State]
           ,[Zip]
           ,[employeeID])
     VALUES
           (@FullName
           ,@address
           ,@city
           ,@state
           ,@zip
           ,@eid)

  SET @eid = SCOPE_IDENTITY()
  end
  commit tran
END

            int eid = 0;

            SqlCommand cmd = new SqlCommand("usp_Employees", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@FullName", txtfname.Text);
            cmd.Parameters.AddWithValue("@address", txtfaddress.Text);
            cmd.Parameters.AddWithValue("@city", txtcity.Text);
            cmd.Parameters.AddWithValue("@state", ddlstates.SelectedValue);
            cmd.Parameters.AddWithValue("@zip", txtfzip.Text);
            SqlParameter employeeID = cmd.Parameters.Add("@eid", SqlDbType.Int);
            employeeID.Direction = ParameterDirection.Output;

            cmd.ExecuteNonQuery();

            eid = Convert.ToInt32(employeeID.Value);

I need to grab this employeeID after insert or update and insert it in other tables.

A: I think your issue is simply you are not passing the employee id in as it should be. Pass it in with the rest of the code, and discard the output and SCOPE_IDENTITY. Amend you C# to add it to the stored proc along with the rest and it should be fine. Also, not sure of the point of using BEGIN TRAN and COMMIT TRAN without a try/catch, to either commit, or rollback. Otherwise it is just getting committed with or without:
ALTER PROCEDURE [DBO].[USP_EMPLOYEES]
 @FULLNAME       VARCHAR(75),
 @ADDRESS       VARCHAR(100),
 @CITY          VARCHAR(50),
 @STATE         VARCHAR(50),
 @ZIP           VARCHAR(50),
 @EMPLOYEEID    INT     ,
 @EID           INT
AS
BEGIN
  SET NOCOUNT ON;
  BEGIN TRAN
      IF EXISTS (SELECT * FROM EMPLOYEES WHERE EMPLOYEEID = @EID)
       BEGIN
        UPDATE EMPLOYEES
        SET [EMPFULLNAME] = @FULLNAME
          ,[ADDRESS] = @ADDRESS
          ,[CITY] = @CITY
          ,[STATE] = @STATE
          ,[ZIP] = @ZIP
         WHERE EMPLOYEEID = @EID
        END
        ELSE
        BEGIN
          INSERT INTO [DBO].[EMPLOYEES]
                   ([EMPFULLNAME]
                   ,[ADDRESS]
                   ,[CITY]
                   ,[STATE]
                   ,[ZIP]
                   ,[EMPLOYEEID])
             VALUES
                   (@FULLNAME
                   ,@ADDRESS
                   ,@CITY
                   ,@STATE
                   ,@ZIP
                   ,@EID)

      END
  COMMIT TRAN
END

A: You can use MERGE (starting with Sql Server 2008)
MERGE Employees AS target
USING (SELECT @eid,
              @fullName,
              @address,
              @city,
              @state,
              @zip) AS source (eid, fullName, address, city, state, zip)
ON (target.employeeID = source.eid)
WHEN MATCHED THEN
    UPDATE SET
        empFullName = source.fullName,
        Address = source.address,
        City = source.city,
        State = source.state,
        Zip = source.zip
WHEN NOT MATCHED THEN
    INSERT (employeeID, empFullName, Address, City, State, Zip)
    VALUES (source.eid,
            source.fullName,
            source.address,
            source.city,
            source.state,
            source.zip)
OUTPUT inserted.employeeID; -- return updated or inserted Id

A: ...
  @eid  int
as
begin
...
  SET @eid = SCOPE_IDENTITY()
  INSERT INTO [dbo].[Employees]
           ([empFullName]
           ,[Address]
           ,[City]
           ,[State]
           ,[Zip]
           ,[employeeID])
     VALUES
           (@FullName
           ,@address
           ,@city
           ,@state
           ,@zip
           ,@eid)


text:
Q: Got an srand error and would like to know if there are other ways to improve this code Basically this is a program to play with dice but i have a problem with srand. it gives an error stating "implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'"
whys that ?
Also i would like to know if there are any other ways to improve this code? currently i only know stdio.h i know there are some out there like iostream or something like that. is there a possible way to explain those to me also.
Here is the code.
i know crt secure no warning is to ignore some errors but i would still like to know why it the error pops up ?
#define _CRT_SECURE_NO_WARNINGS
 #define MAX_CHIPS 400

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void display_details(void);
int throws_die(void);
int main() so on
{
    int die1, die2, throw_sum;
    int PointToMake;

    int Games_Played = 0;
    int Games_Won = 0;
    int Games_Lost = 0;

    int CurrentChips = MAX_CHIPS;
        int BetChips;

    char PlayerName[30];
    char PlayAgain;

    display_details();

    srand(time(NULL));

    printf("Would you like to play Test your luck [y|n]?\n");
    scanf(" %c", &PlayAgain);
    while ((PlayAgain == 'y') && (CurrentChips > 0))
    {
        if (Games_Played == 0)//shows how many games played which is obviously 0
        {
            printf("A new chellenger! What is your name?\n");
            scanf(" %s", &PlayerName);
            printf("Hi %s!\n", PlayerName);
        }

        Games_Played = Games_Played + 1;//each new game it will increase by 1

        printf("Number of chips: %d\n", CurrentChips);
        printf("Place your bet:\n ");
        scanf("%d", &BetChips);

        while ((BetChips < 0) || (BetChips > CurrentChips))
        {
            printf("uuh ....You can only bet the chips you have.. (0-%d)!\n", CurrentChips);
            printf("Place your bet: \n");
            scanf("%d", &BetChips);
        }

        die1 = throws_die();
        die2 = throws_die();
        throw_sum = die1 + die2;
        printf("You Got: %d + %d = %d\n", die1, die2, throw_sum);

        if ((throw_sum == 7) || (throw_sum == 12))
        {
            //+1 to games won
            Games_Won = Games_Won + 1;
            //adding to bet balance
            CurrentChips = CurrentChips + BetChips;
            printf("XXXXX  Winner! d(^_^)  XXXXX\n");
        }

        else if ((throw_sum == 2) || (throw_sum == 3) || (throw_sum == 10))
        {

            Games_Lost = Games_Lost + 1;

            CurrentChips = CurrentChips - BetChips;
            printf("XXXXX  Loser! :( XXXXX\n");
        }

        else
        {

            PointToMake = throw_sum;
            printf("Points to make is: %d\n", PointToMake);

            die1 = throws_die();
            die2 = throws_die();
            throw_sum = die1 + die2;
            printf("    |--->> Spinned: %d + %d = %d\n", die1, die2, throw_sum);

            while (throw_sum != PointToMake && throw_sum != 7)
            {
                die1 = throws_die();
                die2 = throws_die();
                throw_sum = die1 + die2;
                printf("    |--->> Spinned: %d + %d = %d\n", die1, die2, throw_sum);
            }

            if (throw_sum == PointToMake)
            {
                printf("XXXXX  Winner! (x2 the bet) XXXXX\n");
                //x2 added to balance
                CurrentChips = CurrentChips + 2 * BetChips;
                Games_Won = Games_Won + 1;
            }
            else
            {

                Games_Lost = Games_Lost + 1;
                CurrentChips = CurrentChips - BetChips;
                printf("XXXXX  Loser!:(  XXXXX\n");
            }
        }

        if (CurrentChips > 0)
        {
            printf("You now have %d chips.\n", CurrentChips);
            printf("============================\n\n");
            printf("Play Again %s [y|n]? ", PlayerName);
            scanf(" %c", &PlayAgain);
            printf("============================\n");
        }
        else
        {
            printf("you're out of chips.\n");
            printf("XXXXX  GG TRY AGAIN NEXT TIME  XXXXX\n");
        }
    }

    if (Games_Played == 0)
    {
        printf("Oh well.... better luck next time!\n");
    }

    else if (Games_Played == 1)
    {
        printf("%s played %d game and is cashing out with %d chips!\n", PlayerName, Games_Played, CurrentChips);
        printf("   |---> Games won: %d\n", Games_Won);
        printf("   |---> Games lost: %d\n", Games_Lost);
        printf("Thanks for playing, come again to test that luck of yours %s.\n", PlayerName);
    }

    else
    {

        printf("%s played %d games and is cashing out with %d chips!\n", PlayerName, Games_Played, CurrentChips);
        printf("   |---> Games won: %d\n", Games_Won);
        printf("   |---> Games lost: %d\n", Games_Lost);
        printf("\nThanks for playing, come again to test that luck of yours %s!\n", PlayerName);
    }
    return 0;
}

void display_details(void)
{
    printf("File     :.... assignment.c\n");
    printf("Author   :.... \n");
    printf("Stud ID  :.... \n");
    printf("Email ID :.... \n");
    printf("This is my own work as defined by the \n");
    printf("University's Academic Misconduct Policy.\n");
}

int throws_die(void)
{
    return 1 + rand() % 6;

A: srand is defined more or less like this:
void srand(unsigned int seed);

time is defined more or less like this:
__int64 time(__int64 *t);

Thus you pass an __int64 (64 bits) into an unsigned int (32 bits) parameter, which is not possible without potential trunctation. That's what the warning message is telling you.


text:
Q: What does "sex idiot" mean? In this video clip from 30 Rock, the woman says

Ryan is my sex idiot.

I wonder what it means?
Is it a general usage to add an adjective to "idiot" to give it some special meaning?

A: To be clear when discussing English/what exists in the English language, I would take anything having to do with Ryan Lochte with a grain of salt.
He's known to be an "idiot" in general, and I think here it may mean something along the lines of, all he's worth to her is sex.  Good looking, athletic, but when it comes to the smarts, he's just plain stupid.
So maybe they just have sex, without anything else. Because... he's an idiot.
Hope that helps, haven't seen this show.


text:
Q: How to convert working jquery 1.7.2 code into jquery 1.3.2 The below code works fine in jquery 1.7.2 but does not in jquery 1.3.2
$(".selectallItem8CheckBox").click(function () {
        $(".checkboxItem8select").prop("checked", $(".selectallItem8CheckBox").prop("checked"))
    });

Alternative to this would help.
Thanks in advance

A: Use .attr() instead of .prop() for jquery 1.5 and below versions:
$('.checkboxItem8select').attr('checked',$(".selectallItem8CheckBox").attr("checked"));

A: .prop() wasn't added til 1.6. Use .attr() instead


text:
Q: Como pegar o ID de um usuário em uma ListView e usar como uma variável em outra Activity? Estou fazendo meu TCC e estou tendo dificuldades em retirar o ID de algum usuário da ListView e usá-lo em outra Activity (A intenção é que quando o usuário segurar o clique em cima de alguém da lista, apareça uma popup (popAdd) perguntando se ele deseja enviar uma solicitação de amizade para essa pessoa (E pra isso eu preciso de saber o ID da pessoa escolhida)
popAddAmigo.java
public class popAddAmigo extends Activity {

String urlAddress="http://192.168.1.107/line/Pesquisa.php";
// String urlAddress="http://172.16.2.15/line/Pesquisa.php";
SearchView sv;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.popaddamigo);

    lv           = (ListView) findViewById(R.id.listaAmigos);
    sv           = (SearchView) findViewById(R.id.svPesquisa);

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            SenderReceiver sr = new SenderReceiver(popAddAmigo.this, urlAddress, query, lv);
            sr.execute();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            SenderReceiver sr = new SenderReceiver(popAddAmigo.this, urlAddress, query, lv);
            sr.execute();
            return false;
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       final int pos, long id) {

            Intent abreAdd = new Intent(popAddAmigo.this, popAdd.class);
            startActivity(abreAdd);

            return false;
        }
    });

}

}

Parser.java
public class Parser extends AsyncTask<Void,Void,Integer> {

Context c;
String data;
ListView lv;

ArrayList<String> names = new ArrayList<>();

public Parser(Context c, String data, ListView lv) {

    this.c    = c;
    this.data = data;
    this.lv   = lv;

}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Integer doInBackground(Void... params) {
    return this.parse();
}

@Override
protected void onPostExecute(Integer integer) {
    super.onPostExecute(integer);

    if(integer==1) {

        ArrayAdapter adapter = new ArrayAdapter(c,R.layout.listalayout,names);
        lv.setAdapter(adapter);

    } else {

        Toast.makeText(c,"Não encontramos resultado :(",Toast.LENGTH_SHORT).show();

    }
}

private int parse() {

    try {

        JSONArray ja = new JSONArray(data);
        JSONObject jo = null;
        names.clear();

        for(int i=0;i<ja.length();i++) {
            jo=ja.getJSONObject(i);
            String name = jo.getString("nome");
            names.add(name);

        }
        return 1;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return 0;
}
}

SenderReceiver.java
public class SenderReceiver extends AsyncTask<Void,Void,String> {

Context c;
String urlAddress;
String query;
ListView lv;
ProgressDialog pd;

public SenderReceiver(Context c, String urlAddress, String query, ListView lv,ImageView...imageViews) {

    this.c = c;
    this.urlAddress = urlAddress;
    this.query = query;
    this.lv = lv;

}

@Override
protected void onPreExecute() {

    super.onPreExecute();
    pd=new ProgressDialog(c);
    pd.setTitle("Pesquisando...");
    pd.setMessage("Por favor aguarde.");
    pd.show();

}

@Override
protected String doInBackground(Void... params) {
    return this.sendAndReceive();
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    pd.dismiss();

    lv.setAdapter(null);

    if(s != null) {
        if(!s.contains("null")) {

            Parser p = new Parser(c,s,lv);
            p.execute();

        } else {

            Toast.makeText(c.getApplicationContext(), "Usuário não encontrado.", Toast.LENGTH_LONG).show();

        }
    } else {

        Toast.makeText(c.getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();

    }
}

private String sendAndReceive()
{
    HttpURLConnection con = Connector.connect(urlAddress);

    if(con==null) {
        return null;
    } try {

        OutputStream os = con.getOutputStream();
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
        bw.write(new DataPackager(query).packageData());
        bw.flush();
        bw.close();
        os.close();
        int responseCode = con.getResponseCode();

        if(responseCode==con.HTTP_OK) {

            InputStream is = con.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            if(br != null) {
                while ((line=br.readLine()) != null) {
                    response.append(line+"n");
                }
            } else {
                return null;
            }
            return response.toString();
        } else {
            return String.valueOf(responseCode);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
}

DataPackager.java
public class DataPackager {

String query;

public DataPackager(String query) {
    this.query = query;
}

public String packageData() {

    JSONObject jo = new JSONObject();
    StringBuffer queryString = new StringBuffer();

    try {

        jo.put("Query",query);
        Boolean firstValue = true;
        Iterator it = jo.keys();

        do {
            String key = it.next().toString();
            String value = jo.get(key).toString();
            if(firstValue) {
                firstValue = false;
            } else {
                queryString.append("&");
            }

            queryString.append(URLEncoder.encode(key,"UTF-8"));
            queryString.append("=");
            queryString.append(URLEncoder.encode(value,"UTF-8"));

        } while (it.hasNext());

        return queryString.toString();

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

}

A: Dentro do método onItemLongClick(AdapterView<?> adapterView, ...) você deve obter o usuário e passá-lo dentro da intent para iniciar a activity.
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View arg1, final int pos, long id) {

    /*
    Converte do tipo Object para o tipo que você
    passou no seu adapter, por exemplo:
    */
    Usuario usuario = (Usuario) adapterView.getItemAtPosition(pos);

    Intent abreAdd = new Intent(popAddAmigo.this, popAdd.class);
    // Aqui você passa o id para a intent, com a chave "idUsuario"
    abreAdd.putExtra("idUsuario", usuario.getId());
    startActivity(abreAdd);

    return true;
}

popAdd.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pop_add);

    // Obtém o id do usuário
    int idUsuario = getIntent().getIntExtra("idUsuario", 0);
}

ATUALIZAÇÃO
Você vai precisar de uma classe Usuario para armazenar as informações dele. No seu caso, seria o id e o nome.
Usuario.java
public class Usuario {
    private int id;
    private String nome;

    public Usuario(JSONObject object) {
        id = object.getInt("id");
        nome = object.getString("nome");
    }

    public int getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }
}

Você também vai precisar de uma classe customizada para exibir o usuário na lista.
ExampleAdapter.java
public class ExampleAdapter extends ArrayAdapter<Usuario> {
    private final LayoutInflater inflater;

    private List<Usuario> usuarioList;

    public ExampleAdapter(@NonNull Context context, List<Usuario> usuarioList) {
        super(context, R.layout.listalayout);
        inflater = LayoutInflater.from(context);
        this.usuarioList = usuarioList;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        super.getView(position, convertView, parent);

        // Aqui você tem que verificar se o convertView está nulo,
        // porque pode acontecer de ele ser nulo
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listalayout, parent, false);
        }

        Usuario usuario = getItem(position);

        TextView txtNome = (TextView) convertView.findViewById(R.id.txt_nome);

        txtNome.setText(usuario.getNome());

        return convertView;
    }

    @Override
    public Usuario getItem(int position) {
        return usuarioList.get(position);
    }

    @Override
    public int getCount() {
        return usuarioList == null ? 0 : usuarioList.size();
    }
}

E por último altera o seu Parser para processar uma lista de Usuarios ao invés de Strings.
Parser.java
public class Parser extends AsyncTask<Void,Void,Integer> {

    Context c;
    String data;
    ListView lv;

    ArrayList<Usuario> usuarios = new ArrayList<>();

    public Parser(Context c, String data, ListView lv) {

        this.c    = c;
        this.data = data;
        this.lv   = lv;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        return this.parse();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);

        if(integer==1) {

            ExampleAdapter adapter = new ExampleAdapter(c,usuarios);
            lv.setAdapter(adapter);

        } else {

            Toast.makeText(c,"Não encontramos resultado :(",Toast.LENGTH_SHORT).show();

        }
    }

    private int parse() {

        try {

            JSONArray ja = new JSONArray(data);
            usuarios.clear();

            for(int i=0;i<ja.length();i++) {
                usuarios.add(new Usuario(ja.getJSONObject(i)));

            }
            return 1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }
}


text:
Q: convert Base64 string to image in android In an android application we are receiving a byte64 string.I need to convert these strings to images.
I tried getting it but couldnot find any.
Please let me know your valuable suggestions
Thanks in advance :)

A: I had a similar problem for a week. So I built a phonegap plugin for Andriod which i shared here.
Hope that helps. :)


text:
Q: How do I avoid repeating a code in redux + react. Example inside I have redux selectors here in rootReducer:
export const getUser = (state) => fromUser.userGetter(state.user);
export const getUsers = (state) => fromUsers.getUsers(state.users);

// this one is just a function where 1st parameter is array, 2nd is string of ID
export const getUserNameById = (users, id) => {
    let user = ''

    if(users)
        user = users.find(user => user._id === id).name
    return user
}

// this one is selector, which does work fine
export const getUserName = createSelector([getUsers, getUser], (users, id) => {
    let user = ''

    if(users)
        user = users.find(user => user._id === id).name
    return user
});

BUT when I try do this to save line of codes:
export const getUserName = createSelector([getUsers, getUser], getUserNameById (getUsers, getUser));

it gives me error by saying getUsers.find is not an array and indeed when I console.log(getUser) it doesn't return me an array from a store, but returns me a function getUsers(state). Any ideas what should I do? Thank you!

A: @FrozenKiwi is correct that you just need to pass the function rather than calling it.
export const getUserName = createSelector([getUsers, getUser], getUserNameById);

At runtime, the function that you pass as the second argument will be called with the values selected by the selectors of your first argument. The created selector is basically this, but with memoization:
const getUserName = (state) => getUserNameById(getUsers(state), getUser(state));

This will work assuming that getUser returns just an id.  But the name implies that it might return a whole user object?  So double check that.
There is a potential run-time error in your current code if users.find doesn't return a match.  I suggest cleaning it up like this:
export const getUserNameById = (users, id) => {
    return (users || []).find( user => user._id === id)?.name || '';
}

*

*uses an empty array if undefined (users || []) so that you can always call find.  I'm doing this instead of setting a default value users = [] because some linters complain if optional arguments come before required ones.

*uses optional chaining ?. to access name only when a user was found

*returns an empty string if name is falsey


text:
Q: Lightweight Flash Video Recording Server I am currently using Wowza Media server for recording videos from webcam using Flash. However servers like Wowza, Red5 & Flash Media Server seem to be overkill for merely this task.
Are there any alternative lightweight video recording servers which can be used for the purpose? My load would not be more than 5 users at a time and my server is Ubuntu 8.04.
I tried Haxe Server but project seems to be outdated and won't compile on my Ubuntu.

A: The good thing about projects like Red5 is that you can strip them down to fit your need. We are componentizing Red5 for version 1.0; I'll keep your case in mind.


text:
Q: Can't find method Shiny.IShinyStartup.ConfigureServices with Prism 8 The error I'm getting during app startup is the following:

Parent class vtable failed to initialize, due to: Could not load list of method overrides due to Method not found: void Shiny.IShinyStartup.ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection) assembly:/Users/merickson/Library/Developer/CoreSimulator/Devices/D19E269D-A3E5-46C2-BB9C-94A122EA02DC/data/Containers/Bundle/Application/F9A34529-8F64-4868-8D7F-389C77DB54BC/PrismSizeTest.iOS.app/Shiny.Prism.dll type:PrismStartup member:(null)

I'm not sure if I'm missing a NuGet, maybe wrong version of one or more NuGets, or am I initializing something wrong?  Any help is appreciated.
I've been able to replicate this with a bare bones solution which I can provide if necessary.  Here are the main files involved:
App.xaml.cs
public partial class App : PrismApplicationBase
{
    public App(IPlatformInitializer initializer)
        : base(initializer)
    {
    }

    protected override async void OnInitialized()
    {
        InitializeComponent();

        await NavigationService.NavigateAsync("NavigationPage/MainPage");
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterSingleton<IAppInfo, AppInfoImplementation>();

        containerRegistry.RegisterForNavigation<NavigationPage>();
        containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
    }

    protected override IContainerExtension CreateContainerExtension() => ContainerLocator.Current;
}

AppDelegate.cs
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        ShinyHost.Init(new ApplePlatform(), new MyStartup());

        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App(new iOSInitializer()));

        return base.FinishedLaunching(app, options);
    }
}

public class iOSInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        // Register any platform specific implementations
    }
}

MyStartup.cs
public class MyStartup : PrismStartup
{
    protected override void ConfigureServices(IServiceCollection services)
    {
        services.UseGps<GpsDelegate>();
    }
}

NuGets installed:

A: There is nothing directly wrong with the code... however the latest versions of Shiny have breaking ABI changes that make Shiny.Prism and Shiny.Core incompatible which is the result of the issue shown here...
For more information you can track the issue at: https://github.com/dansiegel/Prism.Container.Extensions/issues/183


text: Q: How to create an MLA citation maker in Python through web scraping? I'm a beginner in Python, and for my CS50P final project, I want to make a desktop program that goes through a web page and extracts the title, author's name, publisher, etc. and puts them into a dictionary or something, and then formats them  into a citation. How exactly do I do this, knowing that I only have experience in Python?


text: Q: Lower bound $L_1$ error Let $\mathcal{D}$ be a joint distribution over $X, Y$ and $h:\mathcal{X}\to\mathcal{Y}$ be a function mapping. Assume that there exists a universal constant $M > 0$ such that $\|h\|_\infty \leq M$ and $|Y|\leq M$. I am interested in lower bounding the $\ell_1$ error $\mathbb{E}_{\mathcal{D}}[|h(X) - Y|]$ using some distance metric between the marginal distribution of $Y$ and the induced distribution of $h(\cdot)$ over $\mathcal{Y}$, are there any common techniques that could be used to construct such lower bound?


text:
Q: Permutation with two array in PHP I have list of 100 First Name and 100 Surname.
I want use mix of all the combinations without repetition.
Do you have some math solutions for this?

A: this is called "cartesian product", php man page on arrays http://php.net/manual/en/ref.array.php shows some implementations (in comments).
and here's yet another one:
function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

$cross = array_cartesian(
    array('A', 'B', 'C'),
    array('1', '2')
);

print_r($cross);


text:
Q: Как проверить работоспособность функции и если работает заблокировать event('click') Есть 2 функции которые выполняются каждую секунду и 2 кнопки которые запускают и останавливают эти функции, с кнопкой stop всё хорошо она без проблем работает, но когда нажимаю несколько раз подряд start функция начинает уменьшать интервал выполнения с каждым нажатием, отсюда 2 вопроса:

*

*Как сделать чтобы кнопка start не была доступна, пока работают
функции и не нажата кнопка stop, а после нажатия stop её можно было
нажать 1 раз(чтобы функции setInterval работали корректно)?

*Можно ли сделать так чтобы кнопки обе работали(без нарушения setInterval) и их можно было нажать только по одному разу на чистом
js без Jquery?
 const mySetDate = setInterval(setDate, 1000);
const mySetBg = setInterval(backgr, 1000);
const stopButton = document.querySelector("button[value=stop]");
const startButton = document.querySelector("button[value=go]");
startButton.addEventListener('click', myStartFunction);
stopButton.addEventListener('click', myStopFunction);

function myStopFunction() {
  clearInterval(mySetDate);
  clearInterval(mySetBg);
}

function myStartFunction(e) {
  setInterval(setDate, 1000);
  setInterval(backgr, 1000);
}

A: Не "функция уменьшает интервал", а еще одно выполнение запускается с тем же интервалом, и они начинают вызываться вперемешку.

const mySetDate = setInterval(setDate, 1000);
const mySetBg = setInterval(backgr, 1000);

const stopButton = document.querySelector("button[value=stop]");
const startButton = document.querySelector("button[value=go]");
startButton.addEventListener('click', myStartFunction);
stopButton.addEventListener('click', myStopFunction);

function myStopFunction() {
  clearInterval(mySetDate);
  mySetDate = null;
  clearInterval(mySetBg);
  mySetBg = null;
}

function myStartFunction(e) {
  if (!mySetDate)
    mySetDate = setInterval(setDate, 1000);
  if (!mySetBg)
    mySetBg = setInterval(backgr, 1000);
}

A: var allowStart = true;
function myStopFunction(){
    if(allowStart) return;
    clearInterval(mySetDate);
    clearInterval(mySetBg);
    allowStart = true;
}

function myStartFunction(e){
    if(!allowStart) return;
    setInterval(setDate, 1000);
    setInterval(backgr, 1000);
    allowStart = false;
}


text:
Q: How to prove list concatenation is not commutative using coq? Sorry I am new to coq. I'm wondering how to prove list concatenation is not commutative using coq?

A: You just need to exhibit a counterexample. For instance:
Require Import Coq.Lists.List.
Import ListNotations.

Theorem list_app_is_not_commutative :
  ~ (forall A (l1 l2 : list A), l1 ++ l2 = l2 ++ l1).
Proof.
intros H.
specialize (H bool [true] [false]).
simpl in H.
congruence.
Qed.

A: Like this ?
From Coq Require Import List.

Import ListNotations.

Goal [true] ++ [false] <> [false] ++ [true].
Proof. easy. Qed.


text:
Q: ASP.NET Core: Add custom argument to the method using Action Filter I want to add a custom argument to the method using a custom action filter.
What I tried
I created an action filter that injects an argument using context.ActionArguments. After this change, a GET call using this action filter returns 415 Unsupported Media Type if I do not specify Context-Type as application/json.
Action Filter
    public class AddArgumentActionFilterAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string itemId = context.RouteData.Values["itemId"] as string;
            MyClass item = await db.GetItemAsync(itemId); // Some call to the database
            context.ActionArguments["item"] = item;
            await next();
        }
    }

Controller Method
        [HttpGet]
        [Route("items/{itemId}")]
        [AddArgumentActionFilter]
        public async Task<ActionResult<RoomWebEntity>> GetItem(MyClass item)
        {
            // do stuff
        }

Sending GET request to items/{itemId} returns 415 Unsupported Media Type. If I specify Content-Type as application/json in the header then the call is successful.
There seemed to be some validation done when an action argument is an object. Is there a way to add an argument under the hood without changing the behavior of the HTTP call?
Output of dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.200-preview-014883
 Commit:    4e2a0ee959

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.18363
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.1.200-preview-014883\


text:
Q: how send multi image From img src to controller in asp.net mvc other data the from send form.submit()
I first read the img tags value then converted it to a file , then added it to the form But its value in the controller is null
        var imgs = document.getElementsByName('images');
        var imagefiles = [];
        var data = new FormData();

        for (var i = 0; i < imgs.length; i++) {
            var image = dataURLtoFile(imgs[i].src, FileName());
            imagefiles.push(image);
        }
        data.append('files', imagefiles);
        $("#Form").submit();

      public ActionResult Create(ProductsModel model, HttpPostedFileBase[] files )
      {}


text:
Q: Ceramic Capacitor whistle in DC-DC Converter I have designed a 24V Input, 5V and 30W output DC-DC converter (TPS40170) which is working fine under normal conditions.  This was approved with an evalboard.
But my load is being switched with a frequency between 100Hz-17kHz - I can hear an audible sound.
I first thought:

*

*I have to change the capacitor package. I moved from 0805 to 1210 footprint. But this does not solve my problem.

*I even increased the value of capacitor from 4x22µF (0805) to 3x47µF (1210). This did not solve the problem

*Using the evalbord and making the same test, I am also getting the same sound.
I am now thinking to increase the frequency to more than 20kHz which on test is working, but my µC on the SPI-Bus will not handle this case.
What can I do to solve this problem  withhout changing my µC and also increase the frequency (more than 7kHz which is the maximum.)

A: If you check the ceramic caps and they are definitely the source of the noise you can try adding a drop of hot glue over the offending piece(s). Ceramic caps seldom dissipate much power so should not affect the performance. And if it does, you can just peel it off.


text:
Q: How to show age in PHP I'm trying to show an age from this code:
$dob =  $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay'];
$age = date_diff(date_create($dob), date_create('today'))->y;

echo $age;

but it's not working, tried different kind of tutorials but I'm still having trouble, what should I do?
Cheers

A: Basic Example
$date1 = new DateTime('2011-03-12');
$date2 = new DateTime('2008-03-09');

$diff = $date2->diff($date1);

echo $diff->y;

Your Example
$entrantInfo['dobYear'] = '2011';
$entrantInfo['dobMonth'] = '03';
$entrantInfo['dobDay'] = '12';

$dob =  $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay']; // Get dynamic date

$date1 = new DateTime($dob);
$date2 = new DateTime(); // Get current date

$diff = $date2->diff($date1);

echo $diff->y;

Would you please try above code?


text:
Q: .htaccess force https for a backbone.js application I want to change my current .htaccess which enables a backbone application to work without hashtags - to enable the same functionality but forcing over https... can anyone help with this please?
# html5 pushstate (history) support:
<ifModule mod_rewrite.c>
  RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L]
</ifModule>

A: Forcing request to be HTTPS means you have to redirect the client/browser. If that doesn't mess up your setup, then all you need to do is add these rules right below the RewriteEngine On line:
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]


text:
Q: How to get logged in user's uid from session in Django? I have implemented a registration/login/authentication system using this Django guide.
But, how would I access a user's information from my views so I can send the user's information to a template file?
I want to be able to access a user's ID so I can submit a form with the user's ID attached to the form.

A: In case anyone wants to actually extract a user ID from an actual Session object (for whatever reason - I did!), here's how:
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
session_data = session.get_decoded()
print session_data
uid = session_data.get('_auth_user_id')
user = User.objects.get(id=uid)

Credit should go to Scott Barnham

A: This:
def view(request):
    if request.user.is_authenticated:
         user = request.user
         print(user)
         # do something with user

A: An even easier way to do this is to install django-extensions and run the management command print_user_for_session.
And this is how they do it:
https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/print_user_for_session.py

A: There is a django.contrib.auth.models.User object attached to the request; you can access it in a view via request.user. You must have the auth middleware installed, though.

A: In case hwjp solution doesn't work for you ("Data is corrupted"), here is another solution:
import base64
import hashlib
import hmac
import json

def session_utoken(msg, secret_key, class_name='SessionStore'):
    key_salt = "django.contrib.sessions" + class_name
    sha1 = hashlib.sha1((key_salt + secret_key).encode('utf-8')).digest()
    utoken = hmac.new(sha1, msg=msg, digestmod=hashlib.sha1).hexdigest()
    return utoken

def decode(session_data, secret_key, class_name='SessionStore'):
    encoded_data = base64.b64decode(session_data)
    utoken, pickled = encoded_data.split(b':', 1)
    expected_utoken = session_utoken(pickled, secret_key, class_name)
    if utoken.decode() != expected_utoken:
        raise BaseException('Session data corrupted "%s" != "%s"',
                            utoken.decode(),
                            expected_utoken)
    return json.loads(pickled.decode('utf-8'))

s = Session.objects.get(session_key=session_key)
decode(s.session_data, 'YOUR_SECRET_KEY'))

credit to: http://joelinoff.com/blog/?p=920


text:
Q: Nuget packaging in VS2017 csproj project I have following project structure with 3 Nuget dependencies:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>net45;net46</TargetFrameworks>
    ...
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NUnit" Version="3.9.0" />
    <PackageReference Include="Selenium.WebDriver" Version="3.7.0" />
    <PackageReference Include="SpecFlow.CustomPlugin" Version="2.2.1" />
  </ItemGroup>

</Project>

It's really cool that VS2017 allows creating NuGet packages out of the box.
But what can do if I want to include custom NuGet references and don't wanna include references I use now?
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    ...
    <dependencies>
      <dependency id="SpecFlow" version="2.2.0" />
      <dependency id="NUnit" version="3.0.0" />
      <dependency id="Autofac" version="[3.3.0,3.5.2]" />
      <dependency id="Autofac.Configuration" version="[3.3.0]" />
      <dependency id="Selenium.WebDriver" version="3.0.0" />
    </dependencies>
  </metadata>
</package>

I this case I need to have Autofac with my lib but I don't need it to build my lib.
Or I don't need SpecFlow.CustomPlugin with all dependencies in project which will use my lib but it needs have one to build itself.
I think there is a way to include NuSpec file path to new csproj but I think all csproj PropertyGroup fields won't be used.
Any suggestions? Thanks

A: You should use ExcludeAsset property following official documentation
https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files
I modified the exemple in doc to match with your needs.
You can change the ExcludeAssets property if my change is not correct.
<ItemGroup>
    <!-- ... -->

    <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0">
        <ExcludeAssets>build</ExcludeAssets>

    </PackageReference>

    <!-- ... -->
</ItemGroup>

EDIT :
I think you can try something like :
<PackageReference Include="Autofac" Version="3.5.2">
        <ExcludeAssets>build</ExcludeAssets>
  </PackageReference>
<PackageReference Include="Autofac.Configuration" Version="3.3.0">
        <ExcludeAssets>build</ExcludeAssets>
  </PackageReference>

If I well understand the documentation, this will exclude Props and targets in the build folder that are used to create by nuget package to create the dependencies


text:
Q: How can I send an smtplib email to mulitple groups in python? import smtplib
from email.message import EmailMessage

list1=[
    'Person 1 <email1@outlook.com>',
    'Person 2 <email2@gmail.com>'
    ]

list2=[
    'Person 3 <email3@yahoo.com>',
    'Person 4 <email4@hotmail.com>'
    ]

masterlist = [list1, list2]

for x in masterlist:
    receivers = ", ".join(x)

msg = EmailMessage()
msg['Subject'] = 'This is a Test Email'
msg['From'] = 'Person 5 <email5@outlook.com>'
msg['To'] = receivers
msg.set_content('Ignore this message')

with smtplib.SMTP('smtp.outlook.com', 587) as smtp:
    smtp.send_message(msg)

This is the code that I have used.I would like to send this email out to certain groups, but not join all emails into one email. The way I have it now, only ends up sending the email out to the last list of emails. How should I modify this to be able to send it to multiple lists of emails?

A: You're only passing the last list of emails to msg['To'] because the program overwrites the previous lst assignments with last item in lst. So why want you just concatenate the two lists to send the email to everyone?
#masterlist = [list1, list2]

#for x in masterlist:
   #receivers = ", ".join(x)
# The .join() function doesn't do much in this situation because your lists are already separated by commas.

msg = EmailMessage()
msg['Subject'] = 'This is a Test Email'
msg['From'] = 'Person 5 <email5@outlook.com>'
msg['To'] = list1 + list2 # or use .extend() function the same is accomplished
msg.set_content('Ignore this message')

So just get rid of the masterlist variable and the for loop.

A: import smtplib
from email.message import EmailMessage

list1=[
    'Person 1 <email1@outlook.com>',
    'Person 2 <email2@gmail.com>'
    ]

list2=[
    'Person 3 <email3@yahoo.com>',
    'Person 4 <email4@hotmail.com>'
    ]

masterlist = [list1, list2]

for x in masterlist:
    msg = EmailMessage()
    msg['Subject'] = 'This is a Test Email'
    msg['From'] = 'Person 5 <email5@outlook.com>'
    msg['To'] = x
    msg.set_content('Ignore this message')

    with smtplib.SMTP('smtp.outlook.com', 587) as smtp:
        smtp.send_message(msg)

I was able to correct this by making the email section in to a for loop based on the list of emails.


text:
Q: How to get the full root directory of a ContentManager in XNA 4.0 I was wondering if anyone here knows how to find the complete path (from the drive letter onwards) of a ContentManager instance. using this I could create a string with the right number of "..\" to append to the file path when I want to load a file from anywhere else on the computer (eg. from a registry key).
So basically I'm asking if there is a way.

A: You may just want to use System.GetFolderPath with one of these locations, most likely Program Files. From there, you can navigate to your application's installation directory. You could also use .Load("\MyFolder\blah") which will load from the default disk (e.g. C:\MyFolder\blah.xnb or whatever).
If you want the path of your .exe file...
using System.IO;
using System.Windows.Forms;

//blah blah
string GetAppDir()
{
    return Path.GetDirectoryName(Application.ExecutablePath);
}


text:
Q: How to save VennDiagram as .png file in matplotlib_venn I would like to save a venn diagram as a .png (or some other file) to insert into a document.  I am using matplotlib_venn.
Following the solution here:
How to save VennDiagram as PNG figure in matplotlib_venn
I just get an empty (white) .png file as follows:

My code is:
from matplotlib_venn import venn2
from matplotlib import pyplot as plt

venn2(subsets=(5,8,4))
plt.savefig(path+'venn1A.png')

A: write plt.savefig(path+'venn1A.png') before plt.show() because plt.show() free memory space taken by graph so if you write plt.savefig(path+'venn1A.png') after plt.show() then you will got an empty(white) image.
Note:-if you don't provide the .png extension then by default savefig() method saves images in png format
FURTHER NOTE:
ATOM IDE displays diagrams automatically (ie plt.show() is implicit).  It is thus necessary to submit all lines of code together rather than each line individually.


text:
Q: Unable to get local issuer certificate (but my trusted CA-certificate store seems OK) This has kept me busy for a good number of hours. I have read a good deal other articles and Stackexchange-questions, and tried other things, but no positive result so far.
Running Ubuntu20/Nginx/Openssl v1.1.1.
Using wget, openssl s_client or curl on normal web resources, I get the message: "Verify return code: 20 (unable to get local issuer certificate)", or equivalent.
$ openssl s_client -connect google.com:443
CONNECTED(00000003)
depth=2 C = US, O = Google Trust Services LLC, CN = GTS Root R1
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=1 C = US, O = Google Trust Services LLC, CN = GTS CA 1C3
verify return:1
depth=0 CN = *.google.com
verify return:1
---
Certificate chain
 0 s:CN = *.google.com
   i:C = US, O = Google Trust Services LLC, CN = GTS CA 1C3
 1 s:C = US, O = Google Trust Services LLC, CN = GTS CA 1C3
   i:C = US, O = Google Trust Services LLC, CN = GTS Root R1
 2 s:C = US, O = Google Trust Services LLC, CN = GTS Root R1
   i:C = BE, O = GlobalSign nv-sa, OU = Root CA, CN = GlobalSign Root CA
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIN...

A bit of background. The SSL-handshake used to work for these common web resources. But I had an application that required a self-signed certificate to be added to the trusted CA-certificate store. Worked on that for a good twenty hours, tried many things. In the end decided to 'start anew' and delete my whole trusted certificate store, by deleting everything in /etc/ssl/certs/ and /usr/(local/)share/ca-certificates/) and restoring backups of common CA-certs in these folders, and a restore backup of /etc/ca-certificates.conf. Then ran update-ca-certificates. Also: I downgraded OpenSSL from v1.1.1 to 1.0.2, and then upgraded it again from 1.0.2 to 1.1.1.
Output below to demonstrate that it looks alright.
$ update-ca-certificates -f
Clearing symlinks in /etc/ssl/certs...
done.
Updating certificates in /etc/ssl/certs...
129 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d...
done.

As far as I see, my trusted cert-store seems fine: it contains the requested root-certificates in the chain. Notice in the above example there are two root-certificates: (1) C = US, O = Google Trust Services LLC, CN = GTS Root R1, and (2) C = BE, O = GlobalSign nv-sa, OU = Root CA, CN = GlobalSign Root CA.
I am sure these two root-certificates are in my trusted CA-store. Here's a snippet of the output from a trick suggested by Marlon in NginX client cert authentication fails with "unable to get issuer certificate"
$ awk -v cmd='openssl x509 -noout -subject' ' /BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt
...
subject=OU = GlobalSign ECC Root CA - R4, O = GlobalSign, CN = GlobalSign
subject=OU = GlobalSign ECC Root CA - R5, O = GlobalSign, CN = GlobalSign
subject=C = BE, O = GlobalSign nv-sa, OU = Root CA, CN = GlobalSign Root CA
subject=OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign
subject=OU = GlobalSign Root CA - R3, O = GlobalSign, CN = GlobalSign
subject=OU = GlobalSign Root CA - R6, O = GlobalSign, CN = GlobalSign
...
subject=C = US, O = Google Trust Services LLC, CN = GTS Root R1
subject=C = US, O = Google Trust Services LLC, CN = GTS Root R2
subject=C = US, O = Google Trust Services LLC, CN = GTS Root R3
subject=C = US, O = Google Trust Services LLC, CN = GTS Root R4

So the root-certificates that the host in my example (google.com) uses are there in my trusted CA-store. Why am I still getting "Verification error: unable to get local issuer certificate"?
Additionally, I'll add the output when I explicitly define the path to the trusted CA-cert store. The SSL-handshake succeeds! What am I overlooking?
$ openssl s_client -CApath /etc/ssl/certs -connect google.com:443
CONNECTED(00000003)
depth=2 C = US, O = Google Trust Services LLC, CN = GTS Root R1
verify return:1
depth=1 C = US, O = Google Trust Services LLC, CN = GTS CA 1C3
verify return:1
depth=0 CN = *.google.com
verify return:1
---
Certificate chain
 0 s:CN = *.google.com
   i:C = US, O = Google Trust Services LLC, CN = GTS CA 1C3
 1 s:C = US, O = Google Trust Services LLC, CN = GTS CA 1C3
   i:C = US, O = Google Trust Services LLC, CN = GTS Root R1
 2 s:C = US, O = Google Trust Services LLC, CN = GTS Root R1
   i:C = BE, O = GlobalSign nv-sa, OU = Root CA, CN = GlobalSign Root CA
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIN...
...
-----END CERTIFICATE-----
subject=CN = *.google.com

issuer=C = US, O = Google Trust Services LLC, CN = GTS CA 1C3

---
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: ECDSA
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 6523 bytes and written 392 bytes
Verification: OK
---
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 256 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---

To conclude: I am likely overlooking something, some setting or parameter that may have gotten reset, or set wrongly during my hours of tinkering with the system. However, I just cannot see it, and the sources I've read and tried so far mostly mention making sure my trusted CA-cert store is complete, which I think it is. What am I overlooking? Where should I look, or what should I do to get a grip on this problem?

A: Solved my own problem and will share the solution here. The certificates in the trusted CA-store were indeed fine. My problem was caused by uninstalling and rebuilding OpenSSL.
The 'fresh' OpenSSL install directory contains among other things a /certs and /private folder and an openssl.cnf file.
$ ll
total 68
drwxr-xr-x  9 root root  4096 Jul 28 12:10 ./
drwxr-xr-x 11 root root  4096 Jul 26 21:58 ../
drwxr-xr-x  2 root root  4096 Jul 26 21:59 bin/
drwxr-xr-x  2 root root  4096 Jul 26 21:59 certs/
-rw-r--r--  1 root root   412 Jul 28 12:10 ct_log_list.cnf
-rw-r--r--  1 root root   412 Jul 28 12:10 ct_log_list.cnf.dist
drwxr-xr-x  3 root root  4096 Jul 26 21:59 include/
drwxr-xr-x  4 root root  4096 Jul 26 21:59 lib/
drwxr-xr-x  6 root root  4096 Jul 26 21:58 man/
drwxr-xr-x  2 root root  4096 Jul 28 12:10 misc/
-rw-r--r--  1 root root 10835 Jul 26 21:59 openssl.cnf
-rw-r--r--  1 root root 10909 Jul 28 12:10 openssl.cnf.dist
drwxr-xr-x  2 root root  4096 Jul 26 21:59 private/

But this server (provisioned by a third party, not a 'fresh, default Ubuntu20) stores its trusted CA-store in /etc/ssl/certs. That is why, in simple terms, OpenSSL did not 'find' my CA-store with all the common certificates. The solution was to delete this original folder, and add symlink to my actual trusted CA-store:
$ rmdir certs
$ ln -s /etc/ssl/certs ./certs

Also added:
$ rm openssl.cnf
$ rmdir private
$ ln -s /etc/ssl/openssl.cnf ./openssl.cnf
$ ln -s /etc/ssl/private ./private

And now it looks like:
$ ll
total 48
drwxr-xr-x  7 root root  4096 Jul 30 17:02 ./
drwxr-xr-x 11 root root  4096 Jul 26 21:58 ../
drwxr-xr-x  2 root root  4096 Jul 26 21:59 bin/
lrwxrwxrwx  1 root root    14 Jul 30 16:57 certs -> /etc/ssl/certs/
-rw-r--r--  1 root root   412 Jul 28 12:10 ct_log_list.cnf
-rw-r--r--  1 root root   412 Jul 28 12:10 ct_log_list.cnf.dist
drwxr-xr-x  3 root root  4096 Jul 26 21:59 include/
drwxr-xr-x  4 root root  4096 Jul 26 21:59 lib/
drwxr-xr-x  6 root root  4096 Jul 26 21:58 man/
drwxr-xr-x  2 root root  4096 Jul 28 12:10 misc/
lrwxrwxrwx  1 root root    20 Jul 30 17:02 openssl.cnf -> /etc/ssl/openssl.cnf
-rw-r--r--  1 root root 10909 Jul 28 12:10 openssl.cnf.dist
lrwxrwxrwx  1 root root    16 Jul 30 17:02 private -> /etc/ssl/private/

Found the solution by logging in to another server that was provisioned the same way and looking up the OPENSSLDIR (OpenSSL install directory).
openssl version -d

They differred between these two servers. Went to look inside this folder. Found symlinks in the folder on the server where it was working. Found an empty 'certs' folder on the server where it wasn't. Added symlinks. Solved.