问:
Extracting substring from PDF raw text using regex
I was trying to extract the subsection that has the roman indexing from a pdf document.

For instance this is one section of the document,

\n1.1\n \nSCOPE\n \nThis PTS specifies the\n \nrequirements \nand recommendations for Classification, Verification \n\nFunct\nions.\n \nThe scope includes the following:\n \ni.\n \nSemi\n-\nquantitative SIL classification\n \nii.\n \nSpurious trip analysis\n \niii.\n \nProbabilistic and architectural SIL verification\n \niv.\n \nRecommendations\n \nfor SIL gap closure'

what I want is only below:

This PTS specifies the\n \nrequirements \nand recommendations for Classification, Verification \n\nFunct\nions.\n \nThe scope includes the following:\n \ni.\n \nSemi\n-\nquantitative SIL classification\n \nii.\n \nSpurious trip analysis\n \niii.\n \nProbabilistic and architectural SIL verification\n \niv.\n \nRecommendations\n \nfor SIL gap closure

I need the sentence before the roman indexing as well as the content inside roman indexing.

However, there are also cases like below

3.1.3\n \nDo\nc\numentation\n \nrequired\n \nT\nh\ne\n \nl\nat\ne\ns\nt\n \nissue\n \nof\n \nt\nh\ne\n \nf\no\nllo\nw\ni\nng\n \ndocume\nn\nts\n \nshall\n \nbe\n \nav\na\nilab\nl\ne\n \nto\n \nthe\n \nte\na\nm\n \np\ne\nrf\no\nrm\ni\nng\n \nt\nh\ne \nc\nl\nass\ni\nf\ni\ncati\no\nn:\n \ni.\n \nMandatory reference document\n \na)\n \nCause and effect matrices (CEM)\n \nb)\n \nPiping and Instrument Diagram (P&ID) or Process and utility engineering \nflow schemes (PEFS)\n \nc)\n \nHAZOP report\n \nd)\n \nIPF reliability data\n \nii.\n \nOther reference document\n \na)\n \nProcess Flow Diagram (PFD) or Process Fl\now Scheme (PFS)\n \nb)\n \nPlant layout drawing\n \nc)\n \nProcess safeguarding flow schemes (PSFS)\n \nd)\n \nControl narratives\n \ne)\n \nInterlocks/ ESD logic diagram\n \nf)\n \nEquipment layout diagram\n \ng)\n \nMaintenance and Inspection Data\n \nh)\n \nPlant historian data\n \n \nT\nh\ne\n \nl\ni\ns\nt\n \na\nb\no\nve\n \nis\n \nn\no\nt\n \ne\nx\nh\na\nu\nsti\nv\ne. Any\n \not\nh\ne\nr\n \ndo\nc\nu\nm\ne\nn\nt\ns\n/ \nd\nr\na\nw\nin\ng\ns\n \nreq\nu\nir\ne\nd\n \nf\no\nr\n \nt\nhe \nc\nom\np\nletion\n \no\nf the\n \nIPF\n \ns\nt\nu\nd\ny\n \ns\nh\na\nll\n \nbe\n \nf\nu\nr\nn\nished\n \nas\n \na\nn\nd\n \nw\nhen\n \nre\nq\nui\nr\ne\nd\n.\n \n

I've converted the pdf into raw text and I've managed to extract section of the document. The

```<code>regx = re.compile( '\.\n \n.+?:\n \n',re.DOTALL)
find = str(txt)
indexhead.append((regx.findall(find)))
</code>```

The above code can only extract the headline but not the roman indexing together

.\n \nThe scope includes the following:\n \n

I'm trying to extract based on the pattern but I'm thinking maybe some conditional rules might help.

答:
If I understand the problem right, we would want to just take out the roman indices, and get the entire paragraph, which we would start with a simple expression such as:

```<code>.+[0-9]\.?.+?([A-Z][a-z].*)
</code>```

then as new cases come up, we would just use logical ORs and add additional rules.

Demo

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+[0-9]\.?.+?([A-Z][a-z].*)"

test_str = ("\\n1.1\\n \\nSCOPE\\n \\nThis PTS specifies the\\n \\nrequirements \\nand recommendations for Classification, Verification \\n\\nFunct\\nions.\\n \\nThe scope includes the following:\\n \\ni.\\n \\nSemi\\n-\\nquantitative SIL classification\\n \\nii.\\n \\nSpurious trip analysis\\n \\niii.\\n \\nProbabilistic and architectural SIL verification\\n \\niv.\\n \\nRecommendations\\n \\nfor SIL gap closure'\n\n"
    "3.1.3\\n \\nDo\\nc\\numentation\\n \\nrequired\\n \\nT\\nh\\ne\\n \\nl\\nat\\ne\\ns\\nt\\n \\nissue\\n \\nof\\n \\nt\\nh\\ne\\n \\nf\\no\\nllo\\nw\\ni\\nng\\n \\ndocume\\nn\\nts\\n \\nshall\\n \\nbe\\n \\nav\\na\\nilab\\nl\\ne\\n \\nto\\n \\nthe\\n \\nte\\na\\nm\\n \\np\\ne\\nrf\\no\\nrm\\ni\\nng\\n \\nt\\nh\\ne \\nc\\nl\\nass\\ni\\nf\\ni\\ncati\\no\\nn:\\n \\ni.\\n \\nMandatory reference document\\n \\na)\\n \\nCause and effect matrices (CEM)\\n \\nb)\\n \\nPiping and Instrument Diagram (P&ID) or Process and utility engineering \\nflow schemes (PEFS)\\n \\nc)\\n \\nHAZOP report\\n \\nd)\\n \\nIPF reliability data\\n \\nii.\\n \\nOther reference document\\n \\na)\\n \\nProcess Flow Diagram (PFD) or Process Fl\\now Scheme (PFS)\\n \\nb)\\n \\nPlant layout drawing\\n \\nc)\\n \\nProcess safeguarding flow schemes (PSFS)\\n \\nd)\\n \\nControl narratives\\n \\ne)\\n \\nInterlocks/ ESD logic diagram\\n \\nf)\\n \\nEquipment layout diagram\\n \\ng)\\n \\nMaintenance and Inspection Data\\n \\nh)\\n \\nPlant historian data\\n \\n \\nT\\nh\\ne\\n \\nl\\ni\\ns\\nt\\n \\na\\nb\\no\\nve\\n \\nis\\n \\nn\\no\\nt\\n \\ne\\nx\\nh\\na\\nu\\nsti\\nv\\ne. Any\\n \\not\\nh\\ne\\nr\\n \\ndo\\nc\\nu\\nm\\ne\\nn\\nt\\ns\\n/ \\nd\\nr\\na\\nw\\nin\\ng\\ns\\n \\nreq\\nu\\nir\\ne\\nd\\n \\nf\\no\\nr\\n \\nt\\nhe \\nc\\nom\\np\\nletion\\n \\no\\nf the\\n \\nIPF\\n \\ns\\nt\\nu\\nd\\ny\\n \\ns\\nh\\na\\nll\\n \\nbe\\n \\nf\\nu\\nr\\nn\\nished\\n \\nas\\n \\na\\nn\\nd\\n \\nw\\nhen\\n \\nre\\nq\\nui\\nr\\ne\\nd\\n.\\n \\n")

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I was trying to extract the subsection that has the roman indexing from a pdf document.

For instance this is one section of the document,

\n1.1\n \nSCOPE\n \nThis PTS specifies the\n \nrequirements \nand recommendations for Classification, Verification \n\nFunct\nions.\n \nThe scope includes the following:\n \ni.\n \nSemi\n-\nquantitative SIL classification\n \nii.\n \nSpurious trip analysis\n \niii.\n \nProbabilistic and architectural SIL verification\n \niv.\n \nRecommendations\n \nfor SIL gap closure'

what I want is only below:

This PTS specifies the\n \nrequirements \nand recommendations for Classification, Verification \n\nFunct\nions.\n \nThe scope includes the following:\n \ni.\n \nSemi\n-\nquantitative SIL classification\n \nii.\n \nSpurious trip analysis\n \niii.\n \nProbabilistic and architectural SIL verification\n \niv.\n \nRecommendations\n \nfor SIL gap closure

I need the sentence before the roman indexing as well as the content inside roman indexing.

However, there are also cases like below

