问:
node tcp server stick data together
I am using net module in nodejs.

```<code>net.createServer(function(sock) {
sock.on('data', function(data) {
    console.log(data);
});
});
</code>```

then I tried to use 2000 tcp clients to send data to the server to test how many clients it can support. For the first 20 minutes, it was running ok. But after a period of time, the data stuck together. For example, the data from the client is in json format and look like this:

'{"value":1,"name":"tom"}'

Each client sent the data with different name and value would be incremented each time. From the server side, the data I got look like this:

{"value":1,"name":"tom"}{"value":2,"name":"tom"}{"value":3,"name":"tom"}.

They stick together, I have to split them up and save them into mongodb.

The situation was getting worse when keep the server running longer. the server can't receive any data while the clients were still sending the data.

I'd like to ask how to make the server read one item each time and the server will work well when keep running. Thanks a lot.

答:
node.js stick package

You try this lib,The solution of sticky package problem of TCP for Node.Js

Title: node tcp server stick data together

Body:
I am using net module in nodejs.

net.createServer(function(sock) {
sock.on('data', function(data) {
    console.log(data);
});
});

then I tried to use 2000 tcp clients to send data to the server to test how many clients it can support. For the first 20 minutes, it was running ok. But after a period of time, the data stuck together. For example, the data from the client is in json format and look like this:

'{"value":1,"name":"tom"}'

Each client sent the data with different name and value would be incremented each time. From the server side, the data I got look like this:

{"value":1,"name":"tom"}{"value":2,"name":"tom"}{"value":3,"name":"tom"}.

They stick together, I have to split them up and save them into mongodb.

The situation was getting worse when keep the server running longer. the server can't receive any data while the clients were still sending the data.

I'd like to ask how to make the server read one item each time and the server will work well when keep running. Thanks a lot.


来源: stackexchange

问:
When to delete branches in Git?
Suppose we have an application that's stable.

Tomorrow, someone reports a big ol' bug that we decide to hotfix right away. So we create a branch for that hotfix off of "master", we name it "2011_Hotfix", and we push it up so that all of the developers can collaborate on fixing it.

We fix the bug, and merge "2011_Hotfix" into "master" as well as into the current development branch. And push "master."

What do we do with "2011_Hotfix" now? Should it just sit out there as a branch forever until the end of time or should we now delete it, since it has served its purpose? It seems unclean to just leave branches lying around everywhere, as the list of branches will likely become very long, most of which aren't even necessary anymore.

In the event that it should be deleted, what will happen to its history? Will that be maintained, even though the actual branch is no longer available? Also, how would I remove a remote branch?

答:
You can delete branches in all major web UIs such as github, BitBucket. After deleting the branch online, you can delete the local branch using</p>

```<code>git remote prune origin
</code>```

ContentLicense: CC BY-SA 3.0

Title: When to delete branches in Git?

Body:
You can delete branches in all major web UIs such as github, BitBucket. After deleting the branch online, you can delete the local branch using

git remote prune origin


问:
How to add an existing folder with files to SVN?
How do you add a folder without version control to a specific SVN location?  I often start writing code and only after I have a few folders containing code files do I add it to SVN.

What I usually do is:

svn co the parent directory where I want to make a new folder to store my code.

svn mkdir to make the directory I want to put my code in.

Copy and paste my code over.

svn commit.

Delete my current working code directory.

Re-create my working code directory using svn co.

答:
In Windows 7 I did this:

Have you installed SVN and Tortoise SVN? If not, Google them and do so now.

Go to your SVN folder where you may have other repos (short for repository) (or if you're creating one from scratch, choose a location C drive, D drive, etc or network path).

Create a new folder to store your new repository. Call it the same name as your project title

Right click the folder and choose Tortoise SVN -> Create Repository here

Say yes to Create Folder Structure

Click OK. You should see a new icon looking like a "wave" next to your new folder/repo

Right Click the new repo and choose SVN Repo Browser

Right click 'trunk'

Choose ADD Folder... and point to your folder structure of your project in development.

Click OK and SVN will ADD your folder structure in. Be patient! It looks like SVN has crashed/frozen. Don't worry. It's doing its work.

Done!


问:
How to specify active profiles in Maven3
Our application consists of various active profiles (say A1, A2, A3, A5 ...) which were separately defined in a profiles.xml file. Maven 3 expects all the profile information to be stored as part of the pom.xml file itself.

How should I specify the list of active profiles within a pom.xml file, so that I can avoid specifying them in the command line (e.g. mvn -PA1,A2,A3,A5)

答:
Should this do it:

```<code><profiles>
  <profile>
    <id>profile-1</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    ...
  </profile>
</profiles>
</code>```

From here.

ContentLicense: CC BY-SA 2.5

Body:
Should this do it:

<profiles>
  <profile>
    <id>profile-1</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    ...
  </profile>
</profiles>

From here.


问:
TextureAtlas and renderCalls in libgdx
I'm creating two textures and put them in the same TextureAtlas as shown in the code:

```<code>public void create () {
    pix = new Pixmap(100, 100, Pixmap.Format.RGBA8888);
    textureAtlas = new TextureAtlas();

    pix.setColor(Color.WHITE);
    pix.fill();
    textureAtlas.addRegion("white", new TextureRegion(new Texture(pix)));
    pix.setColor(Color.RED);
    pix.fill();
    textureAtlas.addRegion("red", new TextureRegion(new Texture(pix)));

    tr_list = textureAtlas.getRegions();

    pix.dispose()
}
</code>```

and then when rendering:

```<code>public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    for (int i = 0; i < 200; ++i) {
        batch.draw(tr_list.get(i % tr_list.size), (int)(Math.random()* 500), (int)(Math.random()* 500));
    }
    font.draw(batch, "FPS: " + Integer.toString(Gdx.graphics.getFramesPerSecond()), 0, Gdx.graphics.getHeight() - 20);
    font.draw(batch, "Render Calls: " + Integer.toString(batch.renderCalls), 0, Gdx.graphics.getHeight() - 60);
    batch.end();
}
</code>```

I was expecting batch.renderCalls to be equal to 1, since the textures are in the same TextureAtlas, but instead it's equal to 200. What am I doing wrong?

答:
In order to draw your TextureRegions in a single render call, each of them must be a part of the same Texture, not TextureAtlas.

TextureAtlas can contain TextureRegions of different Textures, which actually happens in your case. Even though you use the same Pixmap, you create two different Textures from it.

Title: TextureAtlas and renderCalls in libgdx

Body:
I'm creating two textures and put them in the same TextureAtlas as shown in the code:

public void create () {
    pix = new Pixmap(100, 100, Pixmap.Format.RGBA8888);
    textureAtlas = new TextureAtlas();

    pix.setColor(Color.WHITE);
    pix.fill();
    textureAtlas.addRegion("white", new TextureRegion(new Texture(pix)));
    pix.setColor(Color.RED);
    pix.fill();
    textureAtlas.addRegion("red", new TextureRegion(new Texture(pix)));

    tr_list = textureAtlas.getRegions();

    pix.dispose()
}

and then when rendering:

public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    for (int i = 0; i < 200; ++i) {
        batch.draw(tr_list.get(i % tr_list.size), (int)(Math.random()* 500), (int)(Math.random()* 500));
    }
    font.draw(batch, "FPS: " + Integer.toString(Gdx.graphics.getFramesPerSecond()), 0, Gdx.graphics.getHeight() - 20);
    font.draw(batch, "Render Calls: " + Integer.toString(batch.renderCalls), 0, Gdx.graphics.getHeight() - 60);
    batch.end();
}

I was expecting batch.renderCalls to be equal to 1, since the textures are in the same TextureAtlas, but instead it's equal to 200. What am I doing wrong?


问:
How can I install torchtext?
I have PyTorch installed in my machine but whenever I try to do the following-

```<code>from torchtext import data
from torchtext import datasets
</code>```

I get the following error.

```<code>ImportError: No module named 'torchtext'
</code>```

How can I install torchtext?

答:
As stated in the PyTorch forum, simply do:

```<code>$ pip install https://github.com/pytorch/text/archive/master.zip
</code>```

That should do it.

If not, as an alternative, try:

```<code>$ pip install torchtext
</code>```

For more advanced options, dependencies, and customized installations see:

pypi.org/project/torchtext

Title: How can I install torchtext?

Body:
I have PyTorch installed in my machine but whenever I try to do the following-

from torchtext import data
from torchtext import datasets

I get the following error.

ImportError: No module named 'torchtext'

How can I install torchtext?

Body:
As stated in the PyTorch forum, simply do:

$ pip install https://github.com/pytorch/text/archive/master.zip

That should do it.

If not, as an alternative, try:

$ pip install torchtext

For more advanced options, dependencies, and customized installations see:

pypi.org/project/torchtext

