问:
Why do I keep losing the values of my struct members?
apologies if this is some stupid mistake I've made, I'm just a rookie.

First off, I have created a struct;

```<code>struct StarsStruct
{
    int SerialNumber;
    char StarName[10];
    double x;
    double y;
};
</code>```

Then, I've created an array of struct pointers using; (NumberOfStars is just an int variable) This was declared and initialised at the top of the program, before any if statements.

```<code>struct StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);
</code>```

And I have done a for loop to change the values of the members, in my struct array;

```<code>for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;
            Plot(r1, r2, '.');
        }
</code>```

However, when I go to my second IF statement, for some reason these values are completely  erased;

full part of the code;

```<code>if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();
        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        //Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

        for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;
            Plot(r1, r2, '.');
        }

    }

    else if (strcmp(CurrentCommand, "list") == 0)
    {
        Stars[0].SerialNumber;
        Stars[1].y;
        Stars[2].SerialNumber;
        Stars[3].SerialNumber;
        Stars[4].x;
        Stars[5].y;
        for (int i = 0; i < NumberOfStars; i++)
        {

            printf("%d", Stars[0].SerialNumber);

        }
    }
</code>```

答:
Note: malloc() returns uninitlized memory. Quoting C11, chapter §7.22.3.4

The malloc function allocates space for an object whose size is specified by size and
  whose value is indeterminate.

In the else if part, (when you reach there), you don't have the members initialized, because, you did not enter the if block which takes care of assigning the values!!

Once again, C11, chapter §6.8.4.1,

In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. [...]

You need to move the assignment part outside of the if condition, if you want the values to be "available" in the else block also.

Body:
apologies if this is some stupid mistake I've made, I'm just a rookie.

First off, I have created a struct;

struct StarsStruct
{
    int SerialNumber;
    char StarName[10];
    double x;
    double y;
};

Then, I've created an array of struct pointers using; (NumberOfStars is just an int variable) This was declared and initialised at the top of the program, before any if statements.

struct StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

And I have done a for loop to change the values of the members, in my struct array;

for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;
            Plot(r1, r2, '.');
        }

However, when I go to my second IF statement, for some reason these values are completely  erased;

full part of the code;

if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();
        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        //Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

        for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;
            Plot(r1, r2, '.');
        }

    }

    else if (strcmp(CurrentCommand, "list") == 0)
    {
        Stars[0].SerialNumber;
        Stars[1].y;
        Stars[2].SerialNumber;
        Stars[3].SerialNumber;
        Stars[4].x;
        Stars[5].y;
        for (int i = 0; i < NumberOfStars; i++)
        {

            printf("%d", Stars[0].SerialNumber);

        }
    }


来源: stackexchange

问:
Implementing Okta in React Native and get: Response to preflight request doesn't pass access
I'm implementing the Okta signin widget with React Native

I get this:

Failed to load https://dev-827074.oktapreview.com/api/v1/sessions/me: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

After trying to login, I get the following:

UnsupportedBrowserError {name: "UNSUPPORTED_BROWSER_ERROR", message: "There was an error sending the request - have you enabled CORS?"}

答:
The API you have written does not support CORS. CORS or Cross origin resource sharing allows a web app to submit requests to an API belonging to a different domain. This setting should be enabled on the API side.

This is how it works, whenever a request is sent to a different domain, an OPTIONS method is sent to the server. The server responds back with available options for the web app. If the verb is supported, the browser will send the actual request with the appropriate verb or method (For example, GET or POST). If the verb is not supported, you get the above error message.

In short, enable CORS for your API. If it is a Node / Express API it is just a simple cors package you need to add to your project and use.

ContentLicense: CC BY-SA 3.0


问:
OpenFile function open file ok but returns a NULL pointer (C program)
I have had some troubles with my C code and decided to ask the gurus here what I am doing wrong.

```<code>//
// Routines.c
//

#include <stdio.h>
#include <errno.h>

...

int OpenFile(FILE * fd, char * nm, char * md){
    FILE *rc;
    printf("nm = %s, md = %s\n", nm, md);
    fd = fopen(nm, md);
    printf("fd fopen... errno = %d\n", errno);
    if ( fd == NULL ) {
        *rc = errno;
        printf("fopen %s -> rc = %d\n", nm, *rc);
        return rc;
    }
    printf("fd not NULL !!!\nrc = %d e errno = %d\n", *rc, errno);
    return 0;
}

...

int Generate (char * v) {
    int rc = 0;
    FILE *fd;

    rc = OpenFile (fd, v, "w");
    if ( rc ){
        printf ("open file error. RC = %d", rc);
        return rc;
    }
    if (fd == NULL){
        printf ("fd NULL !!!\n");
        return 1;
    }

    CloseFile(fd);
    printf("Closed fd\n");

    printf("Leaving Generate. RC = %d\n",rc);
    return rc;
}

...
</code>```

This Routines.c is made this way:

gcc -Wall -g -O0 -pedantic -fPIC -c Routines.c -o Routines.o

================================================================

```<code>//
// Caller.c
//

#include <stdio.h>
#include <string.h>

#include "Routines.h"

....

int main (int argc, char **argv) {
    ....
    char * v = "msgs.txt";

    ....

    Generate(v);

    ....

    return 0;
}
</code>```

This Caller.c is made this way:

gcc -Wall -g -O0 -fno-stack-protector -fPIC -c Caller.c

gcc -Wall -g -O0 -fno-stack-protector -fPIC -o Caller Caller.o Routines.o

================================================================

Both c files compile zero error (no warnings too).

-- Execution --

msgs from OpenFile() (that is, the file has been opened correctly)

nm = msgs.txt, md = w
fd fopen... errno = 0
fd not NULL !!!
rc = 0 e errno = 0

msgs from OpenFile() (What happen here ???)

fd NULL !!!

Someone can tell me what has happened with a file handler returned to Caller
as NULL, when it was correctly set on Routines at file opening ???

To solve my problem I had to do:

```<code>FILE * OpenFile(char * nm, char * md, int * rc){

fd = OpenFile (v, "w", &rc);
</code>```

But I'd like to calm my mind down and understand what the hell i did to that happen.

Thanks (a lot) in advance.

答: FILE * fd in OpenFile() is a local variable containing a pointer to a file. You're changing the pointer inside your local function scope - none of that information gets out of your OpenFile() function.

Body:
I have had some troubles with my C code and decided to ask the gurus here what I am doing wrong.

//
// Routines.c
//

#include <stdio.h>
#include <errno.h>

...

int OpenFile(FILE * fd, char * nm, char * md){
    FILE *rc;
    printf("nm = %s, md = %s\n", nm, md);
    fd = fopen(nm, md);
    printf("fd fopen... errno = %d\n", errno);
    if ( fd == NULL ) {
        *rc = errno;
        printf("fopen %s -> rc = %d\n", nm, *rc);
        return rc;
    }
    printf("fd not NULL !!!\nrc = %d e errno = %d\n", *rc, errno);
    return 0;
}

...

int Generate (char * v) {
    int rc = 0;
    FILE *fd;

    rc = OpenFile (fd, v, "w");
    if ( rc ){
        printf ("open file error. RC = %d", rc);
        return rc;
    }
    if (fd == NULL){
        printf ("fd NULL !!!\n");
        return 1;
    }

    CloseFile(fd);
    printf("Closed fd\n");

    printf("Leaving Generate. RC = %d\n",rc);
    return rc;
}

...

This Routines.c is made this way:

gcc -Wall -g -O0 -pedantic -fPIC -c Routines.c -o Routines.o

================================================================

//
// Caller.c
//

#include <stdio.h>
#include <string.h>

#include "Routines.h"

....

int main (int argc, char **argv) {
    ....
    char * v = "msgs.txt";

    ....

    Generate(v);

    ....

    return 0;
}

This Caller.c is made this way:

gcc -Wall -g -O0 -fno-stack-protector -fPIC -c Caller.c

gcc -Wall -g -O0 -fno-stack-protector -fPIC -o Caller Caller.o Routines.o

================================================================

Both c files compile zero error (no warnings too).

-- Execution --

msgs from OpenFile() (that is, the file has been opened correctly)

nm = msgs.txt, md = w
fd fopen... errno = 0
fd not NULL !!!
rc = 0 e errno = 0

msgs from OpenFile() (What happen here ???)

fd NULL !!!

Someone can tell me what has happened with a file handler returned to Caller
as NULL, when it was correctly set on Routines at file opening ???

To solve my problem I had to do:

FILE * OpenFile(char * nm, char * md, int * rc){

fd = OpenFile (v, "w", &rc);

But I'd like to calm my mind down and understand what the hell i did to that happen.

Thanks (a lot) in advance.


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'title' in 'field list' in Laravel 5.4
Can anyone help me what is the problem of my following data insert code?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'title' in
  'field list' (SQL: insert into  gallery_categories (title,
  description, category_id, image, updated_at, created_at) values (Test
  title, Test details, 1, 1512370315.jpg, 2017-12-04 06:51:55,
  2017-12-04 06:51:55))

I have two model. One of GalleryModel and other of GalleryCategoryModel. When I use dd($request->all()); then it debugging perfect.

N.B: I am new in laravel.

GalleryModel Model

```<code>class GalleryModel extends Model
    {
        protected $table      = 'galleries';
        protected $primaryKey = 'id';
        protected $fillable   = ['title', 'description', 'image', 'category_id'];
    }
</code>```

And here is my GalleryCategoryModel Model

```<code>class GalleryCategoryModel extends Model
    {
        protected $table      = 'gallery_categories';
        protected $primaryKey = 'id';
        protected $fillable   = ['name'];

    }
</code>```

My controller GalleriesController

```<code>public function create()
    {
        $categories = GalleryCategoryModel::all();
        return view('pages.backend.galleries.create')->withCategories($categories);
    }

public function store(StoreGalleryRequest $request)
    {
        $gallery = new GalleryCategoryModel;

        $gallery->title       = $request->title;
        $gallery->description = $request->description;
        $gallery->category_id = $request->category_id;

        if($request->hasFile('gallery_image')){
            $image = $request->file('gallery_image');
            $filename = time() . '.' .$image->getClientOriginalExtension();
            $location = public_path('assets/backend/images/' .$filename);
            Image::make($image)->resize(500, 350)->save($location);

            $gallery->image = $filename;
        }
        $gallery->save();
        Session::flash('success', "Data has been insert success");
        return redirect()->route('galleries.index', $gallery->id);
    }
</code>```

Here is my HTML code

```<code><div class="br-section-wrapper">
      <h6 class="tx-gray-800 tx-uppercase tx-bold tx-14 mg-b-10">Create New Gallery</h6>
      {!! Form::open(array('route' => 'galleries.store', 'data-parsley-validate' => '', 'files' => true)) !!}
  {{ csrf_field() }}
    <div class="row">
      <div class="col-md-12">
        <div class="row">
          <div class="col-md-4">
            <div class="form-group margin-top15">
              <label for="title">Gallery Title: <span class="tx-danger">*</span></label>
              <input type="text" name="title" id="title" class="form-control" required>
            </div>
          </div>

           <div class="col-md-4">
             <div class="form-group margin-top15">
              <label for="category_id">Select Category: <span class="tx-danger">*</span></label>
              <select class="form-control select2 width-100" name="category_id" id="category_id" data-placeholder="Choose one" data-parsley-class-handler="#slWrapper" data-parsley-errors-container="#slErrorContainer" required>
                  <option label="Choose one"></option>
                  @foreach($categories as $category)
                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                  @endforeach
                </select>
            </div>
          </div>
          <div class="col-md-4">
             <div class="form-group margin-top15">
              <label for="gallery_image">Gallery Image: <span class="tx-danger">*</span></label>
              <input type="file" name="gallery_image" id="gallery_image" class="form-control" required>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-md-12">
            <label for="description">Description: <span class="tx-danger">*</span></label>
            <textarea name="description" id="description" class="form-control"></textarea>
          </div>
        </div>

        <div class="form-group margin-top15">
          <button type="submit" class="btn btn-info tx-11 pd-y-12 tx-uppercase tx-spacing-2">Create Gallery</button>
        </div>
      </div>
    </div>
  {!! Form::close() !!}
</div>
</code>```

答: This is because you don't have a column named title in your gallery_categories tables.</p>

Body:
Can anyone help me what is the problem of my following data insert code?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'title' in
  'field list' (SQL: insert into  gallery_categories (title,
  description, category_id, image, updated_at, created_at) values (Test
  title, Test details, 1, 1512370315.jpg, 2017-12-04 06:51:55,
  2017-12-04 06:51:55))

I have two model. One of GalleryModel and other of GalleryCategoryModel. When I use dd($request->all()); then it debugging perfect.

N.B: I am new in laravel.

GalleryModel Model

class GalleryModel extends Model
    {
        protected $table      = 'galleries';
        protected $primaryKey = 'id';
        protected $fillable   = ['title', 'description', 'image', 'category_id'];
    }

And here is my GalleryCategoryModel Model

class GalleryCategoryModel extends Model
    {
        protected $table      = 'gallery_categories';
        protected $primaryKey = 'id';
        protected $fillable   = ['name'];

    }

My controller GalleriesController

public function create()
    {
        $categories = GalleryCategoryModel::all();
        return view('pages.backend.galleries.create')->withCategories($categories);
    }

public function store(StoreGalleryRequest $request)
    {
        $gallery = new GalleryCategoryModel;

        $gallery->title       = $request->title;
        $gallery->description = $request->description;
        $gallery->category_id = $request->category_id;

        if($request->hasFile('gallery_image')){
            $image = $request->file('gallery_image');
            $filename = time() . '.' .$image->getClientOriginalExtension();
            $location = public_path('assets/backend/images/' .$filename);
            Image::make($image)->resize(500, 350)->save($location);

            $gallery->image = $filename;
        }
        $gallery->save();
        Session::flash('success', "Data has been insert success");
        return redirect()->route('galleries.index', $gallery->id);
    }

Here is my HTML code

Create New Gallery

      {!! Form::open(array('route' => 'galleries.store', 'data-parsley-validate' => '', 'files' => true)) !!}
  {{ csrf_field() }}

              Gallery Title: *
              <input type="text" name="title" id="title" class="form-control" required>

              Select Category: *
              <select class="form-control select2 width-100" name="category_id" id="category_id" data-placeholder="Choose one" data-parsley-class-handler="#slWrapper" data-parsley-errors-container="#slErrorContainer" required>
                  <option label="Choose one"></option>
                  @foreach($categories as $category)
                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                  @endforeach
                </select>

              Gallery Image: *
              <input type="file" name="gallery_image" id="gallery_image" class="form-control" required>

            Description: *
            <textarea name="description" id="description" class="form-control"></textarea>

          <button type="submit" class="btn btn-info tx-11 pd-y-12 tx-uppercase tx-spacing-2">Create Gallery</button>

  {!! Form::close() !!}


问:
Can floor-ing a rounded number gives a different answer than the rounded number?
Am I correct that floor(round($number)) is not necessarily equal to round($number) assuming that "round" returns a double?

As an example, imagine that $number = 123456.9999999999999999.  I'm guessing that "round" will be a no-op, since $number is already as close as possible to 123457.
 "floor" would then yield 123456.

Is this correct or is there something about "floor" or "round" that prevents this?

Body:
Can floor-ing a rounded number gives a different answer than the rounded number?

Sometimes looking at corners cases can expose a counter example.

void rtest(double x) {
  double y1 = floor(round(x));
  double y2 = round(x);
  printf("%d %- 14e %- 14e %- 14e\n", y1 != y2, x, y1, y2);
}

int main(void) {
  double x[] = { 0.0, DBL_TRUE_MIN, DBL_MIN, 1.0, 3.14, 3.99, DBL_MAX, 1.0/0.0, 0.0/0.0};
  for (unsigned i=0; i< sizeof x/sizeof x[0]; i++) {
    rtest(x[i]);
    rtest(-x[i]);
  }
}

Output

0  0.000000e+00   0.000000e+00   0.000000e+00
0 -0.000000e+00  -0.000000e+00  -0.000000e+00
0  4.940656e-324  0.000000e+00   0.000000e+00
0 -4.940656e-324 -0.000000e+00  -0.000000e+00
0  2.225074e-308  0.000000e+00   0.000000e+00
0 -2.225074e-308 -0.000000e+00  -0.000000e+00
0  1.000000e+00   1.000000e+00   1.000000e+00
0 -1.000000e+00  -1.000000e+00  -1.000000e+00
0  3.140000e+00   3.000000e+00   3.000000e+00
0 -3.140000e+00  -3.000000e+00  -3.000000e+00
0  3.990000e+00   4.000000e+00   4.000000e+00
0 -3.990000e+00  -4.000000e+00  -4.000000e+00
0  1.797693e+308  1.797693e+308  1.797693e+308
0 -1.797693e+308 -1.797693e+308 -1.797693e+308
0  inf            inf            inf
0 -inf           -inf           -inf
1 -nan           -nan           -nan
1  nan            nan            nan

When dealing with ieee-754 numbers, floor(round(x)) != round(x) is true or ("not necessarily equal" per OP's quesiton) when x is Not-A-Number.

Otherwise the result of a round() is always an integer value or infinity and `floor-ing does not change the value.

I checked various rounding  modes and found  the same result.


问:
Inserting no repeating values in a sql table and get/input foreign key
I will need a little help with this. I got two issues, that I've been working to solve for a couple of days.

First one is this: I am using PrepairedStatement to add a record from a form (of my application to a database, but have it so that the SQL code would only add the record if it doesn't find it in the database. I tried this:

```<code> String sql= "INSERT INTO " + tableName + "(first_name,"+
            " last_name, tel, fax, email, agenda) VALUES"+
            "(?,?,?,?,?,?) SELECT * FROM (SELECT '"+fName+"', '"+lastName+"') AS tmp"+
            " WHERE NOT EXISTS (SELECT first_name FROM "+ tableName +" WHERE"+
            " first_name = '"+fName+"') LIMIT 1;";
</code>```

This code returns me an SQL error that I can't find. Should I perhaps remove the "(?,?,?,?,?,?)" part? It worked beforehand on this:

```<code>String sql = "INSERT INTO " + tableName +" (username, password)"+
              " SELECT * FROM (SELECT 'Administrator', 'admin') AS tmp"+
              " WHERE NOT EXISTS (SELECT username FROM login WHERE "+
              " username = 'Administrator')LIMIT 1;";
        stmt.executeUpdate(sql);
</code>```

So, now the bigger issue that I can't wrap my mind around. I have 2 tables - a Students table and a Doctors table. They have a relationship where the doctor_id is a foreign key in the Students table and the primary key in the Doctors table. So because I am entering the details in a form, I get the strings from the text boxes and pass it to the function that adds these details into the table(s) like this:

```<code>    mrdb.addDoctorRecord("doctorsdetails", txtPDFirstName.getText(),
            txtPDLastName.getText(), txtTel.getText(),
            txtFax.getText(), txtEmail.getText(),txtAppointment.getText());
    mrdb.addStudentRecord ("Students",txtFName.getText(), txtMName.getText(),
    txtLName.getText(),txtareaInformationComments.getText(),
    Integer.parseInt(txtAge.getText(),10),Float.parseFloat(txtWaist.getText()),
    Float.parseFloat(txtHeight.getText()),Float.parseFloat(txtWeight.getText()),
    Integer.parseInt(txtClass.getText(), 10), txtSubClass.getText());
</code>```

And so here is one of these functions (where I fill up a Student record):

```<code>public void addStudentRecord(String tableName, String fName, String midName,
    String lastName, String comment, int age, float waist, float height,
    float weight, int student_class, String subClass, String appointment){

    String sql = "INSERT INTO " + tableName + "(first_name, mid_name,"+
                "last_name, age, class, subclass, gender, doctor_id ,"+
                "diseases, more_info, height, weight, waist, appointment) "+
                "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    try{
    prepSTMT= conn.prepareStatement(sql);
    prepSTMT.setString(1, fName);
    prepSTMT.setString(2, midName);
    prepSTMT.setString(3, lastName);
    prepSTMT.setInt(4, age);
    prepSTMT.setInt(5, student_class);
    prepSTMT.setString(6, subClass);
    prepSTMT.setString(7, "m");
    prepSTMT.setInt(8, 3); // TODO update variable for FOREIGN KEY
    prepSTMT.setString(9, "b"); // TODO update variable
    prepSTMT.setString(10, comment);
    prepSTMT.setFloat(11, height);
    prepSTMT.setFloat(12, weight);
    prepSTMT.setFloat(13, waist);
    prepSTMT.setString(14, appointment);
    prepSTMT.executeUpdate();
    }catch(SQLException e){
    JOptionPane.showMessageDialog(null, e);
    }
}
</code>```

You can probably tell by the comment where I have inserted the foreign key (with a magic number (3)). I think to replace this with a variable, I will need to have someway to check what is the foreign key of the entry that I entered into the doctor's table. This is what I am confused and can't get my mind around. Do I have to do a query for Id and name of the doctor I entered previously? I need a hint.

答:
For your first issue, why are you not using a left join?

For the second issue, even or-mappers like hibernate do a sql request to the database after an insert when the id is setby an id generator within the database even though the created intance with id is returned. Once you enable sql logging you could see the sql request.

If you consider using an or-mapper like hibernate you could use the hibernate id generator to generate the id's. By this the id is set by the client side and you would know it immediately.

Body:
I will need a little help with this. I got two issues, that I've been working to solve for a couple of days.

First one is this: I am using PrepairedStatement to add a record from a form (of my application to a database, but have it so that the SQL code would only add the record if it doesn't find it in the database. I tried this:

 String sql= "INSERT INTO " + tableName + "(first_name,"+
            " last_name, tel, fax, email, agenda) VALUES"+
            "(?,?,?,?,?,?) SELECT * FROM (SELECT '"+fName+"', '"+lastName+"') AS tmp"+
            " WHERE NOT EXISTS (SELECT first_name FROM "+ tableName +" WHERE"+
            " first_name = '"+fName+"') LIMIT 1;";

This code returns me an SQL error that I can't find. Should I perhaps remove the "(?,?,?,?,?,?)" part? It worked beforehand on this:

String sql = "INSERT INTO " + tableName +" (username, password)"+
              " SELECT * FROM (SELECT 'Administrator', 'admin') AS tmp"+
              " WHERE NOT EXISTS (SELECT username FROM login WHERE "+
              " username = 'Administrator')LIMIT 1;";
        stmt.executeUpdate(sql);

So, now the bigger issue that I can't wrap my mind around. I have 2 tables - a Students table and a Doctors table. They have a relationship where the doctor_id is a foreign key in the Students table and the primary key in the Doctors table. So because I am entering the details in a form, I get the strings from the text boxes and pass it to the function that adds these details into the table(s) like this:

    mrdb.addDoctorRecord("doctorsdetails", txtPDFirstName.getText(),
            txtPDLastName.getText(), txtTel.getText(),
            txtFax.getText(), txtEmail.getText(),txtAppointment.getText());
    mrdb.addStudentRecord ("Students",txtFName.getText(), txtMName.getText(),
    txtLName.getText(),txtareaInformationComments.getText(),
    Integer.parseInt(txtAge.getText(),10),Float.parseFloat(txtWaist.getText()),
    Float.parseFloat(txtHeight.getText()),Float.parseFloat(txtWeight.getText()),
    Integer.parseInt(txtClass.getText(), 10), txtSubClass.getText());

And so here is one of these functions (where I fill up a Student record):

public void addStudentRecord(String tableName, String fName, String midName,
    String lastName, String comment, int age, float waist, float height,
    float weight, int student_class, String subClass, String appointment){

    String sql = "INSERT INTO " + tableName + "(first_name, mid_name,"+
                "last_name, age, class, subclass, gender, doctor_id ,"+
                "diseases, more_info, height, weight, waist, appointment) "+
                "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    try{
    prepSTMT= conn.prepareStatement(sql);
    prepSTMT.setString(1, fName);
    prepSTMT.setString(2, midName);
    prepSTMT.setString(3, lastName);
    prepSTMT.setInt(4, age);
    prepSTMT.setInt(5, student_class);
    prepSTMT.setString(6, subClass);
    prepSTMT.setString(7, "m");
    prepSTMT.setInt(8, 3); // TODO update variable for FOREIGN KEY
    prepSTMT.setString(9, "b"); // TODO update variable
    prepSTMT.setString(10, comment);
    prepSTMT.setFloat(11, height);
    prepSTMT.setFloat(12, weight);
    prepSTMT.setFloat(13, waist);
    prepSTMT.setString(14, appointment);
    prepSTMT.executeUpdate();
    }catch(SQLException e){
    JOptionPane.showMessageDialog(null, e);
    }
}

You can probably tell by the comment where I have inserted the foreign key (with a magic number (3)). I think to replace this with a variable, I will need to have someway to check what is the foreign key of the entry that I entered into the doctor's table. This is what I am confused and can't get my mind around. Do I have to do a query for Id and name of the doctor I entered previously? I need a hint.


问:
Convert Excel File to CSV Then Load to SQL Table Using SSIS
I have a very large excel data to load to SQL table. For small data it works. However, for large data (more than 20 million records) I get the following error.

Excel to CSV : There were errors during task validation. Excel to CSV
  Error: "Excel Source" failed validation and returned validation status
  and returned validation status "VS_ISBROKEN". Excel to CSV: opening a
  rowset for "Table1$" failed. check that the object exists in the
  database. Excel to CSV:Error : SSIS  Error code DTS_E_OLEDBERROR. An
  OLE DB error has occurred .Error code 0x80004005.

答: Usually when I get this error, something is wrong with the destination table. Check the existence of the table and also match of fields between source and destination.</p>


问:
FOSuserbundle login form & SamlBundle SSO login
I'm working on a custom membership website which is based on the Symfony2. This website has two type of the bundles. FOSuserbundle and SamlBundle.

I integrated SamlBundle with FOSuserbundle. Single Sign-On system is working now, but FOSuserbundle login form is not working.

This is my security.yml

```<code>security:

encoders:
    FOS\UserBundle\Model\UserInterface:
      id: app.my_password_encoder

    PDias\SamlBundle\Security\User\SamlUser: plaintext

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:

    fos_userbundle:
        id: fos_user.user_provider.username_email

    backend_samlservice:
        id: saml.backend.fosuser.provider

firewalls:

    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle

            csrf_token_generator: security.csrf.token_manager
            require_previous_session: true
            login_path: /login
            check_path: /login_check
            always_use_default_target_path: false
            default_target_path: /
            use_forward: true
            use_referer: false

        saml:
            provider: backend_samlservice
            direct_entry: false
            login_path: /login-saml
            check_path: /login-check-saml
            default_target_path: /
            always_use_default_target_path: true
        logout:
            path:   /logout
            target: /login
        anonymous: true

    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

        remember_me:
            key:      '%secret%'
            lifetime: 604800 # 1 week
            path:     /
            domain: ~

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/sendemail, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }
    - { path: ^, role: ROLE_USER }