3.1.3\n \nDo\nc\numentation\n \nrequired\n \nT\nh\ne\n \nl\nat\ne\ns\nt\n \nissue\n \nof\n \nt\nh\ne\n \nf\no\nllo\nw\ni\nng\n \ndocume\nn\nts\n \nshall\n \nbe\n \nav\na\nilab\nl\ne\n \nto\n \nthe\n \nte\na\nm\n \np\ne\nrf\no\nrm\ni\nng\n \nt\nh\ne \nc\nl\nass\ni\nf\ni\ncati\no\nn:\n \ni.\n \nMandatory reference document\n \na)\n \nCause and effect matrices (CEM)\n \nb)\n \nPiping and Instrument Diagram (P&ID) or Process and utility engineering \nflow schemes (PEFS)\n \nc)\n \nHAZOP report\n \nd)\n \nIPF reliability data\n \nii.\n \nOther reference document\n \na)\n \nProcess Flow Diagram (PFD) or Process Fl\now Scheme (PFS)\n \nb)\n \nPlant layout drawing\n \nc)\n \nProcess safeguarding flow schemes (PSFS)\n \nd)\n \nControl narratives\n \ne)\n \nInterlocks/ ESD logic diagram\n \nf)\n \nEquipment layout diagram\n \ng)\n \nMaintenance and Inspection Data\n \nh)\n \nPlant historian data\n \n \nT\nh\ne\n \nl\ni\ns\nt\n \na\nb\no\nve\n \nis\n \nn\no\nt\n \ne\nx\nh\na\nu\nsti\nv\ne. Any\n \not\nh\ne\nr\n \ndo\nc\nu\nm\ne\nn\nt\ns\n/ \nd\nr\na\nw\nin\ng\ns\n \nreq\nu\nir\ne\nd\n \nf\no\nr\n \nt\nhe \nc\nom\np\nletion\n \no\nf the\n \nIPF\n \ns\nt\nu\nd\ny\n \ns\nh\na\nll\n \nbe\n \nf\nu\nr\nn\nished\n \nas\n \na\nn\nd\n \nw\nhen\n \nre\nq\nui\nr\ne\nd\n.\n \n

I've converted the pdf into raw text and I've managed to extract section of the document. The

regx = re.compile( '\.\n \n.+?:\n \n',re.DOTALL)
find = str(txt)
indexhead.append((regx.findall(find)))

The above code can only extract the headline but not the roman indexing together

.\n \nThe scope includes the following:\n \n

I'm trying to extract based on the pattern but I'm thinking maybe some conditional rules might help.

Body:
If I understand the problem right, we would want to just take out the roman indices, and get the entire paragraph, which we would start with a simple expression such as:

.+[0-9]\.?.+?([A-Z][a-z].*)

then as new cases come up, we would just use logical ORs and add additional rules.

Demo

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+[0-9]\.?.+?([A-Z][a-z].*)"

test_str = ("\\n1.1\\n \\nSCOPE\\n \\nThis PTS specifies the\\n \\nrequirements \\nand recommendations for Classification, Verification \\n\\nFunct\\nions.\\n \\nThe scope includes the following:\\n \\ni.\\n \\nSemi\\n-\\nquantitative SIL classification\\n \\nii.\\n \\nSpurious trip analysis\\n \\niii.\\n \\nProbabilistic and architectural SIL verification\\n \\niv.\\n \\nRecommendations\\n \\nfor SIL gap closure'\n\n"
    "3.1.3\\n \\nDo\\nc\\numentation\\n \\nrequired\\n \\nT\\nh\\ne\\n \\nl\\nat\\ne\\ns\\nt\\n \\nissue\\n \\nof\\n \\nt\\nh\\ne\\n \\nf\\no\\nllo\\nw\\ni\\nng\\n \\ndocume\\nn\\nts\\n \\nshall\\n \\nbe\\n \\nav\\na\\nilab\\nl\\ne\\n \\nto\\n \\nthe\\n \\nte\\na\\nm\\n \\np\\ne\\nrf\\no\\nrm\\ni\\nng\\n \\nt\\nh\\ne \\nc\\nl\\nass\\ni\\nf\\ni\\ncati\\no\\nn:\\n \\ni.\\n \\nMandatory reference document\\n \\na)\\n \\nCause and effect matrices (CEM)\\n \\nb)\\n \\nPiping and Instrument Diagram (P&ID) or Process and utility engineering \\nflow schemes (PEFS)\\n \\nc)\\n \\nHAZOP report\\n \\nd)\\n \\nIPF reliability data\\n \\nii.\\n \\nOther reference document\\n \\na)\\n \\nProcess Flow Diagram (PFD) or Process Fl\\now Scheme (PFS)\\n \\nb)\\n \\nPlant layout drawing\\n \\nc)\\n \\nProcess safeguarding flow schemes (PSFS)\\n \\nd)\\n \\nControl narratives\\n \\ne)\\n \\nInterlocks/ ESD logic diagram\\n \\nf)\\n \\nEquipment layout diagram\\n \\ng)\\n \\nMaintenance and Inspection Data\\n \\nh)\\n \\nPlant historian data\\n \\n \\nT\\nh\\ne\\n \\nl\\ni\\ns\\nt\\n \\na\\nb\\no\\nve\\n \\nis\\n \\nn\\no\\nt\\n \\ne\\nx\\nh\\na\\nu\\nsti\\nv\\ne. Any\\n \\not\\nh\\ne\\nr\\n \\ndo\\nc\\nu\\nm\\ne\\nn\\nt\\ns\\n/ \\nd\\nr\\na\\nw\\nin\\ng\\ns\\n \\nreq\\nu\\nir\\ne\\nd\\n \\nf\\no\\nr\\n \\nt\\nhe \\nc\\nom\\np\\nletion\\n \\no\\nf the\\n \\nIPF\\n \\ns\\nt\\nu\\nd\\ny\\n \\ns\\nh\\na\\nll\\n \\nbe\\n \\nf\\nu\\nr\\nn\\nished\\n \\nas\\n \\na\\nn\\nd\\n \\nw\\nhen\\n \\nre\\nq\\nui\\nr\\ne\\nd\\n.\\n \\n")

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


来源: stackexchange

问:
problems with my SQLiteOpenHelper
```<code>package com.owen.quartergames.dao;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import com.owen.quartergames.R;
import com.owen.quartergames.domain.LogEntry;

public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
        FishLoggerDao {

    private static final String DB_NAME = "fishingLog";

    private static final String TABLE_NAME = "LogEntries";

    private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";

    private static final String FIND_LOG_ENTRY_SQL = "SELECT _id, Longitude, Latitude FROM LogEntries WHERE _id = ?";

    private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";

    private static final String[] NO_ARGS = {};

    private Context context;

    private final SQLiteDatabase db = getWritableDatabase();

    public SqlLiteFishLoggerDao(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
    }

    @Override
    public void deleteLogEntry(String id) {
        id = "0";

        db.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
        // int deleted = db.delete(TABLE_NAME, "_id = ?",
        // new String[] { id.trim() });
        // Log.i("fishlogger", String.format("Delete %d rows", deleted));
        db.close();
    }

    @Override
    public LogEntry findEntry(String id) {
        Cursor cursor = db.rawQuery(FIND_LOG_ENTRY_SQL, new String[] { id });
        if (!cursor.moveToFirst()) {
            return null;
        }

        LogEntry entry = new LogEntry();
        entry.setId(id);
        entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
        entry
                .setLongitude(cursor.getDouble(cursor
                        .getColumnIndex("Longitude")));
        cursor.close();
        db.close();
        return entry;

    }

    @Override
    public void insertLogEntry(LogEntry entry) {
        ContentValues values = new ContentValues();
        values.put("Latitude", entry.getLatitude());
        values.put("Longitude", entry.getLongitude());
        values.put("PictureURL", entry.getPictureUrl());
        values.put("SizeOrWeight", entry.getSizeOrWeight());
        values.put("CreateDate", entry.getEntryDate());
        values.put("Species", entry.getSpecies());
        db.insertOrThrow("LogEntries", null, values);
        db.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s;
        try {
            Toast.makeText(context, "1", 2000).show();
            InputStream in = context.getResources().openRawResource(R.raw.sql);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList statements = doc.getElementsByTagName("statement");
            for (int i = 0; i < statements.getLength(); i++) {
                s = statements.item(i).getChildNodes().item(0).getNodeValue();
                db.execSQL(s);
            }
        } catch (Throwable t) {
            Toast.makeText(context, t.toString(), 50000).show();
        }
        Log.e("DB", "DB Created");

    }

    @Override
    public List<LogEntry> findAllEntries() {

        List<LogEntry> entries = new ArrayList<LogEntry>();

        Cursor cursor = db.rawQuery(FIND_ALL_ENTRIES_SQL, NO_ARGS);

        int entryDateCol = cursor.getColumnIndex("CreateDate");
        int speciesCol = cursor.getColumnIndex("Species");
        int sizeCol = cursor.getColumnIndex("SizeOrWeight");
        int latCol = cursor.getColumnIndex("Latitude");

        if (cursor.moveToFirst()) {
            do {
                LogEntry entry = new LogEntry();
                entry.setEntryDate(cursor.getString(entryDateCol));
                entry.setSpecies(cursor.getString(speciesCol));
                entry.setSizeOrWeight(cursor.getString(sizeCol));
                entry.setLatitude(cursor.getDouble(latCol));

                if (entry.getSpecies() == null) {
                    entry.setSpecies("Not Entered");
                }

                if (entry.getSizeOrWeight() == null) {
                    entry.setSizeOrWeight("Not entered");
                }

                entries.add(entry);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return entries;
    }

    @Override
    public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(getWritableDatabase());
    }
}
</code>```