ContentLicense: CC BY-SA 4.0


问:
Why does running shiny start two Rscript processes on windows when launching from cmd line?
When I start an R script that runs a shiny app from the cmd line, it appears to launch two instances of Rscript.exe? I can always kill the smaller of the two and the app continues to run? Can someone elaborate on what is actually going on behind the scenes or tell me what I am doing wrong that is creating double processes?

super_simple.R

```<code>require(shiny)

app <- shinyApp(
  ui = bootstrapPage(
    numericInput('n', 'Number of obs', 100),
    plotOutput('plot')
  ),
  server = function(input, output) {
    output$plot <- renderPlot({ hist(runif(input$n)) })
  }
)

runApp(app, launch.browser = FALSE, port = 1234, host = "10.123.4.56")
</code>```

Now if I launch this via the cmd line:

```<code>START Rscript --vanilla C:\Users\Jason\Projects\super_simple.R
</code>```

At this point, I can point my browser to http://10.123.4.56:1234 and see the app. However, if I look at my running processes via: tasklist /FI "imagename eq rscript*" I see two Rscript.exe processes:

What I've determined, however, is that I can always kill the smaller of the two (e.g., taskkill /pid 9360 /f) and yet the app still functions in its entirety? NOTE: I have tried starting the command in the background via START \b ... but the outcome is the same.

答:
This is a general thing with the R scripting command-line utilities (Rscript.exe, R.exe, Rcmd.exe) and not specific to Shiny. All of these actually call Rterm.exe underneath to run the actual program in a separate process.

Try Rscript.exe with  --verbose and you'll see what I mean:

```<code>> Rscript --verbose script.R
running
  'C:\PROGRA~1\R\R-34~1.0\bin\x64\Rterm.exe --slave --no-restore --file=script.R'
</code>```

You can try out the other tools and see how they behave.

For more info, check out the source code

https://github.com/wch/r-source/blob/trunk/src/gnuwin32/front-ends

https://github.com/wch/r-source/blob/trunk/src/unix/Rscript.c

This question has some good info as well

R.exe, Rcmd.exe, Rscript.exe and Rterm.exe: what's the difference?

Body:
When I start an R script that runs a shiny app from the cmd line, it appears to launch two instances of Rscript.exe? I can always kill the smaller of the two and the app continues to run? Can someone elaborate on what is actually going on behind the scenes or tell me what I am doing wrong that is creating double processes?

super_simple.R

require(shiny)

app <- shinyApp(
  ui = bootstrapPage(
    numericInput('n', 'Number of obs', 100),
    plotOutput('plot')
  ),
  server = function(input, output) {
    output$plot <- renderPlot({ hist(runif(input$n)) })
  }
)

runApp(app, launch.browser = FALSE, port = 1234, host = "10.123.4.56")

Now if I launch this via the cmd line:

START Rscript --vanilla C:\Users\Jason\Projects\super_simple.R

At this point, I can point my browser to http://10.123.4.56:1234 and see the app. However, if I look at my running processes via: tasklist /FI "imagename eq rscript*" I see two Rscript.exe processes:

What I've determined, however, is that I can always kill the smaller of the two (e.g., taskkill /pid 9360 /f) and yet the app still functions in its entirety? NOTE: I have tried starting the command in the background via START \b ... but the outcome is the same.

Body:
This is a general thing with the R scripting command-line utilities (Rscript.exe, R.exe, Rcmd.exe) and not specific to Shiny. All of these actually call Rterm.exe underneath to run the actual program in a separate process.

Try Rscript.exe with  --verbose and you'll see what I mean:

> Rscript --verbose script.R
running
  'C:\PROGRA~1\R\R-34~1.0\bin\x64\Rterm.exe --slave --no-restore --file=script.R'

You can try out the other tools and see how they behave.

For more info, check out the source code

https://github.com/wch/r-source/blob/trunk/src/gnuwin32/front-ends

https://github.com/wch/r-source/blob/trunk/src/unix/Rscript.c

This question has some good info as well

R.exe, Rcmd.exe, Rscript.exe and Rterm.exe: what's the difference?


问:
Using vectorization to get a specific matrix output from two vectors
I wanted to know if there is a efficient way using MATLAB vectorization to generate a specific matrix from two vectors.

Suppose the vectors are

```<code>x = [u v]

y = [a1 a2 a3 b1 b2 b3]
</code>```

where u, v, a1, a2, a3, b1, b2, b3 are some real numbers.

The 2-column matrix that I wish to generate using these vectors is

```<code>M = [u  a1;
     u  a2;
     u  a3;
     v  a1;
     v  a2;
     v  a3;
     u  b1;
     u  b2;
     u  b3;
     v  b1;
     v  b2;
     v  b3]
</code>```

In general, the length of x can be anything and the length of y is multiple of 3. Here is the code that I have now, but I think there should some better way (that possibly avoids the use of for-loop):

```<code>M = [];
Y = reshape(y, 3, []);

for j = 1:size(Y, 2)
    [a, b] = meshgrid(x, Y(:, j));
    L = [a(:) b(:)];
    M = [M; L];
end
</code>```

答:
A solution using repmat and repelem :

```<code>M = [repmat(repelem(x(:),3),numel(y)/3,1) , ...
reshape(repmat(reshape(y,3,[]),numel(x),1),[],1)];
</code>```

Body:
I wanted to know if there is a efficient way using MATLAB vectorization to generate a specific matrix from two vectors.

Suppose the vectors are

x = [u v]

y = [a1 a2 a3 b1 b2 b3]

where u, v, a1, a2, a3, b1, b2, b3 are some real numbers.

The 2-column matrix that I wish to generate using these vectors is

M = [u  a1;
     u  a2;
     u  a3;
     v  a1;
     v  a2;
     v  a3;
     u  b1;
     u  b2;
     u  b3;
     v  b1;
     v  b2;
     v  b3]

In general, the length of x can be anything and the length of y is multiple of 3. Here is the code that I have now, but I think there should some better way (that possibly avoids the use of for-loop):

M = [];
Y = reshape(y, 3, []);

for j = 1:size(Y, 2)
    [a, b] = meshgrid(x, Y(:, j));
    L = [a(:) b(:)];
    M = [M; L];
end

Body:
A solution using repmat and repelem :

M = [repmat(repelem(x(:),3),numel(y)/3,1) , ...
reshape(repmat(reshape(y,3,[]),numel(x),1),[],1)];


问:
OrmLite delete failed
I am performing a simple delete of a ormlite object. The code is below. But no matter what, the object never get deleted.

```<code>Dao<Subscription, Object> dao = helper.getSubscriptionDataDao();

dao = helper.getSubscriptionDataDao();
QueryBuilder<Subscription, Object> query = dao.queryBuilder();
query.where().eq("key", subKey);
Subscription sub = dao.queryForFirst(query.prepare());
int r = dao.delete(sub); // r is 1
</code>```

Am I missing anything here?

答: This is how I solve the problem: Make sure the object have primary key. Setting the field as ID does not mean the ID will be auto generated. Without the ID, delete will fail.</p>

Title: OrmLite delete failed

Body:
I am performing a simple delete of a ormlite object. The code is below. But no matter what, the object never get deleted.

Dao<Subscription, Object> dao = helper.getSubscriptionDataDao();

dao = helper.getSubscriptionDataDao();
QueryBuilder<Subscription, Object> query = dao.queryBuilder();
query.where().eq("key", subKey);
Subscription sub = dao.queryForFirst(query.prepare());
int r = dao.delete(sub); // r is 1

Am I missing anything here?


问:
Enable only Mondays and start with Monday in html5
I wrote a piece of code to disable future dates:

```<code><input type="date" name="expens_date"  max="<?=date('Y-m-d')?>">
</code>```

but here I need to enable only Mondays and week start on Monday.
Please help me. Thanks in Advance

答:
You can add an or (||) in there, like this:

```<code>beforeShowDay: function(date){
</code>```

var day = date.getDay();

return [day == 1 || day == 1,""];

}

Body:
I wrote a piece of code to disable future dates:

<input type="date" name="expens_date"  max="<?=date('Y-m-d')?>">

but here I need to enable only Mondays and week start on Monday.
Please help me. Thanks in Advance

Body:
You can add an or (||) in there, like this:

beforeShowDay: function(date){

var day = date.getDay();

return [day == 1 || day == 1,""];

}


问:
Attempt to invoke virtual method on a null object reference in sqlite
HI I am new to android i am trying to retrieve the data from sqlite and getting nullpointer reference..Please help me on this.

Here is my code:-

Databasehelper.java

