问:
Auth::attempt always return false even with proper input
Here are the facades I used

```<code>namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
</code>```

I've successfully created user signup page with hashed password using bcrypt.

```<code>    //Get singnup view
    public function getSignup()
    {
        return view('user.signup');
    }
    //Process signup
    public function postSignup(Request $request)
    {
        $this->validate($request, [
            'email' => 'email|required|unique:users',
            'password' => 'required|min:4'
        ]);
        $user = new User([
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
        $user->save();
        return redirect()->route('product.index');
    }
</code>```

And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.

```<code>//Get signin view
    public function getSignin()
    {
        return view('user.signin');
    }
    //Process signin
    public function postSignin(Request $request)
    {
        $this->validate($request, [
                'email' => 'email|required',
                'password' => 'required|min:4'
                ]);
        $credentials = array(
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password'))
                );
        if(Auth::attempt($credentials))
        {
            return redirect()->route('user.profile');
        }
        return redirect()->route('product.index');
    }
</code>```

答:
In config\auth, change guard driver setting is set to api.

```<code>'defaults' => [
    'guards' => 'api',
    'passwords' => 'users'
]
</code>```

But Laravel doesn't support attempt() function with guard api. Thus, you should use some packages like Passport (You can reference here)

Or simplier, just configure you guard driver with Auth::guard('api')->attempt($credentials)

Hope this solve your problem.

Body:
Here are the facades I used

namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