basically the delete doesnt work however i think the problems stems from the findAllEntries() method.  the reason i say that is that i get "leak found" errors in log cat saying the db was created but never closed.  i have throughly searched the internet and have asked friends who code but no luck in solving the problem.  all my cursors are closed and from what i can tell this is how a sqlliteopenhelper should generally look like.

thanks for any responses

答:
just wanted to followup.  i thank you all for your help.
in the end it seems there were a few issues.  Theres very little chance u guys could have figured it out on ur own with what i gave u it took me forever to figure it out.

anyways heres what i did wrong plus the updated code:

I wasnt opening and closing the DB for every
method (leaks found errors)

findallentries was not feeding the
_id field into the object.  and so when my listview was populated and u
said delete, it would use the
iterator id as opposed to the real
database _id of the entry.

i needed to call .trim on my id
field

(both 2 and 3 however produced no errors in logcat.  it would just never delete.  it inserted fine, select * fine, but nothing happened on delete)

```<code>package com.owen.quartergames.dao;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.owen.quartergames.R;
import com.owen.quartergames.domain.LogEntry;

public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
        FishLoggerDao {

    private static final String DB_NAME = "fishingLog";

    private static final String TABLE_NAME = "LogEntries";

    private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";

    private static final String FIND_LOG_ENTRY_SQL = "SELECT _id, Longitude, Latitude FROM LogEntries WHERE _id = ?";

    private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";

    private static final String[] NO_ARGS = {};

    private Context context;

    private SQLiteDatabase DB;

    public SqlLiteFishLoggerDao(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
    }

    @Override
    public void deleteLogEntry(String id) {
        DB = getWritableDatabase();
        DB.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
        DB.close();
    }

    @Override
    public LogEntry findEntry(String id) {
        DB = getReadableDatabase();
        Cursor cursor = DB.rawQuery(FIND_LOG_ENTRY_SQL,
                new String[] { id });
        if (!cursor.moveToFirst()) {
            return null;
        }

        LogEntry entry = new LogEntry();
        entry.setId(id);
        entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
        entry
                .setLongitude(cursor.getDouble(cursor
                        .getColumnIndex("Longitude")));
        cursor.close();
        DB.close();
        return entry;

    }

    @Override
    public void insertLogEntry(LogEntry entry) {
        DB = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("Latitude", entry.getLatitude());
        values.put("Longitude", entry.getLongitude());
        values.put("PictureURL", entry.getPictureUrl());
        values.put("SizeOrWeight", entry.getSizeOrWeight());
        values.put("CreateDate", entry.getEntryDate());
        values.put("Species", entry.getSpecies());
        DB.insertOrThrow("LogEntries", null, values);
        DB.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s;
        try {
            InputStream in = context.getResources().openRawResource(R.raw.sql);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList statements = doc.getElementsByTagName("statement");
            for (int i = 0; i < statements.getLength(); i++) {
                s = statements.item(i).getChildNodes().item(0).getNodeValue();
                db.execSQL(s);
            }
            Log.e("DB", "DB Created Successfully");
        } catch (Throwable t) {
            Log.e("DB error: ",t.toString());
        }
    }

    @Override
    public List<LogEntry> findAllEntries() {
        DB = getReadableDatabase();

        List<LogEntry> entries = new ArrayList<LogEntry>();

        Cursor cursor = DB.rawQuery(FIND_ALL_ENTRIES_SQL,
                NO_ARGS);

        int entryID = cursor.getColumnIndex("_id");
        int entryDateCol = cursor.getColumnIndex("CreateDate");
        int speciesCol = cursor.getColumnIndex("Species");
        int sizeCol = cursor.getColumnIndex("SizeOrWeight");
        int latCol = cursor.getColumnIndex("Latitude");

        if (cursor.moveToFirst()) {
            do {
                LogEntry entry = new LogEntry();
                entry.setId(cursor.getString(entryID));
                entry.setEntryDate(cursor.getString(entryDateCol));
                entry.setSpecies(cursor.getString(speciesCol));
                entry.setSizeOrWeight(cursor.getString(sizeCol));
                entry.setLatitude(cursor.getDouble(latCol));

                if (entry.getSpecies() == null) {
                    entry.setSpecies("Not Entered");
                }

                if (entry.getSizeOrWeight() == null) {
                    entry.setSizeOrWeight("Not entered");
                }

                entries.add(entry);
            } while (cursor.moveToNext());
        }
        cursor.close();
        DB.close();
        return entries;
    }

    @Override
    public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
        DB = getWritableDatabase();
        DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(getWritableDatabase());
        DB.close();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: problems with my SQLiteOpenHelper

Body:
package com.owen.quartergames.dao;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import com.owen.quartergames.R;
import com.owen.quartergames.domain.LogEntry;

public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
        FishLoggerDao {

    private static final String DB_NAME = "fishingLog";

    private static final String TABLE_NAME = "LogEntries";

    private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";

    private static final String FIND_LOG_ENTRY_SQL = "SELECT _id, Longitude, Latitude FROM LogEntries WHERE _id = ?";

    private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";

    private static final String[] NO_ARGS = {};

    private Context context;

    private final SQLiteDatabase db = getWritableDatabase();

    public SqlLiteFishLoggerDao(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
    }

    @Override
    public void deleteLogEntry(String id) {
        id = "0";

        db.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
        // int deleted = db.delete(TABLE_NAME, "_id = ?",
        // new String[] { id.trim() });
        // Log.i("fishlogger", String.format("Delete %d rows", deleted));
        db.close();
    }

    @Override
    public LogEntry findEntry(String id) {
        Cursor cursor = db.rawQuery(FIND_LOG_ENTRY_SQL, new String[] { id });
        if (!cursor.moveToFirst()) {
            return null;
        }

        LogEntry entry = new LogEntry();
        entry.setId(id);
        entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
        entry
                .setLongitude(cursor.getDouble(cursor
                        .getColumnIndex("Longitude")));
        cursor.close();
        db.close();
        return entry;

    }

    @Override
    public void insertLogEntry(LogEntry entry) {
        ContentValues values = new ContentValues();
        values.put("Latitude", entry.getLatitude());
        values.put("Longitude", entry.getLongitude());
        values.put("PictureURL", entry.getPictureUrl());
        values.put("SizeOrWeight", entry.getSizeOrWeight());
        values.put("CreateDate", entry.getEntryDate());
        values.put("Species", entry.getSpecies());
        db.insertOrThrow("LogEntries", null, values);
        db.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s;
        try {
            Toast.makeText(context, "1", 2000).show();
            InputStream in = context.getResources().openRawResource(R.raw.sql);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList statements = doc.getElementsByTagName("statement");
            for (int i = 0; i < statements.getLength(); i++) {
                s = statements.item(i).getChildNodes().item(0).getNodeValue();
                db.execSQL(s);
            }
        } catch (Throwable t) {
            Toast.makeText(context, t.toString(), 50000).show();
        }
        Log.e("DB", "DB Created");

    }

    @Override
    public List<LogEntry> findAllEntries() {

        List<LogEntry> entries = new ArrayList<LogEntry>();

        Cursor cursor = db.rawQuery(FIND_ALL_ENTRIES_SQL, NO_ARGS);

        int entryDateCol = cursor.getColumnIndex("CreateDate");
        int speciesCol = cursor.getColumnIndex("Species");
        int sizeCol = cursor.getColumnIndex("SizeOrWeight");
        int latCol = cursor.getColumnIndex("Latitude");

        if (cursor.moveToFirst()) {
            do {
                LogEntry entry = new LogEntry();
                entry.setEntryDate(cursor.getString(entryDateCol));
                entry.setSpecies(cursor.getString(speciesCol));
                entry.setSizeOrWeight(cursor.getString(sizeCol));
                entry.setLatitude(cursor.getDouble(latCol));

                if (entry.getSpecies() == null) {
                    entry.setSpecies("Not Entered");
                }

                if (entry.getSizeOrWeight() == null) {
                    entry.setSizeOrWeight("Not entered");
                }

                entries.add(entry);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return entries;
    }

    @Override
    public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(getWritableDatabase());
    }
}

basically the delete doesnt work however i think the problems stems from the findAllEntries() method.  the reason i say that is that i get "leak found" errors in log cat saying the db was created but never closed.  i have throughly searched the internet and have asked friends who code but no luck in solving the problem.  all my cursors are closed and from what i can tell this is how a sqlliteopenhelper should generally look like.

thanks for any responses

Body:
just wanted to followup.  i thank you all for your help.
in the end it seems there were a few issues.  Theres very little chance u guys could have figured it out on ur own with what i gave u it took me forever to figure it out.

anyways heres what i did wrong plus the updated code:

I wasnt opening and closing the DB for every
method (leaks found errors)

findallentries was not feeding the
_id field into the object.  and so when my listview was populated and u
said delete, it would use the
iterator id as opposed to the real
database _id of the entry.

i needed to call .trim on my id
field

(both 2 and 3 however produced no errors in logcat.  it would just never delete.  it inserted fine, select * fine, but nothing happened on delete)

package com.owen.quartergames.dao;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.owen.quartergames.R;
import com.owen.quartergames.domain.LogEntry;

public class SqlLiteFishLoggerDao extends SQLiteOpenHelper implements
        FishLoggerDao {

    private static final String DB_NAME = "fishingLog";

    private static final String TABLE_NAME = "LogEntries";

    private static final String DELETE_LOG_ENTRY_SQL = "DELETE FROM LogEntries WHERE _id = ?;";

    private static final String FIND_LOG_ENTRY_SQL = "SELECT _id, Longitude, Latitude FROM LogEntries WHERE _id = ?";

    private static final String FIND_ALL_ENTRIES_SQL = "SELECT * FROM LogEntries";

    private static final String[] NO_ARGS = {};

    private Context context;

    private SQLiteDatabase DB;

    public SqlLiteFishLoggerDao(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
    }

    @Override
    public void deleteLogEntry(String id) {
        DB = getWritableDatabase();
        DB.execSQL(DELETE_LOG_ENTRY_SQL, new Object[] { id });
        DB.close();
    }

    @Override
    public LogEntry findEntry(String id) {
        DB = getReadableDatabase();
        Cursor cursor = DB.rawQuery(FIND_LOG_ENTRY_SQL,
                new String[] { id });
        if (!cursor.moveToFirst()) {
            return null;
        }

        LogEntry entry = new LogEntry();
        entry.setId(id);
        entry.setLatitude(cursor.getDouble(cursor.getColumnIndex("Latitude")));
        entry
                .setLongitude(cursor.getDouble(cursor
                        .getColumnIndex("Longitude")));
        cursor.close();
        DB.close();
        return entry;

    }

    @Override
    public void insertLogEntry(LogEntry entry) {
        DB = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("Latitude", entry.getLatitude());
        values.put("Longitude", entry.getLongitude());
        values.put("PictureURL", entry.getPictureUrl());
        values.put("SizeOrWeight", entry.getSizeOrWeight());
        values.put("CreateDate", entry.getEntryDate());
        values.put("Species", entry.getSpecies());
        DB.insertOrThrow("LogEntries", null, values);
        DB.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s;
        try {
            InputStream in = context.getResources().openRawResource(R.raw.sql);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList statements = doc.getElementsByTagName("statement");
            for (int i = 0; i < statements.getLength(); i++) {
                s = statements.item(i).getChildNodes().item(0).getNodeValue();
                db.execSQL(s);
            }
            Log.e("DB", "DB Created Successfully");
        } catch (Throwable t) {
            Log.e("DB error: ",t.toString());
        }
    }

    @Override
    public List<LogEntry> findAllEntries() {
        DB = getReadableDatabase();

        List<LogEntry> entries = new ArrayList<LogEntry>();

        Cursor cursor = DB.rawQuery(FIND_ALL_ENTRIES_SQL,
                NO_ARGS);

        int entryID = cursor.getColumnIndex("_id");
        int entryDateCol = cursor.getColumnIndex("CreateDate");
        int speciesCol = cursor.getColumnIndex("Species");
        int sizeCol = cursor.getColumnIndex("SizeOrWeight");
        int latCol = cursor.getColumnIndex("Latitude");

        if (cursor.moveToFirst()) {
            do {
                LogEntry entry = new LogEntry();
                entry.setId(cursor.getString(entryID));
                entry.setEntryDate(cursor.getString(entryDateCol));
                entry.setSpecies(cursor.getString(speciesCol));
                entry.setSizeOrWeight(cursor.getString(sizeCol));
                entry.setLatitude(cursor.getDouble(latCol));

                if (entry.getSpecies() == null) {
                    entry.setSpecies("Not Entered");
                }

                if (entry.getSizeOrWeight() == null) {
                    entry.setSizeOrWeight("Not entered");
                }

                entries.add(entry);
            } while (cursor.moveToNext());
        }
        cursor.close();
        DB.close();
        return entries;
    }

    @Override
    public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
        DB = getWritableDatabase();
        DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(getWritableDatabase());
        DB.close();
    }
}


问:
Replace keys in an array based on another lookup/mapping array
I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.

I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?

答:
best way is using reference, and not using unset (which make another step to clean memory)

```<code>$tab = ['two' => [] ];
</code>```

solution:

```<code>$tab['newname'] = & $tab['two'];
</code>```

you have one original and one reference with new name.

or if you don't want have two names in one value is good make another tab and foreach on reference

```<code>foreach($tab as $key=> & $value) {
    if($key=='two') {
        $newtab["newname"] = & $tab[$key];
     } else {
        $newtab[$key] = & $tab[$key];
     }
}
</code>```

Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..

OwnerDisplayName: Thomas Owens

ContentLicense: CC BY-SA 4.0

Body:
best way is using reference, and not using unset (which make another step to clean memory)

$tab = ['two' => [] ];

solution:

$tab['newname'] = & $tab['two'];

you have one original and one reference with new name.

or if you don't want have two names in one value is good make another tab and foreach on reference

foreach($tab as $key=> & $value) {
    if($key=='two') {
        $newtab["newname"] = & $tab[$key];
     } else {
        $newtab[$key] = & $tab[$key];
     }
}

Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..


问:
JavaScript code is not compatible on edge
I have a small JavaScript code, it works on chrome but It's not being compatible on edge. what can i change to make it compatible?</p>

```<code>     var radioBtns = document.querySelectorAll('input[type=radio]')

    for (let i = 0; i < radioBtns.length; i++) {
        radioBtns[i].addEventListener('input', function () {
            document.querySelector('#estimate').innerHTML = `Total Due = $${this.value}`
        })
    }