```<code>public class DatabaseHelper extends SQLiteOpenHelper{
    private final static String DATABASE_NAME="Reminder_details.db";
    private final static String TABLE_NAME="Reminder_detail_insert_tbl";
    private final static String CAL_NO1="Category_img";
    private final static String CAL_NO2="Category_Type";
    private final static String CAL_NO3="Title";
    private final static String CAL_NO4="Description";
    private final static String CAL_NO5="Repeat_type";
    private final static String CAL_NO6="Repeat_value";
    private final static String CAL_NO7="sun_Remind";
    private final static String CAL_NO8="mon_remind";
    private final static String CAL_NO9="tue_remind";
    private final static String CAL_NO10="wed_remind";
    private final static String CAL_NO11="thu_remind";
    private final static String CAL_NO12="fri_remind";
    private final static String CAL_NO13="sat_remind";
    private final static String CAL_NO14="active_date";
    private final static String CAL_NO15="active_end_date";
    private final static String CAL_NO16="creation_date";

    public DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("Create Table " +TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT,Category_img BLOB,Category_Type TEXT,Title TEXT,Description TEXT,Repeat_type TEXT,Repeat_value INTEGER,sun_Remind TEXT,mon_remind TEXT,tue_remind TEXT,wed_remind TEXT,thu_remind TEXT,fri_remind TEXT,sat_remind TEXT,active_date TEXT,active_end_date TEXT,creation_date DATETIME DEFAULT CURRENT_TIMESTAMP)");

    }

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

    public boolean DataInsert(
                    byte[] Category_img,
                    String Category_Type,
                    String Title,
                    String Description,
                    String Repeat_type,
                    int Repeat_value,
                    String sun_Remind,
                    String mon_Remind,
                    String tue_remind,
                    String wed_remind,
                    String thu_remind,
                    String fri_remind,
                    String sat_remind,
                    String active_date,
                    String active_end_date
        )
    {
        SQLiteDatabase db= getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(CAL_NO1,Category_img);
        cv.put(CAL_NO2,Category_Type);
        cv.put(CAL_NO3,Title);
        cv.put(CAL_NO4,Description);
        cv.put(CAL_NO5,Repeat_type);
        cv.put(CAL_NO6,Repeat_value);
        cv.put(CAL_NO7,sun_Remind);
        cv.put(CAL_NO8,mon_Remind);
        cv.put(CAL_NO9,tue_remind);
        cv.put(CAL_NO10,wed_remind);
        cv.put(CAL_NO11,thu_remind);
        cv.put(CAL_NO12,fri_remind);
        cv.put(CAL_NO13,sat_remind);
        cv.put(CAL_NO14,active_date);
        cv.put(CAL_NO15,active_end_date);

        long result=db.insert(TABLE_NAME,null,cv);

        if(result==-1)
            return false;
        else
            return true;

    }

    public Cursor getdata()
    {
        SQLiteDatabase db= getWritableDatabase();
        Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

}
</code>```

This is RecyclerAdaptor to get the data at run time from table please help me here.

in this recycleradaptor i am getting error while getting data from the table.

Cursor result=mydb.getdata(); in this line i am getting error.

RecyclerAdaptor.java

```<code>public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>
{
    DatabaseHelper mydb;
    List<String> title_list,description_list;
    private String[] title ={"Timetable","Subjects","Faculty","Resources"};
    private String[] description={"description1","description2","description3","description4"};
    private int[] images={R.drawable.table,R.drawable.books,R.drawable.faculty,R.drawable.res};
//
//    public void getdatadb()
//    {
//
//
//        title_list=new ArrayList<String>();
//        description_list=new ArrayList<String>();
//
//
//        Cursor result=mydb.getdata();
//
//        if(result.getCount()==0)
//        {
//            return;
//        }else
//        {
//            while (result.moveToNext()){
//                title_list.add(result.getString(2));
//                description_list.add(result.getString(3));
//
//
//            }
//        }
//
//
//
//    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView mTextTile,mTextDescription;
        ImageView mImageview;

        public ViewHolder(View itemView)
        {
            super(itemView);
            mTextTile=(TextView)itemView.findViewById(R.id.tvmain);
            mTextDescription=(TextView)itemView.findViewById(R.id.tvdescription);
            mImageview=(ImageView)itemView.findViewById(R.id.ivmain);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position=getAdapterPosition();
                    String text=mTextTile.getText().toString();
                    Snackbar.make(v,"Click Detected onItem "+position+" Item :"+text,Snackbar.LENGTH_LONG).setAction("Action",null).show();
                }
            });

        }
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout,parent,false);
        ViewHolder viewHolder=new ViewHolder(view);

        title_list=new ArrayList<String>();
        description_list=new ArrayList<String>();

        Cursor result=mydb.getdata();

        while (result.moveToNext()){
            title_list.add(result.getString(2));
            description_list.add(result.getString(3));
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position)
    {
        holder.mTextTile.setText(title_list.get(position));
        holder.mTextDescription.setText(description_list.get(position));
        holder.mImageview.setImageResource(images[position]);
    }

    @Override
    public int getItemCount() {
        return title.length;
    }

}
</code>```

答:
Add this line at the start of "onCreateViewHolder()":

```<code>mydb = new DatabaseHelper(parent.getContext());
</code>```

So your method is like:

```<code>@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    mydb = new DatabaseHelper(parent.getContext());
    View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout,parent,false);
    ViewHolder viewHolder=new ViewHolder(view);

    title_list=new ArrayList<String>();
    description_list=new ArrayList<String>();

    Cursor result=mydb.getdata();

    while (result.moveToNext()){
        title_list.add(result.getString(2));
        description_list.add(result.getString(3));
    }
    return viewHolder;
}
</code>```

Body:
HI I am new to android i am trying to retrieve the data from sqlite and getting nullpointer reference..Please help me on this.

Here is my code:-

Databasehelper.java

public class DatabaseHelper extends SQLiteOpenHelper{
    private final static String DATABASE_NAME="Reminder_details.db";
    private final static String TABLE_NAME="Reminder_detail_insert_tbl";
    private final static String CAL_NO1="Category_img";
    private final static String CAL_NO2="Category_Type";
    private final static String CAL_NO3="Title";
    private final static String CAL_NO4="Description";
    private final static String CAL_NO5="Repeat_type";
    private final static String CAL_NO6="Repeat_value";
    private final static String CAL_NO7="sun_Remind";
    private final static String CAL_NO8="mon_remind";
    private final static String CAL_NO9="tue_remind";
    private final static String CAL_NO10="wed_remind";
    private final static String CAL_NO11="thu_remind";
    private final static String CAL_NO12="fri_remind";
    private final static String CAL_NO13="sat_remind";
    private final static String CAL_NO14="active_date";
    private final static String CAL_NO15="active_end_date";
    private final static String CAL_NO16="creation_date";

    public DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("Create Table " +TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT,Category_img BLOB,Category_Type TEXT,Title TEXT,Description TEXT,Repeat_type TEXT,Repeat_value INTEGER,sun_Remind TEXT,mon_remind TEXT,tue_remind TEXT,wed_remind TEXT,thu_remind TEXT,fri_remind TEXT,sat_remind TEXT,active_date TEXT,active_end_date TEXT,creation_date DATETIME DEFAULT CURRENT_TIMESTAMP)");

    }

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

    public boolean DataInsert(
                    byte[] Category_img,
                    String Category_Type,
                    String Title,
                    String Description,
                    String Repeat_type,
                    int Repeat_value,
                    String sun_Remind,
                    String mon_Remind,
                    String tue_remind,
                    String wed_remind,
                    String thu_remind,
                    String fri_remind,
                    String sat_remind,
                    String active_date,
                    String active_end_date
        )
    {
        SQLiteDatabase db= getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(CAL_NO1,Category_img);
        cv.put(CAL_NO2,Category_Type);
        cv.put(CAL_NO3,Title);
        cv.put(CAL_NO4,Description);
        cv.put(CAL_NO5,Repeat_type);
        cv.put(CAL_NO6,Repeat_value);
        cv.put(CAL_NO7,sun_Remind);
        cv.put(CAL_NO8,mon_Remind);
        cv.put(CAL_NO9,tue_remind);
        cv.put(CAL_NO10,wed_remind);
        cv.put(CAL_NO11,thu_remind);
        cv.put(CAL_NO12,fri_remind);
        cv.put(CAL_NO13,sat_remind);
        cv.put(CAL_NO14,active_date);
        cv.put(CAL_NO15,active_end_date);

        long result=db.insert(TABLE_NAME,null,cv);

        if(result==-1)
            return false;
        else
            return true;

    }

    public Cursor getdata()
    {
        SQLiteDatabase db= getWritableDatabase();
        Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

}

This is RecyclerAdaptor to get the data at run time from table please help me here.

in this recycleradaptor i am getting error while getting data from the table.

Cursor result=mydb.getdata(); in this line i am getting error.

