segmentation fault Segfault python extension in c++

Question: This extension is used to search data in a linked list and return it as a nested tuple of lists.[(ele1,ele2,),...]
However  when the program runs for a period of time, segment fault will occur. I know that there might be something I'm missing with python memory management, but it's not clear to me exactly where the problem is.
header file:
#include "Python.h"
#define  PY_EXTENSION_H
#ifndef TESTFORSCORE_MAIN_H
#define TESTFORSCORE_MAIN_H
#define MAX(a,b) a<b?b:a
#define MIN(a,b) a<b?a:b
typedef unsigned char byte;
typedef struct{
    char* content;
    int content_len;
    int features_len;
    byte* features;
    long id;
}NODE;

typedef struct LISTNODE{
    LISTNODE* next;
    NODE* node;
}LISTNODE;

extern "C"{
static PyObject *compare(byte* features1,byte* features2,int min);
static PyObject *init_map(byte* features,int features_len,char* content ,int content_len,long id);
static PyObject *get_list_size(PyObject *self, PyObject *args);
static PyObject *search(PyObject *self, PyObject *args);
}
#endif

cpp
#define PY_SSIZE_T_CLEAN
#include "example.h"

static LISTNODE *head_of_map=(LISTNODE*) PyMem_RawMalloc(sizeof(LISTNODE));
LISTNODE *current_head=head_of_map;
long COUNTER=0;
static PyObject *get_list_size(PyObject *self, PyObject *args)
{
    return Py_BuildValue("l", COUNTER);
}
static PyObject *init_map(PyObject *self, PyObject *args){//
    PyObject  *obj1,*obj2;
    int len1,len2;
    long activity;
    byte *features,*tmp_b;
    char *content,*tmp_c;
    if (!PyArg_ParseTuple(args,"SSiiL", &obj1,&obj2,&len1,&len2,&activity)) {
        return NULL;
    }

    features=(byte *) PyBytes_AsString(obj1);
    content=PyBytes_AsString(obj2);

    LISTNODE *list_node=(LISTNODE*) PyMem_RawMalloc(sizeof(LISTNODE));
    NODE *node=(NODE*) PyMem_RawMalloc(sizeof(NODE));
    tmp_b=(byte *) PyMem_RawMalloc(sizeof(byte)*len1);
    tmp_c=(char *) PyMem_RawMalloc(sizeof(char)*len2);
    memcpy(tmp_b,features,len1);
    memcpy(tmp_c,content,len2);
    node->features=tmp_b;
    node->content=tmp_c;
    node->features_len=len1;
    node->content_len=len2;
    node->id=activity;
    list_node->node=node;
    current_head->next=list_node;
    current_head=current_head->next;
    COUNTER+=1;
    // err maybe here
    //Py_DecRef(obj1);
    //Py_DecRef(obj2);
    PyMem_FREE(tmp_b);
    PyMem_Free(tmp_c);
    return Py_BuildValue("b",0);
}

static double _compare(byte* features1,byte* features2,int min){
    //do something ...
    return   0.3;
}
static PyObject *search(PyObject *self, PyObject *args){//(byte* features,char *content,int features_len,int content_len,double threshold,int _idx){

    PyObject *obj1,*obj2,*tuple,*content,*matched_content,*score1,*_id,*matched_id, *lis= PyList_New(0);
    byte* features;
    char *c_content,*tmp_content,*tmp_matched;
    int content_len,length ,idx;
    double  threshold,score;
    LISTNODE *p = head_of_map;

    if (!PyArg_ParseTuple(args,"SSiidi", &obj1,&obj2,&length,&content_len,&threshold,&idx)) {

        return NULL;
    }
    features = (unsigned  char*)PyBytes_AsString(obj1);
    c_content = PyBytes_AsString(obj2);
//    Py_DecRef(obj1);
//    Py_DecRef(obj2);
    p=p->next;
    int counter=0;
    while (p!=NULL){
        counter+=1;
//      compare here
        score =0.3;
        if(score>threshold){
            //if(counter>1000) break;
            tuple      = PyTuple_New(5);
            score1     = Py_BuildValue("d",score);
            _id        = Py_BuildValue("b",idx);
            matched_id = Py_BuildValue("l",p->node->id);

            tmp_content = (char*)PyMem_Malloc(sizeof(char)*content_len);
            if (tmp_content == NULL)
                return PyErr_NoMemory();
            memcpy(tmp_content,c_content,content_len);
            content = Py_BuildValue("y#",tmp_content,(Py_ssize_t) sizeof(char)*content_len);

            tmp_matched=(char*) PyMem_Malloc(sizeof(char)*p->node->content_len);
            if (tmp_matched == NULL)
                return PyErr_NoMemory();
            memcpy(tmp_matched,p->node->content, p->node->content_len);
            matched_content = Py_BuildValue("y#",tmp_matched,(Py_ssize_t) sizeof(char)*p->node->content_len);

            PyTuple_SetItem(tuple,0,_id);
            PyTuple_SetItem(tuple,1,matched_id);
            PyTuple_SetItem(tuple,2,score1);
            PyTuple_SetItem(tuple,3,content);
            PyTuple_SetItem(tuple,4,matched_content);

            PyList_Append(lis,tuple);
            Py_DecRef(tuple);

            PyMem_Free(tmp_content);
            PyMem_Free(tmp_matched);
        }
        p=p->next;
    }

    if (PyErr_Occurred()){
        Py_DECREF(lis);
        return NULL ;
    }
    return lis;
}
static PyMethodDef exampleMethods[] = {
        {"get_list_size", get_list_size, METH_VARARGS, "example"},
        {"compare",compare,METH_VARARGS,"example"},
        {"init_map",init_map,METH_VARARGS,"example"},
        {"destory",destory,METH_VARARGS,""},
        {"search",search,METH_VARARGS,"example"},
        { NULL, NULL, 0, NULL}
};

static struct PyModuleDef ptexamplemodule = {
        PyModuleDef_HEAD_INIT,
        "example",           /* name of module */
        "A module that imports an API",  /* Doc string (may be NULL) */
        -1,                 /* Size of per-interpreter state or -1 */
        exampleMethods       /* Method table */
};
/* Module initialization function */
PyMODINIT_FUNC
PyInit_example(void) {
    PyObject *m;

    m = PyModule_Create(&ptexamplemodule);
    if (m == NULL)
        return NULL;

    /* Import sample, loading its API functions */
    return m;
}
int main() {
return 0;
}

setup file
from distutils.core import setup, Extension

setup(name='example',
      ext_modules=[
          Extension('example',
                    ['example.cpp'],
                    include_dirs = [],  # May need pysample.h directory
                    )
      ],
      version="0.0.1"
      )

test file
import example
import random
import time
import faulthandler