</code>```

答:
Change input into click, then the code will work in Edge.

var radioBtns = document.querySelectorAll('input[type=radio]')

for (let i = 0; i < radioBtns.length; i++) {
    radioBtns[i].addEventListener('click', function () {
        document.querySelector('#estimate').innerHTML = `Total Due = $${this.value}`
    })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" name="quantity" value="100" /><text>100</text>
<input type="radio" name="quantity" value="200" /><text>200</text>
<div id='estimate'></div></code>```

Body:
I have a small JavaScript code, it works on chrome but It's not being compatible on edge. what can i change to make it compatible?

     var radioBtns = document.querySelectorAll('input[type=radio]')

    for (let i = 0; i < radioBtns.length; i++) {
        radioBtns[i].addEventListener('input', function () {
            document.querySelector('#estimate').innerHTML = `Total Due = $${this.value}`
        })
    }

Body:
Change input into click, then the code will work in Edge.

var radioBtns = document.querySelectorAll('input[type=radio]')

for (let i = 0; i < radioBtns.length; i++) {
    radioBtns[i].addEventListener('click', function () {
        document.querySelector('#estimate').innerHTML = `Total Due = $${this.value}`
    })
}

<input type="radio" name="quantity" value="100" /><text>100</text>
<input type="radio" name="quantity" value="200" /><text>200</text>
<div id='estimate'></div>


问:
Error using createStore with typescript and thunk
I am new to typescript and am trying to convert a react app to use typescript.
When using the createStore function from 'redux' in my index.tsx file, I am getting the following error.

```<code>  Type '{}' is missing the following properties from type '{ customersLoading: boolean; customersLoadError: boolean; customers: {}; editCustomerInProgress: boolean; editCustomerSuccess: boolean; editCustomerFail: boolean; addCustomerInProgress: boolean; ... 6 more ...; searchResults: {}; }': customersLoading, customersLoadError, customers, editCustomerInProgress, and 10 more.  TS2345
</code>```

It seems like the state is being defined as a type of {}, but I have defined an interface for the state object.

Index.js

```<code>import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';

import reducer from './store/reducer';

import * as serviceWorker from './serviceWorker';

const composeEnhancers = compose;

const rootReducer = reducer;

const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

const app = (
    <Provider store={store}>
        <App />
    </Provider>
);

ReactDOM.render(app, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();
</code>```

Reducer.tsx