I've successfully created user signup page with hashed password using bcrypt.

    //Get singnup view
    public function getSignup()
    {
        return view('user.signup');
    }
    //Process signup
    public function postSignup(Request $request)
    {
        $this->validate($request, [
            'email' => 'email|required|unique:users',
            'password' => 'required|min:4'
        ]);
        $user = new User([
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
        $user->save();
        return redirect()->route('product.index');
    }

And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.

//Get signin view
    public function getSignin()
    {
        return view('user.signin');
    }
    //Process signin
    public function postSignin(Request $request)
    {
        $this->validate($request, [
                'email' => 'email|required',
                'password' => 'required|min:4'
                ]);
        $credentials = array(
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password'))
                );
        if(Auth::attempt($credentials))
        {
            return redirect()->route('user.profile');
        }
        return redirect()->route('product.index');
    }

Body:
In config\auth, change guard driver setting is set to api.

'defaults' => [
    'guards' => 'api',
    'passwords' => 'users'
]

But Laravel doesn't support attempt() function with guard api. Thus, you should use some packages like Passport (You can reference here)

Or simplier, just configure you guard driver with Auth::guard('api')->attempt($credentials)

Hope this solve your problem.


来源: stackexchange

问:
Displaying table content uniformly distributed on html page
JSP Code:

```<code><table>
  <c:forEach var="map" items="${map}">
  <!--no need to have new tr td here that just add extra row to your table-->
    <tr class="header expand">
      <th>${map.key.id}</th>
      <th>${map.key.name}</th>
      <th>${map.key.status}</th>
      <th><span class="sign"></span></th>
    </tr>
   <!--no need to have different table-->
    <tr>
      <th>REQUEST_ID</th>
      <th>LOGIN_USER</th>
      <th>PRICE</th>
      <th>STATUS</th>
    </tr>
    <c:forEach var="item" items="${map.value}">
      <tr>
        <td>${item.REQUEST_ID}</td>
        <td>${item.LOGIN_USER}</td>
        <td>${item.PRICE}</td>
        <td>${item.STATUS}</td>
      </tr>
    </c:forEach>
  </c:forEach>
</table>
</code>```

JS Code:

```<code>$('.header').click(function() {
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});
</code>```

CSS:

```<code>table,tr,td,th {
  border: 1px solid black;
  border-collapse: collapse;}
tr.header {
  cursor: pointer;
  color: blue;}
.header .sign:after {
  content: "-";
  display: inline-block;
}
.header.expand .sign:after {
  content: "+";
}
</code>```

I actually have 11 columns to print under table header.For demo purpose I have given only 4 attributes.I want them to obtain just in middle of table header.That is uniform through the page.I want output something like this:

```<code>                         123 A 1 +
        123 A *** ***  ***  ***  ***  ***  *** *** 1
</code>```

So on clicking + sign all the rows under table header be shown uniformly through the page.What changes in CSS will make this so?I have tried adding up class in tr but no changes take place in styling of rows.

答:
You can use colspan to span columns.i.e : here you have 11 column under your header so just use colspan="11" as you can see in below code snippet as well :

$('.header').click(function() {
  //this()->find parent(th)->parent(tr)->next tr("header1")
  $(this).toggleClass('expand').parent().parent().nextUntil('tr.header1').slideToggle(100);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
tr,
td,
th {
  border: 1px solid black;
}

tr.header1 {
  cursor: not-allowed;
  color: #ffff99;
  word-spacing: 5px;
  background: #1a1a00;
}

.header.sign:after {
  content: "-";
  display: inline-block;
}

.expand.sign:after {
  content: "+";
}

span {
  padding: 3px;
  color: black;
  font-weight: bold;
  background: pink;
  font-size: 18px;
  font-weight: 700;
  cursor: pointer;
}

table {
  width: 100%;
}</code>```

    ${map.key.id} ${map.key.name} ${map.key.status}

    REQUEST_ID
    LOGIN_USER
    PRICE
    STATUS
    REQUEST_ID
    LOGIN_USER
    PRICE
    STATUS
    REQUEST_ID
    LOGIN_USER
    LOGIN_USER

    ${item.REQUEST_ID}
    ${item.LOGIN_USER}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}

    ${map.key.id} ${map.key.name} ${map.key.status}

    REQUEST_ID
    LOGIN_USER
    PRICE
    STATUS
    REQUEST_ID
    LOGIN_USER
    PRICE
    STATUS
    REQUEST_ID
    LOGIN_USER
    LOGIN_USER

    ${item.REQUEST_ID}
    ${item.LOGIN_USER}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}
    ${item.STATUS}
    ${item.PRICE}

```

ContentLicense: CC BY-SA 4.0

Body:
JSP Code:

  <c:forEach var="map" items="${map}">

      ${map.key.id}
      ${map.key.name}
      ${map.key.status}

      REQUEST_ID
      LOGIN_USER
      PRICE
      STATUS

    <c:forEach var="item" items="${map.value}">

        ${item.REQUEST_ID}
        ${item.LOGIN_USER}
        ${item.PRICE}
        ${item.STATUS}

    </c:forEach>
  </c:forEach>

JS Code:

$('.header').click(function() {
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});

CSS:

table,tr,td,th {
  border: 1px solid black;
  border-collapse: collapse;}
tr.header {
  cursor: pointer;
  color: blue;}
.header .sign:after {
  content: "-";
  display: inline-block;
}
.header.expand .sign:after {
  content: "+";
}

I actually have 11 columns to print under table header.For demo purpose I have given only 4 attributes.I want them to obtain just in middle of table header.That is uniform through the page.I want output something like this:

                         123 A 1 +
        123 A *** ***  ***  ***  ***  ***  *** *** 1

So on clicking + sign all the rows under table header be shown uniformly through the page.What changes in CSS will make this so?I have tried adding up class in tr but no changes take place in styling of rows.

Body:
You can use colspan to span columns.i.e : here you have 11 column under your header so just use colspan="11" as you can see in below code snippet as well :

$('.header').click(function() {
  //this(<span>)->find parent(th)->parent(tr)->next tr("header1")
  $(this).toggleClass('expand').parent().parent().nextUntil('tr.header1').slideToggle(100);
});

table,
tr,
td,
th {
  border: 1px solid black;
}

tr.header1 {
  cursor: not-allowed;
  color: #ffff99;
  word-spacing: 5px;
  background: #1a1a00;
}

.header.sign:after {
  content: "-";
  display: inline-block;
}

.expand.sign:after {
  content: "+";
}

span {
  padding: 3px;
  color: black;
  font-weight: bold;
  background: pink;
  font-size: 18px;
  font-weight: 700;
  cursor: pointer;
}

table {
  width: 100%;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr class="header1">
    <th colspan="11">${map.key.id} ${map.key.name} ${map.key.status}
      <span class="sign header expand"></span></th>
  </tr>

  <tr style="display:none">
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>PRICE</th>
    <th>STATUS</th>
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>PRICE</th>
    <th>STATUS</th>
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>LOGIN_USER</th>
  </tr>

  <tr style="display:none">
    <td>${item.REQUEST_ID}</td>
    <td>${item.LOGIN_USER}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
  </tr>

  <tr class="header1">
    <th colspan="11">${map.key.id} ${map.key.name} ${map.key.status}
      <span class="sign header expand"></span></th>
  </tr>

  <tr style="display:none">
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>PRICE</th>
    <th>STATUS</th>
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>PRICE</th>
    <th>STATUS</th>
    <th>REQUEST_ID</th>
    <th>LOGIN_USER</th>
    <th>LOGIN_USER</th>
  </tr>

  <tr style="display:none">
    <td>${item.REQUEST_ID}</td>
    <td>${item.LOGIN_USER}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
    <td>${item.STATUS}</td>
    <td>${item.PRICE}</td>
  </tr>

</table>


问:
How to persist an R workspace across multiple CMD statements in a Dockerfile?
I am creating a docker container to accept input data from a client and then source an R script that runs an analysis on the given data and outputs three plots as PDFs to the working directory.  I am running into the issue of needing two CMD statements in the Dockerfile which is not allowed by the Docker Engine.  I need the reading of the user's data to occur at run time so the data set can be changed depending on the user. The R script then needs to be sourced after the user's data has been read in as a table object in the R workspace.  What happens is, the data reads in just fine but an error message indicates that the second CMD line, to source the R script, can't find the data that has just been read in.  I understand this is because each line of the Dockerfile is executed separately on build, but I don't know how to fix this.  I've researched volumes, the use of supervisor, and the possibility of using multiple containers.  I could also possibly make a Python script to dynamically program my R script but that may still need two CMD lines.  I have yet to find an example specific enough to my situation.  How would any of you solve this?

Here is my R script to create 3 plots from a data frame 'x':

```<code>library(iq)
norm_data <- iq::preprocess(x, median_normalization = FALSE, pdf_out = NULL)
protein_list <- iq::create_protein_list(norm_data)

# basic protein plot
pdf(file = "Protein P00366.pdf")
iq::plot_protein(protein_list$P00366, main = "Protein P00366", split = NULL)
dev.off()

protein_table <- iq::create_protein_table(protein_list)

#MaxLFQ plot
pdf(file = "MaxLFQ quantification of P00366.pdf")
iq::plot_protein(rbind(protein_list$P00366,
                       MaxLFQ = iq::maxLFQ(protein_list$P00366)$estimate),
                 main = "MaxLFQ quantification of P00366",
                 col = c(rep("gray", nrow(protein_list$P00366)), "green"),
                 split = NULL)
dev.off()

# ground truth
MaxLFQ_estimate <- iq::maxLFQ(protein_list$P12799)$estimate

ground_truth <-  log2(rep(c(200, 125.99, 79.37, 50, 4, 2.52, 1.59, 1), each = 3))
ground_truth <- ground_truth - mean(ground_truth) + mean(MaxLFQ_estimate)

#ground truth plot
pdf(file = "P12799 MaxLFQ versus groundtruth.pdf")
iq::plot_protein(rbind(MaxLFQ = MaxLFQ_estimate,
                       Groundtruth = ground_truth),
                 main = "P12799 - MaxLFQ versus groundtruth",
                 split = 0.75,
                 col = c("green", "gold"))
dev.off()

</code>```

Here is my Dockerfile:

```<code>FROM r-base:latest

ENV SCRIPT=""
ENV DATA=""

RUN R -e "install.packages('iq', repos='http://cran.rstudio.com/')"

WORKDIR /home/iq/

CMD R -e "x <- read.table(\"$DATA\", header = TRUE, sep = ",", fill = TRUE)" \
   && R -e "source('$SCRIPT')"
</code>```

In a folder with path /home/iq, I have my script called iqTest.R, the Dockerfile, and data.csv.
I have been building and running my container with the following commands:

```<code>$ cd iq
$ docker build -t my_image .
$ docker run -it -v /home/user/iq:/home/iq --env DATA=data.csv --env SCRIPT=iqTest.R my_image:latest
</code>```

After attempting to run, I get the following error message from the R workspace:

```<code>> source('iqTest.R')
Error in iq::preprocess(x, median_normalization = FALSE, pdf_out = NULL) :
  object 'x' not found
Calls: source -> withVisible -> eval -> eval -> <Anonymous>
</code>```

Edit: I recently discovered that the problem was more R related: you can use a ; to connect multiple lines of R code in a single line, which solves the problem with multiple CMD statements. May this serve as an example to anyone who is connecting R and Docker.
For example, the new Dockerfile with a semicolon to link lines:

```<code>FROM r-base:latest

ENV SCRIPT=""
ENV DATA=""

RUN mkdir /home/analysis/

RUN R -e "install.packages('iq', repos='http://cran.rstudio.com/')"

WORKDIR /home/analysis/

CMD R -e "x = read.csv(\"$DATA\", header = TRUE, sep = ",", fill = TRUE); source('$SCRIPT')"

</code>```

答:
If you want to make the data path configurable via an environment variable, then I would recommend to access that variable in your script with Sys.getenv(). This also allows you to use Rscript instead of R -e "source....

Here is what worked for me:

script.R

```<code>cat(Sys.getenv('SCRIPT'), '\n');
cat(Sys.getenv('DATA'), '\n')
</code>```

Dockerfile

```<code>FROM r-base:latest

ENV SCRIPT="script.R"
ENV DATA="data.csv"

WORKDIR /workspace

CMD R -q -e "source('$SCRIPT')"
# alternative: CMD Rscript $SCRIPT
</code>```

Usage

```<code>daniel@nuest /tmp/stackoverflow []$ docker build --tag stackoverflow .
Sending build context to Docker daemon  4.608kB
Step 1/5 : FROM r-base:latest
 ---> 46edce0e80af
Step 2/5 : ENV SCRIPT="script.R"
 ---> Using cache
 ---> 8f26d34d9c0a
Step 3/5 : ENV DATA="data.csv"
 ---> Using cache
 ---> 16c83c16a4c8
Step 4/5 : WORKDIR /workspace
 ---> Running in fce8619af30b
Removing intermediate container fce8619af30b
 ---> a8278f609d9a
Step 5/5 : CMD R -q -e "source('$SCRIPT')"
 ---> Running in 765bafeb8681
Removing intermediate container 765bafeb8681
 ---> ff7d7b09dffb
Successfully built ff7d7b09dffb
Successfully tagged stackoverflow:latest
daniel@nuest /tmp/stackoverflow []$ docker run --rm -it -v $(pwd):/workspace stackoverflow
> source('script.R')
script.R
data.csv
>
>
</code>```

Alternatively, you could try passing the data path as an argument to your script file, see https://swcarpentry.github.io/r-novice-inflammation/05-cmdline/

As an aside: It is better to pin a specific R version than to use :latest, for reproducibility.

Body:
I am creating a docker container to accept input data from a client and then source an R script that runs an analysis on the given data and outputs three plots as PDFs to the working directory.  I am running into the issue of needing two CMD statements in the Dockerfile which is not allowed by the Docker Engine.  I need the reading of the user's data to occur at run time so the data set can be changed depending on the user. The R script then needs to be sourced after the user's data has been read in as a table object in the R workspace.  What happens is, the data reads in just fine but an error message indicates that the second CMD line, to source the R script, can't find the data that has just been read in.  I understand this is because each line of the Dockerfile is executed separately on build, but I don't know how to fix this.  I've researched volumes, the use of supervisor, and the possibility of using multiple containers.  I could also possibly make a Python script to dynamically program my R script but that may still need two CMD lines.  I have yet to find an example specific enough to my situation.  How would any of you solve this?

Here is my R script to create 3 plots from a data frame 'x':

library(iq)
norm_data <- iq::preprocess(x, median_normalization = FALSE, pdf_out = NULL)
protein_list <- iq::create_protein_list(norm_data)

# basic protein plot
pdf(file = "Protein P00366.pdf")
iq::plot_protein(protein_list$P00366, main = "Protein P00366", split = NULL)
dev.off()

protein_table <- iq::create_protein_table(protein_list)

#MaxLFQ plot
pdf(file = "MaxLFQ quantification of P00366.pdf")
iq::plot_protein(rbind(protein_list$P00366,
                       MaxLFQ = iq::maxLFQ(protein_list$P00366)$estimate),
                 main = "MaxLFQ quantification of P00366",
                 col = c(rep("gray", nrow(protein_list$P00366)), "green"),
                 split = NULL)
dev.off()

# ground truth
MaxLFQ_estimate <- iq::maxLFQ(protein_list$P12799)$estimate

ground_truth <-  log2(rep(c(200, 125.99, 79.37, 50, 4, 2.52, 1.59, 1), each = 3))
ground_truth <- ground_truth - mean(ground_truth) + mean(MaxLFQ_estimate)

#ground truth plot
pdf(file = "P12799 MaxLFQ versus groundtruth.pdf")
iq::plot_protein(rbind(MaxLFQ = MaxLFQ_estimate,
                       Groundtruth = ground_truth),
                 main = "P12799 - MaxLFQ versus groundtruth",
                 split = 0.75,
                 col = c("green", "gold"))
dev.off()

Here is my Dockerfile:

FROM r-base:latest

ENV SCRIPT=""
ENV DATA=""

RUN R -e "install.packages('iq', repos='http://cran.rstudio.com/')"

WORKDIR /home/iq/

CMD R -e "x <- read.table(\"$DATA\", header = TRUE, sep = ",", fill = TRUE)" \
   && R -e "source('$SCRIPT')"

In a folder with path /home/iq, I have my script called iqTest.R, the Dockerfile, and data.csv.
I have been building and running my container with the following commands:

$ cd iq
$ docker build -t my_image .
$ docker run -it -v /home/user/iq:/home/iq --env DATA=data.csv --env SCRIPT=iqTest.R my_image:latest

After attempting to run, I get the following error message from the R workspace:

> source('iqTest.R')
Error in iq::preprocess(x, median_normalization = FALSE, pdf_out = NULL) :
  object 'x' not found
Calls: source -> withVisible -> eval -> eval -> <Anonymous>

Edit: I recently discovered that the problem was more R related: you can use a ; to connect multiple lines of R code in a single line, which solves the problem with multiple CMD statements. May this serve as an example to anyone who is connecting R and Docker.
For example, the new Dockerfile with a semicolon to link lines:

FROM r-base:latest

ENV SCRIPT=""
ENV DATA=""

RUN mkdir /home/analysis/

RUN R -e "install.packages('iq', repos='http://cran.rstudio.com/')"

WORKDIR /home/analysis/

CMD R -e "x = read.csv(\"$DATA\", header = TRUE, sep = ",", fill = TRUE); source('$SCRIPT')"

Body:
If you want to make the data path configurable via an environment variable, then I would recommend to access that variable in your script with Sys.getenv(). This also allows you to use Rscript instead of R -e "source....

Here is what worked for me:

script.R

cat(Sys.getenv('SCRIPT'), '\n');
cat(Sys.getenv('DATA'), '\n')

Dockerfile

FROM r-base:latest

ENV SCRIPT="script.R"
ENV DATA="data.csv"

WORKDIR /workspace

CMD R -q -e "source('$SCRIPT')"
# alternative: CMD Rscript $SCRIPT

Usage

daniel@nuest /tmp/stackoverflow []$ docker build --tag stackoverflow .
Sending build context to Docker daemon  4.608kB
Step 1/5 : FROM r-base:latest
 ---> 46edce0e80af
Step 2/5 : ENV SCRIPT="script.R"
 ---> Using cache
 ---> 8f26d34d9c0a
Step 3/5 : ENV DATA="data.csv"
 ---> Using cache
 ---> 16c83c16a4c8
Step 4/5 : WORKDIR /workspace
 ---> Running in fce8619af30b
Removing intermediate container fce8619af30b
 ---> a8278f609d9a
Step 5/5 : CMD R -q -e "source('$SCRIPT')"
 ---> Running in 765bafeb8681
Removing intermediate container 765bafeb8681
 ---> ff7d7b09dffb
Successfully built ff7d7b09dffb
Successfully tagged stackoverflow:latest
daniel@nuest /tmp/stackoverflow []$ docker run --rm -it -v $(pwd):/workspace stackoverflow
> source('script.R')
script.R
data.csv
>
>

Alternatively, you could try passing the data path as an argument to your script file, see https://swcarpentry.github.io/r-novice-inflammation/05-cmdline/

As an aside: It is better to pin a specific R version than to use :latest, for reproducibility.


问:
confusion_matrix() library is giving ValueError
When trying to get confusion matrix for a ConvNet constantly getting the same error.

```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image
from sklearn.metrics import classification_report, confusion_matrix
img_width, img_height = 150, 150

train_data_dir = "train"
validation_data_dir = "test"
nb_train_samples = 2000
nb_validation_samples = 400
epochs = 50
batch_size = 40 #16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

train_datagen = ImageDataGenerator(
    rescale = 1. / 255,
    shear_range = 0.2,
    zoom_range= 0.2,
    horizontal_flip= True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = test_datagen.flow_from_directory(
    train_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')`
</code>```

Applying CNN Layers        ...

```<code>model.compile(loss= 'binary_crossentropy',
    optimizer= 'rmsprop',
    metrics= ['accuracy'] )

`model.fit_generator(
    train_generator,
    steps_per_epoch= nb_train_samples // batch_size,
    epochs= epochs,
    validation_data= validation_generator,
    validation_steps= nb_validation_samples // batch_size)

Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size+1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(validation_generator.classes, y_pred))`
</code>```

Getting error mentioned below but don't know how to resolve it

ValueError: Found input variables with inconsistent numbers of samples: [400, 440]

答:
I am able to recreate your error using Dogs_Vs_Cats dataset. Where i have 2000 samples in train directory and 400 samples in validation directory.

Please change model.predict_generator from

```<code>Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size+1)
</code>```

to

```<code>Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size)
</code>```

will resolve this ValueError: Found input variables with inconsistent numbers of samples: [400, 440]

Please refer complete code as below

```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image
from sklearn.metrics import classification_report, confusion_matrix

from google.colab import drive
drive.mount('/content/drive')

train_data_dir  = '/content/drive/My Drive/Dogs_Vs_Cats/train'
validation_data_dir = '/content/drive/My Drive/Dogs_Vs_Cats/validation'

img_width, img_height = 150, 150

nb_train_samples = 2000
nb_validation_samples = 400
epochs = 10
batch_size = 40 #16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

train_datagen = ImageDataGenerator(
    rescale = 1. / 255,
    shear_range = 0.2,
    zoom_range= 0.2,
    horizontal_flip= True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = test_datagen.flow_from_directory(
    train_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')

model = Sequential()

model.add(Conv2D(32, (3, 3), strides = (1, 1), input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2)))

model.add(Conv2D(64, (3, 3), strides = (1, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2)))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()

model.compile(loss = 'binary_crossentropy',
            optimizer = 'rmsprop',
            metrics = ['accuracy'])

model.fit_generator(
    train_generator,
    steps_per_epoch= nb_train_samples // batch_size,
    epochs= epochs,
    validation_data= validation_generator,
    validation_steps= nb_validation_samples // batch_size)

Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(validation_generator.classes, y_pred))
</code>```

Output:

```<code>Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
Found 2000 images belonging to 2 classes.
Found 400 images belonging to 2 classes.
Model: "sequential_5"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_9 (Conv2D)            (None, 148, 148, 32)      896
_________________________________________________________________
activation_9 (Activation)    (None, 148, 148, 32)      0
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 (None, 74, 74, 32)        0
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 72, 72, 64)        18496
_________________________________________________________________
activation_10 (Activation)   (None, 72, 72, 64)        0
_________________________________________________________________
max_pooling2d_10 (MaxPooling (None, 36, 36, 64)        0
_________________________________________________________________
flatten_5 (Flatten)          (None, 82944)             0
_________________________________________________________________
dense_9 (Dense)              (None, 64)                5308480
_________________________________________________________________
dropout_5 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_10 (Dense)             (None, 1)                 65
=================================================================
Total params: 5,327,937
Trainable params: 5,327,937
Non-trainable params: 0
_________________________________________________________________
Epoch 1/10
50/50 [==============================] - 12s 233ms/step - loss: 0.9345 - accuracy: 0.5375 - val_loss: 0.6303 - val_accuracy: 0.5225
Epoch 2/10
50/50 [==============================] - 11s 226ms/step - loss: 0.6745 - accuracy: 0.5965 - val_loss: 0.6094 - val_accuracy: 0.6725
Epoch 3/10
50/50 [==============================] - 11s 223ms/step - loss: 0.6196 - accuracy: 0.6605 - val_loss: 0.5694 - val_accuracy: 0.7150
Epoch 4/10
50/50 [==============================] - 11s 223ms/step - loss: 0.5501 - accuracy: 0.7285 - val_loss: 0.6216 - val_accuracy: 0.7225
Epoch 5/10
50/50 [==============================] - 11s 221ms/step - loss: 0.4794 - accuracy: 0.7790 - val_loss: 0.6268 - val_accuracy: 0.6025
Epoch 6/10
50/50 [==============================] - 11s 226ms/step - loss: 0.4038 - accuracy: 0.8195 - val_loss: 0.4842 - val_accuracy: 0.6975
Epoch 7/10
50/50 [==============================] - 11s 222ms/step - loss: 0.3207 - accuracy: 0.8595 - val_loss: 0.5600 - val_accuracy: 0.7325
Epoch 8/10
50/50 [==============================] - 13s 257ms/step - loss: 0.2574 - accuracy: 0.8920 - val_loss: 0.9705 - val_accuracy: 0.7525
Epoch 9/10
50/50 [==============================] - 13s 252ms/step - loss: 0.2049 - accuracy: 0.9235 - val_loss: 0.7311 - val_accuracy: 0.7475
Epoch 10/10
50/50 [==============================] - 13s 251ms/step - loss: 0.1448 - accuracy: 0.9515 - val_loss: 1.0541 - val_accuracy: 0.7150
Confusion Matrix
[[200   0]
 [200   0]]
</code>```

Hope this answers your question. If not please share complete traceback and code for debug, i am happy to help you.

Body:
When trying to get confusion matrix for a ConvNet constantly getting the same error.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image
from sklearn.metrics import classification_report, confusion_matrix
img_width, img_height = 150, 150

train_data_dir = "train"
validation_data_dir = "test"
nb_train_samples = 2000
nb_validation_samples = 400
epochs = 50
batch_size = 40 #16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

train_datagen = ImageDataGenerator(
    rescale = 1. / 255,
    shear_range = 0.2,
    zoom_range= 0.2,
    horizontal_flip= True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = test_datagen.flow_from_directory(
    train_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')`

Applying CNN Layers        ...

model.compile(loss= 'binary_crossentropy',
    optimizer= 'rmsprop',
    metrics= ['accuracy'] )

`model.fit_generator(
    train_generator,
    steps_per_epoch= nb_train_samples // batch_size,
    epochs= epochs,
    validation_data= validation_generator,
    validation_steps= nb_validation_samples // batch_size)

Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size+1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(validation_generator.classes, y_pred))`

Getting error mentioned below but don't know how to resolve it

ValueError: Found input variables with inconsistent numbers of samples: [400, 440]

Body:
I am able to recreate your error using Dogs_Vs_Cats dataset. Where i have 2000 samples in train directory and 400 samples in validation directory.

Please change model.predict_generator from

Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size+1)

to

Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size)

will resolve this ValueError: Found input variables with inconsistent numbers of samples: [400, 440]

Please refer complete code as below

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image
from sklearn.metrics import classification_report, confusion_matrix

from google.colab import drive
drive.mount('/content/drive')

train_data_dir  = '/content/drive/My Drive/Dogs_Vs_Cats/train'
validation_data_dir = '/content/drive/My Drive/Dogs_Vs_Cats/validation'

img_width, img_height = 150, 150

nb_train_samples = 2000
nb_validation_samples = 400
epochs = 10
batch_size = 40 #16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

train_datagen = ImageDataGenerator(
    rescale = 1. / 255,
    shear_range = 0.2,
    zoom_range= 0.2,
    horizontal_flip= True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = test_datagen.flow_from_directory(
    train_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size= (img_width, img_height),
    batch_size= batch_size,
    class_mode= 'binary')

model = Sequential()

model.add(Conv2D(32, (3, 3), strides = (1, 1), input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2)))

model.add(Conv2D(64, (3, 3), strides = (1, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2)))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()

model.compile(loss = 'binary_crossentropy',
            optimizer = 'rmsprop',
            metrics = ['accuracy'])

model.fit_generator(
    train_generator,
    steps_per_epoch= nb_train_samples // batch_size,
    epochs= epochs,
    validation_data= validation_generator,
    validation_steps= nb_validation_samples // batch_size)

Y_pred = model.predict_generator(validation_generator, nb_validation_samples // batch_size)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(validation_generator.classes, y_pred))

Output:

Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
Found 2000 images belonging to 2 classes.
Found 400 images belonging to 2 classes.
Model: "sequential_5"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_9 (Conv2D)            (None, 148, 148, 32)      896
_________________________________________________________________
activation_9 (Activation)    (None, 148, 148, 32)      0
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 (None, 74, 74, 32)        0
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 72, 72, 64)        18496
_________________________________________________________________
activation_10 (Activation)   (None, 72, 72, 64)        0
_________________________________________________________________
max_pooling2d_10 (MaxPooling (None, 36, 36, 64)        0
_________________________________________________________________
flatten_5 (Flatten)          (None, 82944)             0
_________________________________________________________________
dense_9 (Dense)              (None, 64)                5308480
_________________________________________________________________
dropout_5 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_10 (Dense)             (None, 1)                 65
=================================================================
Total params: 5,327,937
Trainable params: 5,327,937
Non-trainable params: 0
_________________________________________________________________
Epoch 1/10
50/50 [==============================] - 12s 233ms/step - loss: 0.9345 - accuracy: 0.5375 - val_loss: 0.6303 - val_accuracy: 0.5225
Epoch 2/10
50/50 [==============================] - 11s 226ms/step - loss: 0.6745 - accuracy: 0.5965 - val_loss: 0.6094 - val_accuracy: 0.6725
Epoch 3/10
50/50 [==============================] - 11s 223ms/step - loss: 0.6196 - accuracy: 0.6605 - val_loss: 0.5694 - val_accuracy: 0.7150
Epoch 4/10
50/50 [==============================] - 11s 223ms/step - loss: 0.5501 - accuracy: 0.7285 - val_loss: 0.6216 - val_accuracy: 0.7225
Epoch 5/10
50/50 [==============================] - 11s 221ms/step - loss: 0.4794 - accuracy: 0.7790 - val_loss: 0.6268 - val_accuracy: 0.6025
Epoch 6/10
50/50 [==============================] - 11s 226ms/step - loss: 0.4038 - accuracy: 0.8195 - val_loss: 0.4842 - val_accuracy: 0.6975
Epoch 7/10
50/50 [==============================] - 11s 222ms/step - loss: 0.3207 - accuracy: 0.8595 - val_loss: 0.5600 - val_accuracy: 0.7325
Epoch 8/10
50/50 [==============================] - 13s 257ms/step - loss: 0.2574 - accuracy: 0.8920 - val_loss: 0.9705 - val_accuracy: 0.7525
Epoch 9/10
50/50 [==============================] - 13s 252ms/step - loss: 0.2049 - accuracy: 0.9235 - val_loss: 0.7311 - val_accuracy: 0.7475
Epoch 10/10
50/50 [==============================] - 13s 251ms/step - loss: 0.1448 - accuracy: 0.9515 - val_loss: 1.0541 - val_accuracy: 0.7150
Confusion Matrix
[[200   0]
 [200   0]]

Hope this answers your question. If not please share complete traceback and code for debug, i am happy to help you.


问:
NoSuchBeanException, even when Bean is defined
I have 2 classes.

Target.java: Class to be tested

Helper.java: Helper class

```<code>@Component
public class Helper {

  public void helperMethod() {
    // some code
  }
}

@Service
public class Target {
  private final Helper helper;

  public Target(Helper helper) {
    this.helper = helper;
  }

  public void someMethod() {
    helper.helperMethod();
  }
}
</code>```

I am testing someMethod() method of Target class. But when running the test case it gives following error:

Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.abc.def.Helper' available: expected at least 1 bean which qualifies as autowire candidate.

Other answers that I have seen for similar question were because of not writing @Component, but I have done that too.

答:
You have provided the correct annotations for the 2 classes in order to ensure that spring treats them as a component and manage their life cycles. Now, if you want to use these beans in any part of the application you would need to declare the dependency for that, the easiest way is as below by using the @Autowired annotation, there are mulitple ways to define dependency and you can choose the best options for your use case accordingly:

```<code>@Service
public class Target {
  @Autowired
  private final Helper helper;

  public Target(Helper helper) {
    this.helper = helper;
  }

  public void someMethod() {
    helper.helperMethod();
  }
}
</code>```

Body:
I have 2 classes.

Target.java: Class to be tested

Helper.java: Helper class

@Component
public class Helper {

  public void helperMethod() {
    // some code
  }
}

@Service
public class Target {
  private final Helper helper;

  public Target(Helper helper) {
    this.helper = helper;
  }

  public void someMethod() {
    helper.helperMethod();
  }
}

I am testing someMethod() method of Target class. But when running the test case it gives following error:

Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.abc.def.Helper' available: expected at least 1 bean which qualifies as autowire candidate.

Other answers that I have seen for similar question were because of not writing @Component, but I have done that too.

Body:
You have provided the correct annotations for the 2 classes in order to ensure that spring treats them as a component and manage their life cycles. Now, if you want to use these beans in any part of the application you would need to declare the dependency for that, the easiest way is as below by using the @Autowired annotation, there are mulitple ways to define dependency and you can choose the best options for your use case accordingly:

@Service
public class Target {
  @Autowired
  private final Helper helper;

  public Target(Helper helper) {
    this.helper = helper;
  }

  public void someMethod() {
    helper.helperMethod();
  }
}


问:
Can not install self-signed certificate on Android Default Emulator or Genymotion
Im having trouble for installing self-signed certificate for ssl on android emulator.
In security settings I selected the certificate to install

However, when I selected the Trusted Credentials -> User

There's nothing in there

答:
you can if you install a self-signed ROOT cert:
ssl app dev</p>

ContentLicense: CC BY-SA 3.0


问:
How to Find Specific Nearby Locations in android
I have requirement in my project that is finding nearby movie theaters upto certain radius from the user present location then i want to show these finding location in the google map. I have seen some posts here but i did not get the clarity on this. Is there any direct API calls to get the nearest specific places or any other way to find.</p>

答: Get list of places surrounding user's current location</p>


问:
from dataGridView1.Rows.Clear() until end to my code
Please Let me explain of there is something weird going on to my codes with my visual studio pro. There are no error messages of disconnected loops. It seems like I give up to check something wrong all files of my point of sales project. So until code below works fine.

```<code> private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");

                    updatedb();

                   }

               }

           catch (Exception ex)
          {
              //MessageBox.Show(ex.Message);
        }

       finally
      {
          con.Close();
      }
    }

// everything worked fine of project till now......
</code>```

but after add these codes from
like this now then nothing worked.

```<code>                    updatedb();

        //Nothing worked from here...

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                con.Close();
                invoice();
     }
           }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }

        finally
        {
            con.Close();
        }
       }
</code>```

Sorry, I couldn't display the picture wholly screenshot or there is no permission here whatever. Please click down the below links.

Please watch the sales window here

then please watch this one to know whats not work

I hope to find a solution without adding extra codes of files. Thanks

答:
I've just deleted catch block and seen this error on the line below.

```<code>// the error was pops to -->`string itmno = `dataGridView1.Rows[row].Cells[1].Value.ToString();`
</code>```

the error is:

```<code>System.NullReferenceException
      HResult=0x80004003
      Message=Object reference not set to an instance of an object.
      Source=superpos3
      StackTrace:
       at superpos3.salesn.updatedb() in D:\superpos3\superpos3\superpos3\salesn.cs:line 174
       at superpos3.salesn.button1_Click(Object sender, EventArgs e) in D:\superpos3\superpos3\superpos3\salesn.cs:line 258
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at superpos3.Program.Main() in D:\superpos3\superpos3\superpos3\Program.cs:line 19
</code>```

Body:
Please Let me explain of there is something weird going on to my codes with my visual studio pro. There are no error messages of disconnected loops. It seems like I give up to check something wrong all files of my point of sales project. So until code below works fine.

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");

                    updatedb();

                   }

               }

           catch (Exception ex)
          {
              //MessageBox.Show(ex.Message);
        }

       finally
      {
          con.Close();
      }
    }

// everything worked fine of project till now......

but after add these codes from
like this now then nothing worked.

                    updatedb();

        //Nothing worked from here...

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                con.Close();
                invoice();
     }
           }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }

        finally
        {
            con.Close();
        }
       }

Sorry, I couldn't display the picture wholly screenshot or there is no permission here whatever. Please click down the below links.

Please watch the sales window here

then please watch this one to know whats not work

I hope to find a solution without adding extra codes of files. Thanks

Body:
I've just deleted catch block and seen this error on the line below.

// the error was pops to -->`string itmno = `dataGridView1.Rows[row].Cells[1].Value.ToString();`

the error is:

System.NullReferenceException
      HResult=0x80004003
      Message=Object reference not set to an instance of an object.
      Source=superpos3
      StackTrace:
       at superpos3.salesn.updatedb() in D:\superpos3\superpos3\superpos3\salesn.cs:line 174
       at superpos3.salesn.button1_Click(Object sender, EventArgs e) in D:\superpos3\superpos3\superpos3\salesn.cs:line 258
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at superpos3.Program.Main() in D:\superpos3\superpos3\superpos3\Program.cs:line 19


问:
Rails form_for that uses STI base class
I've got a pretty simple (I think) single-table inheritance (STI) setup in my Rails app.

There is a User model with a nested resource Post.
Using STI, I have it so that some Posts can be Post::Urgent objects.

I noticed that my URL helpers like <%= [@user, @post] %> needed to be hard-coded to <%= user_post_path[@user, @post] %> or else I'd end up seeing errors about Rails not finding the user_post_urgent_path method. Okay, that was reasonably easy.

(An alternate way of doing this is also <%= [@user, post: @post] %>.)

Well, for some reason I'm not able to figure out how to make the form_for method adjusted in the same way. When I write simply

```<code><%= form_for [@user, @post] do |f| %>
</code>```

, I get similar errors to the URL helper case, but in the form context: undefined method 'user_post_urgen_path'.

I fixed this by specifying:

```<code><%= form_for [@user, @post], url: :user_post do |f| %>
</code>```

But this doesn't completely work, because when I go to submit the form, I get problems in my controller, saying that strong parameters line params.require(:post) failed:

```<code>param is missing or the value is empty: post
</code>```

If I inspect the params I find that the form is passing a post_urgent object and not a post object.

I could, of course, manually put in some logic that always says if !params[:post] and params[:post_urgent], then params[:post] = params[:post_urgent]. But that just seems way too hacky, especially for Rails.

Is there a better way to make a form like this "just work" regardless of what subclass of the Post model it actually happens to be?

答:
I had some nested models initialized in the controller, empty unsaved models to work with accepts_nested_attribues_for and becomes empties them for some reason, so instead, I acted on the controller strong params, not the cleanest, I know.

```<code>  def unpermitted_model_params
    polymorphic_form_params = params.to_unsafe_hash
        .slice('sub_model1', 'sub_model2')
    form_values = polymorphic_form_params.first.to_a.second
    ActionController::Parameters.new(parent_model: form_values)
  end

  def allowed_params
    unpermitted_model_params.require(:parent_model)
                            .permit(:type, :etc, :etc)
  end
</code>```

Title: Rails form_for that uses STI base class

Body:
I've got a pretty simple (I think) single-table inheritance (STI) setup in my Rails app.

There is a User model with a nested resource Post.
Using STI, I have it so that some Posts can be Post::Urgent objects.

I noticed that my URL helpers like <%= [@user, @post] %> needed to be hard-coded to <%= user_post_path[@user, @post] %> or else I'd end up seeing errors about Rails not finding the user_post_urgent_path method. Okay, that was reasonably easy.

(An alternate way of doing this is also <%= [@user, post: @post] %>.)

Well, for some reason I'm not able to figure out how to make the form_for method adjusted in the same way. When I write simply

<%= form_for [@user, @post] do |f| %>

, I get similar errors to the URL helper case, but in the form context: undefined method 'user_post_urgen_path'.

I fixed this by specifying:

<%= form_for [@user, @post], url: :user_post do |f| %>

But this doesn't completely work, because when I go to submit the form, I get problems in my controller, saying that strong parameters line params.require(:post) failed:

param is missing or the value is empty: post

If I inspect the params I find that the form is passing a post_urgent object and not a post object.

I could, of course, manually put in some logic that always says if !params[:post] and params[:post_urgent], then params[:post] = params[:post_urgent]. But that just seems way too hacky, especially for Rails.

Is there a better way to make a form like this "just work" regardless of what subclass of the Post model it actually happens to be?

Body:
I had some nested models initialized in the controller, empty unsaved models to work with accepts_nested_attribues_for and becomes empties them for some reason, so instead, I acted on the controller strong params, not the cleanest, I know.

  def unpermitted_model_params
    polymorphic_form_params = params.to_unsafe_hash
        .slice('sub_model1', 'sub_model2')
    form_values = polymorphic_form_params.first.to_a.second
    ActionController::Parameters.new(parent_model: form_values)
  end

  def allowed_params
    unpermitted_model_params.require(:parent_model)
                            .permit(:type, :etc, :etc)
  end


问:
Autofill clear background trick stopped working?
I had this piece of CSS implemented to have a transparent autofill background. But something has recently changed that it stopped working?

```<code>@-webkit-keyframes autofill {
    to {
        color: white;
        background: transparent;

    }
}

input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
}
</code>```

Is there a fix to this?

  form {
  background-color: red;
}

div {
  margin: 15px 0;
  position: relative;
  width: 360px;
  color: red;
  background-color: red;
}

textarea,
select,
input {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #000;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  color: red;
  background-color: red;
}

textarea {
  height: 200px;
  color: red;
  background-color: red;
}

textarea+label {
  width: calc(100% - 2px) !important;
  top: 1px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  text-align: center;
  color: red;
}

textarea:invalid,
select:invalid,
input:invalid {
  box-shadow: none;
  color: red;
}

textarea:invalid+label,
select:invalid+label,
input:invalid+label {
  padding: 0 10px;
  max-width: 360px;
  color: red;
}

textarea:focus+label,
select:focus+label,
input:focus+label,
label {
  position: absolute;
  background: #a4a290;
  max-width: 0;
  padding: 0;
  overflow: hidden;
  left: 1px;
  top: 1px;
  height: 28px;
  font: 14px/28px sans-serif;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
  transition: all 0.25s;
  color: red;
  border-radius: 5px 0 0 5px;
}

textarea:focus+label {
  height: 0;
  color: red;
  @-webkit-keyframes autofill {
    to {
      color: white;
      background: transparent;
    }
  }
  input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <div>
    <input type="text" id="firstname" required/>
    <label for="firstname">First Name</label>
  </div>
  <div>
    <input type="text" id="secondname" required/>
    <label for="secondname">Second Name</label>
  </div>
  <div>
    <select id="type" required>
      <option value=""></option>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option>
      <option value="3">Type 3</option>
      <option value="4">Type 4</option>
    </select>
    <label for="type">Select type...</label>
  </div>
  <div>
    <textarea id="comment" required/></textarea>
    <label for="comment">Comment</label>
  </div>
</form></code>```

答:
Just this would do the job perfectly :

```<code>input:-webkit-autofill {
  -webkit-text-fill-color: transparent;
  transition: background-color 5000s ease-in-out 0s;
}
</code>```

form {
  background-color: red;
}

div {
  margin: 15px 0;
  position: relative;
  width: 360px;
  color: red;
  background-color: red;
}

textarea,
select,
input {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #000;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  color: red;
  background-color: red;
}

textarea {
  height: 200px;
  color: red;
  background-color: red;
}

textarea+label {
  width: calc(100% - 2px) !important;
  top: 1px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  text-align: center;
  color: red;
}

textarea:invalid,
select:invalid,
input:invalid {
  box-shadow: none;
  color: red;
}

textarea:invalid+label,
select:invalid+label,
input:invalid+label {
  padding: 0 10px;
  max-width: 360px;
  color: red;
}

textarea:focus+label,
select:focus+label,
input:focus+label,
label {
  position: absolute;
  background: #a4a290;
  max-width: 0;
  padding: 0;
  overflow: hidden;
  left: 1px;
  top: 1px;
  height: 28px;
  font: 14px/28px sans-serif;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
  transition: all 0.25s;
  color: red;
  border-radius: 5px 0 0 5px;
}

textarea:focus+label {
  height: 0;
  color: red;
}

input:-webkit-autofill {
  -webkit-text-fill-color: black;
  transition: background-color 5000s ease-in-out 0s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <div>
    <input type="text" id="firstname" required />
    <label for="firstname">First Name</label>
  </div>
  <div>
    <input type="email" id="email" required />
    <label for="email">Email</label>
  </div>
  <div>
    <input type="text" id="secondname" required />
    <label for="secondname">Second Name</label>
  </div>
  <div>
    <select id="type" required>
      <option value=""></option>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option>
      <option value="3">Type 3</option>
      <option value="4">Type 4</option>
    </select>
    <label for="type">Select type...</label>
  </div>
  <div>
    <textarea id="comment" required /></textarea>
    <label for="comment">Comment</label>
  </div>
</form></code>```

Source

Body:
I had this piece of CSS implemented to have a transparent autofill background. But something has recently changed that it stopped working?

@-webkit-keyframes autofill {
    to {
        color: white;
        background: transparent;

    }
}

input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
}

Is there a fix to this?

  form {
  background-color: red;
}

div {
  margin: 15px 0;
  position: relative;
  width: 360px;
  color: red;
  background-color: red;
}

textarea,
select,
input {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #000;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  color: red;
  background-color: red;
}

textarea {
  height: 200px;
  color: red;
  background-color: red;
}

textarea+label {
  width: calc(100% - 2px) !important;
  top: 1px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  text-align: center;
  color: red;
}

textarea:invalid,
select:invalid,
input:invalid {
  box-shadow: none;
  color: red;
}

textarea:invalid+label,
select:invalid+label,
input:invalid+label {
  padding: 0 10px;
  max-width: 360px;
  color: red;
}

textarea:focus+label,
select:focus+label,
input:focus+label,
label {
  position: absolute;
  background: #a4a290;
  max-width: 0;
  padding: 0;
  overflow: hidden;
  left: 1px;
  top: 1px;
  height: 28px;
  font: 14px/28px sans-serif;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
  transition: all 0.25s;
  color: red;
  border-radius: 5px 0 0 5px;
}

textarea:focus+label {
  height: 0;
  color: red;
  @-webkit-keyframes autofill {
    to {
      color: white;
      background: transparent;
    }
  }
  input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
  }

<form>

    <input type="text" id="firstname" required/>
    First Name

    <input type="text" id="secondname" required/>
    Second Name

    <select id="type" required>
      <option value=""></option>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option>
      <option value="3">Type 3</option>
      <option value="4">Type 4</option>
    </select>
    Select type...

    <textarea id="comment" required/></textarea>
    Comment

</form>

Body:
Just this would do the job perfectly :

input:-webkit-autofill {
  -webkit-text-fill-color: transparent;
  transition: background-color 5000s ease-in-out 0s;
}

form {
  background-color: red;
}

div {
  margin: 15px 0;
  position: relative;
  width: 360px;
  color: red;
  background-color: red;
}

textarea,
select,
input {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #000;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  color: red;
  background-color: red;
}

textarea {
  height: 200px;
  color: red;
  background-color: red;
}

textarea+label {
  width: calc(100% - 2px) !important;
  top: 1px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  text-align: center;
  color: red;
}

textarea:invalid,
select:invalid,
input:invalid {
  box-shadow: none;
  color: red;
}

textarea:invalid+label,
select:invalid+label,
input:invalid+label {
  padding: 0 10px;
  max-width: 360px;
  color: red;
}

textarea:focus+label,
select:focus+label,
input:focus+label,
label {
  position: absolute;
  background: #a4a290;
  max-width: 0;
  padding: 0;
  overflow: hidden;
  left: 1px;
  top: 1px;
  height: 28px;
  font: 14px/28px sans-serif;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
  transition: all 0.25s;
  color: red;
  border-radius: 5px 0 0 5px;
}

textarea:focus+label {
  height: 0;
  color: red;
}

input:-webkit-autofill {
  -webkit-text-fill-color: black;
  transition: background-color 5000s ease-in-out 0s;
}

<form>
  <div>
    <input type="text" id="firstname" required />
    <label for="firstname">First Name</label>
  </div>
  <div>
    <input type="email" id="email" required />
    <label for="email">Email</label>
  </div>
  <div>
    <input type="text" id="secondname" required />
    <label for="secondname">Second Name</label>
  </div>
  <div>
    <select id="type" required>
      <option value=""></option>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option>
      <option value="3">Type 3</option>
      <option value="4">Type 4</option>
    </select>
    <label for="type">Select type...</label>
  </div>
  <div>
    <textarea id="comment" required /></textarea>
    <label for="comment">Comment</label>
  </div>
</form>

Source


问:
given a node how can I find previous node in a singly linked list
Given the current node, how can I find its previous node in a Singly Linked List. Thanks. Logic will do , code is appreciated. We all know given a root node one can do a sequential traverse , I want to know if there is a smarter way that avoids sequential access overhead. (assume there is no access to root node) Thanks. </p>

答:
If you want to delete the current node, you can do that without finding previous node as well.

Python Code:

def deleteNode(self, node):

```<code>node.val = node.next.val

node.next = node.next.next
</code>```

@ Delete Node in a Linked List

Body:
If you want to delete the current node, you can do that without finding previous node as well.

Python Code:

def deleteNode(self, node):

node.val = node.next.val

node.next = node.next.next

@ Delete Node in a Linked List


问:
State list for PreferenceScreen?
I've added a widget layout to my preference screens showing an arrow icon, to indicate to users that there are more preferences behind a given PreferenceScreen.

However, I notice when a PreferenceScreen is not enabled it is darkened. Is there a way I could also change the widget layout being used, or make it stateful, so that I could use a faded icon when my PreferenceScreen is disabled? Similar to how a state list drawable can be applied as a button's background?

tl;dr: How can I change the icon displayed when an instance of PreferenceLayout is disabled?

答:
This can be done solely with XML in 3 steps.

First, create a stateful drawable that can change according to whether the widget using it is enabled, disabled, etc. So statelist_example.xml kept in the drawable folder:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:drawable="@drawable/expander_ic_minimized"
    android:state_enabled="true" />
<item
    android:drawable="@drawable/expander_ic_minimized_faded"
    android:state_enabled="false" />
</selector>
</code>```

Then define your own layout to use this drawable in the layouts folder. This will become the "widgetLayout" for the Preference. So layout_example.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+android:id/widget_frame"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
    android:id="@+id/icon"
    android:src="@drawable/statelist_example"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="6dip"
    android:layout_marginRight="6dip"
    android:layout_gravity="center" />
</LinearLayout>
</code>```

Third, specify the widgetLayout in every preference to use this layout:

```<code>        <Preference
        android:key="preference_example"
        android:title="@string/preference_title"
        android:widgetLayout="@layout/layout_example" />
</code>```

So basically you have your Preference reference a Layout which references a stateful drawable.

Android Docs on Statelist Drawable.

Android Docs on Preference widgetLayout.

Title: State list for PreferenceScreen?

Body:
This can be done solely with XML in 3 steps.

First, create a stateful drawable that can change according to whether the widget using it is enabled, disabled, etc. So statelist_example.xml kept in the drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:drawable="@drawable/expander_ic_minimized"
    android:state_enabled="true" />
<item
    android:drawable="@drawable/expander_ic_minimized_faded"
    android:state_enabled="false" />
</selector>

Then define your own layout to use this drawable in the layouts folder. This will become the "widgetLayout" for the Preference. So layout_example.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+android:id/widget_frame"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
    android:id="@+id/icon"
    android:src="@drawable/statelist_example"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="6dip"
    android:layout_marginRight="6dip"
    android:layout_gravity="center" />
</LinearLayout>

Third, specify the widgetLayout in every preference to use this layout:

        <Preference
        android:key="preference_example"
        android:title="@string/preference_title"
        android:widgetLayout="@layout/layout_example" />

So basically you have your Preference reference a Layout which references a stateful drawable.

Android Docs on Statelist Drawable.

Android Docs on Preference widgetLayout.


问:
Row-major vs Column-major confusion
I've been reading a lot about this, the more I read the more confused I get.

My understanding: In row-major rows are stored contiguously in memory, in column-major columns are stored contiguously in memory. So if we have a sequence of numbers [1, ..., 9] and we want to store them in a row-major matrix, we get:

```<code>|1, 2, 3|
|4, 5, 6|
|7, 8, 9|
</code>```

while the column-major (correct me if I'm wrong) is:

```<code>|1, 4, 7|
|2, 5, 8|
|3, 6, 9|
</code>```

which is effectively the transpose of the previous matrix.

My confusion: Well, I don't see any difference. If we iterate on both the matrices (by rows in the first one, and by columns in the second one) we'll cover the same values in the same order: 1, 2, 3, ..., 9

Even matrix multiplication is the same, we take the first contiguous elements and multiply them with the second matrix columns. So say we have the matrix M:

```<code>|1, 0, 4|
|5, 2, 7|
|6, 0, 0|
</code>```

If we multiply the previous row-major matrix R with M, that is R x M we'll get:

```<code>|1*1 + 2*0 + 3*4, 1*5 + 2*2 + 3*7, etc|
|etc.. |
|etc.. |
</code>```

If we multiply the column-major matrix C with M, that is C x M by taking the columns of C instead of its rows, we get exactly the same result from R x M

I'm really confused, if everything is the same, why do these two terms even exist? I mean even in the first matrix R, I could look at the rows and consider them columns...

Am I missing something? What does row-major vs col-major actually imply on my matrix math? I've always learned in my Linear Algebra classes that we multiply rows from the first matrix with columns from the second one, does that change if the first matrix was in column-major? do we now have to multiply its columns with columns from the second matrix like I did in my example or was that just flat out wrong?

Any clarifications are really appreciated!

EDIT: One of the other main sources of confusion I'm having is GLM... So I hover over its matrix type and hit F12 to see how it's implemented, there I see a vector array, so if we have a 3x3 matrix we have an array of 3 vectors. Looking at the type of those vectors I saw 'col_type' so I assumed that each one of those vectors represent a column, and thus we have a column-major system right?

Well, I don't know to be honest. I wrote this print function to compare my translation matrix with glm's, I see the translation vector in glm at the last row, and mine is at the last column...

This adds nothing but more confusion. You can clearly see that each vector in glmTranslate matrix represents a row in the matrix. So... that means that the matrix is row-major right? What about my matrix? (I'm using a float array[16]) the translation values are in the last column, does that mean my matrix is column-major and I didn't now it? tries to stop head from spinning

答:
It's easy:row-major and column-major are from the glUniformMatrix*()'s perspective.
actually, matrix never changed, it is alwarys:

What is difference is matrix class realization. It deterimins how 16 floats stored as parameter passing to glUniformMatrix*()

If you use row-major matrix, memory of 4x4 matrix is:
(a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44), else for column-major is:
(a11, a21, a31, a41, a12, a22, a32, a42, a13, a23, a33, a43, a41, a42, a43, a44).

Because glsl is column-major matrix, so it will read the 16 float data
(b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16) as

Since in row-major, a11=b1, a12=b2, a13=b3, a14=b4, a21=b5, a22=b6,...so in glsl matrix is changed to

while in column-major: a11=b1, a21=b2, a31=b3, a41=b4, a12=b5, a22=b6,...so in glsl matrix is changed to

which is the same as the orign.
So row-major needing a transpose while column-major not.

Hoping this can solve your confusion.

Title: Row-major vs Column-major confusion

Body:
I've been reading a lot about this, the more I read the more confused I get.

My understanding: In row-major rows are stored contiguously in memory, in column-major columns are stored contiguously in memory. So if we have a sequence of numbers [1, ..., 9] and we want to store them in a row-major matrix, we get:

|1, 2, 3|
|4, 5, 6|
|7, 8, 9|

while the column-major (correct me if I'm wrong) is:

|1, 4, 7|
|2, 5, 8|
|3, 6, 9|

which is effectively the transpose of the previous matrix.

My confusion: Well, I don't see any difference. If we iterate on both the matrices (by rows in the first one, and by columns in the second one) we'll cover the same values in the same order: 1, 2, 3, ..., 9

Even matrix multiplication is the same, we take the first contiguous elements and multiply them with the second matrix columns. So say we have the matrix M:

|1, 0, 4|
|5, 2, 7|
|6, 0, 0|

If we multiply the previous row-major matrix R with M, that is R x M we'll get:

|1*1 + 2*0 + 3*4, 1*5 + 2*2 + 3*7, etc|
|etc.. |
|etc.. |

If we multiply the column-major matrix C with M, that is C x M by taking the columns of C instead of its rows, we get exactly the same result from R x M

I'm really confused, if everything is the same, why do these two terms even exist? I mean even in the first matrix R, I could look at the rows and consider them columns...

Am I missing something? What does row-major vs col-major actually imply on my matrix math? I've always learned in my Linear Algebra classes that we multiply rows from the first matrix with columns from the second one, does that change if the first matrix was in column-major? do we now have to multiply its columns with columns from the second matrix like I did in my example or was that just flat out wrong?

Any clarifications are really appreciated!

EDIT: One of the other main sources of confusion I'm having is GLM... So I hover over its matrix type and hit F12 to see how it's implemented, there I see a vector array, so if we have a 3x3 matrix we have an array of 3 vectors. Looking at the type of those vectors I saw 'col_type' so I assumed that each one of those vectors represent a column, and thus we have a column-major system right?

Well, I don't know to be honest. I wrote this print function to compare my translation matrix with glm's, I see the translation vector in glm at the last row, and mine is at the last column...

This adds nothing but more confusion. You can clearly see that each vector in glmTranslate matrix represents a row in the matrix. So... that means that the matrix is row-major right? What about my matrix? (I'm using a float array[16]) the translation values are in the last column, does that mean my matrix is column-major and I didn't now it? tries to stop head from spinning


问:
Android Studio 2.2.1: Slow Debugging
Since the update to version 2.21 the Debugging has become very slow. One exmaple: When I start my app without the debugger in completes one function in less than 2 seconds. With the debugger connected I have to wait more than 4 minutes for its completion. The update 2.2.2 did not solve this problem. What can I do to increase the debug speed again?

答: check your break-points added to your code for debugging before, I fixed this problem with release break-points that added on UI function</p>

Title: Android Studio 2.2.1: Slow Debugging


问:
How to avoid having too many nested function when using promises
So I'm working on a Discord bot using Discord.js. Here's the code I want to simplify:

message.channel.send('**Card 1:** (type `next` to reveal the second card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
  message.channel.awaitMessages(filter, {
      max: 1,
      time: 30000,
      errors: ['time']
    })
    .then(collected => {
      message.channel.send('**Card 2:** (type `next` to reveal the third card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
        message.channel.awaitMessages(filter, {
            max: 1,
            time: 30000,
            errors: ['time']
          })
          .then(collected => {
            message.channel.send('**Card 3:** (type `next` to reveal the fourth card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
              message.channel.awaitMessages(filter, {
                  max: 1,
                  time: 30000,
                  errors: ['time']
                })
                .then(collected => {
                  message.channel.send('**Card 4:** (type `next` to reveal the last card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
                    message.channel.awaitMessages(filter, {
                        max: 1,
                        time: 30000,
                        errors: ['time']
                      })
                      .then(collected => {
                        message.channel.send('**Card 5:** \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
                      })
                  })
                })
            })
          })
      })
    })
    .catch(collected => {
      message.channel.send('Pack forfeited.');
    });
});
```

<p>The code above works, but it's too messy. Is there a way to simplify this?</p>

<p>EDIT: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>async function revealCard(i) {
  message.channel.send(`**Card ${i + 1}:** (type \`next\` to reveal card ${i + 2}) \n` + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
  let collected = await message.channel.awaitMessages(filter, {
    max: 1,
    time: 30000,
    errors: ['time']
  });
}

for (i = 0; i > 5; i++) {
  revealCard(i);

  if (collected === null) {
    break;
  }
}</code>```

This is my current code. Pretty sure I must have done something wrong because when I attempt running this command, nothing happens. No errors. Just nothingness. Am I doing this correctly?

Thanks in advance.

答:
As suggested in one of the comments, you should try using async/await: every time you have a .then() you can replace it like with an await keyword, provided that you're using an async function.

Here's how I would do it:

// It's important that you're inside an async function (it will return a Promise)
async function yourStuff() {
  // Every time you want to wait for a Promise to resolve, use the await keyword
  await message.channel.send('**Card 1:** (type `next` to reveal the second card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey])
  await message.channel.awaitMessages(filter, {
    max: 1,
    time: 30000,
    errors: ['time']
  })

  await message.channel.send('**Card 2:** (type `next` to reveal the third card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey])
  await message.channel.awaitMessages(filter, {
    max: 1,
    time: 30000,
    errors: ['time']
  })

  // And so on...

  // If you want to get the result of the Promise you can store it in a variable like this:
  let collected = await message.channel.awaitMessage(...)
}
```

Body:
So I'm working on a Discord bot using Discord.js. Here's the code I want to simplify:

message.channel.send('**Card 1:** (type `next` to reveal the second card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
  message.channel.awaitMessages(filter, {
      max: 1,
      time: 30000,
      errors: ['time']
    })
    .then(collected => {
      message.channel.send('**Card 2:** (type `next` to reveal the third card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
        message.channel.awaitMessages(filter, {
            max: 1,
            time: 30000,
            errors: ['time']
          })
          .then(collected => {
            message.channel.send('**Card 3:** (type `next` to reveal the fourth card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
              message.channel.awaitMessages(filter, {
                  max: 1,
                  time: 30000,
                  errors: ['time']
                })
                .then(collected => {
                  message.channel.send('**Card 4:** (type `next` to reveal the last card) \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]).then(() => {
                    message.channel.awaitMessages(filter, {
                        max: 1,
                        time: 30000,
                        errors: ['time']
                      })
                      .then(collected => {
                        message.channel.send('**Card 5:** \n' + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
                      })
                  })
                })
            })
          })
      })
    })
    .catch(collected => {
      message.channel.send('Pack forfeited.');
    });
});

The code above works, but it's too messy. Is there a way to simplify this?

EDIT:

async function revealCard(i) {
  message.channel.send(`**Card ${i + 1}:** (type \`next\` to reveal card ${i + 2}) \n` + specs[Math.floor(Math.random() * specs.length)][pictureKey]);
  let collected = await message.channel.awaitMessages(filter, {
    max: 1,
    time: 30000,
    errors: ['time']
  });
}

for (i = 0; i > 5; i++) {
  revealCard(i);

  if (collected === null) {
    break;
  }
}

This is my current code. Pretty sure I must have done something wrong because when I attempt running this command, nothing happens. No errors. Just nothingness. Am I doing this correctly?

Thanks in advance.


问:
Showing "Forbidden" message when creating meetings MS Teams
I am trying to integrate ms teams API to my project. I have created an app in the Azure portal.I have added permissions User.ReadWriteAll and Meetings.ReadWriteAll.I can create a user through API but I am not able to create a meeting. Is there anything else I need to do for creating a meeting using API.

UPDATE
I gave delegated permission for creating the meeting,but unable to create the meeting.
Error Message

```<code>{code:"Forbidden",message:"Forbidden",innerError:{"request-id":"e1abb815-09d3-4b78-5063-39b0236c0968","Date":"2020-06-09T04:14:39"}}
</code>```

Permissions
Screenshot of permission

答:
You should check what kind of permissions are added for your app. To be able to create a meeting, only delegated permission OnlineMeetings.ReadWrite is supported - https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=http#permissions

If you have added an application permission, then the request for creating meetings won't work.

Update:

In the beta version of the MS Graph API, there is an OnlineMeetings.ReadWrite.All application permission which doesn't seem to be implemented yet. There is a note on the documentation page (https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-beta&tabs=http#permissions) that supports this.

Creating an online meeting with an application token will be supported
  in the near future.

Body:
I am trying to integrate ms teams API to my project. I have created an app in the Azure portal.I have added permissions User.ReadWriteAll and Meetings.ReadWriteAll.I can create a user through API but I am not able to create a meeting. Is there anything else I need to do for creating a meeting using API.

UPDATE
I gave delegated permission for creating the meeting,but unable to create the meeting.
Error Message

{code:"Forbidden",message:"Forbidden",innerError:{"request-id":"e1abb815-09d3-4b78-5063-39b0236c0968","Date":"2020-06-09T04:14:39"}}

Permissions
Screenshot of permission


问:
Is it possible to send mails by bash script via smtp?
I have postfix+dovecot.  I want to make bash script which can use SMTP for this. I don't want use sendmail.

Is it possible?  May be someone has some examples of code?

答:
Also wanted to throw in another solution here, useful if you don't have access to sendmail etc. Most linux servers will have telnet, so we can use that.</p>

```<code>function send_email{

echo "EHLO my_mail_server.example.com"   # replace this with your mail server domain
sleep 1
echo "MAIL FROM: my_from_address@example.com
sleep 1
echo "RCPT TO: my_to_address@example.com
sleep 1
echo "DATA
sleep 1
echo "Subject: My Subject Line"
sleep 1
echo "To: my_to_address@example.com"
sleep 1
echo "From: my_from_address@example.com"
sleep 1
echo "This is the body of my email. Put whatever in here."
sleep 1
echo "." # signifies the end of data entry, mail will be queued to send.
}

send_email | telnet 1.2.3.4 25 # call the function and pass it into telnet command.
</code>```

Body:
Also wanted to throw in another solution here, useful if you don't have access to sendmail etc. Most linux servers will have telnet, so we can use that.

function send_email{

echo "EHLO my_mail_server.example.com"   # replace this with your mail server domain
sleep 1
echo "MAIL FROM: my_from_address@example.com
sleep 1
echo "RCPT TO: my_to_address@example.com
sleep 1
echo "DATA
sleep 1
echo "Subject: My Subject Line"
sleep 1
echo "To: my_to_address@example.com"
sleep 1
echo "From: my_from_address@example.com"
sleep 1
echo "This is the body of my email. Put whatever in here."
sleep 1
echo "." # signifies the end of data entry, mail will be queued to send.
}

send_email | telnet 1.2.3.4 25 # call the function and pass it into telnet command.


问:
Undocumented way to define Identity Server clients in appsettings
I've found an interesting feature while exploring identity server configs. This is how clients should be defined in appsettings.json according to the official document:

```<code>{
  "IdentityServer": {
    "Clients": [
      {
        "ClientId": "TestClient1",
        "RedirectUri": "/redirect",
        "AccessTokenLifetime": 1800
      },
      {
        "ClientId": "TestClient2",
        "RedirectUri": "/redirect",
        "AccessTokenLifetime": 1800
      }
    ]
  }
}
</code>```

As you can see, one is expected to pass an array of into the "Clients" property of IdentityServer config.

Surprisingly, the following code also works:

```<code>{
    "IdentityServer": {
        "Clients": {
            "TestClient1": {
                "Profile": "SPA",
                "RedirectUri": "/redirect",
                "AccessTokenLifetime": 1800
            },
            "TestClient2": {
                "Profile": "SPA",
                "RedirectUri": "/redirect",
                "AccessTokenLifetime": 1800
            }
        }
    }
}
</code>```

It passes an object into the "Clients" property. In this case, name of subproperty ("TestClient1", "TestClient2") is mapped to ClientId. RedirectUri also works just fine, but other properties (like AccessTokenLifetime) are skipped.

So, why does it work? Where can I find documents describing this way of IdentityServer configuration?

答: There is nothing special about this on IdentityServer code really, thats why its not documented. here is the line of code where it reads the config. As you see it uses Config.Bind extension. </p>

Body:
I've found an interesting feature while exploring identity server configs. This is how clients should be defined in appsettings.json according to the official document:

{
  "IdentityServer": {
    "Clients": [
      {
        "ClientId": "TestClient1",
        "RedirectUri": "/redirect",
        "AccessTokenLifetime": 1800
      },
      {
        "ClientId": "TestClient2",
        "RedirectUri": "/redirect",
        "AccessTokenLifetime": 1800
      }
    ]
  }
}

As you can see, one is expected to pass an array of into the "Clients" property of IdentityServer config.

Surprisingly, the following code also works:

{
    "IdentityServer": {
        "Clients": {
            "TestClient1": {
                "Profile": "SPA",
                "RedirectUri": "/redirect",
                "AccessTokenLifetime": 1800
            },
            "TestClient2": {
                "Profile": "SPA",
                "RedirectUri": "/redirect",
                "AccessTokenLifetime": 1800
            }
        }
    }
}

It passes an object into the "Clients" property. In this case, name of subproperty ("TestClient1", "TestClient2") is mapped to ClientId. RedirectUri also works just fine, but other properties (like AccessTokenLifetime) are skipped.

So, why does it work? Where can I find documents describing this way of IdentityServer configuration?


问:
Xamarin forms: Xamarin.Plugin.FilePicker is not working on ios
I am using Xamarin.Plugin.FilePicker to choose a file from the device.

Following is my code for picking a file from device:

```<code>var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
    filename_label.Text = file.FileName;
}
</code>```

But this is not working on ios platform (Working fine on android and windows). Getting the below exception when running on ios simulator:

System.NotImplementedException has been thrown.
  This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

What I am missing on the ios part? Is this package only for android and windows?

答:
Most probably you haven't configured your iCloud Driver (CloudKit). As it states in the project's documentation:

iOS: You need to Configure iCloud Driver for your app.

You can follow the steps and everything will be working in no time. This is needed, since on iOS you don't have a "simple" file system, to choose your file from. It needs to go "through" iCloud.

Body:
I am using Xamarin.Plugin.FilePicker to choose a file from the device.

Following is my code for picking a file from device:

var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
    filename_label.Text = file.FileName;
}

But this is not working on ios platform (Working fine on android and windows). Getting the below exception when running on ios simulator:

System.NotImplementedException has been thrown.
  This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

What I am missing on the ios part? Is this package only for android and windows?