faulthandler.enable()
lis=[(b'\xd3\nR\x952\xbf\x8e\xeb[\xdc\xe8\xfb\xcb\x9f\xb4\xd2', b'\x856\x96\xda\xe4H_\xf9\xb3\x95\xff\xda\xc9\x05\x17\xd5'), (b'!\xdf\xc1\xc20h\xc3#\x8f\x8a\xd3\x92\xc9}\x1b\x08', b'\xa3\x03m\xd3\x96\x01\xb2\xe0\xfcOg\x87\xfa\xadA\x89'), (b'Fu\xe6\x97=\xb9\x88S\xe4Q\xc06\x9f[\x84J', b'`9\xf2- \x89\xc63?\xe3=\xf9o\x9b\xe4\x8e'), (b'\x95b\x1f\xba\x90\xfa\xe9j#\xd4\x12x\xc3\x93#\x1c', b'8f\xc4\xeb\xef\x95\xe8\x81\xec\xed1\x00j\xc2\xd2j'), (b'\xf9\x8bUk"\xa2y\xfbHI\x08\xf6\x03\xd3Ye', b'\xdf\xdb\xb6\x87\xf3\x05-p\x80%8\x8cd[43'), (b'\xee\x92\xcf\xb5\xd7\x05j\x92\xa2\x1c\xf7a.[\x05\x86', b'Y\x00|\x02\xa1\xb1wI\x08\xb3\xfc\xfc\xc7\xf5db'), (b"\x9d\xe0&\\~\xbf\xaf`\xae\xc2?'B\xfa\x95\x86", b'FL\xe3\xbb\x18\xeef\x08%\xe1\xc8,\xe3J=\xd5'), (b'\xe1\xfb\xc9n\x89\x1d\x9a\x9d\xe9\x1a\x9c\xde\xcd\xce\xbd\xcf', b'\xa7\xe0\x9b\x8bl\x88\x85,b\x04`3\xe6\x03\x85\x8e'), (b'\xc5\xbf\xd4\xa7\xe7e\xe5\x8a\xe0\xbc\xa8\xb8Yw\x0c\xd3', b":\xc2a\xb6\xd3\x1ct'z\xfe\xf9\xa7P\x8c\x1c\x7f"), (b'\xfd\xb2\x9aP\xc9\x0c\xcf\xe2\x8c\x82g\x8c{r\x94\x84', b'3B\xca\x8c\xd8\x9a\xb8\x94iyT\xd6\x05N_\x8a'), (b'\xea\x7f\x83\xaa\\\x10y\xd1h\x93l\xd9\xfe\x87\xe8j', b'jj\x8f\x1a-tq\xd9\xf1\xf8\xf7\xa5\xf6\x86\xb9\xdb'), (b'\xa4\x0b\x0f\xf1\x84\x95\x1eK\xddtH\xf0IaY:', b'p\xb5\xd9"\xb7\x0f(\r\xb1\x9bm\xc0hq\x00e'), (b'ga\x8f\xbbo\xff\xedQ\x9aM\xbe\x9cTO\xd35', b'=\xc3\x9d\x8d\xd0\xae8*1\x1d\xbf\x84\x89~76'), (b'\xaf\xe1%\xc6\xedo\xec24\xc0\x9d\xa8\x9fy=N', b'\x03m\x81\xd7B\x04\x1a*`C\xee\xccb\x1fm\xf0'), (b'\x1f\x10\xf6\x9fa\xc5\xbf\xaf\x18\xb1Mw\xba\x92&\xe1', b'\xb7\x90/\r$\t\xce}xk\xe7\xbeL\xe9\x8e\xc6'), (b'\xc8.\xd9)\x08g/\xc6\x0e\xed\xbb\xb9\xab\xad\xc8\xa1', b'\xa1c\xcc\xe9\xaasJ\x98\x1d\xd24\xc0\xf2+\x9d\xac'), (b'\xa1\x91\xa0:D\x11(\xb3\xbc0\x13\xd9\xdeD\xb9\x86', b'\x0fV\xa1\x8fl\x0c\xf4\x94=\xe7\xd0*\xdb\xcb\xa5;'), (b'bx;\x8dA\x83\xb8lca\x9c\xadV\xc2\xba/', b'\xe9\xe0\xe7({\x11\r*\xca\xf1\x08\x9bG\x830\x82'), (b"\xde\xbb\xd9\xce{%MP'Xj\xed8>\xa3a", b'\\5M\x13\x13\xb1YY\xa53y\x99$a\x91\xa5'), (b'\xf1\xda\xc4\xfe\xc6\x83\xe6\xf3\xc6\x88\x86H\xc4\x15\x12\xb4', b"\xf8'^\xe5\xb8`\x0fl\x06$\x1cz:\x93\xa1\\"), (b'\xc7@\x03Ny\x11\x96\xcb\xfe\x19\x0e\x18\xbf\xd59I', b'P\xf0\x0f\xec\xaf\x1bS\xa8\x8dt\x11O\xe8\x0f|2'), (b'\xb4\xda\xff\x8c0\x18/\xf1\xad\xa4F\x94\xb1\xad\xf4\xf1', b'.\x83(\x8f#\xe1\x11\x96\xdeS\x17\x8b\xe3]\xb5\xca'), (b'\x1d\t\x11\xc1\x15\xdc\x8e\xea\xe1\xd2\xba%J\\\xf2\xfd', b'\x070ht\xb4\xdeQ+\xc5\xb8#\xac\xd9z\xc0A'), (b' V\xe3\xc5gEg\xc5\xd5\xe1\xd6\xd7\xab\xd0\xb6n', b'\x88\x9b8\xf6\xe26\x92z\x91\xe4\x92\x1e\xbc\xc5;u'), (b'\x88}\xd7*QFn:\xd7\x12RA\xe6-\xd2)', b'\xeb\x04<\xe6\xfa)u\x9ds\xecj\xa7\x84\xcf\xa7\xa7'), (b"\xec\x04.bP)'\xb6\x08\x05\x92\x8c\x85\x1a\x84\x8f", b'@\x80\x08A\xba\x9c2Sd\xdf\x97\x07\xc4Im\xef'), (b'\x11(\x9ez\x0c\xd7\xca+7\xcc\xb0\x19,:\xcb5', b'\xf9V\x8cm\xe5-\xf9\xf1\xf6g\x86~\x8f\xd0<\x84'), (b'\xbb\xe9I=\xc74\xc9C\x0cT\x81\x9d\x85\xdeWF', b'\xfe\x1b\xb1gi\x94O\x98\xf0\x90cJ\xdb\xbf\xc7\x1e'), (b'2`\x9d\x9c\x02\xe4\xce\xf0\x14\xc0Z\xaaW\xf2\xa5\xff', b'\xe6\x05?\xe3X"\xb2O)~\x96\x8f^\x9c\x077'), (b'\xaf\x87,a\xa9\xcd\n|O\x1e\xa7\xdd\xba\x89;\x9d', b'\x98b\xac?\x13*\xf2m\xfeo=v\x96\xd5\x14\x8d'), (b'\xee\xcb{\xeeRQ\x82}\x05|\xc6S\x82\x85\xa4\xff', b'C\x93\xdes\x00\xe8cY<\xde1.\x19\xd8\xe5R'), (b'\xack\x036\x9b4\xca\xa4\x15\xbd\xd5\xbe\xd3\xd4\xfb{', b'm?\xc44>\xf4qig\x10\x8c\xeb\x11o\x99\xb4'), (b'D!\x0e*\xb3/<\x15F_\xd6;j\x85\xbe,', b'Y\xb01H\xb6:\x04_]OL\x9d\x8e\xbcp\xdc'), (b'\xe6\x9d\x02L[\x1c\xee\x8b0lu\xdd\x00\x9a\xfa!', b'J&\tkf\xa8\xeb\x1b\x90\x81\xce\\\x1b\xe8\xb6\x1d'), (b'\xcdnd\xf6\xf6\x11\x9e\x06\x10\xce\xcfP\x89\xed\xad\x02', b'I:\xe0{8H\xfcw\xb1\xe9v\x11p-/0'), (b'\xa22?\xcd\xfbU+\xbf- \xe3<\xc2\x94\xef\xb6', b'\xc7\x89\xc4K?{\x18\x1ftd\x0f\x19L}\xba\xf9'), (b'8\xf9\xe9\xd0\xa0\x97\x8e\rp\xe9\xd6[\x8e`\x93\x81', b'\xf7\x16"\xaa\x86\\b\x9d\x0c\x17"\x81\xeea\x03\x19'), (b')\xfb\x0c\xc7-D\xd8\xa4\xf7\x8d%\x02\x06\xa1\xbf\x94', b'\xc8s!s\xe2n\xee\xb0\x1eC\x15\xc0\xb4d\x08\xa7'), (b'\x7f\xa6\xdc\xf4\x9e\xe3\xda\xd3\x8a\xcb\xfc\x98,1\\\xe5', b'\x82,\xfbKL_\xe9\xc9L`\xc7"&3#\xb5'), (b'&\x98,\x88\xff\x0e\xca[\xcb\xc6t;\xbc5Y"', b'\x1b\x8bA\xd1\x8a\x9e\xe6\xce\xc4#C\x89\xe9Uon'), (b'\x1c\x1b\xac2\x86\xd6\x9a\xf9\xdd\x8d=\xa3\xff\x9a\xe1\xa5', b'\xed\x10\xed\xc1\xfe\xec\xd3\x0b\x8b\xe9\xd4?H"\xd6\x8f'), (b'9\x8f3\x8b\x02\xb7\xe7\xe5\xa1TO\x1a\xb6N\x0b\xb6', b'\xb4\x0f\xa7 \xc7\x83\x81\x18\x9cU\xfd2\x93\xb8(\xe9'), (b'\x8d\xbe\xcf`\xc3d\xde\xca\xf4\n.\x92Mrw\xa6', b';\t\xfb\x19eKt0\x8foG\xcd\xd5\xe0\xf6\x9d'), (b'd\xbcG)\xec\xc8\x04 \xdd\xd9\xf6\xd6\x91/\xb2\xd3', b'2\xba\xa8\x8a\xc5\xd6h\xab\x9c\x9e\x8b\x1b5\xcc_.'), (b'\x98\xea\xf0\xcbJ-c\xea\x81\xcf?B\x17\xcb\x99\xf9', b'\x82\x05\x14\xf2\x05q\x97\xf7Z-B\xad\xa2\x16\xa0`'), (b'\x1c\x94A\xfd\xe1\xf2\x06\x8b\x19\x80\xfa\x01g\xc3V\xaf', b'\x1c\xde\xec\xdf&\x93u\xab\xf9\x12\xfb\x04\xbc0\x99d'), (b'6\xfa\x993b\t\x12E\xd2t\xde\xb6\xfa\x98Im', b',\xa2\xf7VB\x81\x048\xc8\xbf3\xce\x8d\xecn\x82'), (b'L\xd6\x93\xbe\x02\xbeT\xa1\x8d\x88\x84\x18\xc7\xcf\x9fE', b'\x16i"\xb7\x81\xef7\x7f\xdb\x7fY\xbft\x1b\xac\xd0'), (b'\x90\xd6\xe7>Z\x8b\x83\x14\xab\xefH\xa1\x95\xe6\x8e\xc3', b'\xebJ\xfcXd\xd75I@\x12\xe9\x88\xdcG\x15\xb7'), (b'\xb8\xd6\xd03j\xed\xf9\xa0\xb1L3\x8d\x89P\xb4\xe5', b'\xe3\xdf)CR\x03s\x19\x8f\xb5\xc6\xf5\xee&W\xee'), (b'cx\xd7dQ\xc3)YR\x9c7\xf0\xb4\xe4P\xfd', b'h\xa8\x122\xceV\x8c\xf4\x12\x14J\x08\x91\xcf\x93\xfa'), (b'\x1d\x14\x86\xccTi\xdd\xc3L!\x97\x92\xb3\xb7X$', b't\x84\xa4\xe72\xa5X\xe9Ta\x03\x0c\xb00\x07\x83'), (b'\xa6\xdd\x1f\xfc\xca2\x88\x99\xbeA\x9a\xa6JVJ\x84', b'B\x81\x8e-K\xde\x15\xfd\t"\x08\x04@/-\xc9'), (b']b\x18\xe65C\x17*\x103J?\xe79!\x9b', b'\n\xbb\x1f\x98\nZZ\x97\xe0\x12\xf6W\xc4\x1e_~'), (b'\x9a\x9f-c\t\x14\xa4NL\xc5\xc0\x99R\x15\x94\xca', b'\xa0\xf9\x11\xfa\xd7\xf3\xb5\x11\xb2SK\xe8\xdb\x06\x94\x1f'), (b'!\xf0\x90\xd8t_O\xc1\xb5\xfe}\xca\xa6\x15}\x19', b'\xc9+\x89a9y3\xe0\xffh\xedmMq\x13\xcc'), (b'`\xf1\xab\x07A\xe9\xe5\x805\xf2\xabD8\xce\x85A', b'\x9d\x0f\x91\xc2\x01\x93\x8fm\xd6\x03XZl\t\x15J'), (b')\r\xcf\xc0\xa1\xa9\xf7i\x94\xa9\x8d\xed\xea\xcd\xb0B', b'jq\xe9\x01*H\x14\xa7M\x8c\xd2\xa5\x19\\\x80\x12'), (b'vJ\x98\xbf\xd5D\x15\xdb\xa1\xd7\xdc\xaf\xa0\xaa\xf7\xc1', b'\x06\xd8-\x05\xfe\x172W\xa4\xab\xe4\x97_h\xe6\xac'), (b"\xc6'P\xd2\xfcq\xcb\n\xe2\xc1sN>\xbc\x9a\x08", b'\xacysx4z\x96\x8f\xf1\xa5M\x9e\xe7f\\\x16'), (b'\x00\xc6\x81\xf0\xf1\xcb\xa8_\x1fF\x18\xe9\xb0\x95\xa3\xab', b'N\xd8\xdaz\xe8F4\xb1\x88>\xec\xd6[\x15\xd7\xfd'), (b'E\x1ee\x8f\xd5\x0f\x19\xa8\xb6~-\xe0n\xe7\x89\xe1', b'\x83\x90\xa0\x93\xec\x086+\xcf\x08\x9c\x048\x85\x88^'), (b"\x82\x13\xfa\x9f 6\xd3'\xd7\xd2\xc1\xf9\x03.\x13*", b'J\xe2\xf8\x1e\xec\xeb\xd9"q\xbb:\x04\xc2\xdf<\xa8'), (b'\x01\xdf\xfcPW\xc80&{\xfe\x99\xf8\x10\xc6R\xce', b'=Cnh3\x9drKE\x1aU\x8e\xcc\x84jS'), (b'<\xeeo[J\xb0r0N\x07\xf4\x1e\xfb\x16\xac\x07', b'\xf9KP\xfe\xd2\xed\xc7`\xc7\x0c\x9et\xd3^\xc9g'), (b'P\xa1b#\x07V\xb0s\x86S\x9a\x1d[\xd9\xe7\x92', b'r&\xb1a\x0ff2\xd2\x8ft\x13\xff\xba\x0fy\xf4'), (b'\xc8t\xcc\x96V\x8bS\xde\x98\xf1\xa33\xa9\xdb\x1b\x85', b'13\xf1&\x8c\xfe3\xf9\xca\\\xc6\xdb\x1dT\x04b'), (b'\xb9u\xf2O\xfb\x05\xb3\xc2r*\x17d\\\x8f9M', b'\xeeQ\xf9&\xc5\xc8\xc8\xe6B\x1d\xcf\x184\x19]b'), (b'\x96\xe6\xc9\x1e;\x83e4\xb0\xbe\xf6\x94\x03\x06\x85:', b'\xa2\xb0\nS\xaf\xads.\x94\x16s\x901\xaf-\xe4'), (b'&\x81t\x048(\xd7 \xb6\x1aR\xaa\x98\xdbN\x0b', b'\x9cd\x8a#\xdd \xdcS\x14\x1e\x1b\xea\x87\x1b\xa41'), (b"\x1fC\x0cr,\x1d\xab\xa8\xd9\xfc\xa1\xa2\xbb\xcdw'", b'D\xb6)\x7f\xd7\xe6\xb2@\x18D\x1d\x08c\xce2k'), (b'$\xc1\xabD\r\xe0a\x0co\x12\x17\xbdB\x06\xc9y', b's\xd8\xf8\x05\x81\xfeY\xc4\xc8|\xe5\xe2]U\xfa"'), (b'\x8f\xe3\xd6\xc9d\xc4\xf0\xd0\xe3\x17\x12\x82\xb2\xfd\xe9\xef', b'\xf1\r/9\x97/\xd4\xf6dz\x89\x7fEG/\x15'), (b'\x16\xf2\xd8\x9a\x029\x9b{\x02\xf4u\x08~\x80\xb9Z', b'\xe1+:9\xaa\x87:\xf0\x02\xdd\xe5}G\x0ch\x98'), (b'\xe5\n\xf8gP\xfd\x8aT\x04\xf2\xdc\xa4dgcO', b'\x13\xd0\x1c[\xe6\x8aa\xd6\xa0a\xb1X\x84\xb8\xde2'), (b'\xa8\xaa\xa8\xe7\xcal>\xe6\xdb\x18vL\xdak%}', b"\xe5W'\x83\xbd\xf2\x01\x9b\x89\x98l\xfd\xcf\x02\x84\x13"), (b'6\x9b\xae\x07\xe0+\xa0\xcd\xdbT\t\x02@\x81$E', b'\x10Q\x1an\xaa\xe7\x9cy\x04t\x16\x1d\xea\x9d\xd2\xe6'), (b'ne\x83\xb0\xe2\x8aG\xda\xaf%\x93cg\x84\xaf\xea', b'p!}\x8aQ(C\x08\xaf\x8bi\x80\xdaw\x7f\x81'), (b'<\xa6\x90\xb2\x03\x8f\xa4\x17$\xc7\xbe\x8a\x1e!\x01s', b'\x19\x7ftaaLUB\x1aBt\xf5U~\xeeY'), (b'\xe4|z\xaer8\xa0\xa3\xc8\x9c\x8d\x03`\xb8rN', b'b\xda\xf8e\n\x1f\xc1\xb2\x97\x13\xd7\x91\x91\x86\xbe\x13'), (b'\x00\x84\xc1\xd8\xe0ub\x1a\xc0\xa1\xfe\x08K\xfb>,', b'g\xb06$\xbb{s\xb9-\x8e5h|+\xf8\xb1'), (b'(\xac{\xb1^OOy\xc98\xf5\xc5\xc2\xd3\xb3\x1e', b'\x8d\xfc\x0f\xda\xd5\xa6\x89)\x92\x173\x1e)*\xf4&'), (b'G*.\xe2\xd8\xee\x87\xfa\x83~eS\xcc\x1e\xdeQ', b'\xc9y \x1a]Y\x8d\xf8\xa0\xd0^p\xc1\xf1\xa4\xd2'), (b'\x16\x91\xd7[\xbeC\x80T\x08\x0f\xbd\xe1\xf7\xbd\x1b\xb8', b'\xcc\x8c\xfb\x1f"\x16\xa7/\xe2inK\xaa\xdf\xc0\xe4'), (b'\x1d\xbc\xf2\x9b\xe90\x13\xc9\tuuk\r\xe4\xa9\xfa', b'\xf6\x97\xf2B\xaa\x83\xf9k\x15K\xa0\xb9\xdf\xf4,\x02'), (b'hIA(;\x8b\x92G!K\xca\x1a\xfd\x8c9\x95', b'0!V\xfc\xfb\xa1,R\xc6\xdaO\x9c\x16\xa8<\xe2'), (b'?\xd8\xd7e\x88\xad\xcd\xd6\x8d\\\x1e\xc2l$;\xd8', b"\x88\x8e\x86'#f\xcf\xe3,\x96&\r\xb1\xee@g"), (b"\x81\n\x18\xd7\x92\\dv'\x1a\xea\x8c7\xf2S\xb0", b'\x99\xbf\xf9qo\xde\x92xge\x04\x84\xb8 \xfb\xe3'), (b'\xa7\x8d\x83\xc8\xa3\xc15\xdc`\x82\xed\xae.\xea\xf2\xea', b'[\xe8{\r\xd6g\xcf\xe8L\x16\xde\xcd\x90M\xbd\x9e'), (b'\x1a\x1b;\xa62\x10i\xb2\x19n\xc1\xddKz\xb4\xd8', b';On\xd2N\xef%B\x05_T9)IG\xcf'), (b'@g`\x1e\xc1\xdf\x14A\xc1\x04N\xb6]\x97\xd3\x17', b'\xbc6\xcb\xaah*\xf1\xd0_\xd9B\x94F\xa8\xd8\r'), (b'<\x86\xa4z\xb4\xaeS\x90\xa9\xb5I\xe8\xe6FI\x8c', b'\r2\xd2.H"\xfb\x9d}{\x11^\xdf\xcb\x186'), (b'\xf0\xb8J|\x0b\xfe\xcd\x8b\xc0$&"8\xffob', b'\xa8}\xf31\xdd\x07\xc6\xa0\xbb\x9f0\xca\xe3&^\xf6'), (b'r\x9b\x81\xa0D\x94\x80\xfdu\xb1O\xbc\xf6\x1a\xd8\xe0', b'\xd4)\xb6\xdbQ\xa5#\x16\xed9\xadM\xf82%\xeb'), (b'\xb9V\xb7R\xb9\xcdJ9c\x1a`V\xb9\xb0oX', b'\x9a\xff]\xb3\x83\x96\xf5\r\x98\xe2\xc5\x86\xa21k%'), (b"J\xe9\xaa\x8f\x07\xab\x90\x18'\xa6\x85\x08\x18\xa8\x96?", b'\xa7\x83\xed\xd9\t\xd8\x85\xe4\xf8\xcb0\x95n\xf2`\xa8'), (b'\xc3\xaf\xc8m\xfc\x90}=\xb8\x1fr\xab}\r\xc1!', b'\x04\xa0sq\xf7\xd3Dm\xb9\xb8\x9c\xbap(\xa1L'), (b'\x97bq\x0f\x93\xb5\xa1\xa1\xf58\xdcu5\x9a\xbd\x8b', b"\x07'\xc0\xdb/0\xd9H\x81\x06\xe2^ `F\xa9"), (b'Nn\xd4\xbd\x13dN\x9e\xcd\xd4\x06kk~\xf5\x7f', b"\x98j'}\xc5\xb0\x1d\x19\xe2/\x92'\x9e\xd4\xba("), (b'\x08ty\x84\xde>\x0f5jL6\x05\xe1\x02pH', b'0\xb9\xd5\xd40u\x04\xfdK\xe2D\xbc\xddy\xd4\x11')]
def cost(func):
    def wrapper(*args,**kwargs):
        start=time.time()
        res=func(*args,**kwargs)
        end=time.time()
        spend=end-start
        print(f"cost:{spend}")
        return res
    return wrapper