acl:
    connection: default
</code>```

Even if I was not using Single Sign-On, backend_samlservice will be executed.
When I use ID & Password to login to the website, I will be redirected to the login page.

Do I have to add something?

Thanks for your anwsers.

答:
I've fixed this problem.

The point was SimpleSAML_Session. I had to clean up the session like this.

https://simplesamlphp.org/docs/stable/simplesamlphp-sp#section_6

```<code>$session = SimpleSAML_Session::getSessionFromRequest();
$session->cleanup();
</code>```

I added this code on the SamlAuth.php(pdias/saml-bundle/PDias/SamlBundle/Saml). Then it started working.

Body:
I'm working on a custom membership website which is based on the Symfony2. This website has two type of the bundles. FOSuserbundle and SamlBundle.

I integrated SamlBundle with FOSuserbundle. Single Sign-On system is working now, but FOSuserbundle login form is not working.

This is my security.yml

security:

encoders:
    FOS\UserBundle\Model\UserInterface:
      id: app.my_password_encoder

    PDias\SamlBundle\Security\User\SamlUser: plaintext

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN

providers:

    fos_userbundle:
        id: fos_user.user_provider.username_email

    backend_samlservice:
        id: saml.backend.fosuser.provider

firewalls:

    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle

            csrf_token_generator: security.csrf.token_manager
            require_previous_session: true
            login_path: /login
            check_path: /login_check
            always_use_default_target_path: false
            default_target_path: /
            use_forward: true
            use_referer: false

        saml:
            provider: backend_samlservice
            direct_entry: false
            login_path: /login-saml
            check_path: /login-check-saml
            default_target_path: /
            always_use_default_target_path: true
        logout:
            path:   /logout
            target: /login
        anonymous: true

    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

        remember_me:
            key:      '%secret%'
            lifetime: 604800 # 1 week
            path:     /
            domain: ~

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/sendemail, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }
    - { path: ^, role: ROLE_USER }

acl:
    connection: default

Even if I was not using Single Sign-On, backend_samlservice will be executed.
When I use ID & Password to login to the website, I will be redirected to the login page.

Do I have to add something?

Thanks for your anwsers.

Body:
I've fixed this problem.

The point was SimpleSAML_Session. I had to clean up the session like this.

https://simplesamlphp.org/docs/stable/simplesamlphp-sp#section_6

$session = SimpleSAML_Session::getSessionFromRequest();
$session->cleanup();

I added this code on the SamlAuth.php(pdias/saml-bundle/PDias/SamlBundle/Saml). Then it started working.


问:
Updating multiple lines from table using an UPDATE line with select
I have this problem

I would like to update a table using the following SQL sentence.

```<code>update materia_prima
set cantidad = cantidad - ((select cantidad from detalle_producto
                            where codigo_producto=1) * 15)