```<code>import {stateShape, actionShape} from '../types/index';

const initialState = {
    customersLoading: false,
    customersLoadError: false,
    customers: {},
    editCustomerInProgress: false,
    editCustomerSuccess: false,
    editCustomerFail: false,
    addCustomerInProgress: false,
    addCustomerSuccess: false,
    addCustomerFail: false,
    deleteCustomerInProgress: false,
    deleteCustomerSuccess: false,
    deleteCustomerFail: false,
    searchMode: false,
    searchResults: {}
};

const updateObject = (oldObject: {}, updatedProperties: {}) => {
    return {
        ...oldObject,
        ...updatedProperties
    };
};

const editCustomer = (state: stateShape, action: actionShape) => {
    let updatedState = {
        editCustomerInProgress: false,
        editCustomerFail: false,
        editCustomerSuccess: true,
        customers: {
            ...state.customers,
            [action.payload.customerId]: action.payload.customerDetails
        },
        searchResults: {...state.searchResults}
    };

    if (state.searchMode){
        updatedState = {
            ...updatedState,
            searchResults: {
                ...state.searchResults,
                [action.payload.customerId]: action.payload.customerDetails
            }
        }
    };
    return updateObject(state, updatedState);
};

const addCustomer = (state: stateShape, action: actionShape) => {
    const updatedState = {
        addCustomerInProgress: false,
        addCustomerFail: false,
        addCustomerSuccess: true,
        customers: {
            ...state.customers,
            [action.payload.customerId]: action.payload.customerData
        }
    };
    return updateObject(state, updatedState);
};

const deleteCustomer = (state: stateShape, action: actionShape) => {
    const updatedState = {
        deleteCustomerInProgress: false,
        deleteCustomerFail: false,
        deleteCustomerSuccess: true,
        customers: {
            ...state.customers,
            [action.payload.customerId]: null
        }
    };
    return updateObject(state, updatedState);
};

const searchCustomers = (state: stateShape, action: actionShape) => {
    interface arrayInterface {
        [key: number]: any
    };

    //filter matching customers from list of customers by search term
    const matchingCustomers = Object.entries(state.customers).filter((current: arrayInterface) => {
        let firstname = current[1].firstName.toLowerCase();
        let lastname = current[1].lastName.toLowerCase();
        let searchTerm = action.payload.searchTerm.toLowerCase();
        return firstname === searchTerm || lastname === searchTerm;
    });

    let matchingCustomersObject;

    matchingCustomers.forEach((current: arrayInterface) => {
        matchingCustomersObject[current[0]] = current[1];
    });

    const updatedState = {
        searchMode: true,
        searchResults: matchingCustomersObject
    };

    return updateObject(state, updatedState);
};

let reducer = (state = initialState, action: actionShape) => {
    switch (action.type){
        case actionTypes.LOAD_CUSTOMERS_START:
            return updateObject(state, {customersLoading: true});
        case actionTypes.LOAD_CUSTOMERS_FAIL:
            return updateObject(state, {customersLoading: false, customersLoadError: true});
        case actionTypes.LOAD_CUSTOMERS_SUCCESS:
            return updateObject(state, {customersLoading: false, customers: action.payload.customers});
        case actionTypes.EDIT_CUSTOMER_START:
            return updateObject(state, {editCustomerInProgress: true, editCustomerSuccess: false});
        case actionTypes.EDIT_CUSTOMER_FAIL:
            return updateObject(state, {editCustomerInProgress: false, editCustomerFail: true});
        case actionTypes.EDIT_CUSTOMER_SUCCESS:
            return editCustomer(state, action)
        case actionTypes.ADD_CUSTOMER_START:
            return updateObject(state, {addCustomerInProgress: true});
        case actionTypes.ADD_CUSTOMER_FAIL:
            return updateObject(state, {addCustomerInProgress: false, addCustomerFail: true});
        case actionTypes.ADD_CUSTOMER_SUCCESS:
            return addCustomer(state, action);
        case actionTypes.DELETE_CUSTOMER_START:
            return updateObject(state, {deleteCustomerInProgress: true});
        case actionTypes.DELETE_CUSTOMER_FAIL:
            return updateObject(state, {deleteCustomerInProgress: false, deleteCustomerFail: true});
        case actionTypes.DELETE_CUSTOMER_SUCCESS:
            return deleteCustomer(state, action);
        case actionTypes.SEARCH_CUSTOMER_START:
            return searchCustomers(state, action)
        case actionTypes.SEARCH_CUSTOMER_END:
            return updateObject(state, {searchMode: false, searchResults: []})
        default:
            return state;
    }
};

export default reducer;
</code>```

Action and state shapes imported by reducer.tsx

```<code>    customersLoading: boolean,
    customersLoadError: boolean,
    customers: {},
    editCustomerInProgress: boolean,
    editCustomerSuccess: boolean,
    editCustomerFail: boolean,
    addCustomerInProgress: boolean,
    addCustomerSuccess: boolean,
    addCustomerFail: boolean,
    deleteCustomerInProgress: boolean,
    deleteCustomerSuccess: boolean,
    deleteCustomerFail: boolean,
    searchMode: boolean,
    searchResults: {}
};

export interface actionShape {
    type: string,
    payload: {
        customerId: string,
        customerData: Object,
        customerDetails: Object,
        customers: Object,
        searchTerm: string
    }
};
</code>```

Is anyone able to point me in the right direction to fix this problem?

答:
Problem arises from reducer signature incompatibility. Lets look at how createStore is defined.

```<code>export interface StoreCreator {
    <S, A extends Action, Ext, StateExt>(
        reducer: Reducer<S, A>,
        enhancer?: StoreEnhancer<Ext, StateExt>
    ): Store<S & StateExt, A> & Ext
    <S, A extends Action, Ext, StateExt>(
       reducer: Reducer<S, A>,
       preloadedState?: DeepPartial<S>,
       enhancer?: StoreEnhancer<Ext>
    ): Store<S & StateExt, A> & Ext
}
</code>```

Essentillly it is overloaded function and we are interested in type of the first argument, reducer.

```<code>export type Reducer<S = any, A extends Action = AnyAction> = (
    state: S | undefined,
    action: A
) => S
</code>```

Reducer takes two arguments of type S (for state) and of type A (for action) and returns value of type S.

But your reducer defined as follows

```<code>let reducer = (state = initialState, action: actionShape) => { /*...*/ }
</code>```

For all actions it returns updateObject(state, { /*...*/ }) which in turn defined as

```<code>const updateObject = (oldObject: {}, updatedProperties: {}) =>
{
    return {
        ...oldObject,
        ...updatedProperties
    }
}
</code>```

As a result TS infer return type of updateObject to be {} and it is incompatioble with S which is stateShape in your case.

To solve this issue I suggest to use following signature for updateObject

```<code>const updateObject = (oldObject: stateShape, updatedProperties: Partial<stateShape>): stateShape => {/*...*/}
</code>```

So it takes first argument of type stateShape and second - as Partial<stateShape>. This allows you to pass second argument with only some properties of original stateShape, but prohibits adding non existant properties to state.

It also good idea to update signature of reducer function to make it return only stateShape

```<code>let reducer = (state = initialState, action: actionShape): stateShape
</code>```

Body:
I am new to typescript and am trying to convert a react app to use typescript.
When using the createStore function from 'redux' in my index.tsx file, I am getting the following error.

  Type '{}' is missing the following properties from type '{ customersLoading: boolean; customersLoadError: boolean; customers: {}; editCustomerInProgress: boolean; editCustomerSuccess: boolean; editCustomerFail: boolean; addCustomerInProgress: boolean; ... 6 more ...; searchResults: {}; }': customersLoading, customersLoadError, customers, editCustomerInProgress, and 10 more.  TS2345

It seems like the state is being defined as a type of {}, but I have defined an interface for the state object.

Index.js

import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';

import reducer from './store/reducer';

import * as serviceWorker from './serviceWorker';

const composeEnhancers = compose;

const rootReducer = reducer;

const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

const app = (
    <Provider store={store}>
        <App />
    </Provider>
);