@cost
def test(repeat):
    tmp=[*lis*repeat]
    if example.get_list_size()<4000000:

        for it in tmp:
            t=b'something here'
            example.init_map(it[0],t ,16,len(t),int(random.random()*10000))

    print(f"pool size is {example.get_list_size()}")
    print(f"get args from lis start")
    print(lis)
    arg1=lis[0][0]
    print(f"get args from lis complete")
    t=b'something need search'
    print(f"start search")
    res=example.search(arg1,t,16,len(t),0.1,int(random.random()*10000))
    l=len(gc.get_objects())
    print(f"res is {len(res)},gc:{l}")

if __name__=='__main__':
    for i in range(10000):
        test(10)

error
pool size is 1000
get args from lis start
Fatal Python error: Segmentation fault

Current thread 0x00007f0ca3c90340 (most recent call first):
  File "/tmp/tmp.ztKz0S1yKb/test.py", line 29 in test
  File "/tmp/tmp.ztKz0S1yKb/test.py", line 12 in wrapper
  File "/tmp/tmp.ztKz0S1yKb/test.py", line 41 in <module>
Segmentation fault (core dumped)

I tried using PyMem_RawMalloc and Py_DecRef but still segfault. what should i do?
Sorry for the little misinformation I gave.
I may have located where the problem is:
problem here
Everything works when I comment out Py_DecRef ,otherwise it throws a seg fault exception:
gdb backtrace,
print info
I don't understand why Py_DecRef can't be used here.
Comment: Have you used a debugger? What did it tell you?
Comment: Why the header file? If that is a *Python* module, it doesn't have to export anything (*C* style).
Comment: *but it's not clear to me exactly where the problem is.* -- Did you do the obvious thing, and that is to verify that those values you are sending to `PyMem_RawMalloc` are valid?  What about the return values from that function?  Did you check them for NULL?  The first thing you should do is debug and/or log the values you are using in that C++ function.  Right now, it seems you aren't doing either one (debugging or logging).
Comment: At the top of your cpp file, `#include `, then `assert(statement)` every statement that could possibly be in doubt. Build without optimizations and try again - rather than a segfault, you are likely to get an assert firing, with a much more useful message (because you wrote it yourself).
Comment: @CristiFati  ,Thanks for the reminder, I'll fix this question.
Comment: I added some error messages and what might be the problem.
Comment: @MattDMo   The error message indicates that an error occurred in [test.py]:func test while get the arguments for example.search. It was unable to get the list element.
Comment: @PaulMcKenzie  The error did not appear on the PyMem_RawMalloc. It seems that it appeared on the Py_DecRef or dealloc. However, I will add some valid checks for PyMem_Malloc. Thanks.
Comment: You're freeing *tmp\_b* and *tmp\_c* while their addresses are still referenced in the map. That's clearly recipe for disaster.
Comment: Neither *C*,. nor *Python* code "compiles" *OOTB*. [\[SO\]: How to create a Minimal, Reproducible Example (reprex (mcve))](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: There are some things wrong:

C and Python code have errors, so it doesn't compile / run - not an MCVE ([SO]: How to create a Minimal, Reproducible Example (reprex (mcve)))

There is a mix of raw (malloc) and pymalloc memory functions

Mismatches between types and format specifiers

C API misunderstanding. According to [Python.Docs]: Parsing arguments and building values (emphasis is mine):

Note that any Python object references which are provided to the caller are borrowed references; do not decrement their reference count!

Design flaw mixing C and Python types. There is the C list that is supposed to be the backbone, but it's tightly coupled with Python structures. Also attempting to export the functions from the .dll makes me think that things are not very clear for the OP. I'd suggest to keep the core functionality at the C level and provide wrappers for interacting with Python. Otherwise, keep switching from one to another would lose the speed advantage (which I assume is the reason for not writing everything in Python)

The question is tagged C++, but there's nothing C++'y about the code, it's rather C (in C++ there is std::list, smart pointers and other features that could save writing a lot of code)

Minor ones:

LISTNODE - NODE nesting. Although it looks better structured, the overhead for working with nested structures might be a greater loss

Passing the size of bytes (which is held inside it)

Method arguments specifications

Code style

Many many others

Before going further, I suggest a thorough reading of the following (including referenced URLs):

[Python.Docs]: Extending Python with C or C++

[Python.PEPs]: Python/C API Reference Manual

Now, there are multiple problems, each with multiple solutions.
Starting from your code, I prepared an example. It's written in C (lots of code which doesn't have anything to do with the goal).
All the business logic is carried out in C (it's callable from a C application), and the Python wrapping layer is on top of that.

dll00.h:
#include <stdint.h>

#if defined(_WIN32) && !defined(PY_MOD_BUILD)
#  if defined(DLL00_STATIC)
#    define DLL00_EXPORT_API
#  else
#    if defined DLL00_EXPORTS
#      define DLL00_EXPORT_API __declspec(dllexport)
#    else
#      define DLL00_EXPORT_API __declspec(dllimport)
#    endif
#  endif
#else
#  define DLL00_EXPORT_API
#endif

typedef uint8_t byte;
typedef unsigned long ulong;

typedef struct Node_ {
    byte *features;
    ulong features_len;
    char *content;
    ulong content_len;
    long id;

    struct Node_ *next;
} Node, *PNode;

typedef struct {
    size_t len;
    PNode *nodes;
    double *scores;
} FoundData, *PFoundData;

#if defined(__cplusplus)
extern "C" {
#endif

DLL00_EXPORT_API int addNode(const byte *features, ulong features_len, const char *content, ulong content_len, long id);
DLL00_EXPORT_API size_t size();
DLL00_EXPORT_API PFoundData search(const byte *features, ulong features_len, const char *content, ulong content_len, long id, double threshold);
DLL00_EXPORT_API void freeFoundData(PFoundData data, int membersOnly);
DLL00_EXPORT_API size_t cleanup();

#if defined(__cplusplus)
}
#endif

dll00.c:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DLL00_EXPORTS
#include "dll00.h"

static Node *gHead = NULL;
static Node *gCur = NULL;
static size_t gLen = 0;

int addNode(const byte *features, ulong features_len, const char *content, ulong content_len, long id)
{
    Node *node = malloc(sizeof(Node));
    if (node == NULL) {
        return -1;
    }
    node->features = malloc(sizeof(byte) * features_len);
    if (node->features == NULL) {
        free(node);
        return -2;
    }
    node->content = malloc(sizeof(char) * content_len);
    if (node->content == NULL) {
        free(node->features);
        free(node);
        return -3;
    }
    memcpy(node->features, features, features_len);
    node->features_len = features_len;
    memcpy(node->content, content, content_len);
    node->content_len = content_len;
    node->id = id;
    node->next = NULL;
    if (gCur == NULL) {
        gCur = node;
        gHead = node;
    } else {
        gCur->next = node;
        gCur = node;
    }
    ++gLen;
    return 0;
}

size_t size()
{
    return gLen;
}

static double compare(const byte *features0, ulong features0_len, const byte *features1, ulong features1_len, int min)
{
    // @TODO - cfati: Dumb comparison
    if ((features0_len > 1) && (features1_len > 1) && ((features0[0] == features1[0]) || (features0[0] == features1[1]) || (features0[1] == features1[0]) || (features0[1] == features1[1]))) {
        return 0.3;
    }
    return 0;
}

PFoundData search(const byte *features, ulong features_len, const char *content, ulong content_len, long id, double threshold)
{
    if (gCur == NULL) {
        return NULL;
    }
    Node *node = gHead;
    FoundData tmp = {0, NULL, NULL};
    tmp.nodes = malloc(sizeof(PNode) * gLen);
    if (tmp.nodes == NULL) {
        perror("malloc failed 1.");
        freeFoundData(&tmp, 1);
        return NULL;
    }
    tmp.scores = malloc(sizeof(double) * gLen);
    if (tmp.scores == NULL) {
        perror("malloc failed 2.");
        freeFoundData(&tmp, 1);
        return NULL;
    }
    while (node != NULL) {
        double score = compare(features, features_len, node->features, node->features_len, 0);
        if (score > threshold) {
            tmp.nodes[tmp.len] = node;
            tmp.scores[tmp.len] = score;
            ++tmp.len;
        }
        node = node->next;
    }
    if (tmp.len == 0) {
        return NULL;
    } else {
        PFoundData ret = calloc(1, sizeof(FoundData));
        if (ret == NULL) {
            perror("malloc failed 3.");
            freeFoundData(&tmp, 1);
            return NULL;
        }
        ret->nodes = malloc(sizeof(PNode) * tmp.len);
        if (ret->nodes == NULL) {
            perror("malloc failed 4.");
            freeFoundData(ret, 0);
            freeFoundData(&tmp, 1);
            return NULL;
        }
        ret->scores = malloc(sizeof(double) * tmp.len);
        if (ret->scores == NULL) {
            perror("malloc failed 5.");
            freeFoundData(ret, 0);
            freeFoundData(&tmp, 1);
            return NULL;
        }
        ret->len = tmp.len;
        memcpy(ret->nodes, tmp.nodes, sizeof(PNode) * tmp.len);
        memcpy(ret->scores, tmp.scores, sizeof(double) * tmp.len);
        freeFoundData(&tmp, 1);
        return ret;
    }
}

void freeFoundData(PFoundData data, int membersOnly)
{
    if (data == NULL)
        return;
    free(data->nodes);
    free(data->scores);
    if (!membersOnly)
        free(data);
}

size_t cleanup()
{
    size_t ret = 0;
    Node *node = gHead;
    while (node != NULL) {
        free(node->features);
        free(node->content);
        Node *next = node->next;
        free(node);
        node = next;
        ++ret;
    }
    gHead = NULL;
    gCur = NULL;
    gLen = 0;
    return ret;
}

main00.c:
#include <stdio.h>
#include <string.h>
#include "dll00.h"

void handleFoundData(PFoundData data)
{
    printf("Found data (%d items):\n", data == NULL ? 0 : data->len);
    if (data == NULL)
        return;
    for (size_t i = 0; i < data->len; ++i) {
        printf(" Index: %d\n  Score: %.03f\n", i, data->scores[i]);
        printf("  Id: %d, Features length: %d, Content length: %d\n", data->nodes[i]->id, data->nodes[i]->features_len, data->nodes[i]->content_len);
        printf("  Feats: %s\n", data->nodes[i]->features);
        printf("  Cnt: %s\n", data->nodes[i]->content);
    }
    freeFoundData(data, 0);
}

int main()
{
    Node dummies[] = {
        {"1\02", 3, "567\0890", 7, 2},
        {"ab\0c", 4, "d4567\0890", 9, 3},
    };
    printf("Element count: %zu\n", size());
    for (int i = 0; i < sizeof(dummies) / sizeof(dummies[0]); ++i)
        printf("Add node (%d) returned: %d\n", i, addNode(dummies[i].features, dummies[i].features_len, dummies[i].content, dummies[i].content_len, dummies[i].id));
    printf("Element count: %zu\n", size());
    // @TODO - cfati: Values based on .dll's dumb comparison
    byte *src[] = {
        "xxx",  // None
        "111",  // 1st
        "xaa",  // 2nd
        "1bd",  // Both
    };
    for (int i = 0; i < sizeof(src) / sizeof(src[0]); ++i) {
        printf("Search for '%s' ...\n", src[i]);
        PFoundData found = search(src[i], strlen(src[i]), "", 0, 0, 0.1);
        handleFoundData(found);
    }
    printf("Freed %zu nodes\n", cleanup());
    printf("Element count: %zu\n", size());
    printf("\nDone.\n\n");
    return 0;
}

example.c:
#define PY_SSIZE_T_CLEAN
#include <Python.h>

//#define PY_MOD_BUILD
#include "dll00.h"

#define MOD_NAME "_example"

static PyObject* example_size(PyObject *self, PyObject *Py_UNUSED(args))
{
    return PyLong_FromSize_t(size());
}

static PyObject* example_add_node(PyObject *self, PyObject *args)
{
    PyObject *feat = NULL, *cnt = NULL;
    long id;
    if (!PyArg_ParseTuple(args, "SSl", &feat, &cnt, &id)) {
        return NULL;
    }
    int ret = addNode((const byte*)PyBytes_AsString(feat), (ulong)PyBytes_Size(feat), PyBytes_AsString(cnt), (ulong)PyBytes_Size(cnt), id);
    return PyLong_FromLong(ret);
}

static PyObject* example_search(PyObject *self, PyObject *args)
{
    PyObject *feat = NULL, *cnt = NULL;
    long id;
    double thres;
    if (!PyArg_ParseTuple(args, "SSld", &feat, &cnt, &id, &thres)) {
        return NULL;
    }
    PFoundData tmp = search((const byte*)PyBytes_AsString(feat), PyBytes_Size(feat), PyBytes_AsString(cnt), PyBytes_Size(cnt), id, thres);
    if (tmp == NULL) {
        return PyList_New(0);
    } else {
        PyObject *ret = PyList_New(tmp->len);
        if (ret == NULL) {
            freeFoundData(tmp, 0);
            return NULL;
        }
        for (size_t i = 0; i < tmp->len; ++i) {
            PyObject *tup = Py_BuildValue(
                "(ly#y#d)",
                tmp->nodes[i]->id,
                tmp->nodes[i]->content,
                tmp->nodes[i]->content_len,
                tmp->nodes[i]->features,
                tmp->nodes[i]->features_len,
                tmp->scores[i]);
                // @TODO - cfati: No need to include data passed in arguments in each of the output tuples !!!
            if (tup == NULL) {
                Py_XDECREF(ret);
                freeFoundData(tmp, 0);
                return NULL;
            } else {
                PyList_SET_ITEM(ret, i, tup);
            }
        }
        freeFoundData(tmp, 0);
        return ret;
    }
}

static PyObject* example_cleanup(PyObject *self, PyObject *Py_UNUSED(args))
{
    size_t ret = 0;
    //Py_BEGIN_ALLOW_THREADS
    ret = cleanup();
    //Py_END_ALLOW_THREADS
    return PyLong_FromSize_t(ret);
}

static PyMethodDef methDef[] = {
    {"size", example_size, METH_NOARGS, "Get List size"},
    {"add_node", example_add_node, METH_VARARGS, "Add node"},
    {"search", example_search, METH_VARARGS, "Search elements"},
    {"cleanup", example_cleanup, METH_NOARGS, "Clean up"},
    {NULL, NULL, 0, NULL},
};

static struct PyModuleDef modDef = {
        PyModuleDef_HEAD_INIT,
        MOD_NAME,  // name
        "A module that imports an API",  // Doc string (may be NULL)
        -1,  // Size of per-interpreter state or -1
        methDef,  // Method table
};

PyMODINIT_FUNC PyInit__example() {
    PyObject *m;

    m = PyModule_Create(&modDef);
    if (m == NULL)
        return NULL;

    /* Import sample, loading its API functions */
    return m;
}

setup.py:
#!/usr/bin/env python

from distutils.core import setup, Extension

setup(
    name="example",
    ext_modules=[
        Extension("_example",
                  ["example.c", "dll00.c"],
                  include_dirs=(),
                  define_macros=[
                    ("PY_MOD_BUILD", None),
                  ],
        ),
    ],
    version="0.0.1",
)

data.py (I just extracted input data to avoid polluting the other source file):
data = [
    (b"\xd3\nR\x952\xbf\x8e\xeb[\xdc\xe8\xfb\xcb\x9f\xb4\xd2", b"\x856\x96\xda\xe4H_\xf9\xb3\x95\xff\xda\xc9\x05\x17\xd5"),
    # @TODO - cfati: !!! DELETED NEXT 20 TUPLES so the answer fits the 30K characters limit !!!
    (b"\xb4\xda\xff\x8c0\x18/\xf1\xad\xa4F\x94\xb1\xad\xf4\xf1", b".\x83(\x8f#\xe1\x11\x96\xdeS\x17\x8b\xe3]\xb5\xca"),
    (b"\x1d\t\x11\xc1\x15\xdc\x8e\xea\xe1\xd2\xba%J\\\xf2\xfd", b"\x070ht\xb4\xdeQ+\xc5\xb8#\xac\xd9z\xc0A"),
    (b" V\xe3\xc5gEg\xc5\xd5\xe1\xd6\xd7\xab\xd0\xb6n", b"\x88\x9b8\xf6\xe26\x92z\x91\xe4\x92\x1e\xbc\xc5;u"),
    (b"\x88}\xd7*QFn:\xd7\x12RA\xe6-\xd2)", b"\xeb\x04<\xe6\xfa)u\x9ds\xecj\xa7\x84\xcf\xa7\xa7"),
    (b"\xec\x04.bP)'\xb6\x08\x05\x92\x8c\x85\x1a\x84\x8f", b"@\x80\x08A\xba\x9c2Sd\xdf\x97\x07\xc4Im\xef"),
    (b"\x11(\x9ez\x0c\xd7\xca+7\xcc\xb0\x19,:\xcb5", b"\xf9V\x8cm\xe5-\xf9\xf1\xf6g\x86~\x8f\xd0<\x84"),
    (b"\xbb\xe9I=\xc74\xc9C\x0cT\x81\x9d\x85\xdeWF", b"\xfe\x1b\xb1gi\x94O\x98\xf0\x90cJ\xdb\xbf\xc7\x1e"),
    (b"2`\x9d\x9c\x02\xe4\xce\xf0\x14\xc0Z\xaaW\xf2\xa5\xff", b"\xe6\x05?\xe3X\"\xb2O)~\x96\x8f^\x9c\x077"),
    (b"\xaf\x87,a\xa9\xcd\n|O\x1e\xa7\xdd\xba\x89;\x9d", b"\x98b\xac?\x13*\xf2m\xfeo=v\x96\xd5\x14\x8d"),
    (b"\xee\xcb{\xeeRQ\x82}\x05|\xc6S\x82\x85\xa4\xff", b"C\x93\xdes\x00\xe8cY<\xde1.\x19\xd8\xe5R"),
    (b"\xack\x036\x9b4\xca\xa4\x15\xbd\xd5\xbe\xd3\xd4\xfb{", b"m?\xc44>\xf4qig\x10\x8c\xeb\x11o\x99\xb4"),
    (b"D!\x0e*\xb3/<\x15F_\xd6;j\x85\xbe,", b"Y\xb01H\xb6:\x04_]OL\x9d\x8e\xbcp\xdc"),
    (b"\xe6\x9d\x02L[\x1c\xee\x8b0lu\xdd\x00\x9a\xfa!", b"J&\tkf\xa8\xeb\x1b\x90\x81\xce\\\x1b\xe8\xb6\x1d"),
    (b"\xcdnd\xf6\xf6\x11\x9e\x06\x10\xce\xcfP\x89\xed\xad\x02", b"I:\xe0{8H\xfcw\xb1\xe9v\x11p-/0"),
    (b"\xa22?\xcd\xfbU+\xbf- \xe3<\xc2\x94\xef\xb6", b"\xc7\x89\xc4K?{\x18\x1ftd\x0f\x19L}\xba\xf9"),
    (b"8\xf9\xe9\xd0\xa0\x97\x8e\rp\xe9\xd6[\x8e`\x93\x81", b"\xf7\x16\"\xaa\x86\\b\x9d\x0c\x17\"\x81\xeea\x03\x19"),
    (b")\xfb\x0c\xc7-D\xd8\xa4\xf7\x8d%\x02\x06\xa1\xbf\x94", b"\xc8s!s\xe2n\xee\xb0\x1eC\x15\xc0\xb4d\x08\xa7"),
    (b"\x7f\xa6\xdc\xf4\x9e\xe3\xda\xd3\x8a\xcb\xfc\x98,1\\\xe5", b"\x82,\xfbKL_\xe9\xc9L`\xc7\"&3#\xb5"),
    (b"&\x98,\x88\xff\x0e\xca[\xcb\xc6t;\xbc5Y\"", b"\x1b\x8bA\xd1\x8a\x9e\xe6\xce\xc4#C\x89\xe9Uon"),
    (b"\x1c\x1b\xac2\x86\xd6\x9a\xf9\xdd\x8d=\xa3\xff\x9a\xe1\xa5", b"\xed\x10\xed\xc1\xfe\xec\xd3\x0b\x8b\xe9\xd4?H\"\xd6\x8f"),
    (b"9\x8f3\x8b\x02\xb7\xe7\xe5\xa1TO\x1a\xb6N\x0b\xb6", b"\xb4\x0f\xa7 \xc7\x83\x81\x18\x9cU\xfd2\x93\xb8(\xe9"),
    (b"\x8d\xbe\xcf`\xc3d\xde\xca\xf4\n.\x92Mrw\xa6", b";\t\xfb\x19eKt0\x8foG\xcd\xd5\xe0\xf6\x9d"),
    (b"d\xbcG)\xec\xc8\x04 \xdd\xd9\xf6\xd6\x91/\xb2\xd3", b"2\xba\xa8\x8a\xc5\xd6h\xab\x9c\x9e\x8b\x1b5\xcc_."),
    (b"\x98\xea\xf0\xcbJ-c\xea\x81\xcf?B\x17\xcb\x99\xf9", b"\x82\x05\x14\xf2\x05q\x97\xf7Z-B\xad\xa2\x16\xa0`"),
    (b"\x1c\x94A\xfd\xe1\xf2\x06\x8b\x19\x80\xfa\x01g\xc3V\xaf", b"\x1c\xde\xec\xdf&\x93u\xab\xf9\x12\xfb\x04\xbc0\x99d"),
    (b"6\xfa\x993b\t\x12E\xd2t\xde\xb6\xfa\x98Im", b",\xa2\xf7VB\x81\x048\xc8\xbf3\xce\x8d\xecn\x82"),
    (b"L\xd6\x93\xbe\x02\xbeT\xa1\x8d\x88\x84\x18\xc7\xcf\x9fE", b"\x16i\"\xb7\x81\xef7\x7f\xdb\x7fY\xbft\x1b\xac\xd0"),
    (b"\x90\xd6\xe7>Z\x8b\x83\x14\xab\xefH\xa1\x95\xe6\x8e\xc3", b"\xebJ\xfcXd\xd75I@\x12\xe9\x88\xdcG\x15\xb7"),
    (b"\xb8\xd6\xd03j\xed\xf9\xa0\xb1L3\x8d\x89P\xb4\xe5", b"\xe3\xdf)CR\x03s\x19\x8f\xb5\xc6\xf5\xee&W\xee"),
    (b"cx\xd7dQ\xc3)YR\x9c7\xf0\xb4\xe4P\xfd", b"h\xa8\x122\xceV\x8c\xf4\x12\x14J\x08\x91\xcf\x93\xfa"),
    (b"\x1d\x14\x86\xccTi\xdd\xc3L!\x97\x92\xb3\xb7X$", b"t\x84\xa4\xe72\xa5X\xe9Ta\x03\x0c\xb00\x07\x83"),
    (b"\xa6\xdd\x1f\xfc\xca2\x88\x99\xbeA\x9a\xa6JVJ\x84", b"B\x81\x8e-K\xde\x15\xfd\t\"\x08\x04@/-\xc9"),
    (b"]b\x18\xe65C\x17*\x103J?\xe79!\x9b", b"\n\xbb\x1f\x98\nZZ\x97\xe0\x12\xf6W\xc4\x1e_~"),
    (b"\x9a\x9f-c\t\x14\xa4NL\xc5\xc0\x99R\x15\x94\xca", b"\xa0\xf9\x11\xfa\xd7\xf3\xb5\x11\xb2SK\xe8\xdb\x06\x94\x1f"),
    (b"!\xf0\x90\xd8t_O\xc1\xb5\xfe}\xca\xa6\x15}\x19", b"\xc9+\x89a9y3\xe0\xffh\xedmMq\x13\xcc"),
    (b"`\xf1\xab\x07A\xe9\xe5\x805\xf2\xabD8\xce\x85A", b"\x9d\x0f\x91\xc2\x01\x93\x8fm\xd6\x03XZl\t\x15J"),
    (b")\r\xcf\xc0\xa1\xa9\xf7i\x94\xa9\x8d\xed\xea\xcd\xb0B", b"jq\xe9\x01*H\x14\xa7M\x8c\xd2\xa5\x19\\\x80\x12"),
    (b"vJ\x98\xbf\xd5D\x15\xdb\xa1\xd7\xdc\xaf\xa0\xaa\xf7\xc1", b"\x06\xd8-\x05\xfe\x172W\xa4\xab\xe4\x97_h\xe6\xac"),
    (b"\xc6'P\xd2\xfcq\xcb\n\xe2\xc1sN>\xbc\x9a\x08", b"\xacysx4z\x96\x8f\xf1\xa5M\x9e\xe7f\\\x16"),
    (b"\x00\xc6\x81\xf0\xf1\xcb\xa8_\x1fF\x18\xe9\xb0\x95\xa3\xab", b"N\xd8\xdaz\xe8F4\xb1\x88>\xec\xd6[\x15\xd7\xfd"),
    (b"E\x1ee\x8f\xd5\x0f\x19\xa8\xb6~-\xe0n\xe7\x89\xe1", b"\x83\x90\xa0\x93\xec\x086+\xcf\x08\x9c\x048\x85\x88^"),
    (b"\x82\x13\xfa\x9f 6\xd3'\xd7\xd2\xc1\xf9\x03.\x13*", b"J\xe2\xf8\x1e\xec\xeb\xd9\"q\xbb:\x04\xc2\xdf<\xa8"),
    (b"\x01\xdf\xfcPW\xc80&{\xfe\x99\xf8\x10\xc6R\xce", b"=Cnh3\x9drKE\x1aU\x8e\xcc\x84jS"),
    (b"<\xeeo[J\xb0r0N\x07\xf4\x1e\xfb\x16\xac\x07", b"\xf9KP\xfe\xd2\xed\xc7`\xc7\x0c\x9et\xd3^\xc9g"),
    (b"P\xa1b#\x07V\xb0s\x86S\x9a\x1d[\xd9\xe7\x92", b"r&\xb1a\x0ff2\xd2\x8ft\x13\xff\xba\x0fy\xf4"),
    (b"\xc8t\xcc\x96V\x8bS\xde\x98\xf1\xa33\xa9\xdb\x1b\x85", b"13\xf1&\x8c\xfe3\xf9\xca\\\xc6\xdb\x1dT\x04b"),
    (b"\xb9u\xf2O\xfb\x05\xb3\xc2r*\x17d\\\x8f9M", b"\xeeQ\xf9&\xc5\xc8\xc8\xe6B\x1d\xcf\x184\x19]b"),
    (b"\x96\xe6\xc9\x1e;\x83e4\xb0\xbe\xf6\x94\x03\x06\x85:", b"\xa2\xb0\nS\xaf\xads.\x94\x16s\x901\xaf-\xe4"),
    (b"&\x81t\x048(\xd7 \xb6\x1aR\xaa\x98\xdbN\x0b", b"\x9cd\x8a#\xdd \xdcS\x14\x1e\x1b\xea\x87\x1b\xa41"),
    (b"\x1fC\x0cr,\x1d\xab\xa8\xd9\xfc\xa1\xa2\xbb\xcdw'", b"D\xb6)\x7f\xd7\xe6\xb2@\x18D\x1d\x08c\xce2k"),
    (b"$\xc1\xabD\r\xe0a\x0co\x12\x17\xbdB\x06\xc9y", b"s\xd8\xf8\x05\x81\xfeY\xc4\xc8|\xe5\xe2]U\xfa"),
    (b"\x8f\xe3\xd6\xc9d\xc4\xf0\xd0\xe3\x17\x12\x82\xb2\xfd\xe9\xef", b"\xf1\r/9\x97/\xd4\xf6dz\x89\x7fEG/\x15"),
    (b"\x16\xf2\xd8\x9a\x029\x9b{\x02\xf4u\x08~\x80\xb9Z", b"\xe1+:9\xaa\x87:\xf0\x02\xdd\xe5}G\x0ch\x98"),
    (b"\xe5\n\xf8gP\xfd\x8aT\x04\xf2\xdc\xa4dgcO", b"\x13\xd0\x1c[\xe6\x8aa\xd6\xa0a\xb1X\x84\xb8\xde2"),
    (b"\xa8\xaa\xa8\xe7\xcal>\xe6\xdb\x18vL\xdak%}", b"\xe5W'\x83\xbd\xf2\x01\x9b\x89\x98l\xfd\xcf\x02\x84\x13"),
    (b"6\x9b\xae\x07\xe0+\xa0\xcd\xdbT\t\x02@\x81$E", b"\x10Q\x1an\xaa\xe7\x9cy\x04t\x16\x1d\xea\x9d\xd2\xe6"),
    (b"ne\x83\xb0\xe2\x8aG\xda\xaf%\x93cg\x84\xaf\xea", b"p!}\x8aQ(C\x08\xaf\x8bi\x80\xdaw\x7f\x81"),
    (b"<\xa6\x90\xb2\x03\x8f\xa4\x17$\xc7\xbe\x8a\x1e!\x01s", b"\x19\x7ftaaLUB\x1aBt\xf5U~\xeeY"),
    (b"\xe4|z\xaer8\xa0\xa3\xc8\x9c\x8d\x03`\xb8rN", b"b\xda\xf8e\n\x1f\xc1\xb2\x97\x13\xd7\x91\x91\x86\xbe\x13"),
    (b"\x00\x84\xc1\xd8\xe0ub\x1a\xc0\xa1\xfe\x08K\xfb>,", b"g\xb06$\xbb{s\xb9-\x8e5h|+\xf8\xb1"),
    (b"(\xac{\xb1^OOy\xc98\xf5\xc5\xc2\xd3\xb3\x1e", b"\x8d\xfc\x0f\xda\xd5\xa6\x89)\x92\x173\x1e)*\xf4&"),
    (b"G*.\xe2\xd8\xee\x87\xfa\x83~eS\xcc\x1e\xdeQ", b"\xc9y \x1a]Y\x8d\xf8\xa0\xd0^p\xc1\xf1\xa4\xd2"),
    (b"\x16\x91\xd7[\xbeC\x80T\x08\x0f\xbd\xe1\xf7\xbd\x1b\xb8", b"\xcc\x8c\xfb\x1f\"\x16\xa7/\xe2inK\xaa\xdf\xc0\xe4"),
    (b"\x1d\xbc\xf2\x9b\xe90\x13\xc9\tuuk\r\xe4\xa9\xfa", b"\xf6\x97\xf2B\xaa\x83\xf9k\x15K\xa0\xb9\xdf\xf4,\x02"),
    (b"hIA(;\x8b\x92G!K\xca\x1a\xfd\x8c9\x95", b"0!V\xfc\xfb\xa1,R\xc6\xdaO\x9c\x16\xa8<\xe2"),
    (b"?\xd8\xd7e\x88\xad\xcd\xd6\x8d\\\x1e\xc2l$;\xd8", b"\x88\x8e\x86'#f\xcf\xe3,\x96&\r\xb1\xee@g"),
    (b"\x81\n\x18\xd7\x92\\dv'\x1a\xea\x8c7\xf2S\xb0", b"\x99\xbf\xf9qo\xde\x92xge\x04\x84\xb8 \xfb\xe3"),
    (b"\xa7\x8d\x83\xc8\xa3\xc15\xdc`\x82\xed\xae.\xea\xf2\xea", b"[\xe8{\r\xd6g\xcf\xe8L\x16\xde\xcd\x90M\xbd\x9e"),
    (b"\x1a\x1b;\xa62\x10i\xb2\x19n\xc1\xddKz\xb4\xd8", b";On\xd2N\xef%B\x05_T9)IG\xcf"),
    (b"@g`\x1e\xc1\xdf\x14A\xc1\x04N\xb6]\x97\xd3\x17", b"\xbc6\xcb\xaah*\xf1\xd0_\xd9B\x94F\xa8\xd8\r"),
    (b"<\x86\xa4z\xb4\xaeS\x90\xa9\xb5I\xe8\xe6FI\x8c", b"\r2\xd2.H\"\xfb\x9d}{\x11^\xdf\xcb\x186"),
    (b"\xf0\xb8J|\x0b\xfe\xcd\x8b\xc0$&\"8\xffob", b"\xa8}\xf31\xdd\x07\xc6\xa0\xbb\x9f0\xca\xe3&^\xf6"),
    (b"r\x9b\x81\xa0D\x94\x80\xfdu\xb1O\xbc\xf6\x1a\xd8\xe0", b"\xd4)\xb6\xdbQ\xa5#\x16\xed9\xadM\xf82%\xeb"),
    (b"\xb9V\xb7R\xb9\xcdJ9c\x1a`V\xb9\xb0oX", b"\x9a\xff]\xb3\x83\x96\xf5\r\x98\xe2\xc5\x86\xa21k%"),
    (b"J\xe9\xaa\x8f\x07\xab\x90\x18'\xa6\x85\x08\x18\xa8\x96?", b"\xa7\x83\xed\xd9\t\xd8\x85\xe4\xf8\xcb0\x95n\xf2`\xa8"),
    (b"\xc3\xaf\xc8m\xfc\x90}=\xb8\x1fr\xab}\r\xc1!", b"\x04\xa0sq\xf7\xd3Dm\xb9\xb8\x9c\xbap(\xa1L"),
    (b"\x97bq\x0f\x93\xb5\xa1\xa1\xf58\xdcu5\x9a\xbd\x8b", b"\x07'\xc0\xdb/0\xd9H\x81\x06\xe2^ `F\xa9"),
    (b"Nn\xd4\xbd\x13dN\x9e\xcd\xd4\x06kk~\xf5\x7f", b"\x98j'}\xc5\xb0\x1d\x19\xe2/\x92'\x9e\xd4\xba("),
    (b"\x08ty\x84\xde>\x0f5jL6\x05\xe1\x02pH", b"0\xb9\xd5\xd40u\x04\xfdK\xe2D\xbc\xddy\xd4\x11"),
]

code00.py:
#!/usr/bin/env python

import gc
import random
import sys
from pprint import pprint as pp

import _example as ex
from data import data

def test(repeat):
    tmp = data * repeat
    if ex.size() < 4000000:
        for idx, it in enumerate(tmp):
            t = f"dummy content {idx}"
            ex.add_node(it[0], t.encode(), random.randint(0, 10000))

    print(f"List (internal) size: {ex.size()}")
    print(f"Input data len: {len(data)}")
    search_feat = data[0][0]
    t = b"\xd3 "
    print("Start search:")
    res = ex.search(search_feat, t, random.randint(0, 10000), 0.1)
    pp(res)
    print(f"GC len: {len(gc.get_objects())}")

def main(*argv):
    test(1)
    print(f"List (internal) size: {ex.size()}")
    print(f"Freed {ex.cleanup()} elements")
    print(f"List (internal) size: {ex.size()}")
    print(f"GC len: {len(gc.get_objects())}")

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Outputs:

Win (C .dll called from a C .exe):

[cfati@CFATI-5510-0:e:\Work\Dev\StackExchange\StackOverflow\q076229579]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> "c:\Install\pc032\Microsoft\VisualStudioCommunity\2019\VC\Auxiliary\Build\vcvarsall.bat" x64 > nul

[prompt]>
[prompt]> dir /b
code00.py
data.py
dll00.c
dll00.h
example.c
main00.c
orig
setup.py

[prompt]>
[prompt]> cl /nologo /MD /DDLL dll00.c  /link /NOLOGO /DLL /OUT:dll00.dll
dll00.c
   Creating library dll00.lib and object dll00.exp

[prompt]> cl /nologo /MD /W0 main00.c  /link /NOLOGO /OUT:win_main00.exe dll00.lib
main00.c

[prompt]> del *.obj *.exp

[prompt]> dir /b
code00.py
data.py
dll00.c
dll00.dll
dll00.h
dll00.lib
example.c
main00.c
orig
setup.py
win_main00.exe

[prompt]>
[prompt]> win_main00.exe
Element count: 0
Add node (0) returned: 0
Add node (1) returned: 0
Element count: 2
Search for 'xxx' ...
Found data (0 items):
Search for '111' ...
Found data (1 items):
 Index: 0
  Score: 0.300
  Id: 2, Features length: 3, Content length: 7
  Feats: 1?
  Cnt: 567
Search for 'xaa' ...
Found data (1 items):
 Index: 0
  Score: 0.300
  Id: 3, Features length: 4, Content length: 9
  Feats: ab
  Cnt: d4567
Search for '1bd' ...
Found data (2 items):
 Index: 0
  Score: 0.300
  Id: 2, Features length: 3, Content length: 7
  Feats: 1?
  Cnt: 567
 Index: 1
  Score: 0.300
  Id: 3, Features length: 4, Content length: 9
  Feats: ab
  Cnt: d4567
Freed 2 nodes
Element count: 0

Done.

Nix (Python module):

(py_pc064_03.10_test0) [cfati@cfati-5510-0:/mnt/e/Work/Dev/StackExchange/StackOverflow/q076229579]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[064bit prompt]>
[064bit prompt]> ls
code00.py  data.py  dll00.c  dll00.dll  dll00.h  dll00.lib  example.c  main00.c  orig  setup.py  win_main00.exe
[064bit prompt]>
[064bit prompt]> python setup.py build
[064bit prompt]>
[064bit prompt]> ls
build  code00.py  data.py  dll00.c  dll00.dll  dll00.h  dll00.lib  example.c  main00.c  orig  setup.py  win_main00.exe
[064bit prompt]> ls build/lib.linux-x86_64-cpython-310/
_example.cpython-310-x86_64-linux-gnu.so
[064bit prompt]>
[064bit prompt]> PYTHONPATH=${PYTHONPATH}:build/lib.linux-x86_64-cpython-310 python code00.py
Python 3.10.11 (main, Apr  5 2023, 14:15:10) [GCC 9.4.0] 064bit on linux

List (internal) size: 100
Input data len: 100
Start search:
[(4555,
  b'dummy content 0',
  b'\xd3\nR\x952\xbf\x8e\xeb[\xdc\xe8\xfb\xcb\x9f\xb4\xd2',
  0.3),
 (273, b'dummy content 74', b'\xe5\n\xf8gP\xfd\x8aT\x04\xf2\xdc\xa4dgcO', 0.3),
 (9201,
  b'dummy content 87',
  b"\x81\n\x18\xd7\x92\\dv'\x1a\xea\x8c7\xf2S\xb0",
  0.3)]
GC len: 8942
List (internal) size: 100
Freed 100 elements
List (internal) size: 0
GC len: 8937

Done.

Comment: Yeah,the most critical issue is the incorrect decrementing of the reference count and the combination of malloc and pymalloc. Your code has provided me with invaluable insights into nested struct overhead and the importance of separating core processing from wrapping. Thank you for your answer!


Codeigniter can't use this->uri->segment(3) as value in function

Question: Why this code is ok
$this->sch_teacher_id = $this->ion_auth->user_by_username("vika")->row()->id;

But this doesn't work?
$this->sch_teacher_id = $this->ion_auth->user_by_username($this->uri->segment(3))->row()->id;

My url is domain:8888/admin_schedule/teacher/vika
route.php contains
$route['admin_schedule/teacher/(:any)'] = "admin_schedule/index/$1";

I use code lines in function __construct(), and the result of it use in another controller function, because 3 functions use this result. If I move this code in one of this functions and use $this->uri->segment(3) then I get not 'vika's lessons, but my own lessons, so
public function user_by_username($username = FALSE)
    {
        $this->trigger_events('user');

        //if no id was passed use the current users id
        $username || $username = $this->session->userdata('username');

        $this->limit(1);
        $this->where($this->tables['users'].'.username', $username);

        $this->users();

        return $this;
    }

works good. But $this->uri->segment(3) if use it as parameter in user_by_username function, doesn't work!
page generated next way:
controller admin_schedule have function index which render view index.php.
And in that view I use javascript, that call another function from admin_schedule controller = get_schedule_db_recurring_events_on_daysweek such way:
...
{
                url: '/admin_schedule/get_schedule_db_recurring_events_on_daysweek/',//"<?echo $data_path?>",
                backgroundColor: 'red',
            }

and in controller
function get_schedule_db_recurring_events_on_daysweek()
    {
        $start = date('Y-m-d H:i', $this->input->get('start'));
        $end = date('Y-m-d H:i', $this->input->get('end'));
        $sch_teacher_id = $this->uri->segment(3); // <--- this doesn't work, but $sch_teacher_id = 111 works perfectly
        $result=$this->Schedule_model->get_schedule_recurring_events_on_daysweek($start, $end, $sch_teacher_id);
        $count=count($result);
        if($count>0){
                echo json_encode($result);
        }
    }

Please, help understand this problem.
Comment: Have you tried to assign this to a variable and echo it to see what is going on?
Comment: yes, of course: $username1 = "'".$this->uri->segment(3)."'";
  print_r($username1); This print 'vika' as it should.
Comment: If so, your last question is already answered. This left us with the main problem. Have you tried to pass this value with a variable instead of directly to the method (seems weird but it causes some trouble with references in some cases). Just a try.
Comment: Passing value 'vika' in variable $username1 = "vika"; gives good result, yes. Problem happened if I use $this->uri->segment(3). I've tried rsegment instead segment and it doesn't help.
Comment: If you solved your problem, post the solution as an answer, so it can help others.
Answer: I solved my problem!
Think that something goes wrong because of ajax calls. So when I code in controller
function __construct()
 {
        parent::__construct();
        ...

        $this->sch_teacher_row = $this->ion_auth->user_by_username($this->uri->segment(3))->row();
        $this->data['sch_teacher_id'] = $this->sch_teacher_row->id;
        $this->data['subtitle'] = $this->sch_teacher_row->username;
 }

Next I have the right value ('vika'), or to be more precise vika's id ('911') in view file but not in other function of my controller. But I can pass this value now (sch_teacher_id) from the view to this controller with jQuery $.ajax option data:
eventSources: [
...
{
                url: '/admin_schedule/get_schedule_db_recurring_events_on_daysweek/',//"<?echo $data_path?>",
                type: 'GET',
                data: {sch_teacher_id: sch_teacher_id},
                backgroundColor: 'red',
            }
        ],

And next (on the other side of the mountain) catch this GET parameter and kick it to the model function:
function get_schedule_db_recurring_events_on_daysweek()
    {
        ...
        $sch_teacher_id_from_view = $this->input->get('sch_teacher_id');
        $result=$this->Schedule_model->get_schedule_recurring_events_on_daysweek($start, $end, $sch_teacher_id_from_view);
        ...
    }

And it is all the breakdance.
Comment: This is the same as our suggestion to assign it then pass it.
Answer: I can't remember the reason - it's just CI quirk you have learn to accept - you can't use $this->uri->segment(3) etc as an argument directly, you will need to assign it and then pass that as @almix suggested for his sanity test.
At-least I have also always had trouble using it directly as an argument - tho I will be happy for anyone to correct me!
Comment: No, Brian, assigning it to argument doesn't work too. $sch_teacher_id = 111;//$this->uri->segment(3);
  $result=$this->Schedule_model->get_schedule_recurring_events_on_daysweek($start, $end, $sch_teacher_id); works, but with $sch_teacher_id = $this->uri->segment(3); doesn't!
Comment: you mean: $username1 = $this->uri->segment(3); then using $username1 does'nt work?
Comment: Hmmm ok http://ellislab.com/codeigniter/user-guide/libraries/uri.html states that it will return 'false' if the item is not found.
Comment: I add explaination about route in question.
Comment: may be somehow use this advise http://stackoverflow.com/questions/2062086/how-to-get-controller-action-url-informations-with-codeigniter#2071176


Which ports do I use to send get requests for a full-stack Vue/Flask/MongoDB project?

Question: I've built a mongo database and a Python/PyMongo/Flask script. Now I'm learning Vue so I can put that data on a webpage, but I'm having trouble understanding which ports to use in my path. I understand mongodb uses 27017, Flask uses 5000, and Vue uses 8080.
Here's my Python/PyMongo/Flask script (app.py). Since I can't give you the entire database data, I altered the 'findNames' function to just return a string.
from flask import Flask, jsonify
from flask_cors import CORS
from pymongo import MongoClient

DEBUG = True

app = Flask(__name__)
app.config.from_object(__name__)

client = MongoClient('localhost', 27017)
db = client.argodb

CORS(app)

@app.route('/searchDB', methods=['GET'])
def findNames():
    return jsonify('The database is connected!')

if __name__ == '__main__':
    app.run()

And on the client side, here's my Vue index.js:
import Vue from 'vue';
import Router from 'vue-router';
import searchDB from '@/components/searchDB';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/searchDB',
      component: searchDB,
    },
  ],
});