RecyclerAdaptor.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>
{
    DatabaseHelper mydb;
    List<String> title_list,description_list;
    private String[] title ={"Timetable","Subjects","Faculty","Resources"};
    private String[] description={"description1","description2","description3","description4"};
    private int[] images={R.drawable.table,R.drawable.books,R.drawable.faculty,R.drawable.res};
//
//    public void getdatadb()
//    {
//
//
//        title_list=new ArrayList<String>();
//        description_list=new ArrayList<String>();
//
//
//        Cursor result=mydb.getdata();
//
//        if(result.getCount()==0)
//        {
//            return;
//        }else
//        {
//            while (result.moveToNext()){
//                title_list.add(result.getString(2));
//                description_list.add(result.getString(3));
//
//
//            }
//        }
//
//
//
//    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView mTextTile,mTextDescription;
        ImageView mImageview;

        public ViewHolder(View itemView)
        {
            super(itemView);
            mTextTile=(TextView)itemView.findViewById(R.id.tvmain);
            mTextDescription=(TextView)itemView.findViewById(R.id.tvdescription);
            mImageview=(ImageView)itemView.findViewById(R.id.ivmain);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position=getAdapterPosition();
                    String text=mTextTile.getText().toString();
                    Snackbar.make(v,"Click Detected onItem "+position+" Item :"+text,Snackbar.LENGTH_LONG).setAction("Action",null).show();
                }
            });

        }
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout,parent,false);
        ViewHolder viewHolder=new ViewHolder(view);

        title_list=new ArrayList<String>();
        description_list=new ArrayList<String>();

        Cursor result=mydb.getdata();

        while (result.moveToNext()){
            title_list.add(result.getString(2));
            description_list.add(result.getString(3));
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position)
    {
        holder.mTextTile.setText(title_list.get(position));
        holder.mTextDescription.setText(description_list.get(position));
        holder.mImageview.setImageResource(images[position]);
    }

    @Override
    public int getItemCount() {
        return title.length;
    }

}

Body:
Add this line at the start of "onCreateViewHolder()":

mydb = new DatabaseHelper(parent.getContext());

So your method is like:

@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    mydb = new DatabaseHelper(parent.getContext());
    View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout,parent,false);
    ViewHolder viewHolder=new ViewHolder(view);

    title_list=new ArrayList<String>();
    description_list=new ArrayList<String>();

    Cursor result=mydb.getdata();

    while (result.moveToNext()){
        title_list.add(result.getString(2));
        description_list.add(result.getString(3));
    }
    return viewHolder;
}


问:
Finding minimum value more efficiently in racket

Hello,

I am working on some Racket practice. I am aware that Racket has a built in min function, but I am trying to write one from scratch. I have done some work and found some ideas online, but the code is not very efficient. I am thinking I will need to use a helper method. I am a bit lost on how to further modify this code to make it efficient. I ran this code on the test case shown and it took way too long. On smaller test cases the code does return the correct results. Any suggestions would be great.

```<code>(define (minim lst)
    (cond
      ((null? (cdr lst)) (car lst))
      ((< (car lst) (minim (cdr lst))) (car lst))
      (else
        (minim (cdr lst)))) )
</code>```

(minim '(3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4))

Would return 1.

答:
The code runs longer than it needs to because for each item in the list, minim is called recursively on the cdr in the test condition. It has what known as tree recursion.

A more "Rackety" way to write minim might be to define a simple function that compares two numbers:

```<code>(define (min-of-2 x y)
  (if (< x y)
      x
      y))
</code>```

And then fold it over the list using foldl:

```<code>(define (minim lst)
  (foldl min-of-2 (first lst) (rest lst)))
</code>```

The time to use foldl is when an operation over a list produces a single value based on the contents of the list as is the case here.

The function min-of-2 need not be given a name and can be passed as a lamda. For example:

```<code>(define (minim lst)
  (foldl
    (lambda (x y) (if (< x y) x y))
    (first lst)
    (rest lst)))
</code>```

Body:
Hello,

I am working on some Racket practice. I am aware that Racket has a built in min function, but I am trying to write one from scratch. I have done some work and found some ideas online, but the code is not very efficient. I am thinking I will need to use a helper method. I am a bit lost on how to further modify this code to make it efficient. I ran this code on the test case shown and it took way too long. On smaller test cases the code does return the correct results. Any suggestions would be great.

(define (minim lst)
    (cond
      ((null? (cdr lst)) (car lst))
      ((< (car lst) (minim (cdr lst))) (car lst))
      (else
        (minim (cdr lst)))) )

(minim '(3 4 2 9 3 8 7 7 7 7 7 7 7 7 7 8 2 1 3 2 2 2 3 4))

Would return 1.

Body:
The code runs longer than it needs to because for each item in the list, minim is called recursively on the cdr in the test condition. It has what known as tree recursion.

A more "Rackety" way to write minim might be to define a simple function that compares two numbers:

(define (min-of-2 x y)
  (if (< x y)
      x
      y))

And then fold it over the list using foldl:

(define (minim lst)
  (foldl min-of-2 (first lst) (rest lst)))

The time to use foldl is when an operation over a list produces a single value based on the contents of the list as is the case here.

The function min-of-2 need not be given a name and can be passed as a lamda. For example:

(define (minim lst)
  (foldl
    (lambda (x y) (if (< x y) x y))
    (first lst)
    (rest lst)))


问:
How to create zookeeper auth mechanism?
i'm trying to create an acl for a node:

```<code>    ZooKeeper client = new ZooKeeper("host:port/rootNode", 3000, null);
    ACL acl = new ACL(Perms.CREATE,new Id("digest","user:pass"));
    client.create("/testNode",new String("test").getBytes(), Arrays.asList(acl), CreateMode.PERSISTENT);
    client.close();
</code>```

Then i try to access to that node and create a node under "testNode":

```<code>    ZooKeeper client = new ZooKeeper(" host:port/rootNode", 3000, null);
    client.addAuthInfo("digest", new String("user:pass").getBytes());
    Stat stat;
    try {
        stat = client.exists("/testNode", false);
        if(stat!=null){
            client.create("/testNode/clientTest", new String("clienttest").getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }
    } catch (KeeperException e) {
        e.printStackTrace();
    }
    client.close();
</code>```

but it gives me:

```<code>    org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /testNode/clientTest
</code>```

when i'm wrong?

Thanks!

答:
The document says:

digest uses a username:password string to generate MD5 hash which is
  then used as an ACL ID identity. Authentication is done by sending the
  username:password in clear text. When used in the ACL the expression
  will be the username:base64 encoded SHA1 password digest.

So, when creating the node, the ACL expression can not be just user:pass, it must be encoded.
Do this:

```<code>String s = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest("user:pass".getBytes()));
ACL acl = new ACL(ZooDefs.Perms.ALL, new Id("digest","user:" + s));
</code>```

Btw, the document is kind of wrong. Because according to that, you should digest("pass"). But that won't work, you must hash the whole string digest("user:pass")

Title: How to create zookeeper auth mechanism?

Body:
i'm trying to create an acl for a node:

    ZooKeeper client = new ZooKeeper("host:port/rootNode", 3000, null);
    ACL acl = new ACL(Perms.CREATE,new Id("digest","user:pass"));
    client.create("/testNode",new String("test").getBytes(), Arrays.asList(acl), CreateMode.PERSISTENT);
    client.close();

Then i try to access to that node and create a node under "testNode":

    ZooKeeper client = new ZooKeeper(" host:port/rootNode", 3000, null);
    client.addAuthInfo("digest", new String("user:pass").getBytes());
    Stat stat;
    try {
        stat = client.exists("/testNode", false);
        if(stat!=null){
            client.create("/testNode/clientTest", new String("clienttest").getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }
    } catch (KeeperException e) {
        e.printStackTrace();
    }
    client.close();

but it gives me:

    org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /testNode/clientTest

when i'm wrong?

Thanks!

Body:
The document says:

digest uses a username:password string to generate MD5 hash which is
  then used as an ACL ID identity. Authentication is done by sending the
  username:password in clear text. When used in the ACL the expression
  will be the username:base64 encoded SHA1 password digest.

So, when creating the node, the ACL expression can not be just user:pass, it must be encoded.
Do this:

String s = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest("user:pass".getBytes()));
ACL acl = new ACL(ZooDefs.Perms.ALL, new Id("digest","user:" + s));

Btw, the document is kind of wrong. Because according to that, you should digest("pass"). But that won't work, you must hash the whole string digest("user:pass")


问:
C#: Split comma-separated strings, but not if comma enclosed in single quotes
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.

Elements are comma-separated

Each individual string is enclosed in single quotes

'Hello', 'World'

```<code>{"'Hello', "'World'"}
</code>```

Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".

Ordinarily it would be easy to get the individual elements by splitting on the comma:

```<code>string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');
</code>```

But I can't do this; if a comma is in-between single quotes it is text, not a separator.

This is one element:

'Hello, World'

```<code>{"'Hello, World'"}
</code>```

How can I extract the elements checking to see if the comma is in-between single quotes?

'Hello', 'World', 'Hello, World'

```<code>{"'Hello'", "'World'", "'Hello, World'"}
</code>```

One more detail: I cannot guarantee the amount of whitespace between elements:

'Hello',     'World',  'Hello, World'

P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes

答:
You have not answered whether the strings can contain embedded single quotes & how they might be escaped.

If every string follows the pattern of [SingleQuote][Text][SingleQuote], here's a RegEx that will do what you need:

'[^']+'

If you have empty strings in the single quotes, use:

'[^']*'