ReactDOM.render(app, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();

Reducer.tsx

import {stateShape, actionShape} from '../types/index';

const initialState = {
    customersLoading: false,
    customersLoadError: false,
    customers: {},
    editCustomerInProgress: false,
    editCustomerSuccess: false,
    editCustomerFail: false,
    addCustomerInProgress: false,
    addCustomerSuccess: false,
    addCustomerFail: false,
    deleteCustomerInProgress: false,
    deleteCustomerSuccess: false,
    deleteCustomerFail: false,
    searchMode: false,
    searchResults: {}
};

const updateObject = (oldObject: {}, updatedProperties: {}) => {
    return {
        ...oldObject,
        ...updatedProperties
    };
};

const editCustomer = (state: stateShape, action: actionShape) => {
    let updatedState = {
        editCustomerInProgress: false,
        editCustomerFail: false,
        editCustomerSuccess: true,
        customers: {
            ...state.customers,
            [action.payload.customerId]: action.payload.customerDetails
        },
        searchResults: {...state.searchResults}
    };

    if (state.searchMode){
        updatedState = {
            ...updatedState,
            searchResults: {
                ...state.searchResults,
                [action.payload.customerId]: action.payload.customerDetails
            }
        }
    };
    return updateObject(state, updatedState);
};

const addCustomer = (state: stateShape, action: actionShape) => {
    const updatedState = {
        addCustomerInProgress: false,
        addCustomerFail: false,
        addCustomerSuccess: true,
        customers: {
            ...state.customers,
            [action.payload.customerId]: action.payload.customerData
        }
    };
    return updateObject(state, updatedState);
};

const deleteCustomer = (state: stateShape, action: actionShape) => {
    const updatedState = {
        deleteCustomerInProgress: false,
        deleteCustomerFail: false,
        deleteCustomerSuccess: true,
        customers: {
            ...state.customers,
            [action.payload.customerId]: null
        }
    };
    return updateObject(state, updatedState);
};

const searchCustomers = (state: stateShape, action: actionShape) => {
    interface arrayInterface {
        [key: number]: any
    };

    //filter matching customers from list of customers by search term
    const matchingCustomers = Object.entries(state.customers).filter((current: arrayInterface) => {
        let firstname = current[1].firstName.toLowerCase();
        let lastname = current[1].lastName.toLowerCase();
        let searchTerm = action.payload.searchTerm.toLowerCase();
        return firstname === searchTerm || lastname === searchTerm;
    });

    let matchingCustomersObject;

    matchingCustomers.forEach((current: arrayInterface) => {
        matchingCustomersObject[current[0]] = current[1];
    });

    const updatedState = {
        searchMode: true,
        searchResults: matchingCustomersObject
    };

    return updateObject(state, updatedState);
};

let reducer = (state = initialState, action: actionShape) => {
    switch (action.type){
        case actionTypes.LOAD_CUSTOMERS_START:
            return updateObject(state, {customersLoading: true});
        case actionTypes.LOAD_CUSTOMERS_FAIL:
            return updateObject(state, {customersLoading: false, customersLoadError: true});
        case actionTypes.LOAD_CUSTOMERS_SUCCESS:
            return updateObject(state, {customersLoading: false, customers: action.payload.customers});
        case actionTypes.EDIT_CUSTOMER_START:
            return updateObject(state, {editCustomerInProgress: true, editCustomerSuccess: false});
        case actionTypes.EDIT_CUSTOMER_FAIL:
            return updateObject(state, {editCustomerInProgress: false, editCustomerFail: true});
        case actionTypes.EDIT_CUSTOMER_SUCCESS:
            return editCustomer(state, action)
        case actionTypes.ADD_CUSTOMER_START:
            return updateObject(state, {addCustomerInProgress: true});
        case actionTypes.ADD_CUSTOMER_FAIL:
            return updateObject(state, {addCustomerInProgress: false, addCustomerFail: true});
        case actionTypes.ADD_CUSTOMER_SUCCESS:
            return addCustomer(state, action);
        case actionTypes.DELETE_CUSTOMER_START:
            return updateObject(state, {deleteCustomerInProgress: true});
        case actionTypes.DELETE_CUSTOMER_FAIL:
            return updateObject(state, {deleteCustomerInProgress: false, deleteCustomerFail: true});
        case actionTypes.DELETE_CUSTOMER_SUCCESS:
            return deleteCustomer(state, action);
        case actionTypes.SEARCH_CUSTOMER_START:
            return searchCustomers(state, action)
        case actionTypes.SEARCH_CUSTOMER_END:
            return updateObject(state, {searchMode: false, searchResults: []})
        default:
            return state;
    }
};

export default reducer;

Action and state shapes imported by reducer.tsx

    customersLoading: boolean,
    customersLoadError: boolean,
    customers: {},
    editCustomerInProgress: boolean,
    editCustomerSuccess: boolean,
    editCustomerFail: boolean,
    addCustomerInProgress: boolean,
    addCustomerSuccess: boolean,
    addCustomerFail: boolean,
    deleteCustomerInProgress: boolean,
    deleteCustomerSuccess: boolean,
    deleteCustomerFail: boolean,
    searchMode: boolean,
    searchResults: {}
};

export interface actionShape {
    type: string,
    payload: {
        customerId: string,
        customerData: Object,
        customerDetails: Object,
        customers: Object,
        searchTerm: string
    }
};

Is anyone able to point me in the right direction to fix this problem?

Body:
Problem arises from reducer signature incompatibility. Lets look at how createStore is defined.

export interface StoreCreator {
    <S, A extends Action, Ext, StateExt>(
        reducer: Reducer<S, A>,
        enhancer?: StoreEnhancer<Ext, StateExt>
    ): Store<S & StateExt, A> & Ext
    <S, A extends Action, Ext, StateExt>(
       reducer: Reducer<S, A>,
       preloadedState?: DeepPartial<S>,
       enhancer?: StoreEnhancer<Ext>
    ): Store<S & StateExt, A> & Ext
}

Essentillly it is overloaded function and we are interested in type of the first argument, reducer.

export type Reducer<S = any, A extends Action = AnyAction> = (
    state: S | undefined,
    action: A
) => S

Reducer takes two arguments of type S (for state) and of type A (for action) and returns value of type S.

But your reducer defined as follows

let reducer = (state = initialState, action: actionShape) => { /*...*/ }

For all actions it returns updateObject(state, { /*...*/ }) which in turn defined as

const updateObject = (oldObject: {}, updatedProperties: {}) =>
{
    return {
        ...oldObject,
        ...updatedProperties
    }
}

As a result TS infer return type of updateObject to be {} and it is incompatioble with S which is stateShape in your case.

To solve this issue I suggest to use following signature for updateObject

const updateObject = (oldObject: stateShape, updatedProperties: Partial<stateShape>): stateShape => {/*...*/}

So it takes first argument of type stateShape and second - as Partial<stateShape>. This allows you to pass second argument with only some properties of original stateShape, but prohibits adding non existant properties to state.

It also good idea to update signature of reducer function to make it return only stateShape

let reducer = (state = initialState, action: actionShape): stateShape


问:
How to make where condition always be true with field =?
I have a sql statement follow:

select * from table where id = ?

Now, problem is, l don't know whether front end will send me the value of id, if it did, this sql seem like id = 1, and if not, sql should be like id = true(fake code) to find all data

How could I write my sql?

Or, It is fundamentally wrong?

答:
You can try doing this to get your right sql statement in PHP</p>

```<code> function GetSqlStatement($id){
       return $sql = "select * from table where id = ".$id.";";
 }
</code>```

Body:
You can try doing this to get your right sql statement in PHP

 function GetSqlStatement($id){
       return $sql = "select * from table where id = ".$id.";";
 }


问:
iPhone AVAudioPlayer release EXC_BAD_ACCESS
I play sound making this:

```<code>NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
</code>```

In this buffer i have sound with aac format.
Everything is ok, until I want to release it, and sometimes not always i get EXC_BAD_ACCESS

I release it in this way:

```<code>[player release];
free (buffer);
</code>```

I think that player stil wants to do something with this data, but this data not longer exist after I make free (buffer);

But I don't know when make this free (buffer). If i remove this line everything is ok.
But when i remove this free (buffer) i will have memory leaks:(

Best regards
Chudziutki

答:
(When putting code in a question, put 4 spaces in front of the line of code to format it as code.  Inline code needs to be surrounding by little quote marks like this.)

If you have a crash, there will be a backtrace.

From the symptoms, you are apparently freeing the buffer before the AVAudioPlayer is done with it.   You need to make sure that the audio player is entirely done with the buffer before you free the memory.

Likely, the most effective solution is something like:

```<code>buffer = malloc(...);
.... fill buffer ....
NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:YES];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
... let player play ...
</code>```

Then, when you want the buffer to be deallocated, you stop and release the player:

```<code>[player stop];
[player release];
player = nil; // not necessary, but prevents a dangling pointer if player is an ivar and this isn't -dealloc
</code>```

That is, let the audio player take ownership of the memory and the responsibility for free()ing it when done.

Body:
I play sound making this:

NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];

In this buffer i have sound with aac format.
Everything is ok, until I want to release it, and sometimes not always i get EXC_BAD_ACCESS

I release it in this way:

[player release];
free (buffer);

I think that player stil wants to do something with this data, but this data not longer exist after I make free (buffer);

But I don't know when make this free (buffer). If i remove this line everything is ok.
But when i remove this free (buffer) i will have memory leaks:(

Best regards
Chudziutki

Body:
(When putting code in a question, put 4 spaces in front of the line of code to format it as code.  Inline code needs to be surrounding by little quote marks like this.)

If you have a crash, there will be a backtrace.

From the symptoms, you are apparently freeing the buffer before the AVAudioPlayer is done with it.   You need to make sure that the audio player is entirely done with the buffer before you free the memory.

Likely, the most effective solution is something like:

buffer = malloc(...);
.... fill buffer ....
NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:YES];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
... let player play ...

Then, when you want the buffer to be deallocated, you stop and release the player:

[player stop];
[player release];
player = nil; // not necessary, but prevents a dangling pointer if player is an ivar and this isn't -dealloc

That is, let the audio player take ownership of the memory and the responsibility for free()ing it when done.


问:
laravel updating editing database record - getting error when submitting the form
I am using this code to edit database record :

```<code>public function service_edit($id)
{
    $service = Service::find($id);
    return view('Super_Admin/service/.service_edit')->with('service', $service);
}

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $input['title_name'] = strtoupper ($request['title_name']);
    $input['link'] = strtoupper ($request['link']);
    $input['note'] = strtoupper ($request['note']);
    $input['image'] = time().'.'.$request->

    image->getClientOriginalExtension();
    $folder1 = public_path('WEBSITE-FILE/SERVICE/1');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']);
    $path2 = public_path('WEBSITE-FILE/SERVICE/2').$input['image'];// path 2
    $path3 = public_path('WEBSITE-FILE/SERVICE/3'). $input['image']; // path 3
    $path4 = public_path('WEBSITE-FILE/SERVICE/4'). $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}
</code>```