Here's the main component, App.vue:
<template>

    <router-view/>

</template>

And here's my component, searchDB.vue:
<template>

Database Search

</template>

Comment: You're more or less free to use whichever ports you want as long as they don't interfere with any other applications running on those ports. Are you running into any errors with what you have set up?
Comment: Yes. I can't connect my mongodb to my Vue instance. My Vue isn't consuming the Flask/Mongo data that I've parsed (in this case, the string that is returned).
Comment: Just so I'm crystal on this, when I run 'npm run dev' on my client-side Vue API (the Vue index.html), I'm using Axios to send a 'get' request. After that, I'm not sure what happens. Does my request go through Flask (port 5000) first? Or does it go to mongodb (port 27017)? Or both?
Answer: You have each application running on its own port -- MongoDB running on 27017, Flask running on 5000 and Vue (npm) running on 8080. The chain of events that you'd ideally like to happen is this.

Vue uses axios to send an http request to Flask on port 5000
Flask receives the request and handles the request and recognizes that it needs to retrieve data from the database before sending a response, so it submits a query to Mongo which is running on port 27017.
Mongo returns the requested data to Flask
Flask formats the data into an appropriate http response and returns it to the requester (Vue)
The axios call receives its response and reacts to the response data, storing the data if the response was successful (e.g. status code 200 for a Get)