</code>```

15 is a quantity that I will set with a variable with PHP, it may change.

This is the primary sentence:(which is used in PHP)

```<code>update materia_prima set cantidad=cantidad - ((select cantidad from detalle_producto where codigo_producto=\"$this->codigo_producto\") * \"$this->cantidad\"
</code>```

materia_prima is a inventory table of raw materials

detalle_product is a table that has default quantities with raw materials quantities that are needed to create an specific product

My problem is that using that sentence SQL, it says that it is a multiple select, and I need to update my inventory

Please help

答:
I finally found it

This  answer  is for PHP

```<code>public function DecreaseRW() {
        $sql = "UPDATE materia_prima mp INNER JOIN detalle_producto dp ON mp.id = dp.codigo_materia_prima  SET mp.cantidad = mp.cantidad - ( dp.cantidad * \"$this->cantidad\" )WHERE dp.codigo_producto = \"$this->codigo_producto\"";
        Executor::doit($sql);
    }
</code>```

Body:
I have this problem

I would like to update a table using the following SQL sentence.

update materia_prima
set cantidad = cantidad - ((select cantidad from detalle_producto
                            where codigo_producto=1) * 15)

15 is a quantity that I will set with a variable with PHP, it may change.

This is the primary sentence:(which is used in PHP)

update materia_prima set cantidad=cantidad - ((select cantidad from detalle_producto where codigo_producto=\"$this->codigo_producto\") * \"$this->cantidad\"

materia_prima is a inventory table of raw materials

detalle_product is a table that has default quantities with raw materials quantities that are needed to create an specific product

My problem is that using that sentence SQL, it says that it is a multiple select, and I need to update my inventory

Please help

Body:
I finally found it

This  answer  is for PHP

public function DecreaseRW() {
        $sql = "UPDATE materia_prima mp INNER JOIN detalle_producto dp ON mp.id = dp.codigo_materia_prima  SET mp.cantidad = mp.cantidad - ( dp.cantidad * \"$this->cantidad\" )WHERE dp.codigo_producto = \"$this->codigo_producto\"";
        Executor::doit($sql);
    }


问:
How do I write a route that allows for underscores in ASP.NET MVC?
I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?

You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)

```<code>01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }
</code>```

You implement a controller named HomeController that includes methods with the following
signatures.

```<code>public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)
</code>```

You need to add a route to meet the following requirements:

The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.

User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?

A. Replace line 05 with the following code segment.

```<code>routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );
</code>```

B. Replace line 05 with the following code segment.

```<code>routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );
</code>```

C. At line 04, add the following code segment.

```<code>routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );
</code>```

D. At line 04, add the following code segment.

```<code>routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );
</code>```

答:
Replacing the route would make Details not work, since Id is not mapped any more.

C is the correct one

ContentLicense: CC BY-SA 2.5

Body:
I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?

You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)

01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }

You implement a controller named HomeController that includes methods with the following
signatures.

public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)

You need to add a route to meet the following requirements:

The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.

User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?

A. Replace line 05 with the following code segment.

routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );

B. Replace line 05 with the following code segment.

routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );

C. At line 04, add the following code segment.

routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );

D. At line 04, add the following code segment.

routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );


问:
Rails has_one relation not working, but only inside Heroku worker
`We have the following has_one association:

```<code>class InspectionSettings < ApplicationRecord
  has_one :inspection_evaluation_lights, dependent: :destroy
end

class InspectionEvaluationLights < ApplicationRecord
  belongs_to :inspection_settings
end
</code>```

Both model names are not inflected, which is noted in inflections.rb.

It all works as expected, ActiveRecord methods like InspectionSettings.find(xy).inspection_evaluation_lights return the object one would expect.

Except when run inside a Heroku worker instance, where it throws an undefined method inspection_evaluation_lights for InspectionSettings classerror.

I've tried all kinds of workarounds like specifying a class_name or inverse_of for both relations, but to no avail.

Strangest bug I've seen in a while.

答:
Ok, the problem was the inclusion of an ActiveSupport::Concern in the `InspectionSettings' model.

Why this problem only occurs when the ActiveRecord method is called inside a Heroku worker is still beyond me.

Body:
`We have the following has_one association:

class InspectionSettings < ApplicationRecord
  has_one :inspection_evaluation_lights, dependent: :destroy
end

class InspectionEvaluationLights < ApplicationRecord
  belongs_to :inspection_settings
end

Both model names are not inflected, which is noted in inflections.rb.

It all works as expected, ActiveRecord methods like InspectionSettings.find(xy).inspection_evaluation_lights return the object one would expect.

Except when run inside a Heroku worker instance, where it throws an undefined method inspection_evaluation_lights for InspectionSettings classerror.

I've tried all kinds of workarounds like specifying a class_name or inverse_of for both relations, but to no avail.

Strangest bug I've seen in a while.


问:
Load page into webview swift 2 from java class
I am developing an App for the iPhone using Xwebview which enables me to download a page then interact with the javascript on the downloaded page.
All works, but if the internet connection drops, a default local page is loaded, informing the user there is no internet connection. The page displays a retry button that, when pressed checks, the internet connection: if the connection is made the app tries to connect again to the external page and load the page into the webview.
I cannot get this to work: the code downloads the page (I can see this in my session data) but I can't get that page to load back into the webview.

```<code>override func viewDidLoad() {
        super.viewDidLoad()
              login()
        }

    func login()
    {
        // *********** Get stored hashkey **************
        let hashcode = getHashcode()

        // ********** Check network connection *********
        let netConnection = Connection.isConnectedToNetwork()
        print("net connection: ", netConnection)

        if netConnection == true
        {
            if hashcode != "00000"
            {

                print("local key found", hashcode)
                // We dont have local key
                let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
                //webview.loadRequest(NSURLRequest(URL: NSURL(string: "about:blank")!))
                view.addSubview(webview)
                webview.loadPlugin(jsapi(), namespace: "jsapi")

                let url:NSURL = NSURL(string: serverLocation + onlineLoginApi)!
                let session = NSURLSession.sharedSession()
                let request = NSMutableURLRequest(URL: url)

                request.HTTPMethod = "POST"
                request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

                let paramString = "/?username=username&password=password"
                request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

                let task = session.downloadTaskWithRequest(request) {
                    (
                    let location, let response, let error) in

                    guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
                        print("error")
                        return
                    }

                    let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

                    guard let _:NSString = urlContents else {
                        print("error")
                        return
                    }

                    print(urlContents)

                }

                task.resume()

                // you must tell webview to load response
                webview.loadRequest(request)

            }
            else{

                print("local key found", hashcode)
                // ********* Found local key go to site pass key over ************

                let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
                view.addSubview(webview)
                webview.loadPlugin(jsapi(), namespace: "jsapi")

                let req = NSMutableURLRequest(URL: NSURL(string:serverLocation + onlineLoginApi + "?hashcode=\(hashcode)")!)
                req.HTTPMethod = "POST"
                req.HTTPBody = "/?hashcode=\(hashcode)".dataUsingEncoding(NSUTF8StringEncoding)
                NSURLSession.sharedSession().dataTaskWithRequest(req)
                { data, response, error in
                    if error != nil
                    {
                        //Your HTTP request failed.
                        print(error!.localizedDescription)
                    } else {
                        //Your HTTP request succeeded
                        print(String(data: data!, encoding: NSUTF8StringEncoding))
                    }
                    }.resume()
                webview.loadRequest(req)

            }

        }
        else{

            // No connection to internet

            let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
            view.addSubview(webview)
            webview.loadPlugin(jsapi(), namespace: "jsapi")

            let root = NSBundle.mainBundle().resourceURL!
            let url = root.URLByAppendingPathComponent("/www/error-no-connection.html")
            webview.loadFileURL(url, allowingReadAccessToURL: root)
            print("No internet connection")

            }
    }
class jsapi: NSObject {

        // Reconnect button on interface
        func retryConnection()
        {
            print("Reconnect clicked")
            dispatch_async(dispatch_get_main_queue())
            {
            let netConnections = Connection.isConnectedToNetwork()

                if netConnections == true {
                let netalert = UIAlertView(title: "Internet on line", message: nil, delegate: nil, cancelButtonTitle: "OK")
                netalert.show()

                let url = self.serverLocation + self.onlineLoginApi
                let hashcode = ViewController().getHashcode()

                if(hashcode != "00000") {
                    let url = url + "?hashcode=\(hashcode)"
                    print("url: ", url)
                }

                   ViewController().loadPagelive(url)

                }

            else{
                let netalert = UIAlertView(title: "Internet off line", message: nil, delegate: nil, cancelButtonTitle: "OK")
                netalert.show()
                }
            }
            print("retryConnect end")
            }
        }
</code>```

答:
You try to perform the loadPagelive(url) on a new instance of your ViewController, not on the current one shown on the screen, that's why you don't see any update.

You should create a delegate or a completion block in order to execute code on you ViewController instance loaded on the screen: every time you do ViewController(), a new object is created.

You can try using the delegate pattern, which is simple to achieve. I will try to focus on the important part and create something that can be used with your existing code:

```<code>class ViewController: UIViewController {
    let jsapi = jsapi() // You can use only 1 instance

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set your ViewController as a delegate, so the jsapi can update it
        jsapi.viewController = self
        login()
    }

    func loadPagelive(_ url: URL) {
        // Load page, probably you already have it
    }
}

class jsapi: NSObject {
    weak var viewController: ViewController?

    func retryConnection() {
       // We check if the delegate is set, otherwise it won't work
       guard viewController = viewController else {
           print("Error: delegate not available")
       }

       [... your code ...]

       // We call the original (and hopefully unique) instance of ViewController
       viewController.loadPagelive(url)
    }
}
</code>```

Body:
I am developing an App for the iPhone using Xwebview which enables me to download a page then interact with the javascript on the downloaded page.
All works, but if the internet connection drops, a default local page is loaded, informing the user there is no internet connection. The page displays a retry button that, when pressed checks, the internet connection: if the connection is made the app tries to connect again to the external page and load the page into the webview.
I cannot get this to work: the code downloads the page (I can see this in my session data) but I can't get that page to load back into the webview.

override func viewDidLoad() {
        super.viewDidLoad()
              login()
        }

    func login()
    {
        // *********** Get stored hashkey **************
        let hashcode = getHashcode()

        // ********** Check network connection *********
        let netConnection = Connection.isConnectedToNetwork()
        print("net connection: ", netConnection)

        if netConnection == true
        {
            if hashcode != "00000"
            {

                print("local key found", hashcode)
                // We dont have local key
                let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
                //webview.loadRequest(NSURLRequest(URL: NSURL(string: "about:blank")!))
                view.addSubview(webview)
                webview.loadPlugin(jsapi(), namespace: "jsapi")

                let url:NSURL = NSURL(string: serverLocation + onlineLoginApi)!
                let session = NSURLSession.sharedSession()
                let request = NSMutableURLRequest(URL: url)

                request.HTTPMethod = "POST"
                request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

                let paramString = "/?username=username&password=password"
                request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

                let task = session.downloadTaskWithRequest(request) {
                    (
                    let location, let response, let error) in

                    guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
                        print("error")
                        return
                    }

                    let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

                    guard let _:NSString = urlContents else {
                        print("error")
                        return
                    }

                    print(urlContents)

                }

                task.resume()

                // you must tell webview to load response
                webview.loadRequest(request)

            }
            else{

                print("local key found", hashcode)
                // ********* Found local key go to site pass key over ************

                let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
                view.addSubview(webview)
                webview.loadPlugin(jsapi(), namespace: "jsapi")

                let req = NSMutableURLRequest(URL: NSURL(string:serverLocation + onlineLoginApi + "?hashcode=\(hashcode)")!)
                req.HTTPMethod = "POST"
                req.HTTPBody = "/?hashcode=\(hashcode)".dataUsingEncoding(NSUTF8StringEncoding)
                NSURLSession.sharedSession().dataTaskWithRequest(req)
                { data, response, error in
                    if error != nil
                    {
                        //Your HTTP request failed.
                        print(error!.localizedDescription)
                    } else {
                        //Your HTTP request succeeded
                        print(String(data: data!, encoding: NSUTF8StringEncoding))
                    }
                    }.resume()
                webview.loadRequest(req)

            }

        }
        else{

            // No connection to internet

            let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
            view.addSubview(webview)
            webview.loadPlugin(jsapi(), namespace: "jsapi")

            let root = NSBundle.mainBundle().resourceURL!
            let url = root.URLByAppendingPathComponent("/www/error-no-connection.html")
            webview.loadFileURL(url, allowingReadAccessToURL: root)
            print("No internet connection")

            }
    }
class jsapi: NSObject {

        // Reconnect button on interface
        func retryConnection()
        {
            print("Reconnect clicked")
            dispatch_async(dispatch_get_main_queue())
            {
            let netConnections = Connection.isConnectedToNetwork()

                if netConnections == true {
                let netalert = UIAlertView(title: "Internet on line", message: nil, delegate: nil, cancelButtonTitle: "OK")
                netalert.show()

                let url = self.serverLocation + self.onlineLoginApi
                let hashcode = ViewController().getHashcode()

                if(hashcode != "00000") {
                    let url = url + "?hashcode=\(hashcode)"
                    print("url: ", url)
                }

                   ViewController().loadPagelive(url)

                }

            else{
                let netalert = UIAlertView(title: "Internet off line", message: nil, delegate: nil, cancelButtonTitle: "OK")
                netalert.show()
                }
            }
            print("retryConnect end")
            }
        }

Body:
You try to perform the loadPagelive(url) on a new instance of your ViewController, not on the current one shown on the screen, that's why you don't see any update.

You should create a delegate or a completion block in order to execute code on you ViewController instance loaded on the screen: every time you do ViewController(), a new object is created.

You can try using the delegate pattern, which is simple to achieve. I will try to focus on the important part and create something that can be used with your existing code:

class ViewController: UIViewController {
    let jsapi = jsapi() // You can use only 1 instance

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set your ViewController as a delegate, so the jsapi can update it
        jsapi.viewController = self
        login()
    }

    func loadPagelive(_ url: URL) {
        // Load page, probably you already have it
    }
}

class jsapi: NSObject {
    weak var viewController: ViewController?

    func retryConnection() {
       // We check if the delegate is set, otherwise it won't work
       guard viewController = viewController else {
           print("Error: delegate not available")
       }

       [... your code ...]

       // We call the original (and hopefully unique) instance of ViewController
       viewController.loadPagelive(url)
    }
}


问:
LC-3 Instruction Understanding
Hey Stackoverflow I was going over some example code our professor has left us to study with, and I've had some problems understanding what some of the codes mean and it doesnt help that some of his comments are vague. the first is R3,R1,0; check for end of line, the second thing I dont get is really the logic behind the beginning of the placeolnul, and lastly the .fill values for negeol which seem oddly specific but i have no idea why. if you could really help me with those issues it would really help me understand the code alot better. </p>

```<code> .orig x3000
    getstring:
     lea r0,prompt ;get string prompt
     puts
     ld r1,negeol ;to test end of line
     lea r2,rdbuff ;prep to read string
    rdloop:
     getc ;get string char
     out
     str r0,r2,0 ;store it
     add r3,r1,r0 ;check for end of line
     brz placeeolnul ;if so process
     add r2,r2,1 ;ready for next char
     br rdloop ;get it
    placeeolnul:
     and r0,r0,0 ;overwrite eol with
     str r0,r2,0 ;nul

     lea r1,rdbuff ;get address for len
     jsr strlen ;get length
     add r0,r0,0 ;if 0
     brz quit ;then prog finished
     trap xfc ;print length
     lea r0,colon ;print colon
     puts
     lea r0,eol ;print lf
     puts
     br getstring ;go again
    quit
     halt
    prompt: .stringz "Enter a string:"
    eol: .fill x000d ; or x000a
     .fill x0000
    negeol: .fill xfff3 ; or xfff6
    colon: .fill x003a
    rdbuff .blkw 80

    ; length subroutine
    strlen:
     and r0,r0,0 ;counter for length
     st r2,saveX2 ;save regs used
     st r3,saveX3
     add r2,r1,0 ;copy of string addr
    cloop:
     ldr r3,r2,0 ;get char
     brz exit ;check for nul
     add r0,r0,1 ;incr counter
     add r2,r2,1 ;go to next char
     br cloop ;process it
    exit:
     ld r2,saveX2 ;restore used regs
     ld r3,saveX3
     ret
    saveX2: .blkw 1
    saveX3: .blkw 1
    .end
</code>```

答:
In regards to this:

```<code>add r3,r1,r0 ;check for end of line
</code>```

Here he is setting up for the subsequent "brz" to branch on zero.

So we are adding the contents of registers r1 and r0 and putting them in r3, so that if r3 is zero, we will branch in the next line:

```<code> brz placeeolnul ;if so process
</code>```

Remember that r1 is already pre-loaded with a value based on this code:

```<code>ld r1,negeol ;to test end of line
</code>```

which has loaded r1 with the value at the tag negeol per this code:

```<code>negeol
    .fill xfff3 ; or xfff6
</code>```

So this is just a quick way to detect if an EOL character has been found by adding the compliment of the EOL character, which presumably here is xfff3.

Regarding the brz statement and the logic for it (your 2nd question):

```<code>brz placeeolnul ;if so process
</code>```

As mentioned, we are branching here if the add is zero.  If we do not branch (meaning we did not find a EOL character), then we will continue, but that continuation will essentially loop back to rdloop tag:

```<code> add r2,r2,#1 ;ready for next char
 br rdloop ;get it
</code>```

If we DO jump via the brz line, that means we got the entire string, and we are ready to process it.... so jumping to placeeolnul  just puts us into the code where we can process the string:

```<code> and r0,r0,#0 ;overwrite eol with
 str r0,r2,#0 ;nul
 .... etc...
</code>```

Not sure if you have questions with this part of the code as well.

Hope this helps.

Jeff

Title: LC-3 Instruction Understanding