I am facing this error when I submit the form

"Call to a member function save() on array"

答:
You initialize $input as an array, then you call $input->save(),  that's why the error is raised.

Maybe you wanted to use $service in place of $input ?

Body:
I am using this code to edit database record :

public function service_edit($id)
{
    $service = Service::find($id);
    return view('Super_Admin/service/.service_edit')->with('service', $service);
}

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $input['title_name'] = strtoupper ($request['title_name']);
    $input['link'] = strtoupper ($request['link']);
    $input['note'] = strtoupper ($request['note']);
    $input['image'] = time().'.'.$request->

    image->getClientOriginalExtension();
    $folder1 = public_path('WEBSITE-FILE/SERVICE/1');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']);
    $path2 = public_path('WEBSITE-FILE/SERVICE/2').$input['image'];// path 2
    $path3 = public_path('WEBSITE-FILE/SERVICE/3'). $input['image']; // path 3
    $path4 = public_path('WEBSITE-FILE/SERVICE/4'). $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}

I am facing this error when I submit the form

"Call to a member function save() on array"


问:
HTML5 Types in ASP.NET
Site will exclusively be used on mobile devices. So for fields requiring only numeric input, I want to bring up the numeric keypad. I can successfully do this by using an html input element with the type set to tel. I want to add an asp:RequiredFieldValidator to this field and based on MSDN.

I need to set the input to runat="server". When I do this, I get this error;

tel is not a valid type for an input tag.

If I remove the runat="server", I get

Unable to find control id Contract referenced by the ControlToValidate property of ''

Here is my code:

<input type="tel" runat="server" id="Contract"></input>
<asp:RequiredFieldValidator runat="server" ControlToValidate="Contract"
                            ValidationGroup="IfOnRent" Text="*"
                            ErrorMessage="Contract Required">
</asp:RequiredFieldValidator>
```

Am I just out of luck and have to code my own validations?

答:
If you are using C#

```<code>Contract.Attributes["type"]="tel"
</code>```

Writing inline types for html inputs may produce parse error in .net.  So add the above line of code in your PageLoad()

Title: HTML5 Types in ASP.NET

Body:
Site will exclusively be used on mobile devices. So for fields requiring only numeric input, I want to bring up the numeric keypad. I can successfully do this by using an html input element with the type set to tel. I want to add an asp:RequiredFieldValidator to this field and based on MSDN.

I need to set the input to runat="server". When I do this, I get this error;

tel is not a valid type for an input tag.

If I remove the runat="server", I get

Unable to find control id Contract referenced by the ControlToValidate property of ''

Here is my code:

<input type="tel" runat="server" id="Contract"></input>
<asp:RequiredFieldValidator runat="server" ControlToValidate="Contract"
                            ValidationGroup="IfOnRent" Text="*"
                            ErrorMessage="Contract Required">
</asp:RequiredFieldValidator>

Am I just out of luck and have to code my own validations?

Body:
If you are using C#

Contract.Attributes["type"]="tel"

Writing inline types for html inputs may produce parse error in .net.  So add the above line of code in your PageLoad()


问:
How to raycasting hidden object or not add to scene in Threejs
I created 1000 hidden objects with BoxGeometry geometry using THREE.JS. I set object.visible = false to hide each object, however this causes the raycasting/interaction to not work.

I expect that hiding the objects will give me a performance boost.

I can hide the box objects by setting material.visible = false on each object, however the performance of my app is still terrible.

How can I achieve the required raycasting interaction with hidden objects in the performance friendly way?

答:
One way to achieve what you require would be to not add your Box objects to your scene which would ensure that they are not rendered, and pass those directly to a THREE.Raycaster to determine if intersection between any of those boxes has occurred.

You could for instance crate a THREE.Raycaster object from your ray primitive, and then pass an array of your Box objects to the .intersectObjects() method to determine ray intersection.

In code, that would look something like this:

```<code>// ray is your intersection primitive
const raycaster = new THREE.Raycaster(ray.origin, ray.direction);

// boxObjects is an array of THREE.Object3D's representing your 1000 boxes
const intersectionResult = raycaster.intersectObjects(boxObjects)
</code>```

Body:
One way to achieve what you require would be to not add your Box objects to your scene which would ensure that they are not rendered, and pass those directly to a THREE.Raycaster to determine if intersection between any of those boxes has occurred.

You could for instance crate a THREE.Raycaster object from your ray primitive, and then pass an array of your Box objects to the .intersectObjects() method to determine ray intersection.

In code, that would look something like this:

// ray is your intersection primitive
const raycaster = new THREE.Raycaster(ray.origin, ray.direction);

// boxObjects is an array of THREE.Object3D's representing your 1000 boxes
const intersectionResult = raycaster.intersectObjects(boxObjects)


问:
Populate PHP associative array using loop with mysql data
I'm creating simple PHP for output data to apexcharts javascript charts. To make apexcharts usable output I need to provide x and y value of the graphs as JSON. below code, I wrote to output the expected JSON.

```<code>$data_arr = array();

    global $mysqli_conn;
    $result = $mysqli_conn->query("sql");
    $sql_out = array();
    $sql_out = $result->fetch_all(MYSQLI_ASSOC);
    $num_rows = mysqli_num_rows($result);

        if ($num_rows < 1){
            echo "zero";
        }else{
            foreach($sql_out as $item) {
                $data_arr['x'][] = $item['time'];
                $data_arr['y'][] = $item['status_code'];
            }
        }

$test_arr = array(
    array(
        "name"=>"lock",
        "data"=>array($data_arr),
    )
);

echo json_encode($test_arr);
</code>```

my expected json output is like below

```<code>[
    {
        "name": "lock",
        "data": [
                    {
                        "x": "2019-05-30 07:53:07",
                        "y": "1470"
                    },
                    {
                        "x": "2019-05-29 07:52:27",
                        "y": "1932"
                    }
                ]
    }
]
</code>```

But when I request data from my code what I'm getting something like this

```<code>[
    {
        "name": "lock",
        "data": [
            {
                "x": [
                    "2019-05-30 07:53:07",
                    "2019-05-29 07:52:27",
                    "2019-05-26 15:46:56",
                    "2019-05-25 07:39:24"
                ],
                "y": [
                    "1470",
                    "1932",
                    "1940",
                    "1470"
                ]
            }
        ]
    }
]
</code>```

How can I create my expected JSON result from PHP code?.

答:
You're creating them on a seprate space. When you declare and push them, put them on one container:

```<code>foreach ($sql_out as $item) {
    $data_arr[] = array(
        'x' => $item['time'],
        'y' => $item['status_code']
    );
}
</code>```

When you do this:

```<code>$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];
</code>```

They are on a separate containers, x and y containers, therefore you get the wrong format, like the one you showed.

When you declare them as:

```<code>$data_arr[] = array(
    'x' => $item['time'],
    'y' => $item['status_code']
);
</code>```

You're basically tellin to push the whole sub batches but together.

Body:
I'm creating simple PHP for output data to apexcharts javascript charts. To make apexcharts usable output I need to provide x and y value of the graphs as JSON. below code, I wrote to output the expected JSON.

$data_arr = array();

    global $mysqli_conn;
    $result = $mysqli_conn->query("sql");
    $sql_out = array();
    $sql_out = $result->fetch_all(MYSQLI_ASSOC);
    $num_rows = mysqli_num_rows($result);

        if ($num_rows < 1){
            echo "zero";
        }else{
            foreach($sql_out as $item) {
                $data_arr['x'][] = $item['time'];
                $data_arr['y'][] = $item['status_code'];
            }
        }

$test_arr = array(
    array(
        "name"=>"lock",
        "data"=>array($data_arr),
    )
);

echo json_encode($test_arr);

my expected json output is like below

[
    {
        "name": "lock",
        "data": [
                    {
                        "x": "2019-05-30 07:53:07",
                        "y": "1470"
                    },
                    {
                        "x": "2019-05-29 07:52:27",
                        "y": "1932"
                    }
                ]
    }
]

But when I request data from my code what I'm getting something like this

[
    {
        "name": "lock",
        "data": [
            {
                "x": [
                    "2019-05-30 07:53:07",
                    "2019-05-29 07:52:27",
                    "2019-05-26 15:46:56",
                    "2019-05-25 07:39:24"
                ],
                "y": [
                    "1470",
                    "1932",
                    "1940",
                    "1470"
                ]
            }
        ]
    }
]

How can I create my expected JSON result from PHP code?.

Body:
You're creating them on a seprate space. When you declare and push them, put them on one container:

foreach ($sql_out as $item) {
    $data_arr[] = array(
        'x' => $item['time'],
        'y' => $item['status_code']
    );
}

When you do this:

$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];

They are on a separate containers, x and y containers, therefore you get the wrong format, like the one you showed.

When you declare them as:

$data_arr[] = array(
    'x' => $item['time'],
    'y' => $item['status_code']
);

You're basically tellin to push the whole sub batches but together.


问:
How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?
For some reason, when I initially did a pull from the repository for a git project of mine,
I got a ton of files in my working copy that have no discernible changes made to them, but keep showing up in my unstaged changes area.

I'm using Git Gui on Windows xp, and when I go to look at the file to see what has changed.
All I see is:

```<code>old mode 100755
new mode 100644
</code>```

Does anyone know what this means?

How can I get these files out of my list of unstaged changes? (Very annoying to have to go through 100's of files, just to pick out files I've recently edited and want to commit).

答:
This usually happens when the repo is cloned between Windows and Linux/Unix machines.

Just tell git to ignore filemode change. Here are several ways to do so:

Config ONLY for current repo:

```<code> git config core.filemode false
</code>```

Config globally:

```<code> git config --global core.filemode false
</code>```

Add in ~/.gitconfig:

```<code> [core]
      filemode = false