Since there are a lot of steps along the way that need to go correctly, it's a good idea to test in small pieces first to ensure the whole chain is working properly. I would suggest:

Test to ensure Flask is connecting to Mongo properly and can retrieve data
Next use a curl statement or Postman to check to see if your Flask webserver is handling calls to http://localhost:5000/searchDB properly. Note that if you can also take Mongo out of the equation (as you have done) for this test by just having the call return a string.
Once you are sure you can make calls to that endpoint (/searchDB) successfully, then you can start testing Vue and Axios. This is where you are likely to run into CORS issues.

If you are able to get everything working but cannot resolve the CORS issues, then another possible setup would be to stick NGINX in front of Flask and Vue. This solution involves running NGINX on its own port, let's say port 3000 and then configuring the server to proxy for ports 5000 and 8080. Then you would change your Vue/Axios code to make calls to port 3000 instead of port 5000, which avoids CORS since this would then be the same port that Vue is being served on through NGINX.


How to transfer HTML-String from component.ts to component.html

Question: I would like to ask how to transfer a HTML format string from the .component.ts file into the .component.html file.
In my App there is a layout folder. The layout.component.ts file has the code:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.css']
})

export class LayoutComponent implements OnInit {
  htmlText: string;

  constructor() {
   }

  ngOnInit() {
    this.htmlText = 'title Title Hier some texts hier.';
  }
}