Body:
Hey Stackoverflow I was going over some example code our professor has left us to study with, and I've had some problems understanding what some of the codes mean and it doesnt help that some of his comments are vague. the first is R3,R1,0; check for end of line, the second thing I dont get is really the logic behind the beginning of the placeolnul, and lastly the .fill values for negeol which seem oddly specific but i have no idea why. if you could really help me with those issues it would really help me understand the code alot better.

 .orig x3000
    getstring:
     lea r0,prompt ;get string prompt
     puts
     ld r1,negeol ;to test end of line
     lea r2,rdbuff ;prep to read string
    rdloop:
     getc ;get string char
     out
     str r0,r2,0 ;store it
     add r3,r1,r0 ;check for end of line
     brz placeeolnul ;if so process
     add r2,r2,1 ;ready for next char
     br rdloop ;get it
    placeeolnul:
     and r0,r0,0 ;overwrite eol with
     str r0,r2,0 ;nul

     lea r1,rdbuff ;get address for len
     jsr strlen ;get length
     add r0,r0,0 ;if 0
     brz quit ;then prog finished
     trap xfc ;print length
     lea r0,colon ;print colon
     puts
     lea r0,eol ;print lf
     puts
     br getstring ;go again
    quit
     halt
    prompt: .stringz "Enter a string:"
    eol: .fill x000d ; or x000a
     .fill x0000
    negeol: .fill xfff3 ; or xfff6
    colon: .fill x003a
    rdbuff .blkw 80

    ; length subroutine
    strlen:
     and r0,r0,0 ;counter for length
     st r2,saveX2 ;save regs used
     st r3,saveX3
     add r2,r1,0 ;copy of string addr
    cloop:
     ldr r3,r2,0 ;get char
     brz exit ;check for nul
     add r0,r0,1 ;incr counter
     add r2,r2,1 ;go to next char
     br cloop ;process it
    exit:
     ld r2,saveX2 ;restore used regs
     ld r3,saveX3
     ret
    saveX2: .blkw 1
    saveX3: .blkw 1
    .end

Body:
In regards to this:

add r3,r1,r0 ;check for end of line

Here he is setting up for the subsequent "brz" to branch on zero.

So we are adding the contents of registers r1 and r0 and putting them in r3, so that if r3 is zero, we will branch in the next line:

 brz placeeolnul ;if so process

Remember that r1 is already pre-loaded with a value based on this code:

ld r1,negeol ;to test end of line

which has loaded r1 with the value at the tag negeol per this code:

negeol
    .fill xfff3 ; or xfff6

So this is just a quick way to detect if an EOL character has been found by adding the compliment of the EOL character, which presumably here is xfff3.

Regarding the brz statement and the logic for it (your 2nd question):

brz placeeolnul ;if so process

As mentioned, we are branching here if the add is zero.  If we do not branch (meaning we did not find a EOL character), then we will continue, but that continuation will essentially loop back to rdloop tag:

 add r2,r2,#1 ;ready for next char
 br rdloop ;get it

If we DO jump via the brz line, that means we got the entire string, and we are ready to process it.... so jumping to placeeolnul  just puts us into the code where we can process the string:

 and r0,r0,#0 ;overwrite eol with
 str r0,r2,#0 ;nul
 .... etc...

Not sure if you have questions with this part of the code as well.

Hope this helps.

Jeff


问:
jackson deserialize string to a parameterized map
I have a json string in the following structure:

```<code>{
    "1": { ... },
    "2": { ... },
    "3": { ... }
}
</code>```

where 1, 2 and 3 are identifiers.

I want to deserialize this string and cast it to the following type - Map<Integer, List<MyCustomPojo>>

The thing is that each value { ... } has its own structure, but I need to parse them all and cast to a common structure - MyCustomPojo.

I can do it by implementing a custom deserializer:

```<code>public class CustomMapDeserializer extends JsonDeserializer<Map<Integer, List<MyCustomPojo>>> {

    @Override
    public Map<Integer, List<MyCustomPojo>> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        JsonNode root = jsonParser.getCodec().readTree(jsonParser);

    // parse JsonNode and return  Map<Integer, List<MyCustomPojo>>
}
</code>```

Now I need to add this deserializer to a module and then register it with an object mapper.

```<code>SimpleModule module = new SimpleModule();
module.addDeserializer(Map.class, new CustomMapDeserializer()); // can’t specify type for map
objectMapper.registerModule(module);
</code>```

The problem is that now it will be applied to all Map classes in my application. I want it to apply only to parameterized map - Map<Integer, List<MyCustomPojo>>.

Is it possible to do it?

答: Simplest solution should be to create a new class which inherit from Map and use it when you add deserializer</p>

Body:
I have a json string in the following structure:

{
    "1": { ... },
    "2": { ... },
    "3": { ... }
}

where 1, 2 and 3 are identifiers.

I want to deserialize this string and cast it to the following type - Map<Integer, List<MyCustomPojo>>

The thing is that each value { ... } has its own structure, but I need to parse them all and cast to a common structure - MyCustomPojo.

I can do it by implementing a custom deserializer:

public class CustomMapDeserializer extends JsonDeserializer<Map<Integer, List<MyCustomPojo>>> {

    @Override
    public Map<Integer, List<MyCustomPojo>> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        JsonNode root = jsonParser.getCodec().readTree(jsonParser);

    // parse JsonNode and return  Map<Integer, List<MyCustomPojo>>
}

Now I need to add this deserializer to a module and then register it with an object mapper.

SimpleModule module = new SimpleModule();
module.addDeserializer(Map.class, new CustomMapDeserializer()); // can’t specify type for map
objectMapper.registerModule(module);

The problem is that now it will be applied to all Map classes in my application. I want it to apply only to parameterized map - Map<Integer, List<MyCustomPojo>>.

Is it possible to do it?


问:
Replace multiple words in string
I have multiple words I want to replace with values, whats the best way to do this?

Example:
This is what I have done but it feels and looks so wrong

```<code>string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;
</code>```

There has to be a better way?

thanks

答:
If you're planning on having a dynamic number of replacements, which could change at any time, and you want to make it a bit cleaner, you could always do something like this:</p>

```<code>// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());

// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
   s = s.Replace(replacement.Key, replacement.Value);
}
</code>```

Title: Replace multiple words in string

Body:
I have multiple words I want to replace with values, whats the best way to do this?

Example:
This is what I have done but it feels and looks so wrong

string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;

There has to be a better way?

thanks

Body:
If you're planning on having a dynamic number of replacements, which could change at any time, and you want to make it a bit cleaner, you could always do something like this:

// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());

// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
   s = s.Replace(replacement.Key, replacement.Value);
}


问:
choco meteor install - customize / different installation location
Hi I am trying to install meteor with choco using

```<code>choco install meteor
</code>```

And I understand it will install in C:\Users\yourUserName\AppData\Local\.meteor\.

Is there a way to install directly to different folder. Or once installed is it good to move to different folder  ?

Thanks in advance !

答:
As for now meteor isn't giving an option to install on a different location. In these two issue (a, b) you can read more.

This is the bottom line from abernix:

As to your request, while using a global install shared by multiple users might seem nice in some aspects, it would cause permissions issues for many users who might not be able to install things outside their home directory. Meteor has no global configuration which would allow the location of the .meteor directory to be set, but you are welcome to move the Meteor installation wherever you would like, but currently, the .meteor directory does need to be in the home directory, and we currently have no intentions to re-work that, mainly as we start make considerations for a full transition to npm, which would solve this.

If you find something else I would like to know as well.

Body:
Hi I am trying to install meteor with choco using

choco install meteor

And I understand it will install in C:\Users\yourUserName\AppData\Local\.meteor\.

Is there a way to install directly to different folder. Or once installed is it good to move to different folder  ?

Thanks in advance !


问:
Unable to observe "Publish" menu item in VS2017 for .Net Core app
I'm unable to observe the "Publish" feature in VS2017 for my .Net Core web app.

My goal is to publish my web services to a remote host that runs IIS.

How do I get the Publish menu item to show up on the context menu?

答:
To deploy ASP.NET Core Applications to an IIS instance,

you first need to download and install ASPNETCoreModule IIS Handler on the Server
https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.0-download.md#windows-server-hosting

This is what allows your IIS launch and manage your .NET Core App

When that is done, you need to "publish" your application. So from the Web Application directory, you run

dotnet publish -o "C:\Temp"

you can also enter any other Directory. Just copy the contents to the server and it should work

NOTE:

For older versions of .NET Core (1.x) with F#, you need to verify that you have the IISHandler middleware configured you'd do something like app.UseIISIntegration()

In some few cases, It also did not generate web.config files in those cases, you need to manually add them. Below is a sample of the web.config file

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>
</code>```

Body:
To deploy ASP.NET Core Applications to an IIS instance,

you first need to download and install ASPNETCoreModule IIS Handler on the Server
https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.0-download.md#windows-server-hosting

This is what allows your IIS launch and manage your .NET Core App

When that is done, you need to "publish" your application. So from the Web Application directory, you run

dotnet publish -o "C:\Temp"

you can also enter any other Directory. Just copy the contents to the server and it should work

NOTE:

For older versions of .NET Core (1.x) with F#, you need to verify that you have the IISHandler middleware configured you'd do something like app.UseIISIntegration()

In some few cases, It also did not generate web.config files in those cases, you need to manually add them. Below is a sample of the web.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>


问:
How to pass string to a makefile from shell script?
I tried in the following way

In shell script :

```<code>Var='abc xyz' make one myvar=$Var
</code>```

But when it goes into makefile it is just showing myvar as abc but it is not taking abc xyz as my input

答:
Is there a reason you can't just pass it through the environment?  E.g.,

```<code>.PHONY: all
all: DEBUG

.PHONY: DEBUG
DEBUG:
        @echo $(test)
</code>```

yields

```<code>$ test="this is a test" make DEBUG
this is a test
</code>```

Body:
I tried in the following way

In shell script :

Var='abc xyz' make one myvar=$Var

But when it goes into makefile it is just showing myvar as abc but it is not taking abc xyz as my input

Body:
Is there a reason you can't just pass it through the environment?  E.g.,

.PHONY: all
all: DEBUG

.PHONY: DEBUG
DEBUG:
        @echo $(test)

yields

$ test="this is a test" make DEBUG
this is a test


问:
Elasticsearch query on apostrophes
I am querying on elasticsearch the query is apples. In our index data, the text is presented like apple's. If I search like apples I got no results. If I searched for apple's we got results. But in my concern, if I search with apples also I need same results for apple's query. Is there any way to handle these type of cases.

答:
You can do this with a char_filter set in the following way:

```<code>PUT my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "keyword",
          "char_filter": [
            "my_char_filter"
          ]
        }
    },
    "char_filter": {
      "my_char_filter": {
        "type": "mapping",
        "mappings": [
          "' => "
        ]
       }
      }
    }
  }
}