Body:
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.

Elements are comma-separated

Each individual string is enclosed in single quotes

'Hello', 'World'

{"'Hello', "'World'"}

Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".

Ordinarily it would be easy to get the individual elements by splitting on the comma:

string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');

But I can't do this; if a comma is in-between single quotes it is text, not a separator.

This is one element:

'Hello, World'

{"'Hello, World'"}

How can I extract the elements checking to see if the comma is in-between single quotes?

'Hello', 'World', 'Hello, World'

{"'Hello'", "'World'", "'Hello, World'"}

One more detail: I cannot guarantee the amount of whitespace between elements:

'Hello',     'World',  'Hello, World'

P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes


问:
Is SQL the assembly for databases?
Talking about hibernate and others ORMs, the ORMs evangelists talk about SQL like the assembly language for Databases.

I think is soon to assert this, but I guess can be true on a near future, not sure.

UPDATE: The analogy I was referring means SQL is to assembly what ORM is to C/Java/C#. Of course, an exact analogy is not possible. The question is if in the future, with more powerful computers the developers are going to use only ORM (or ORM like) instead of SQL.

答:
SQL shares some traits with assembly language:

Coding in SQL directly gives you the opportunity to write very efficient code in a very compact way.

Using SQL effectively is a neglected skill by both professional software developers and by college curricula.

Because SQL is very compact, refactoring SQL tends to be wearisome and costly.

There's a large "base of the pyramid" of software developers who hate SQL with a passion and prefer to use layers of abstraction that mimic their preferred OO programming paradigm, even though these layers limit their effective use of SQL and result in slow, heavyweight applications.

However, unlike assembly, SQL is a high-level, platform-independent language.  Also, there is no ANSI/ISO standard for assembly language.

OwnerDisplayName: FerranB

Title: Is SQL the assembly for databases?

LastEditorDisplayName: FerranB

OwnerDisplayName: Bill Karwin


问:
Difference between ListView and DataGrid in WPF?
I have to retrieve some questions from the database and display them on the user screen dynamically. I also need to add some controls in the columns of grid view, basically a question and input box for an answer.

Please suggest which one should I use? ListView or DataGrid?

答:
Well, in WPF the difference between ListView and DataGrid is just one. Editing. You need editing use DataGrid, otherwise use ListView. You can edit in ListView also but it is easier and build in DataGrid. Otherwise, whatever can be displayed in DataGrid, can be displayed in ListView.

One thing which DataGrid supports and ListView doesn't (out of the box) is automatic column generation.

You can read this article on CodeProject for a better understanding of DataGrid and also about the major differences between ListView and DataGrid.


问:
Regexp for match second numeric values
Current Strings are

```<code>   ABC 70 1 MG-MCG Paper
   ABC 70 10 MCG Paper
   ABC 70 150 MG-MCG Paper
   ABC 70 1.50 MG-MCG Paper
   ABC 70 10.50 MG-MCG Paper
   ABC 70 10-50 MG-MCG Paper

   ABC 705 1 MG-MCG Paper
   ABC 705 10 MCG Paper
   ABC 705 150 MG-MCG Paper
   ABC 705 1.50 MG-MCG Paper
   ABC 705 10.50 MG-MCG Paper
   ABC 705 10-50 MG Paper
</code>```

Expected Output :

```<code>1
 10
 150
 1.50
 10.50
 10-50
 1
 10
 150
 1.50
 10.50
 10-50
</code>```

Treid Exp -

```<code>string c=Regex.Match(result,@"(\d{4}|\d{3}|(..\.\d{1,2}))").Value;
return c
</code>```

How to select second numeric value and Before MG or MCG value

答:
Following regex provides the output you want:</p>

```<code>var match = Regex.Match(result, @"\d+\s+(\d+(?:[.-]\d+)?)");
if (match.Success)
{
    var num = match.Groups[1].Value;
}
</code>```

Title: Regexp for match second numeric values

Body:
Current Strings are

   ABC 70 1 MG-MCG Paper
   ABC 70 10 MCG Paper
   ABC 70 150 MG-MCG Paper
   ABC 70 1.50 MG-MCG Paper
   ABC 70 10.50 MG-MCG Paper
   ABC 70 10-50 MG-MCG Paper

   ABC 705 1 MG-MCG Paper
   ABC 705 10 MCG Paper
   ABC 705 150 MG-MCG Paper
   ABC 705 1.50 MG-MCG Paper
   ABC 705 10.50 MG-MCG Paper
   ABC 705 10-50 MG Paper

Expected Output :

1
 10
 150
 1.50
 10.50
 10-50
 1
 10
 150
 1.50
 10.50
 10-50

Treid Exp -

string c=Regex.Match(result,@"(\d{4}|\d{3}|(..\.\d{1,2}))").Value;
return c

How to select second numeric value and Before MG or MCG value

Body:
Following regex provides the output you want:

var match = Regex.Match(result, @"\d+\s+(\d+(?:[.-]\d+)?)");
if (match.Success)
{
    var num = match.Groups[1].Value;
}


问:
How to get object in jsonarray firebase android?
Structure Firebase data

DetailItemOrderSetGet

I want to get all data in order_detail or one of data inside order_detail like detail_item_id. I always get error force close because order_detail, but how to make looping for that or How is to get one of array object? I just can get for data with one level like order_customer_name or order_date. this is my code. thanks

```<code>mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            processOrderList.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    DetailitemOrderSetGet orderDetail = postSnapshot.child("order_detail").getValue(DetailitemOrderSetGet.class);
                        processOrderList.add(postSnapshot.getValue(OrderHistorySetGet.class));

                }
            processAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

答:
Well I do not know what is the Setter getter of you class DetailitemOrderSetGet. But I would talk about its general pattern.Do not confuse yourself with the Json object and Json Array.  This Firebase data return is in Json format and that is really very simple and fast to execute.

I will talk about its general pattern using your Json return.

The First thing that I can see is Json Array in your return namely Transactions

first of all get it and store it. for an instance look below

```<code>JSONArray transactionsArray = myFirebaseReturnOBJECT.get("Transactions");
</code>```

Now that you have got the array in your transactionsArray . Now you need to loop through it to get your required Data.

Now the second step is to get another data segment which is also a JSONArray so we have to do same procedure but in for loop since we have our TransactionsArray.

```<code>for (int i = 0; i<transactionsArray.length();i++){
            JSONArray orderDetailsArray = jsonObject.getJSONArray("order_details");

            for (int j = 0; j <orderDetailsArray.length() ; j++) {
                JSONObject order_detail_OBJ = orderDetailsArray.getJSONObject(j);
                String detail_item_id  = order_detail_OBJ.getString("detail_item_id");
            }

        }
</code>```

You can see that I have managed to do the 2 for loops since that there is 2 jsonArrays. so in step 2 have used for loop and got the JsonObject at index "j" and from that JsonObject namely  order_detail_OBJ i have successfully gotten my desired field that is detail_item_id

I hope this will help you in getting what you are looking for.I have just put up this as example there could be some type mistakes.

Body:
Structure Firebase data

DetailItemOrderSetGet

I want to get all data in order_detail or one of data inside order_detail like detail_item_id. I always get error force close because order_detail, but how to make looping for that or How is to get one of array object? I just can get for data with one level like order_customer_name or order_date. this is my code. thanks

mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            processOrderList.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    DetailitemOrderSetGet orderDetail = postSnapshot.child("order_detail").getValue(DetailitemOrderSetGet.class);
                        processOrderList.add(postSnapshot.getValue(OrderHistorySetGet.class));

                }
            processAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Body:
Well I do not know what is the Setter getter of you class DetailitemOrderSetGet. But I would talk about its general pattern.Do not confuse yourself with the Json object and Json Array.  This Firebase data return is in Json format and that is really very simple and fast to execute.

I will talk about its general pattern using your Json return.

The First thing that I can see is Json Array in your return namely Transactions

first of all get it and store it. for an instance look below

JSONArray transactionsArray = myFirebaseReturnOBJECT.get("Transactions");

Now that you have got the array in your transactionsArray . Now you need to loop through it to get your required Data.

Now the second step is to get another data segment which is also a JSONArray so we have to do same procedure but in for loop since we have our TransactionsArray.

for (int i = 0; i<transactionsArray.length();i++){
            JSONArray orderDetailsArray = jsonObject.getJSONArray("order_details");

            for (int j = 0; j <orderDetailsArray.length() ; j++) {
                JSONObject order_detail_OBJ = orderDetailsArray.getJSONObject(j);
                String detail_item_id  = order_detail_OBJ.getString("detail_item_id");
            }

        }

You can see that I have managed to do the 2 for loops since that there is 2 jsonArrays. so in step 2 have used for loop and got the JsonObject at index "j" and from that JsonObject namely  order_detail_OBJ i have successfully gotten my desired field that is detail_item_id

I hope this will help you in getting what you are looking for.I have just put up this as example there could be some type mistakes.


问:
Reversing Characters within a List using a loop
This is my code I have come up with trying to reverse these strings

```<code>presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)
</code>```

As of now, it only prints the list backwards like this:

```<code>John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington
</code>```

I need it to output the list like:

```<code>notgnihsaW egroeG
smadA nhoJ
</code>```

and so on

答:
Try this:</p>

```<code>>>> reversedPresidents = [p[::-1] for p in presidents]
>>> print(reversedPresidents)
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
>>>
</code>```

Body:
This is my code I have come up with trying to reverse these strings

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)

As of now, it only prints the list backwards like this:

John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington

I need it to output the list like:

notgnihsaW egroeG
smadA nhoJ

and so on

Body:
Try this:

>>> reversedPresidents = [p[::-1] for p in presidents]
>>> print(reversedPresidents)
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
>>>


问:
Clean array indexing with arrays in numpy
I'm running into this problem over and over again, and can't seem to find a clean solution for this. So I'm trying to index an array with another array. I have a 2d numpy array. And a 1d numpy array with the same length as the 1st dimension of the 2d array I'm trying to index and the elements represent the indices of the columns I try to extract:

```<code>import numpy as np