Both the text and its HTML format are defined. Thus I want to show the text with its own HTML-defination in the browser.
The layout.component.html file looks like:

{{ htmlText }}

After compiling the browser shows the full text of the htmlText string, but the HTML format was just ignored.
What have I done wrong? Thanks for any kind of hint+help.
Answer: create a pipe with the following code:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({ name: 'keepHtml', pure: false })
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}

public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
    case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
    case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
    case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
    case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
    case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
    default:
        throw new Error(`Unable to bypass security for invalid type: ${type}`);
}
}
}

and in the html file use the following line of code:

Comment: Thank you so much!
Answer: Just need to use [innerHTML]

That would be enough.


Setting the photometric interpretation tag for a multi-page tiff

Question: While trying to convert a multipage document from a tiff to a pdf, I encountered the following problem:
↪ tiff2pdf 0271.f1.tiff -o 0271.f1.pdf
tiff2pdf: No support for 0271.f1.tiff with no photometric interpretation tag.
tiff2pdf: An error occurred creating output PDF file.

Does anybody know what causes this and how to fix it?
Answer: This is caused because one or more of the pages in the multi-page tiff does not have the photometric interpretation tag set. This is a required tag, so that means your tiffs are technically invalid (though I bet they work fine anyway).
To fix this, you must identify the page (or pages) that does not have the photometric interpretation set and fix it.
To identify the page, you can simply run something like:
↪ tiffinfo your-file.tiff

This will spit out the info for every page of your tiff. For each good page, you'll see something like:
TIFF Directory at offset 0x105c0 (67008)
  Subfile Type: (0 = 0x0)
  Image Width: 1760 Image Length: 2639
  Resolution: 300, 300 pixels/inch
  Bits/Sample: 1
  Compression Scheme: CCITT Group 4
  **Photometric Interpretation: min-is-white**
  FillOrder: msb-to-lsb
  Orientation: row 0 top, col 0 lhs
  Samples/Pixel: 1
  Rows/Strip: 2639
  Planar Configuration: single image plane
  Software: ScanFix(TM) Enhanced ImageGear Version:  11.00.024
  DateTime: Mon Oct 31 15:11:07 2005
  Artist: 1996-2001 AccuSoft Co., All rights reserved

If you have a bad page, it'll lack the photometric interpretation section, and you can fix it with:
 ↪ tiffset -d $page-number -s 262 0 your-file.tiff

Note that the value of zero is the default for the photometric interpretation key, which is 262. You can see the other values for this key at the link above.
If your tiff has a lot of pages (like mine does), you may not be able to easily identify the bad page by eye. In that case, you can take a brute force approach, setting the photometric interpretation for all pages to the default value.
# First, split the tiff into many one-page files
↪ tiffsplit your-file.tiff
# Then, set the photometric interpretation to the default for all pages
↪ find . -name '*.tiff' -exec tiffset -s 262 0 '{}' \;
# Then rejoin the pages
↪ tiffcp *.tiff -o out-file.tiff

Lot of dummy work, but gets the job done.


Javascript in SVG

Question: I created a SVG file contains 5 polygons, then I need to embed Javascript so 4 of the polygons' color changes to Red when mouseover, and when mouseout, the color changes to Green. I tried to write the code but it didn't work, what could be the problem? Thanks for help and tips!
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="26cm" height="24cm" viewBox="0 0 2600 2400" version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink= "http://www.w3.org/1999/xlink">

<circle cx="1600" cy="700" r="600" fill="yellow" stroke="black" stroke-width="3"/>
<ellipse id="test" cx="1300" cy="500" rx="74" ry="120" fill="blue" stroke="black"  stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<ellipse id="test" cx="1850" cy="500" rx="74" ry="120"  fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<rect id="test" x="1510" y="650" width="160" height="160" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<polygon id="test" points="1320,800 1370,1080 1820,1080 1870,800 1820,1000 1370,1000" name="mouth" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>

</svg>

Comment: You can't reuse the same ID. You need to use a class instead and iterate through each by using a for loop and `.length`, applying the listeners to both. You'll also have to have different behavior for `onmouseover` and `onmouseout`
Comment: I'm new to Javascrip, could you please give me examples?
Answer: For what you are doing I would recommend using pure CSS.
Here is some working code.
svg:hover .recolor {
    fill: red;
}

As you see, you can just use the :hover event in CSS to recolor the necessary elements. And set them to your default color (green), which will take effect when the user is not hovered.
Comment: Well in my opinion StackOverflow is about best practice, not completing an assignment. I would not choose to do what you are being asked with JS, is inefficient in terms of performance.
Answer: You have various errors

you've two functions called changeColor, functions must have unique names
SVG does not use color to colour elements, instead it uses fill (and stroke).
id values must be unique, you probably want to replace id by class and then use getElementsByClassName instead of getElementById. If you do that you'll need to cope with more than one element though. I've not completed that part, you should try it yourself so you understand what's going on.

I've removed all but one id from my version so you can see it working on the left eye.

document.getElementById("test").onmouseover = function(){changeColor()};

function changeColor() {
document.getElementById("test").style.fill = "red";
}

document.getElementById("test").onmouseout = function(){changeColor2()};

function changeColor2() {
document.getElementById("test").style.fill = "green";
}
<svg width="26cm" height="24cm" viewBox="0 0 2600 2400" version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink= "http://www.w3.org/1999/xlink">

<circle cx="1600" cy="700" r="600" fill="yellow" stroke="black" stroke-width="3"/>
<ellipse id="test" cx="1300" cy="500" rx="74" ry="120" fill="blue" stroke="black"  stroke-width="3"/>
<ellipse cx="1850" cy="500" rx="74" ry="120"  fill="blue" stroke="black" stroke-width="3" />
<rect x="1510" y="650" width="160" height="160" fill="blue" stroke="black" stroke-width="3" />
<polygon points="1320,800 1370,1080 1820,1080 1870,800 1820,1000 1370,1000" name="mouth" fill="blue" stroke="black" stroke-width="3"/>

</svg>
Comment: You've got more than one bug is all.
Comment: I see it works (Run code snippet), however, it still not working after I did all changes. I also tried to wirte exact the same code as yours (for testing) and it's not working. How is this possible, I mean the code indeed work well in Run code snippet but then why it won't work when I run SVG file in my browser.

Javascript in SVG


Exit poll in elections

Question:
We want to run an exit poll for the government referendum, by asking the voters in one vote center whether they voted for option A or B.
  We have an urn with 5 red, 3 green and 2 blue marbles. Each voter randomly picks one marble from the urn, sees its color and then places it back in the urn. If it is red, he tells the truth (we assume that he must have voted either A or B – there is no other option). If it is green, he replies "B", regardless of what he has actually voted and if it is blue, he replies "A", again regardless of what he has actually voted.
  At the end of the exit poll, we got 40% A's. What is the actual percentage of the A's voters in this vote center?