POST my_index/_analyze
{
 "analyzer": "my_analyzer",
 "text": "apple's"
}
</code>```

This will result in:

```<code>{
  "tokens": [
  {
    "token": "apples",
    "start_offset": 0,
    "end_offset": 7,
    "type": "word",
    "position": 0
  }
 ]
}
</code>```

You are removing apostrophe from index and you can search successfully for both apples and apple's

Title: Elasticsearch query on apostrophes

Body:
You can do this with a char_filter set in the following way:

PUT my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "keyword",
          "char_filter": [
            "my_char_filter"
          ]
        }
    },
    "char_filter": {
      "my_char_filter": {
        "type": "mapping",
        "mappings": [
          "' => "
        ]
       }
      }
    }
  }
}

POST my_index/_analyze
{
 "analyzer": "my_analyzer",
 "text": "apple's"
}

This will result in:

{
  "tokens": [
  {
    "token": "apples",
    "start_offset": 0,
    "end_offset": 7,
    "type": "word",
    "position": 0
  }
 ]
}

You are removing apostrophe from index and you can search successfully for both apples and apple's


问:
Do users need to fulfill any prerequisites to run C++17 software?
My team and I are currently developing a piece of software that is built on C++14 specs. We are considering adding some C++17 features (primarily std::variants) in our code, but my supervisor was unsure if we could simply put these in our code, build with an appropriate compiler and then ship it.

From what I know, this should not make any difference if we pre-compile our application for our target platforms and make them available as executables, but I have never actually had to deal with deployment of software to customers yet, so I am unsure if I am overlooking anything here (like if we would have to also supply according C++ redistributables for Windows or so).

As background info: our software is heavily Qt-based and should thus be deployable to all major desktop operating systems. We're mainly working in a Windows environment, and for most testing purposes we are compiling with MSVC2017 at the moment.

We technically also plan to release an SDK/library to facilitate interfacing with the network part of our application, which may also benefit from C++17 features. I would assume that developers willing to use this SDK would then be forced to use a C++17-compliant build environment, even if the C++17 features are pretty much encapsulated in the library and not exposed in the headers - is that correct?

答:
The answer is (as usual) "it depends."

If the C++17 features being used are built entirely from templates, and C++17 types/features are not exposed in your SDK header, then this absolutely should work fine, since the templates would be instantiated and included in your library's native code by your compiler.

If the C++17 features depend on some runtime library support, but are not exposed in your SDK, then you would just need to ship that runtime library or otherwise make it available.

Regardless of whether you use C++17 features, your SDK users should use exactly the same C++ environment (including the version, if possible) that you use, because there is no guarantee of ABI-compatibility between C++ versions, nor between different versions of the same compiler.  If you use MSVC++2017, your SDK users must also use either MSVC++2017 or another environment that is explicitly documented to be compatible with the MSVC++2017 ABI.  (So instead of asking if this will work, you should be asking what version of MSVC++ it is reasonable to require your SDK users to use, and that's a question I cannot answer for you.)

In all cases, end users who are not intending to use the SDK should be fine as long as you ship the required runtime libraries, which you are almost certainly already doing (though you may need to change which runtime library you ship).


问:
Powershell Scheduled Task At Startup Repeating
I'm trying to create a Scheduled Task with the following Trigger:

 - Startup

 - Run every 5 minutes

 - Run indefinitely

In the GUI I can do this easily by selecting:

 - Begin the task: at startup

And in the Advanced tab:

 - Repeat task every: 5 minutes

 - For a duration of: indefinitely

But I'm having trouble doing it with Powershell.

My troubled code:

$repeat = (New-TimeSpan -Minutes 5)

$duration = ([timeSpan]::maxvalue)

$trigger = New-ScheduledTaskTrigger -AtStartup -RepetitionInterval $repeat -RepetitionDuration $duration

It won't take the RepetitionInterval and RepetitionDuration parameters. But I need that functionality.
How could I accomplish my goal?

答:
New-ScheduledTaskTrigger uses parameter sets.  When you specify that you want the scheduled task to start up "at logon" you are restricting yourself to the following parameter set:

```<code>Parameter Set: AtStartup
New-ScheduledTaskTrigger [-AtStartup] [-RandomDelay <TimeSpan> ] [ <CommonParameters>]
</code>```

What may be more beneficial is if you use your "at startup" scheduled task to register a new scheduled task to run every five minutes using the "once" parameter set:

```<code>Parameter Set: Once
New-ScheduledTaskTrigger [-Once] -At <DateTime> [-RandomDelay <TimeSpan> ] [-RepetitionDuration <TimeSpan> ] [-RepetitionInterval <TimeSpan> ] [ <CommonParameters>]
</code>```

Your Scheduled Task Trigger should successfully be assigned once you are using the correct parameter set.

Body:
New-ScheduledTaskTrigger uses parameter sets.  When you specify that you want the scheduled task to start up "at logon" you are restricting yourself to the following parameter set:

Parameter Set: AtStartup
New-ScheduledTaskTrigger [-AtStartup] [-RandomDelay <TimeSpan> ] [ <CommonParameters>]

What may be more beneficial is if you use your "at startup" scheduled task to register a new scheduled task to run every five minutes using the "once" parameter set:

Parameter Set: Once
New-ScheduledTaskTrigger [-Once] -At <DateTime> [-RandomDelay <TimeSpan> ] [-RepetitionDuration <TimeSpan> ] [-RepetitionInterval <TimeSpan> ] [ <CommonParameters>]

Your Scheduled Task Trigger should successfully be assigned once you are using the correct parameter set.


问:
ProgressDialog not showing/only showing after asyncTask
i'm trying to add a indeterminate progressDialog to my UI once i click a list element that calls a AsyncTask, but unfortunately, if I call the dialog on the onPreExecute like this:

```<code>@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog.setProgressStyle(R.style.AppTheme_Dark_Dialog);
    dialog.setIndeterminate(true);
    dialog.setMessage(activity.getString(R.string.Buscando));
    dialog.show();
}
</code>```

Obs: Worth noting that the Async is not a subClass of the Activity Class, i'm passing the activity as a parameter to the constructor.

and

```<code>@Override
protected void onPostExecute(BuscaPendentesFechamento buscaPendentesFechamento) {
    super.onPostExecute(buscaPendentesFechamento);
    if(dialog.isShowing())
        dialog.dismiss();
}
</code>```

the dialog simply doesn't show at all, although it is created and called(alredy checked, the activity instance is correct)

and if I set the dialog on the activity itself, like:

```<code>final ProgressDialog progressDialog = new ProgressDialog(RegistraPeso.this, R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage(getString(R.string.Buscando));
    progressDialog.show();
    BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
    response = exportProjectRequisition.execute(nomeEquip,RegistraPeso.this);
    progressDialog.dismiss();
</code>```

the Dialog shows on the Ui, but only after the AsyncTask alredy performed, and not before it is called, and according to the code, it should be showing before the Async even gets created.

What can I do? What am I doing wrong? Please help.

Edit: Added where the Dialog is created:

```<code>private ProgressDialog dialog;
private RegistraPeso activity;
BuscaPendentesFechamento(RegistraPeso activity) {
    this.dialog = new ProgressDialog(activity);
    this.activity = activity;
}
</code>```

Edit: Added the doInBackground:

```<code>    @Override
protected BuscaPendentesFechamento doInBackground(String... params) {
    ArrayList<UmData> jsonArrayResponse = JSONParser.makeHttpRequestArray(
            Constants.URL_PENDENTES_FECHAMENTO,
            Constants.METHOD_POST, requisition.writeJSON(params[0]),
            requisition.getContext());
    if(jsonArrayResponse!=null)
    requisition.setJsonArrayResponse(jsonArrayResponse);
    else {
        UmData umData = new UmData();
        umData.setItemUm("Server not responding");
        jsonArrayResponse = new ArrayList<>();
        jsonArrayResponse.add(umData);
        requisition.setJsonArrayResponse(jsonArrayResponse);
    }
    return requisition;
}
</code>```

答:
OP here, the problem was solved by changing the code based on [this][1]

[1]: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? post here, sent to me by @MikeM, The problem was that I was getting the response using the .get() from the AsyncTask, and it was transforming the Async into a Syncronous Task.
Thanks for the support Mike!

Body:
i'm trying to add a indeterminate progressDialog to my UI once i click a list element that calls a AsyncTask, but unfortunately, if I call the dialog on the onPreExecute like this:

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog.setProgressStyle(R.style.AppTheme_Dark_Dialog);
    dialog.setIndeterminate(true);
    dialog.setMessage(activity.getString(R.string.Buscando));
    dialog.show();
}

Obs: Worth noting that the Async is not a subClass of the Activity Class, i'm passing the activity as a parameter to the constructor.

and

@Override
protected void onPostExecute(BuscaPendentesFechamento buscaPendentesFechamento) {
    super.onPostExecute(buscaPendentesFechamento);
    if(dialog.isShowing())
        dialog.dismiss();
}

the dialog simply doesn't show at all, although it is created and called(alredy checked, the activity instance is correct)

and if I set the dialog on the activity itself, like:

final ProgressDialog progressDialog = new ProgressDialog(RegistraPeso.this, R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage(getString(R.string.Buscando));
    progressDialog.show();
    BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
    response = exportProjectRequisition.execute(nomeEquip,RegistraPeso.this);
    progressDialog.dismiss();

the Dialog shows on the Ui, but only after the AsyncTask alredy performed, and not before it is called, and according to the code, it should be showing before the Async even gets created.

What can I do? What am I doing wrong? Please help.

Edit: Added where the Dialog is created:

private ProgressDialog dialog;
private RegistraPeso activity;
BuscaPendentesFechamento(RegistraPeso activity) {
    this.dialog = new ProgressDialog(activity);
    this.activity = activity;
}

Edit: Added the doInBackground:

    @Override
protected BuscaPendentesFechamento doInBackground(String... params) {
    ArrayList<UmData> jsonArrayResponse = JSONParser.makeHttpRequestArray(
            Constants.URL_PENDENTES_FECHAMENTO,
            Constants.METHOD_POST, requisition.writeJSON(params[0]),
            requisition.getContext());
    if(jsonArrayResponse!=null)
    requisition.setJsonArrayResponse(jsonArrayResponse);
    else {
        UmData umData = new UmData();
        umData.setItemUm("Server not responding");
        jsonArrayResponse = new ArrayList<>();
        jsonArrayResponse.add(umData);
        requisition.setJsonArrayResponse(jsonArrayResponse);
    }
    return requisition;
}


问:
Woocommerce custom function - Add to cart
We had been using a custom function in our theme.

```<code>    add_shortcode('add_to_cart_button', 'add_to_cart_func');

    function add_to_cart_func($atts) {

      $str = '<span class="new_product_header"><span class="button single_add_to_cart_button" onclick="jQuery(\'.single_add_to_cart_button \').click()">ADD TO CART</span></span>';

      return $str;

    }
</code>```

Worked fine until last WP update, now when you click the button, it does an infinite loop of adding the product to the cart over and over.

Any ideas on why the infinite loop  or a way to stop it?

答:
There is a unique thing in your code on line

```<code>$str = '<span class="new_product_header"><span class="button single_add_to_cart_button" onclick="jQuery(\'.single_add_to_cart_button \').click()">ADD TO CART</span></span>';
</code>```

You have attached click event to span having class .single_add_to_cart_button and on click event your trying to run following code same element.

```<code>jQuery('.single_add_to_cart_button').click();
</code>```

So basically when your event fire it keep firing event.

Just remove

```<code>onclick="jQuery(\'.single_add_to_cart_button \').click()"
</code>```

And all will be fine.

Body:
We had been using a custom function in our theme.

    add_shortcode('add_to_cart_button', 'add_to_cart_func');

    function add_to_cart_func($atts) {

      $str = 'ADD TO CART';

      return $str;

    }

Worked fine until last WP update, now when you click the button, it does an infinite loop of adding the product to the cart over and over.

Any ideas on why the infinite loop  or a way to stop it?

Body:
There is a unique thing in your code on line

$str = '<span class="new_product_header"><span class="button single_add_to_cart_button" onclick="jQuery(\'.single_add_to_cart_button \').click()">ADD TO CART</span></span>';

You have attached click event to span having class .single_add_to_cart_button and on click event your trying to run following code same element.

jQuery('.single_add_to_cart_button').click();

So basically when your event fire it keep firing event.

Just remove

onclick="jQuery(\'.single_add_to_cart_button \').click()"

And all will be fine.


问:
Spring Mongodb: configure documents to use specific dbs?
I have a rest based spring-boot microservice that I want to configure to store authentication and session data in one mongo database and application data in another database.

My current setup mostly works, except that spring is creating all of my documents in both databases.  I looked at the @Document() annotation, but it does not have a parameter for the database to use.

In mongo shell:

```<code>> show dbs
admin                 0.000GB
authentication        0.000GB
prospect              0.000GB

> use authentication
switched to db authentication

> show collections
credentials
credentials_authorities
prospects
roles
sessions

> use prospect
switched to db prospect

> show collections
prospects
</code>```

application.properties:

```<code>com.mycompany.prospect.domainName=mycompany.com

spring.data.mongodb.host=mongodb-service
spring.data.mongodb.port=27017

com.mycompany.prospect.server.appDatabase=prospect
com.mycompany.prospect.server.sessionDatabase=authentication
</code>```

HttpSessionConfig.java

```<code>@Configuration
@EnableMongoHttpSession()
public class HttpSessionConfig {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Bean
  public CookieSerializer cookieSerializer(
      @Value("${com.mycompany.prospect.domainName:localhost}")
          final String domainName) {

    logger.info("Configuring DefaultCookieSerializer with DomainName '{}'.", domainName);

    final DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setDomainName(domainName);
    serializer.setUseHttpOnlyCookie(true);
    return serializer;
  }

  @Bean
  public JdkMongoSessionConverter jdkMongoSessionConverter() {
    return new JdkMongoSessionConverter();
  }
}
</code>```

MongoConfig.java

```<code>@Configuration
@EnableMongoRepositories
public class MongoConfig {

  private final Environment env;

  public MongoConfig(Environment env) {
    this.env = env;
  }

  @Bean("applicationTemplate")
  @Qualifier("applicationTemplate")
  public MongoTemplate mongoTemplate(
      final MappingMongoConverter mappingMongoConverter, final MongoClient mongoClient) {
    final String databaseName =
        env.getRequiredProperty("com.mycompany.prospect.server.appDatabase");

    final MongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient, databaseName);
    return new MongoTemplate(dbFactory, mappingMongoConverter);
  }

  @Bean("mongoOperations")
  @Qualifier("mongoOperations")
  @Primary
  public MongoTemplate mongoOperations(
      final MappingMongoConverter mappingMongoConverter, final MongoClient mongoClient) {
    final String databaseName =
        env.getRequiredProperty("com.mycompany.prospect.server.sessionDatabase");
    final MongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient, databaseName);
    final MongoTemplate mongoTemplate = new MongoTemplate(dbFactory, mappingMongoConverter);
    return mongoTemplate;
  }
}
</code>```

Prospect.java

```<code>@Document(collection = "prospects")
public class Prospect {
  @Id private String prospectId;