A = np.random.rand((5,3))

B = np.asarray([2,1,2,0,1])
</code>```

The behaviour that I want is extracting for all rows the corresponding column in array B. This could be done by

```<code>C = A[np.arange(A.shape[0]),B]
</code>```

But I can imagine that there is a better way to get this behaviour. Using a : as indexing the first row gives the wrong behaviour.

If there is a cleaner way of doing this that would be great. I'm really used to this array indexing from Matlab, but maybe there is no equivalent in numpy. Using boolean indices is of course an option, but that also requires converting arrays all the time.

答:
```<code>In [60]: A = np.arange(1,16).reshape(5,3)
In [61]: B = np.array([2,1,2,0,1])
In [62]: C = A[np.arange(A.shape[0]),B]
In [63]: C
Out[63]: array([ 3,  5,  9, 10, 14])
</code>```

In Octave

```<code>>>  A = reshape(1:15, 3,5).';
>> B = [3,2,3,1,2];
>> A
A =

    1    2    3
    4    5    6
    7    8    9
   10   11   12
   13   14   15

>> A(:,B)
ans =

    3    2    3    1    2
    6    5    6    4    5
    9    8    9    7    8
   12   11   12   10   11
   15   14   15   13   14
</code>```

This is the same as numpy:

```<code>In [65]: A[:,B]
Out[65]:
array([[ 3,  2,  3,  1,  2],
       [ 6,  5,  6,  4,  5],
       [ 9,  8,  9,  7,  8],
       [12, 11, 12, 10, 11],
       [15, 14, 15, 13, 14]])
</code>```

You imply that there's something clean for indexing one item from each column in MATLAB/Octave, but I missing it.  I used to work a lot in that language, but I've gotten out of practice.

sub2ind does the job:

```<code>>> sub2ind([3,5],B, 1:5)
ans =

    3    5    9   10   14

>> A.'(:)(sub2ind([3,5],B,1:5))
ans =

    3
    5
    9
   10
   14
</code>```

(The 'F' vs 'C' ordering is complicating my comparison)

numpy has a similar ravel_multi_index:

```<code>In [69]: np.ravel_multi_index((np.arange(5),B),(5,3))
Out[69]: array([ 2,  4,  8,  9, 13], dtype=int32)
In [71]: A.flat[_]
Out[71]: array([ 3,  5,  9, 10, 14])
</code>```

Body:
I'm running into this problem over and over again, and can't seem to find a clean solution for this. So I'm trying to index an array with another array. I have a 2d numpy array. And a 1d numpy array with the same length as the 1st dimension of the 2d array I'm trying to index and the elements represent the indices of the columns I try to extract:

import numpy as np

A = np.random.rand((5,3))

B = np.asarray([2,1,2,0,1])

The behaviour that I want is extracting for all rows the corresponding column in array B. This could be done by

C = A[np.arange(A.shape[0]),B]

But I can imagine that there is a better way to get this behaviour. Using a : as indexing the first row gives the wrong behaviour.

If there is a cleaner way of doing this that would be great. I'm really used to this array indexing from Matlab, but maybe there is no equivalent in numpy. Using boolean indices is of course an option, but that also requires converting arrays all the time.

Body:
In [60]: A = np.arange(1,16).reshape(5,3)
In [61]: B = np.array([2,1,2,0,1])
In [62]: C = A[np.arange(A.shape[0]),B]
In [63]: C
Out[63]: array([ 3,  5,  9, 10, 14])

In Octave

>>  A = reshape(1:15, 3,5).';
>> B = [3,2,3,1,2];
>> A
A =

    1    2    3
    4    5    6
    7    8    9
   10   11   12
   13   14   15

>> A(:,B)
ans =

    3    2    3    1    2
    6    5    6    4    5
    9    8    9    7    8
   12   11   12   10   11
   15   14   15   13   14

This is the same as numpy:

In [65]: A[:,B]
Out[65]:
array([[ 3,  2,  3,  1,  2],
       [ 6,  5,  6,  4,  5],
       [ 9,  8,  9,  7,  8],
       [12, 11, 12, 10, 11],
       [15, 14, 15, 13, 14]])

You imply that there's something clean for indexing one item from each column in MATLAB/Octave, but I missing it.  I used to work a lot in that language, but I've gotten out of practice.

sub2ind does the job:

>> sub2ind([3,5],B, 1:5)
ans =

    3    5    9   10   14

>> A.'(:)(sub2ind([3,5],B,1:5))
ans =

    3
    5
    9
   10
   14

(The 'F' vs 'C' ordering is complicating my comparison)

numpy has a similar ravel_multi_index:

In [69]: np.ravel_multi_index((np.arange(5),B),(5,3))
Out[69]: array([ 2,  4,  8,  9, 13], dtype=int32)
In [71]: A.flat[_]
Out[71]: array([ 3,  5,  9, 10, 14])


问:
WordPress: how best can I categorize Woocommerce products by registered system users?
I am looking for a reasonable way to allow specific site users to manage their own little online stores such that each user of a specific role of users/registered site members can associate themselves with their own products.

Is there a 'right way' to set up a relation between these two separate content types? I would like to then offer a global search of all products that could be filtered by the creator and the product previews and details would include a link back to the creator's details.

答:
You can use ACF and assign the Product post type to a User.

EDIT

The User Relationship ACF fields is only available in ACF Pro, it appears. https://www.advancedcustomfields.com/pro/

Without using ACF, you are essentially creating a new piece of postmeta for the Product post type called user_id.  This is good for a one-to-many relationship between Users and Products.

If Products can have more than one User, I would create an intermediary table called wp_users_products, or something similar, to establish the many-to-many relationship.


答:
Try using Regex.Match with the following pattern:

```<code>(\d+(?:[.-]\d+)?) MG-MCG
</code>```

This matches the number, optionally a decimal or two part number separated by hyphen, which comes immediately before the string MG-MCG.

```<code>string input = " ABC 70 10.1-50.2 MG-MCG Paper";
Match match = Regex.Match(input, @"(\d+(?:\.\d+)?(?:[.-]\d+(?:\.\d+)?)?) MG-MCG");
if (match.Success)
{
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}
</code>```

Demo

Title: Regexp for match second numeric values

Body:
Try using Regex.Match with the following pattern:

(\d+(?:[.-]\d+)?) MG-MCG

This matches the number, optionally a decimal or two part number separated by hyphen, which comes immediately before the string MG-MCG.

string input = " ABC 70 10.1-50.2 MG-MCG Paper";
Match match = Regex.Match(input, @"(\d+(?:\.\d+)?(?:[.-]\d+(?:\.\d+)?)?) MG-MCG");
if (match.Success)
{
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}

Demo


问:
how to Parse values from Array?this is my sample array code?
```<code>Array
(
    [Action] => Array
        (
            [0] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => OfferActivationByOfferID
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
            [1] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => Ranjith
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
        )
)
</code>```

in this array i need [Name] attribute Value for Every Action tag.please do help.

sample output;

1.OfferActivationByOfferID

2.Ranjith

答:
Hope you are saving array data in some variable. It is very simple :-

```<code>$data = //Your arraydata
foreach($data['Action'] as $key=> $value){
    echo $value['@attributes']['Name'];
}
</code>```

Hope it helps!

Body:
Array
(
    [Action] => Array
        (
            [0] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => OfferActivationByOfferID
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
            [1] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => Ranjith
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
        )
)

in this array i need [Name] attribute Value for Every Action tag.please do help.

sample output;

1.OfferActivationByOfferID

2.Ranjith

Body:
Hope you are saving array data in some variable. It is very simple :-

$data = //Your arraydata
foreach($data['Action'] as $key=> $value){
    echo $value['@attributes']['Name'];
}

Hope it helps!


问:
Please explain Get and Post in ASP.net
I am new to ASP.net . Can any one please explain what is the difference between Get and Post method in asp.Net.

Thanks
Pradeep.A

答: I'm a sucker for detailed explanations, so This Article and This one do a good job with the details. But the short version is that GET passes data to the server encoded in the URL, and POST passes it in the body of the http request.  </p>

Title: Please explain Get and Post in ASP.net


问:
Entity Framework Core 2.0 migrations update database with seed data throwing error
I am using EF Core 2.0 code first migration. I am trying to run the migration sin to the new database. I am using seed data. I am getting error if i use seed data and no error if i comment out the seed data method. Not sure what is the problem. Can anyone please help?

Error:

System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'WorkflowBranches' in the database.

The tables are created, but no records appear in the migrationhistory table, even though I have around 5 migration scripts. Also the seed data is inserted.

I think the database is getting created twice. I am using migrations
  script and also in the seed method, there is
  dbContext.Database.EnsureCreatedAsync(). This could be the reason but
  i am not sure.

Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    //Other code
    services.AddTransient<DbSeeder>();
}

public void Configure(IApplicationBuilder app,
                      IHostingEnvironment env,
                      DbSeeder dbSeeder)
{
    app.UseMvc();

    dbSeeder.SeedAsync(app.ApplicationServices).Wait();
}
</code>```