</code>```

Just select one of them.

Body:
For some reason, when I initially did a pull from the repository for a git project of mine,
I got a ton of files in my working copy that have no discernible changes made to them, but keep showing up in my unstaged changes area.

I'm using Git Gui on Windows xp, and when I go to look at the file to see what has changed.
All I see is:

old mode 100755
new mode 100644

Does anyone know what this means?

How can I get these files out of my list of unstaged changes? (Very annoying to have to go through 100's of files, just to pick out files I've recently edited and want to commit).

Body:
This usually happens when the repo is cloned between Windows and Linux/Unix machines.

Just tell git to ignore filemode change. Here are several ways to do so:

Config ONLY for current repo:

 git config core.filemode false

Config globally:

 git config --global core.filemode false

Add in ~/.gitconfig:

 [core]
      filemode = false

Just select one of them.


问:
virtual function with user-defined-type vector
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

```<code>class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};
</code>```

but when I write the derived class:

```<code>#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};
</code>```

I get this error:

```<code>invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’
</code>```

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?

答:
The duplicate private structure is a bit odd in your example.  The below compiles fine, for instance:

class TestFather {

```<code>protected:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

class TestSon : public TestFather{

public:
    vector<myStruct> get_myStructVect();
};

int main(int argc, char**argv)
{
   TestSon testSon;
}
</code>```

Note the replacement of private with protected, allowing derived classes access to the parent structure definition and myStructVect storage.

Body:
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

but when I write the derived class:

#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};

I get this error:

invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?

Body:
The duplicate private structure is a bit odd in your example.  The below compiles fine, for instance:

class TestFather {

protected:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

class TestSon : public TestFather{

public:
    vector<myStruct> get_myStructVect();
};

int main(int argc, char**argv)
{
   TestSon testSon;
}

Note the replacement of private with protected, allowing derived classes access to the parent structure definition and myStructVect storage.


问:
If a page has not been requested, the page will be refreshed or the route will be redirected. How to solve it?
In the front-end development, when the background data has not returned to the foreground, the page is refreshed and the latter route jumps. How should this problem be solved?</p>

答:
This is the case when you are calling a backend API from frontend, and you don't know when you will recieve the response.In that case you show the user spinner before redirecting to the next page which depends on the API response.

You should conditionally render the component which requires the data from your api as props.
Once you receive the data from the API you can update the state of hasReceivedData  to true.

```<code>hasReceivedData ? <Component> : '<Spinner>'
</code>```

Body:
This is the case when you are calling a backend API from frontend, and you don't know when you will recieve the response.In that case you show the user spinner before redirecting to the next page which depends on the API response.

You should conditionally render the component which requires the data from your api as props.
Once you receive the data from the API you can update the state of hasReceivedData  to true.

hasReceivedData ? <Component> : '<Spinner>'


问:
how to center horizonally everything in forms
so in my render function, I have

```<code> render() {
     <div>
        <form id="one">
          <TextField id="t1" ... />
          <Button id="b1" />
        </form>

        <div id="empty"><div/>

        <form id="two">
          <TextField id="t2" ... />
          <TextField id="t3" ... />
          <Button id="b2" />
        </form>

     </div>
  }
</code>```

and i'm trying to center everything horizontally. the 'empty' div in between the forms are to create space between the forms.

How can I do this?

Thanks !

答: Try Grid system from react bootstrap, With help of Row and Col you will have better control over displaying your controls horizontally and vertically. This is the link for more info. https://react-bootstrap.netlify.com/layout/grid/#grid</p>

Body:
so in my render function, I have

 render() {

        <form id="one">
          <TextField id="t1" ... />
          <Button id="b1" />
        </form>

        <form id="two">
          <TextField id="t2" ... />
          <TextField id="t3" ... />
          <Button id="b2" />
        </form>

  }

and i'm trying to center everything horizontally. the 'empty' div in between the forms are to create space between the forms.

How can I do this?

Thanks !


问:
Using pcre2 in a c++ project
I am looking at using pcre2 in my simple c++ app, (I am using vs2015).
(I am looking at various regex libraries and the general feeling is that pcre/pcre2 are the most flexible)

First I downloaded pcre2 from the official location, (http://sourceforge.net/projects/pcre/files/pcre2/10.20/) and created a very simple example.

```<code>#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
...
PCRE2_SPTR subject = (PCRE2_SPTR)std::string("this is it").c_str();
PCRE2_SPTR pattern = (PCRE2_SPTR)std::string("([a-z]+)|\\s").c_str();

...
int errorcode;
PCRE2_SIZE erroroffset;
pcre2_code *re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED,
                                PCRE2_ANCHORED | PCRE2_UTF, &errorcode,
                                &erroroffset, NULL);
...
</code>```

First of all the file "pcre2.h" does not exist, so I renamed pcre2.h.generic to pcre2.h

But then I get linker errors with unresolved externals.

I am guessing I need to include one or more files from the source to project.
But I am reluctant to just randomly add files without knowing what it all does.

Can someone give some simple steps to follow to successfully build a project using pcre2?

UPDATE

This is not an import library issue, pcre2.h does not come with a librar, (not one that I can see in their release location).

答:
You can follow these steps:

Download and install cmake.

Set the source folder location and a VS project folder.

Hit configure and select your VS version.

Once the configure process is done you can select 8, 16, and / or 32 bit from the list.

Press generate, then open the VS solution file in the project folder. This will open the solution in VS.

There are about 6 projects. Highlight the pcre2._ project. Go to preferences and make sure the output file is for a DLL.  Repeat this step for the pcre2posix project. And then set the greptest to be built as an exe (executable) and the other one as executable.

At this point you can try to builld all, but you might need to build the DLLs first because the executables rely on them (or rather their static libraries) for linking.

After all 6 projects are built successfully you should have shared /static libraries and test programs in your debug or release folders.

Title: Using pcre2 in a c++ project

Body:
I am looking at using pcre2 in my simple c++ app, (I am using vs2015).
(I am looking at various regex libraries and the general feeling is that pcre/pcre2 are the most flexible)

First I downloaded pcre2 from the official location, (http://sourceforge.net/projects/pcre/files/pcre2/10.20/) and created a very simple example.

#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
...
PCRE2_SPTR subject = (PCRE2_SPTR)std::string("this is it").c_str();
PCRE2_SPTR pattern = (PCRE2_SPTR)std::string("([a-z]+)|\\s").c_str();

...
int errorcode;
PCRE2_SIZE erroroffset;
pcre2_code *re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED,
                                PCRE2_ANCHORED | PCRE2_UTF, &errorcode,
                                &erroroffset, NULL);
...

First of all the file "pcre2.h" does not exist, so I renamed pcre2.h.generic to pcre2.h

But then I get linker errors with unresolved externals.

I am guessing I need to include one or more files from the source to project.
But I am reluctant to just randomly add files without knowing what it all does.

Can someone give some simple steps to follow to successfully build a project using pcre2?

UPDATE

This is not an import library issue, pcre2.h does not come with a librar, (not one that I can see in their release location).


问:
Counting number of sequences of particular value for multiple columns in a data frame
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

```<code>x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))
</code>```

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

```<code>     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3
</code>```

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

答:
Here is another idea. We can combine and collapse all string, split the string that is not a, and count how many elements containing a. result2 is the final outcome.

```<code>result <- sapply(x, function(x) {
  x2 <- as.character(x)
  y <- paste0(x2, collapse = "")
  z <- strsplit(y, "[^a]")[[1]]
  return(sum(grepl("a", z)))
})

result2 <- data.frame(Color = names(result), a_sequence = unname(result))
result2
#   Color a_sequence
# 1   Red          2
# 2  Blue          1
# 3 Green          3
</code>```

Body:
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

Body:
Here is another idea. We can combine and collapse all string, split the string that is not a, and count how many elements containing a. result2 is the final outcome.

result <- sapply(x, function(x) {
  x2 <- as.character(x)
  y <- paste0(x2, collapse = "")
  z <- strsplit(y, "[^a]")[[1]]
  return(sum(grepl("a", z)))
})

result2 <- data.frame(Color = names(result), a_sequence = unname(result))
result2
#   Color a_sequence
# 1   Red          2
# 2  Blue          1
# 3 Green          3