Probabilities is not my strong area of knowledge :(
I was told that this is an easy example of Bayes theorem - I went through it but really can't find how to apply it!
\begin{align}
\mathsf P(R\mid G, B) & = \frac{\mathsf P(R,G,B)}{\mathsf P(G, B)}
\end{align}
OK of course the probability of R is 0.5, of G 0.333 and for B 0.2.
But I don't know what to do then.
Answer: A voter votes, picks a ball and based on the color of the ball and the rule in place says "A" or "B". What is the probability that the voter will say "A" in the end? The voter will eventually say "A" in two cases only:

He really voted for option A and picked the red ball forcing him to tell the truth
...or the voter picked the blue ball that forces him to say "A"

Translated to probabilities:
$$p(\text{voter says "A" in the end})= \\
p(\text{voter voted for option A})\times p(\text{voter picked the red ball})+p(\text{voter picked the blue ball})$$
...or with the numbers that you have:
$$p(\text{voter says "A" in the end})=
p(\text{voter voted for option A})\times \frac{5}{10}+\frac{2}{10}\tag{1}$$
We also know (based on our exit poll) that:
$$p(\text{voter says "A" in the end})=40\%=0.4$$
Replace that into (1) and you get:
$$0.4= p(\text{voter voted for option A})\times 0.5+0.2\tag{1}$$
$$p(\text{voter voted for option A})=0.4=40\%$$
Turns out to be the same, but that's just a lucky coincidence.
Answer: Suppose there are $1000$ voters, $10a$ vote for $A$ and $10b$ for $B$.
Also let it be that $5a$ of the $A$-voters picks a red marble, $3a$ a green marble and $2a$ a blue marble.
Similarly $5b$ of the $B$-voters picks a red marble, $3b$ a green marble and $2b$ a blue marble.
Then in total $7a+2b$ will say to have voted for $A$, so we have the equalities:

$a+b=100$
$7a+2b=400$

leading to $a=40$, i.e. $40\%$ voters for $A$.

Exit poll in elections


Bound on the sequence satisfying $z_{n+1} \leq cz_n^{1+\epsilon}$

Question: Let $z_n$ be a sequence of numbers such that
$$z_{n+1} \leq cz_n^{1+\epsilon}$$
for a constant $c>0$ and $\epsilon > 0$.
If $z_0$ is sufficiently small, is it possible to say that
$$z_n \leq f(n)$$
where $f(n) \to 0$ as $n \to \infty$? $f$ may depend on $\epsilon$ and $z_0$.
Answer: Iterating the inequality we get
$$\begin{align*}
z_{n+1}&\le c\,z_n^{1+\epsilon}\\
&\le c^{1+(1+\epsilon)}\,z_{n-1}^{(1+\epsilon)^2}\\
&\le c^{1+(1+\epsilon)+(1+\epsilon)^2}\,z_{n-2}^{(1+\epsilon)^3}\\
&\le\dots\\
&\le c^{1+(1+\epsilon)+(1+\epsilon)^2+\dots+(1+\epsilon)^n}\,z_0^{(1+\epsilon)^{n+1}}\\
&=c^{\tfrac{(1+\epsilon)^n-1}{\epsilon}}\,z_0^{(1+\epsilon)^{n+1}}\\
&=c^{-1/\epsilon}\,z_0^{1+\epsilon}\bigl(c^{1/\epsilon}\,z_0\bigr)^{(1+\epsilon)^n}.
\end{align*}$$
If $c^{1/\epsilon}\,z_0<1$, then $z_n\to0$.


Runge-Kutta with impulse

Question: I'm trying to study a simple predator-prey type ODE system of two variables, but I'd like to analyze the impulse response.  Really, I have two versions of the same dynamical system, so two copies of each variable, where all the variables interact according to the same predator-prey model (so the herbivores in both systems can be eaten by carnivores in both systems), but where one of the systems is always on and where the other is off until some time when I subject it to an impulse.  I'm using Runge-Kutta for integration, and I'd like to study the impulse response of that parallel system.
Note that I want the total sum of the copies of the two variables to be constant (when I impulse the one system I 'negative' impulse the other, to keep this consistent).  Really I'm trying to study a single system, but separate out the contribution of the driving signal in a single time step so I can track how long it contributes to system dynamics.
I noticed that if I start the one system in steady state, so nothing is changing, and then impulse the other, the first system is kicked out of steady state and starts oscillating (while the other decays to 0, as expected).  This oscillation suggested something was wrong, since it should return to steady state when the other system dies out.  I've since learned that Runge-Kutta was not meant to deal with impulse.
I've tried two things: the first is to only have the impulse in the first of the four elements of the runge-kutta scheme at impulse time.  This seems to work, and gives me back my steady state after the other system decays, but there is some very weird transience in between (when the sum of variables from the two systems is no longer constant).  I have also tried explicitly using only Euler's method at the impulse time, and this gives a similar result.
Is there something else I can try or a better solution to this problem?
Answer: This is actually a fairly complicated system. Let me see if I am interpreting what you have properly.
You begin with some system with initial conditions, and a forcing function, but there is no "input" term, i.e.
$$y' = f(t,y).$$
At some point $t = T$, you want to add an impulse of some magnitude. So what you really have now is
$$y' = f(t,y)+u(t)$$
where, with $K$ being the amplitude of your impulse,
$$u(t) = \left\{ \begin{array}{cc} 0, & t \neq T, \\ K, & t = T, \end{array}\right.$$
Presumably, you can compute with some accuracy a solution of your system prior to $t=T$.
I would then examine solving the finite impulse response of the modified system
$$y'(t-T) = f(t-T,y)+K\delta(0)$$
where $\delta$ is the impulse "function". You can then use your solution at time $t=T$ as the initial conditions for this system. There might be some better ways to handle the impulse response at non-zero $t$, but effectively this is what it's doing.
You can analyze this system with a Laplace tranform, but what you're really looking for is the finite impulse response of your ODE system. I might also recommend looking at SignalProcessing.SE for some advice.

In general, however, numerical schemes do very poorly with discontinuous input terms. The problem is that most numerical methods "look ahead" either to predict where the system will be (in a PECE technique) and then adjust, or use some moving estimate of the prior slope of the solution to project the solution forward. In either case, the approach has a really hard time with the discontinuity.
A PECE method might give you better results, but it really all depends on many factors.
Comment: Just to be slightly more explicit about what Arkamis is saying (if I understand correctly): use Runge-Kutta or whatever to solve your system up to slightly before the impulse, giving you $y(T-)$ where $T$ is the time of the impulse and $T-$ is "just before"; then add in the impulse, giving you $y(T+) = y(T-) + K$; and then use Runge-Kutta again with that as initial condition.

Runge-Kutta with impulse


How to get Apple Sign-in to work in iOS 15 Simulator?

Question: Is there a trick to get Apple Sign-In to work on the iOS 15 simulators? It works fine on the iOS 13 simulators, but for iOS 15 it just stays stuck on the modal view where it asks for your password.
Answer: This has been fixed on iOS 16 simulator. Update to latest iOS simulator.


Simulating difference equation

Question: I am struggling with this particular problem:
When I try to simulate the difference equation: $x_{n+2} = 6x_{n+1} - 3x_{n}$ with initial conditions $x_{0} = 1$ and $x_{1} = 3 - \sqrt{6}$, it gives very different answers from it's actual analytical solution $x_{n} = (3 - \sqrt{6})^n$. Can someone please show how I can fix my code in order to resolve this problem?
code:
import numpy as np
from math import sqrt

#simulating numerically over 100 terms
index_seq = []
for i in range(99):
    index_seq.append(i)

x = np.zeros(101)

x[0] = 1; x[1] = 3 - sqrt(6)

for n in index_seq:
    x[n+2] = 6*x[n+1]-3*x[n]

for x_val in x:
    print(x_val)

#simulating analytically over 100 terms
x_a = np.zeros(101)
for n in range(101):
    x_a[n] = ((3 - sqrt(6))**n)

for x_val in x_a:
    print(x_val)

Comment: Off topic to this site.  MathSE is for attacking Math problems, not Computer Programming problems.  If you want to delete all of your computer code from your posting, and replace it with **pseudocode**, then a moderate argument could then be made that the posting is appropriate for this site.  Personally, I would then regard the issue as *iffy*, but as the posting stands now, my take on the issue seems clear.
Answer: Your code is fine. From comparing x and x_a side-by-side, it is highly likely that you observe an example of catastrophic cancellation, which is due to floating point arithmetics in your case.
In general, try avoiding subtraction of very small numbers in calculations using programming languages. As an example, you can check that both approaches that are used in the code work fine for a sequence $x_{n+2} = 0.2 x_{n+1} + 0.15x_{n}$ with $x_0 = 1$ and $x_1 = 0.5$, which has an analytical solution $x_n = 2^{-n}$, but doesn't contain subtraction.

Simulating difference equation


Identifying boundary of solid torus with itself by swapping coordinates

Question: Probably the following question is very elementary, but I couldn't find it anywhere.
Let $T$ be the solid 2-torus and let $\sim$ be the equivalence relation on $T$ generated by the relation $\{(\alpha,\beta) \sim (\beta,\alpha) \mid \alpha, \beta \in S^1\}$ on the boundary $\partial T=S^1\times S^1$. What kind of 3-fold is $T/{\sim}$?
I believe that it is $S^3$, but I can't prove it.
EDIT: My idea is the following: Take two copies of the 3-ball $B$. Represent $T=B\coprod B/{\sim}$ by identifying half of their respective boundaries (I'm not sure how exactly, maybe opposite quadrants..). Then the quotient $T/{\sim}$ should be given by identifying the other half of the boundaries, but it is known that this gives $S^3$. Can this work?
EDIT: This question has been answered here:
https://mathoverflow.net/questions/412288/quotient-of-solid-torus-by-swapping-coordinates-on-boundary
Comment: There is a cohomology theory for abelian groups by Eilenberg/MacLane which takes into account not just associativity but also commutativity. I wanted to find the geometrical counterparts of the generators of this complex. In particular, in addition to $[a,b,c] \in C_3(G)$ (3-simplex with vertices identified) we have a new generator $[a|b] \in C_3(G)$ corresponding to the solid torus with $\partial[a|b]=[a,b]-[b,a]$. In particular, $[a|a]$ is a cycle and this led me to the conjecture that the above quotient is $S^3$.
Comment: Just out of curiosity, how does this quotient space comes into your mind? I mean, from where does this question come?
Answer: I assume that you're familiar with the construction of compact surfaces by glueing edges of a square. The torus $T$ can be obtain from Fig. $1$ below by glueing edges of the same color (red, blue) with respect to given direction. Under relation $\sim$, every point is identified with its reflection over the diagonal (the dashed line). So the quotient space we want is given by Fig. $2$, here we glue the colored edges together.

It's easy to see that Fig. $2$ can be obtained from Fig. $3$ by deform the bottom edge into a point. To get the quotient spaces of Fig. 2, one can change the order of taking quotient; that is, to find the quotient space of Fig. 3 first, after that deform the image of the bottom edge (under the quotient map) into a point. But the quotient space $X$ corresponds to Fig. $3$ is just the Mobius strip. The black edges on the top and bottom of the square is joined to become $X$'s boundary, which is $S^1$. Moreover, two pairs of opposite vertices are identified; they become $2$ separated points $A$ and $B$ on $X$'s boundary and divide  the boundary into $2$ half-circles (each of them is the image of a black edge in the quotient). Hence the deformation of the bottom edge still make $X$ a Mobius strip, but with $A$ and $B$ identified. Therefore, $\partial T/{\sim}$ (edited $T\to \partial T$) is homeomorphic to a Mobius strip.
Comment: Thx for this nice answer! However, I don't quite believe what you are saying. Up to Fig. 2 everything is fine and also deforming the lower right vertex into an edge is cool. But then after identifying red and blue edge, we need to identify half of the boundary of that moebius band and not just two points, right? I don't think that it's the same result, but maybe I'm wrong..
Comment: @BipolarMinds: I believe that in the question as stated, $T$ is the **solid** torus, which would mean $D^2 \times S^1$, and $S^1 \times S^1$ is not $T$ itself but instead just the boundary $\partial T$. Is this correct?
Comment: I will think about this more carefully and edit the answer. If there are some better answers after me, feel free to accept them. However, what make thing obscure here is that I implicitly use the following property: Instead of deforming Fig. 3 into Fig. 2 then taking quotient out of Fig. 2, I take the quotient spaces of Fig. 3 first and deform it after. The question is: how can these processes commute? Can we change the order of the quotient? I will figure it out somehow...
Comment: I was edited the answer. Hope that it's clear now.
Comment: @LeeMosher thats correct!
Comment: @withoutfeather As a quotient of a compact space, $T/\sim$ should again be compact
Comment: Sorry, I didn't read the question carefully. I will fix this one more time. Again, feel free to accept other answers if there are some. Also you can answer your question yourself!
Comment: Thank you! I would if I could ;)


Ler um número Par

Question: Estou novamente com dúvidas,agora a dúvida é relacionada a exercício sobre
Desvio de condicional Simples usando apenas o comando IF

Após ler um valor inteiro, calcular e apresentar o seu quadrado apenas se o valor lido for par. Caso contrário, o programa deve ser encerrado, sem apresentar nada.

Estou em dúvida em qual será a minha condição do IF que indique que o cálculo só sera realizado se o número informado pelo usuário for par!
Eu declarei três variáveis

O Numero que sera digitado
A váriavel que ira apresentar o calculo(no caso o numero ao quadrado)
A variável para indicar que o valor é par!

E minha segunda dúvida é : Se devo declarar uma variável para indicar que o valor precisa ser par... Ou se apenas indico duas variáveis!
Comment: Utilize o *mod*, ele irá capturar o resto da divisão, por exemplo: `if ( (10 % 2) == 0 )` a expressão quer dizer: *Se o resto da divisão 10/2 for igual à 0, então faça isso. Você também pode utilize `Math.floorMod`
Comment: Se já tem algum código para a resolução do problema, é importante que o coloque na pergunta, dando mais contexto e realçando a sua dificuldade
Comment: Isac..não fiz o código,apenas pensei nas váriaveis!
Comment: Valdeir...no meu caso irei usar o if 10 %2..ja que ainda não vi o método Math!
Answer: Só precisa de duas variáveis.
Pode fazer assim:
int calculo = numero * numero;
if (calculo % 2 == 0) System.out.println(calculo);
// O operador % retorna o resto da divisão. 0 seria numero par, e 1 impar!
// O if não precisa de estar com chaves por conter apenas uma instrução.

E pode-se fazer até mesmo com uma variável apenas!
if ((numero * numero) % 2 == 0) System.out.println(numero * numero);

Ler um número Par


Longitudinal data, 4 years, 3 levels - wanting to visualise transitions

Question: I have a dataframe which in R looks somewhat like this.
set.seed(100)

df <- data.frame(ID = 1:10,
            I.2011 = sample(1:3, rep = 1, 10),
            I.2012 = sample(1:3, rep = 1, 10),
            I.2013 = sample(1:3, rep = 1, 10),
            I.2014 = sample(1:3, rep = 1, 10))

   ID I.2011 I.2012 I.2013 I.2014
1   1      1      2      2      2
2   2      1      3      3      3
3   3      2      1      2      2
4   4      1      2      3      3
5   5      2      3      2      3
6   6      2      3      1      3
7   7      3      1      3      1
8   8      2      2      3      2
9   9      2      2      2      3
10 10      1      3      1      1

The data is longitudinal, and I am interested in people's transitions over time. Particularly important are the group of people who begin in 2011 in group 2, so perhaps in some visualisation the people who satisfy this criteria would have their trajectory in colour whereas all other trajectories would be in shades of grey.
I am wondering if anyone had a neat solution for visualising these transitions, perhaps implementable in R with ggplot2 or something interactive which would be implementable with d3.js (I am new to d3.js so I'm looking for a chance to try it out!)
If example code is available that would be fantastic, however I'm not so worried about that, and instead wish to focus on how best this information could be visualised. A type of sankey or chord diagram is coming to mind, but overall I am unsure.
Answer: You might be looking for sequence analysis methods. Have a look at the R package called TraMineR. It might be a good starting place to see what you could do, then try and implement in ggplot or d3.js. At the very least, it will hopefully help you learn some names of plots which you can use and then search for them more effectively. Here is just some of the plotting capabilities in TraMineR:
library(TraMineR)
set.seed(100)
df <- data.frame(ID = 1:100,
             I.2011 = sample(1:3, rep = 1, 100),
             I.2012 = sample(1:3, rep = 1, 100),
             I.2013 = sample(1:3, rep = 1, 100),
             I.2014 = sample(1:3, rep = 1, 100))

seq <- seqdef(data = df[,grep("I.",names(df),fixed = T)])

seqiplot(seq, title = "First ten sequences",  tlim=1:10)

seqIplot(seq, sortv = "from.start", title = "Grouping sequences by starting patterns") # this might be of particular interest.

seqfplot(seq, title = "The most common pathways", tlim=1:10)

See http://traminer.unige.c or ?TraMineR in R for more details.


How can I define and add a lagend to this ggplot 2 script?

Question: I came up with the following script to bin my data on X values, and plot the means of those bins in overlapping bar graphs. It works fine, but I can't seem to get a legend to generate, probably due to poor understanding of aesthetic mapping.
Here is the script, note that "MOI" and "T_cell_contacts" are two data columns in each DF.
ggplot(mapping=aes(MOI, T_cell_contacts))  +   stat_summary_bin(data = Cleaned24hr4, fun = "mean", geom="bar", bins= 100, fill = "#FF6666", alpha = 0.3) + stat_summary_bin(data = cleaned24hr8, fun = "mean", geom="bar", bins= 100, fill = "#3733FF", alpha = 0.3) +   ylab("mean")

I also added the graph that it plots.
Answer: Full disclosure: I was in the middle of writing this when @schumacher posted their response :).  Decided to finish anyway.
There are two ways to approach this.  One way (more complicated) is to keep the dataframes separate and ask ggplot2 to create a legend via mapping, and the second (simpler) way is to combine into one dataset similar to what @schumacher posted and map the fill color to the extra id column created.
I'll show you both, but first, here's a sample dataset:
library(ggplot2)
set.seed(8675309)
df1 <- data.frame(my_x=rep(1:100, 3), my_y=rnorm(300, 40, 4))
df2 <- data.frame(my_x=rep(11:110, 3), my_y=rnorm(300, 110, 10))

# and the plot code similar to OP's question
ggplot(mapping=aes(x = my_x, y = my_y)) +
  stat_summary_bin(data=df1, fun="mean", geom="bar", bins=40, fill="blue", alpha=0.3) +
  stat_summary_bin(data=df2, fun="mean", geom="bar", bins=40, fill="red", alpha=0.3)

Method 1 : Combine Dataframes
This is the preferred method for a variety of reasons I can't list completely here.  There are a lot of options you can use for combining datasets.  One is using union() or rbind() after adding some sort of ID column to your data, but you can do all in one shot using bind_rows() from dplyr:
df <- dplyr::bind_rows(list(dataset1 = df1, dataset2 = df2), .id="id")

The result will bind the rows together and by specifying the .id argument, it will create a new column in the dataset called "id" that uses the names for each of the datasets in the list as the value.  In this case, the value in thd df$id column is either "dataset1" if it originated from df1 or "dataset2" if it originated from df2.
Then you use aes(fill=...) to map the fill color to the column "id" in the combined dataset.
p <- ggplot(df, aes(x=my_x, y=my_y)) +
  stat_summary_bin(aes(fill=id), fun="mean", geom="bar", bins=40, alpha=0.3)
p

This creates a plot with the default colors for fill, so if you want to supply your own, just use scale_fill_manual(values=...) to specify the particular colors.  Using a named vector for values= ensures that each color is applied the way you want it to be, but you can just supply an unnamed vector of color names.
p + scale_fill_manual(values = c("dataset1" = "blue", "dataset2" = "red"))

Method 2 : Use mapping to add the legend
While Method 1 is preferred, there is another way that does not force you to combine  your dataframes.  This is also useful to illustrate a bit about how ggplot2 decides to create and draw legends.  The legend is created automaticaly via the mapping= argument, specifically via aes().  If you put any aesthetic inside of aes() that would normally impart a different appearance and not location (with some exceptions like x, y, and label), then this initiates the creation of a legend.  You can map either a column in your dataset (like above), or you can just supply a single value and that will be applied to the entire dataset used for the geom.  In this case, see what happens when you change the fill= argument for each geom call to be within aes() and assign it to a character value:
p1 <- ggplot(mapping = aes(x=my_x, y=my_y)) +
  stat_summary_bin(aes(fill="first"), data=df1, fun="mean", geom="bar", bins=40, alpha=0.3) +
  stat_summary_bin(aes(fill="second"), data=df2, fun="mean", geom="bar", bins=40, alpha=0.3) +
  scale_fill_manual(values = c("first" = "blue", "second" = "red"))
p1

It works!  When you provide a character value for the fill= aesthetic inside aes(), it's basically labeling every observation in that data to have the value "first" or "second" and using that to make the legend.  Cool, right?
You notice a problem though, which is that the alpha value for the legend is not correct.  This is because you get overplotting.  It's just one of the reasons why you shouldn't really do it this way, but... sort of works.  It is only noticeable if you ahve an alpha value.  You can get that to look normal, but you need to use guide_legend() to override the aesthetics.  Since the code effectively causes the legend to be drawn completely for each geom... you have to cut the alpha value in half for it to display correctly.
p1 + guides(fill=guide_legend(override.aes = list(alpha=0.15)))

Oh, and the real reason why not to use Method 2 is.... just think about doing that again for 5 datasets... how about 10?... how about 20?.....
Comment: Sorry for never commenting, this was a super helpful and detailed answer. This not only solved my problem, but also taught me a little bit more about how R works. Thanks for the time and effort you put into this!
Answer: I think the difficulty has to do with building a single legend out of two different geoms.  My approach was to combine your data into a single data frame.  The records from each to be set apart by a new category column, I'll call "cat" for short.
With the popular dplyr package:
Cleaned24hr4 <- mutate(Cleaned24hr4, cat = "hr4")
Cleaned24hr8 <- mutate(Cleaned24hr8, cat = "hr8")

Then put them together:
Cleaned <- union(Cleaned24hr4,Cleaned24hr8)

Define your colors:
colorcode <- c("hr4" = "#FF6666", "hr8" = "#3733FF")

Here's my ggplot statement:
ggplot(Cleaned, mapping=aes(MOI, T_cell_contacts)) +
  stat_summary_bin(fun = "mean", geom="bar", bins= 100, aes(fill = cat), alpha = 0.3) +
  scale_fill_manual(values = colorcode) +
  ylab("mean")

Output using some dummy data.


Running Script on EC2 Boot

Question: I want to mount my EBS volume and start up the Apache/MySQL servers on my EC2 machine, but I can't even get my script to run at startup.
I've tried putting it in:
/etc/init.d/
/etc/rc.d/rc5.d/
/etc/rc.local
None of them are working... Where should I put my script?
Comment: What operating system? If it is a CentOS/RHEL derivative (e.g. Amazon's Linux) /etc/init.d/ is good, but you also need to run chkconfig, and turn the service on at the correct run levels.
Comment: Looks like I fixed it by setting the script chmod +x
Answer: Make sure your script is runnable. (chmod +x)
But why would you use a script to mount it? You can add it to /etc/fstab.
Comment: Considering the fact that my newbie-ness has let me forget to make a script executable probably means I shouldn't fool around too much with the file system stuff. I know this works and I won't be rebooting the server very often :P
Comment: @Andrew M: No problem :-)

Running Script on EC2 Boot


How return a Tuple from a SQL Server 2012 database Table

Question: I have 2 columns GetProviders and GetAwaitingPatients in a single table in a SQL Server 2012 database.

GetProviders has it is elements stored as a Tuple<long, string> array
GetAwaitingPatients has its elements stored as Tuple<long, long, string> array

I am trying to simply read and return the data from each of these columns in this single table using C# and Linq with this two methods.
public Tuple<long, string>[] GetProviders(Guid sessionId)
{
    var objproviders = (from objProvider in db.Licenses
                        where objProvider.GUID == Convert.ToString(sessionId)
                        select objProvider.GetProviders).ToList();

    return objproviders;
}

I am getting an error

can't convert expression type  "system.Collection.generic.List" to return type "System.Tuple [ ]

Example of data in this column:
   10556, Memorial
   21456, Dallas
   38678, Chicago

Here is the second method:
 public Tuple<long, long, string>[] GetAwaitingPatients(Guid sessionId)
 {
     var objGetAwaiting = (from objGetAwaitingPatient in db.Licenses
                           where objGetAwaitingPatient.GUID == Convert.ToString(sessionId)
                           select objGetAwaitingPatient.GetAwaitingPatients).ToList();

     return objGetAwaiting;
}

I am getting an error

can't convert expression type "system.Collection.generic.List" to return type "System.Tuple [ ]

Example of data in this column:
   10,10556, Steven
   35,21456, Sandy
   77,21456, John

How do I return the correct return type and also do it correctly? I tried using list to return as a list but that does not seem to work for me. Any insights or help is well appreciated.
Comment: you can change your return types or build up the Tuples that you seem to be expecting.  The error message is pretty straightforward, why are you expecting Tuples when you call `ToList()`?
Comment: i tried to see if i could convert it to List but that did not work
Comment: You can try this link, look like similar to your question  http://stackoverflow.com/questions/18664186/convert-list-of-ef-objects-to-tuple-without-iterating    List> tuples = subjectList.Select(x => new Tuple(x, false)).ToList();
Comment: The **real solution** would be to store the data in a *real, relational fashion* - don't store multiple values into a single table cell! If you have five tuple - those should be **five rows** in a separate table!
Comment: Why is the property GetAwaitingPatients named like a method? I was about to post an answer that you are simply not calling this method.
Answer: Have you tried simply calling the ToArray() extension method instead of ToList().
That should do the trick.


polynomial ring modulo: what are the residues?

Question: I am working with the polynomial ring $K[X,Y]/(X^5,Y^4,XY^3)$. Is it correct that $[1],[X],[X^2],[X^3],[X^4],[Y],[Y^2],[Y^3],[XY],[XY^2],[XY^3]$ are the residues?
Thanks for your answers!
Edit: I am working with this ring as a vector space over $K$.
Edit 2:
$[1],[X],[X^2],[X^3],[X^4],[Y],[Y^2],[Y^3],[XY],[XY^2]$
Comment: But $[XY^3]=0$.
Comment: I think a basis is
$$\{[X^iY^j]\mid0\le i\le 4,0\le j\le2\}\cup\{[Y^3]\}.$$The dimension would then be $16,$ not $10.$
Comment: @hannah2002, those are included, as the cases of $i=0$ and $j=1,$ $i=0$ and $j=2.$
Comment: Are you looking for a basis of your ring as a vector space over $K$?
Comment: @doetoe Yes, I will add that to my post
Comment: @AnneBauval Oh yes, of course, I totally forgot about that! Are the other residues correct?
Comment: @AnneBauval But what about $[Y]$ and $[Y^2]$?
Answer: Well, the elements of $K[X,Y]$ can be thought of as $K$-linear combinations of finite subsets of the set of formal monomials $\{X^iY^j:i\ge0,j\ge0\}.$ (Here, a $K$-linear combination of the empty set is thought of as the $0$ element, by default.) The set of formal monomials then comprises a basis.
To find a basis for $R:=K[X,Y]/\bigl(X^5,Y^4,XY^3\bigr),$ it suffices to determine which of the standard basis elements aren't in $I:=(X^5,Y^4,XY^3),$ which is the ideal generated by $X^5,Y^4,$ and $XY^3.$ The residues of these basis elements will provide a basis for $R.$ Clearly, since $X^5\in I$ and $Y^4\in I,$ then if $X^iY^j$ is such that $i\geq 5$ and/or $j\geq 4,$ we necessarily have $X^iY^j\in I$ by properties of ideals. That eliminates the vast majority of the standard basis elements right away, leaving only those with $0\leq i\leq 4$ and $0\leq j\leq 3$ as viable options. However, since $XY^3\in I,$ then for any $i\geq 1,$ we have $X^iY^3\in I$ by properties of ideals, which eliminates $4$ more of the remaining $20$ options that we had.
All that remains are $Y^3$ and those of the form $X^iY^j$ for $0\leq i\leq 4$ and $0\leq j\leq 2.$ The residues of these $16$ elements (most of which you already found) give us the basis we desire!


Array Bitmap em um único arquivo

Question: Estou fazendo uma aplicação para o Solidwoks e baixei alguns exemplos, nele são usados algumas imagens BMP como a vista a seguir:

Estas imagens são utilizadas como imagens em menus da seguinte forma no código C#:
<code>BitmapHandler iBmp = new BitmapHandler();
cmdGroup = iCmdMgr.CreateCommandGroup2(mainCmdGroupID, TitleDr, ToolTipDr, "", -1, ignorePrevious, ref cmdGroupErr);
cmdGroup.LargeIconList = iBmp.CreateFileFromResourceBitmap("EngToolsSW.ToolbarLarge.bmp", thisAssembly);
cmdGroup.SmallIconList = iBmp.CreateFileFromResourceBitmap("EngToolsSW.ToolbarSmall.bmp", thisAssembly);
cmdGroup.LargeMainIcon = iBmp.CreateFileFromResourceBitmap("EngToolsSW.MainIconLarge.bmp", thisAssembly);
cmdGroup.SmallMainIcon = iBmp.CreateFileFromResourceBitmap("EngToolsSW.MainIconSmall.bmp", thisAssembly);
</code>
Ou seja, ele busca as imagens separadamente dentro de um mesmo bitmap como se fosse ou Array de imagens. Na documentação do Solidworks fala dessa forma:

The bitmap or PNG file should contain all of the images for all of the large buttons and separators for this CommandGroup, in a single bitmap for both parent and child toolbars. Each image of each button must be 24x24. The images should use a 256-color palette. Use gray (RGB 192, 192, 192) for transparent areas in your graphic.
You can only set this property for the top-level CommandGroup.

disponível neste link.
Como é possível criar um bitmap desses?
Answer: Basicamente você adiciona o arquivo ao seu projeto no Visual Studio. Depois você abre a caixa de diálogo com as propriedades do arquivo. Lá vai ter um campo com o nome "Build Action" define ele como "Embedded Resource". Depois disso você vai poder acessar esses arquivos da mesma forma que você está fazendo no exemplo. É só utilizar a dll que o Visual Studio gera.
Referência: http://support.microsoft.com/kb/319292
Comment: Ok Lucas, já cheguei a usar a opção de "Embedded Resource" para imagens no projeto, porém minha dúvida é porque é usado um único arquivo bitmap com várias imagens que podem ser usadas separadamente de acordo com um index da classe `SmallIconList`, não entendo como é possível criar um bitmap desses com várias imagens.
Comment: @DanielMasarin , se chamar somente isso `cmdGroup.LargeIconList`. É retornado um array de bitmaps?
Comment: Não, é retornado uma string com o local do bitmap.

Array Bitmap em um único arquivo


Métodos sem parâmetros e com parâmetros

Question: Declaração métodos sem parâmetros:
void exemploDeMetodo(){
    int i;
}

Chamada de métodos sem parâmetros:
exemploDeMetodo();

Se eu quiser fazer um método com parâmetros é como?
É assim?
void exemplo(int i){
    faz algo com o i
}

Chamada de métodos com parâmetros:
int inteiro = 1;
exemplo(inteiro);

Se eu quiser retornar um inteiro, terei que colocar um parâmetro no método?
Comment: Isto é Java ou é C?
Comment: @JoseMaximilian procure sempre usar as tags corretas que ajudam definir sobre o que é seu problema para facilitar para as pessoas te ajudarem. Veja as edições feitas para entender que as perguntas devem ser o mais limpas possíveis, sem nada que não importe para a pergunta, assim ela poderá ajudar outras pessoas no futuro.
Comment: Exato, seria bom especificar qual das duas linguagens está utilizando, pois existem algumas diferenças que devem ser consideradas.
Comment: o exemplo está em C.
Comment: @JoseMaximilian é normal, o pessoal demora um pouco se acostumar com um site de **Perguntas e Respostas**. Quando pegar o jeito vai ver que é para o benefício de todos.
Comment: desculpe, farei na próxima vez. Sou Noob por aqui.
Answer: Você está correto em todas suas suposições iniciais.
Para retornar um inteiro você não precisa de parâmetros. O retorno funciona de forma separada. Você pode ter parâmetro mas ele não tem relação direta com o retorno. O retorno é um resultado que você passa de volta para quem chamou.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int exemplo1() { return 1; }

int exemplo2(int i) { return i * 2; }

int exemplo3() {
    srand(time(0));
    return rand();
}

int exemplo4(int i) { return i > 0 ? 1 : 0; }

int main(void) {
    printf("%i\n", exemplo1());
    printf("%i\n", exemplo2(2));
    printf("%i\n", exemplo3());
    printf("%i\n", exemplo4(2));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que em C você sempre deve declarar o tipo do dado para tudo: variáveis, elementos de vetores, campos de estruturas, de parâmetros e claro, pode declarar o tipo das funções, que se confundem com o tipo de retorno da função. void significa retornar nada. E claro, int significa que vai retornar um inteiro.
Em C até existe como retornar valores através de parâmetros, mas isto é avançado, não se preocupe com isto até aprender outras coisas antes. Ainda não terá utilidade para você.
Comment: muito obrigado.
Answer: Você acertou quase tudo, só lhe faltou a parte de retornar um valor.
Uma função tem o seguinte formato:
tipoDeRetorno nomeDoMetodo(tipoDoParametro valorDoParametro) {
    //se o tipoDeRetorno for void não precisa retornar nada
    //caso contrário deve-se usar a seguinte notação:
    return variavelCompativelComOTipoDeRetorno;
}

Para fazer uma função que retorne um valor do tipo inteiro você deve trocar o void que você pôs no seu exemplo, assim:
int exemplo(int i) {
    int j = i*2;
    return j;
}

Perceba que você não precisa necessariamente retornar i, você pode retornar uma outra variável, o resultado de uma expressão ou um valor, desde que corresponda com o tipoDeRetorno.

Métodos sem parâmetros e com parâmetros