DbSeeder.cs:

```<code>using Workflow.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Workflow.DBContext
{
    public class DbSeeder
    {
        readonly ILogger _Logger;

        public DbSeeder(ILoggerFactory loggerFactory)
        {
            _Logger = loggerFactory.CreateLogger("DbSeederLogger");
        }

        public async Task SeedAsync(IServiceProvider serviceProvider)
        {
            //Based on EF team's example at https://github.com/aspnet/MusicStore/blob/dev/samples/MusicStore/Models/SampleData.cs
            using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService<WorkflowDBContext>();
                if (await dbContext.Database.EnsureCreatedAsync())
                {
                    if (!await dbContext.Alert.AnyAsync())
                    {
                        await InsertAlertsSampleData(dbContext);
                    }
                }
            }
        }

        public async Task InsertAlertsSampleData(WorkflowDBContext dbContext)
        {
            //Insert Risktypes
            var riskTypes = GetRiskTypes();
            dbContext.RiskType.AddRange(riskTypes);

            try
            {
                int numAffected = await dbContext.SaveChangesAsync();
                _Logger.LogInformation($@"Saved {numAffected} riskTypes");
            }
            catch (Exception exp)
            {
                _Logger.LogError($"Error in {nameof(DbSeeder)}: " + exp.Message);
                throw;
            }

            //Insert categories
            var categories = GetCategories(riskTypes);
            dbContext.Category.AddRange(categories);

            try
            {
                int numAffected = await dbContext.SaveChangesAsync();
                _Logger.LogInformation($"Saved {numAffected} categories");
            }
            catch (Exception exp)
            {
                _Logger.LogError($"Error in {nameof(DbSeeder)}: " + exp.Message);
                throw;
            }

            //var alerts = GetAlerts(categories);
        }

        private List<Alert> GetAlerts(List<Category> categories)
        {
            return new List<Alert>();
        }

        private List<RiskType> GetRiskTypes()
        {
            var riskTypes = new List<RiskType>
            {
                new RiskType { Name = "Risk1"},
                new RiskType { Name = "Risk2"}
            };

            return riskTypes;
        }

        private List<Category> GetCategories(List<RiskType> riskTypes)
        {
            var categoryList = new List<Category>();

            var categories = new string[]
            {
                "Category1Risk1",
                "Category2Risk1",
                "Category3Risk1",
                "Category1Risk2"
            };

            //Low Risk
            foreach (var category in categories.Take(3))
            {
                categoryList.Add(new Category
                {
                    Name = category,
                    RiskType = riskTypes.FirstOrDefault(rt=>rt.Name=='Risk1')
                });
            }

            //High Risk
            foreach (var category in categories.Skip(3))
            {
                categoryList.Add(new Category
                {
                    Name = category,
                    RiskType = riskTypes.FirstOrDefault(rt=>rt.Name=='Risk2')
                });
            }

            return categoryList;
        }
    }
}
</code>```

Thanks

答:
If you are in the Ef Core 2.0 you need to kwno this:

In 2.0 projects using EF Core 2.0, Program.BuildWebHost is invoked to
  obtain the application services. Unlike 1.x, this has the additional
  side effect of invoking Startup.Configure. If your 1.x app invoked
  database initialization code in its Configure method, unexpected
  problems can occur. For example, if the database doesn't yet exist,
  the seeding code runs before the EF Core Migrations command execution.
  This problem causes a dotnet ef migrations list command to fail if the
  database doesn't yet exist. Consider the following 1.x seed
  initialization code in the Configure method of Startup.cs:

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

SeedData.Initialize(app.ApplicationServices);
</code>```

In 2.0 projects, move the SeedData.Initialize call to the Main method of Program.cs:+

```<code>var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    try
    {
        // Requires using RazorPagesMovie.Models;
        SeedData.Initialize(services);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred seeding the DB.");
    }
}

host.Run();
</code>```

As of 2.0, it's bad practice to do anything in BuildWebHost except
  build and configure the web host. Anything that is about running the
  application should be handled outside of BuildWebHost — typically in
  the Main method of Program.cs.

Today i changed my code for this code, and mi solution worked properly.

I am leaving you the reference link:

https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#move-database-initialization-code

Body:
I am using EF Core 2.0 code first migration. I am trying to run the migration sin to the new database. I am using seed data. I am getting error if i use seed data and no error if i comment out the seed data method. Not sure what is the problem. Can anyone please help?

Error:

System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'WorkflowBranches' in the database.

The tables are created, but no records appear in the migrationhistory table, even though I have around 5 migration scripts. Also the seed data is inserted.

I think the database is getting created twice. I am using migrations
  script and also in the seed method, there is
  dbContext.Database.EnsureCreatedAsync(). This could be the reason but
  i am not sure.

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    //Other code
    services.AddTransient<DbSeeder>();
}

public void Configure(IApplicationBuilder app,
                      IHostingEnvironment env,
                      DbSeeder dbSeeder)
{
    app.UseMvc();

    dbSeeder.SeedAsync(app.ApplicationServices).Wait();
}

DbSeeder.cs:

using Workflow.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Workflow.DBContext
{
    public class DbSeeder
    {
        readonly ILogger _Logger;

        public DbSeeder(ILoggerFactory loggerFactory)
        {
            _Logger = loggerFactory.CreateLogger("DbSeederLogger");
        }

        public async Task SeedAsync(IServiceProvider serviceProvider)
        {
            //Based on EF team's example at https://github.com/aspnet/MusicStore/blob/dev/samples/MusicStore/Models/SampleData.cs
            using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService<WorkflowDBContext>();
                if (await dbContext.Database.EnsureCreatedAsync())
                {
                    if (!await dbContext.Alert.AnyAsync())
                    {
                        await InsertAlertsSampleData(dbContext);
                    }
                }
            }
        }

        public async Task InsertAlertsSampleData(WorkflowDBContext dbContext)
        {
            //Insert Risktypes
            var riskTypes = GetRiskTypes();
            dbContext.RiskType.AddRange(riskTypes);

            try
            {
                int numAffected = await dbContext.SaveChangesAsync();
                _Logger.LogInformation($@"Saved {numAffected} riskTypes");
            }
            catch (Exception exp)
            {
                _Logger.LogError($"Error in {nameof(DbSeeder)}: " + exp.Message);
                throw;
            }

            //Insert categories
            var categories = GetCategories(riskTypes);
            dbContext.Category.AddRange(categories);

            try
            {
                int numAffected = await dbContext.SaveChangesAsync();
                _Logger.LogInformation($"Saved {numAffected} categories");
            }
            catch (Exception exp)
            {
                _Logger.LogError($"Error in {nameof(DbSeeder)}: " + exp.Message);
                throw;
            }

            //var alerts = GetAlerts(categories);
        }

        private List<Alert> GetAlerts(List<Category> categories)
        {
            return new List<Alert>();
        }

        private List<RiskType> GetRiskTypes()
        {
            var riskTypes = new List<RiskType>
            {
                new RiskType { Name = "Risk1"},
                new RiskType { Name = "Risk2"}
            };

            return riskTypes;
        }

        private List<Category> GetCategories(List<RiskType> riskTypes)
        {
            var categoryList = new List<Category>();

            var categories = new string[]
            {
                "Category1Risk1",
                "Category2Risk1",
                "Category3Risk1",
                "Category1Risk2"
            };

            //Low Risk
            foreach (var category in categories.Take(3))
            {
                categoryList.Add(new Category
                {
                    Name = category,
                    RiskType = riskTypes.FirstOrDefault(rt=>rt.Name=='Risk1')
                });
            }

            //High Risk
            foreach (var category in categories.Skip(3))
            {
                categoryList.Add(new Category
                {
                    Name = category,
                    RiskType = riskTypes.FirstOrDefault(rt=>rt.Name=='Risk2')
                });
            }

            return categoryList;
        }
    }
}

Thanks

Body:
If you are in the Ef Core 2.0 you need to kwno this:

In 2.0 projects using EF Core 2.0, Program.BuildWebHost is invoked to
  obtain the application services. Unlike 1.x, this has the additional
  side effect of invoking Startup.Configure. If your 1.x app invoked
  database initialization code in its Configure method, unexpected
  problems can occur. For example, if the database doesn't yet exist,
  the seeding code runs before the EF Core Migrations command execution.
  This problem causes a dotnet ef migrations list command to fail if the
  database doesn't yet exist. Consider the following 1.x seed
  initialization code in the Configure method of Startup.cs:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

SeedData.Initialize(app.ApplicationServices);

In 2.0 projects, move the SeedData.Initialize call to the Main method of Program.cs:+

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    try
    {
        // Requires using RazorPagesMovie.Models;
        SeedData.Initialize(services);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred seeding the DB.");
    }
}

host.Run();

As of 2.0, it's bad practice to do anything in BuildWebHost except
  build and configure the web host. Anything that is about running the
  application should be handled outside of BuildWebHost — typically in
  the Main method of Program.cs.

Today i changed my code for this code, and mi solution worked properly.

I am leaving you the reference link:

https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#move-database-initialization-code


问:
pass data from a table view Controller to View Controller using data stored in core data
I'm a little newbie and I have a doubt, I have a TableViewController and another ViewController that I have as a detailViewController, what I try to do is that when a cell is selected in the tableview, it presents the corresponding data stored in core data for that cell in the detailViewcontroller.

This is the file that controls the tableViewcontroller :

```<code>import UIKit