  @TextIndexed() private String businessName;

  public String getProspectId() {
    return prospectId;
  }

  public void setProspectId(String prospectId) {
    this.prospectId = prospectId;
  }

  public String getBusinessName() {
    return businessName;
  }

  public void setBusinessName(final String businessName) {
    this.businessName = businessName;
  }
}
</code>```

I would like for the prospects collection to only exist in the prospect database.

I've tried dropping the databases and restarting the services, but they come back on restart.  Any ideas on how to do this properly?

答:
If your application points to a single mongodb instance and you want to switch database based on each web request. You can take a look at this sample example,
https://github.com/Loki-Afro/multi-tenant-spring-mongodb/blob/master/src/main/java/com/github/zarathustra/mongo/MultiTenantMongoDbFactory.java

PS:- I found this, When I was doing research for achieving multi-tenancy

Body:
I have a rest based spring-boot microservice that I want to configure to store authentication and session data in one mongo database and application data in another database.

My current setup mostly works, except that spring is creating all of my documents in both databases.  I looked at the @Document() annotation, but it does not have a parameter for the database to use.

In mongo shell:

> show dbs
admin                 0.000GB
authentication        0.000GB
prospect              0.000GB

> use authentication
switched to db authentication

> show collections
credentials
credentials_authorities
prospects
roles
sessions

> use prospect
switched to db prospect

> show collections
prospects

application.properties:

com.mycompany.prospect.domainName=mycompany.com

spring.data.mongodb.host=mongodb-service
spring.data.mongodb.port=27017

com.mycompany.prospect.server.appDatabase=prospect
com.mycompany.prospect.server.sessionDatabase=authentication

HttpSessionConfig.java

@Configuration
@EnableMongoHttpSession()
public class HttpSessionConfig {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Bean
  public CookieSerializer cookieSerializer(
      @Value("${com.mycompany.prospect.domainName:localhost}")
          final String domainName) {

    logger.info("Configuring DefaultCookieSerializer with DomainName '{}'.", domainName);

    final DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setDomainName(domainName);
    serializer.setUseHttpOnlyCookie(true);
    return serializer;
  }

  @Bean
  public JdkMongoSessionConverter jdkMongoSessionConverter() {
    return new JdkMongoSessionConverter();
  }
}

MongoConfig.java

@Configuration
@EnableMongoRepositories
public class MongoConfig {

  private final Environment env;

  public MongoConfig(Environment env) {
    this.env = env;
  }

  @Bean("applicationTemplate")
  @Qualifier("applicationTemplate")
  public MongoTemplate mongoTemplate(
      final MappingMongoConverter mappingMongoConverter, final MongoClient mongoClient) {
    final String databaseName =
        env.getRequiredProperty("com.mycompany.prospect.server.appDatabase");

    final MongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient, databaseName);
    return new MongoTemplate(dbFactory, mappingMongoConverter);
  }

  @Bean("mongoOperations")
  @Qualifier("mongoOperations")
  @Primary
  public MongoTemplate mongoOperations(
      final MappingMongoConverter mappingMongoConverter, final MongoClient mongoClient) {
    final String databaseName =
        env.getRequiredProperty("com.mycompany.prospect.server.sessionDatabase");
    final MongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient, databaseName);
    final MongoTemplate mongoTemplate = new MongoTemplate(dbFactory, mappingMongoConverter);
    return mongoTemplate;
  }
}

Prospect.java

@Document(collection = "prospects")
public class Prospect {
  @Id private String prospectId;

  @TextIndexed() private String businessName;

  public String getProspectId() {
    return prospectId;
  }

  public void setProspectId(String prospectId) {
    this.prospectId = prospectId;
  }

  public String getBusinessName() {
    return businessName;
  }

  public void setBusinessName(final String businessName) {
    this.businessName = businessName;
  }
}

I would like for the prospects collection to only exist in the prospect database.

I've tried dropping the databases and restarting the services, but they come back on restart.  Any ideas on how to do this properly?