class CostumerTableViewController: UITableViewController {
    var costumerArray:[Costumer] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.reloadData()
        self.fetchData()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return costumerArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let name = costumerArray[indexPath.row]
        cell.textLabel?.text = name.costumerName!
        return cell
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        if editingStyle == .delete {
            let costumerDelete = costumerArray[indexPath.row]
            context.delete(costumerDelete)
            (UIApplication.shared.delegate as! AppDelegate).saveContext()
            do {
                costumerArray = try context.fetch(Costumer.fetchRequest())
            } catch {
                print(error)
            }
        }
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let DvC = Storyboard.instantiateViewController(withIdentifier: "costumerDetailViewController") as! costumerDetailViewController
        let n = costumerArray[indexPath.row]
        let Cn = n.costumerName!
        DvC.getCostumerName = Cn
        self.navigationController?.pushViewController(DvC, animated: true)
    }

    func fetchData() {
        // se crea el context
        let  context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {  // se hace el request del array
            costumerArray = try context.fetch(Costumer.fetchRequest())
        } catch {
            print(error)
        }
    }
}
</code>```

In the compilation does not give me any problem, some everything goes well the problem is that it does not present anything in the detail viewController label that in this case I try to send the data from this code.

This is the detailViewController code :

```<code>import UIKit

class costumerDetailViewController: UIViewController {
    var getCostumerName = String()

    @IBOutlet weak var labelName: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        labelName.text! = getCostumerName
    }
}
</code>```

答:
First Check Cn has value or "" on this line.

```<code>let Cn = n.costumerName
</code>```

Change your code in class costumerDetailViewController for declare getCostumerName

```<code>var getCostumerName = "" //for avoid crash. if value goes nil.
</code>```

Use Print() in viewDidLoad and debug it.

Hope this will help you.

Body:
I'm a little newbie and I have a doubt, I have a TableViewController and another ViewController that I have as a detailViewController, what I try to do is that when a cell is selected in the tableview, it presents the corresponding data stored in core data for that cell in the detailViewcontroller.

This is the file that controls the tableViewcontroller :

import UIKit

class CostumerTableViewController: UITableViewController {
    var costumerArray:[Costumer] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.reloadData()
        self.fetchData()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return costumerArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let name = costumerArray[indexPath.row]
        cell.textLabel?.text = name.costumerName!
        return cell
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        if editingStyle == .delete {
            let costumerDelete = costumerArray[indexPath.row]
            context.delete(costumerDelete)
            (UIApplication.shared.delegate as! AppDelegate).saveContext()
            do {
                costumerArray = try context.fetch(Costumer.fetchRequest())
            } catch {
                print(error)
            }
        }
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let DvC = Storyboard.instantiateViewController(withIdentifier: "costumerDetailViewController") as! costumerDetailViewController
        let n = costumerArray[indexPath.row]
        let Cn = n.costumerName!
        DvC.getCostumerName = Cn
        self.navigationController?.pushViewController(DvC, animated: true)
    }

    func fetchData() {
        // se crea el context
        let  context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {  // se hace el request del array
            costumerArray = try context.fetch(Costumer.fetchRequest())
        } catch {
            print(error)
        }
    }
}

In the compilation does not give me any problem, some everything goes well the problem is that it does not present anything in the detail viewController label that in this case I try to send the data from this code.

This is the detailViewController code :

import UIKit

class costumerDetailViewController: UIViewController {
    var getCostumerName = String()

    @IBOutlet weak var labelName: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        labelName.text! = getCostumerName
    }
}

Body:
First Check Cn has value or "" on this line.

let Cn = n.costumerName

Change your code in class costumerDetailViewController for declare getCostumerName

var getCostumerName = "" //for avoid crash. if value goes nil.

Use Print() in viewDidLoad and debug it.

Hope this will help you.


问:
How to check existed value in json file

app.js

  var permission = require('./permission.json');

for(i in permission) {
    if(permission[i] == "admin")
      console.log('admin role is present');
}```
</div>
</div>
</p>

<h2>json file</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
    "admin": {
        "user": {
            "read": true,
            "write": true
        },
        "packages": {
            "read": true,
            "write": true
        }
    }
}</code>```

I am trying to check the admin role in my json file. How to do this, any suggestion??

答:
Since you do not have an array in your json, what you are doing won't work. Instead of 'permission[i]' simply use 'i'.
Example-</p>

```<code>var permission = require('./permission.json');

for(i in permission) {

    //because 'i' already contains the value of the key
    if(i == "admin")
      console.log('admin role is present');
}
</code>```

Title: How to check existed value in json file

Body:
app.js

  var permission = require('./permission.json');

for(i in permission) {
    if(permission[i] == "admin")
      console.log('admin role is present');
}

json file

{
    "admin": {
        "user": {
            "read": true,
            "write": true
        },
        "packages": {
            "read": true,
            "write": true
        }
    }
}

I am trying to check the admin role in my json file. How to do this, any suggestion??

Body:
Since you do not have an array in your json, what you are doing won't work. Instead of 'permission[i]' simply use 'i'.
Example-

var permission = require('./permission.json');

for(i in permission) {

    //because 'i' already contains the value of the key
    if(i == "admin")
      console.log('admin role is present');
}


问:
Signature Error in Gear S3 after OS upgrade from Tizen 2.3.2.3 to Tizen 3.0.0.1
My Gear S3 was running on Tizen 2.3.2.3. Yesterday, I updated it to Tizen 3.0.0.1. Now, when I am trying to install app from Tizen Studio 1.2, it shows following error

"The application installation on the device has failed due to a signature error! (error code: -12)"

Previously it worked with a certificate I generated with my device's DUID. But, its not working now. I have created new Certificates(both public and partner level), but still its showing same error for both certificate profiles.

Can anyone help me? Thanks in advance

答:
Please update Tizen Studio version to 2.0 and apply light reset to your gear device. After completing reset, connect it with gear manager to start the device and set date & time of gear device exactly to the date & time of your development PC.

If still the problem exists, delete old certificates and create new one.