问:
ValueError: Dimension 1 in both shapes must be equal, but are 10 and 1
I was trying to implement shap DeepExplainer (DeepSHAP) module with the help of MNIST Dataset. But i am getting the following error:

ValueError: Dimension 1 in both shapes must be equal, but are 10 and 1. Shapes are [?,10] and [?,1]. for gradients_7/dense_2_1/Softmax_grad/gradients/gradients_7/dense_2_1/Softmax_grad/truediv_grad/Select_1 (op: 'Select') with input shapes: [?,1], [?,10], [?,10].

The error is in the line:
shap_values = e.shap_values(x_test[1:5])

Full code:

```<code>from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
          optimizer=keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

import shap
import numpy as np

# select a set of background examples to take an expectation over
background = x_train[np.random.choice(x_train.shape[0], 100, replace=False)]

# explain predictions of the model on three images
e = shap.DeepExplainer(model, background)
shap_values = e.shap_values(x_test[1:5])
shap.image_plot(shap_values, -x_test[1:5])
</code>```

答:
Which Keras version you are using? You can print from your code keras.__version__

When I imported keras under Tensorflow, your code worked as expected. One of the major change is using adam optimizer which works better in your case as it is able to improve accuracy within few epochs. I tried Adadelta but it was slowly optimizing. check the performance yourself.

Check the following code for small modifications (not much). All i did was to import modules under Tensorflow as keas 2.3.1 was throwing some other error.

```<code>from __future__ import print_function
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 256
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu', input_shape=input_shape,))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tf.keras.losses.categorical_crossentropy,
          optimizer=tf.keras.optimizers.Adam(0.001),#tf.keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
          steps_per_epoch = x_train.shape[0]//batch_size,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test),validation_steps=x_test.shape[0]//batch_size)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
</code>```

Body:
I was trying to implement shap DeepExplainer (DeepSHAP) module with the help of MNIST Dataset. But i am getting the following error:

ValueError: Dimension 1 in both shapes must be equal, but are 10 and 1. Shapes are [?,10] and [?,1]. for gradients_7/dense_2_1/Softmax_grad/gradients/gradients_7/dense_2_1/Softmax_grad/truediv_grad/Select_1 (op: 'Select') with input shapes: [?,1], [?,10], [?,10].

The error is in the line:
shap_values = e.shap_values(x_test[1:5])

Full code:

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
          optimizer=keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

import shap
import numpy as np

# select a set of background examples to take an expectation over
background = x_train[np.random.choice(x_train.shape[0], 100, replace=False)]

# explain predictions of the model on three images
e = shap.DeepExplainer(model, background)
shap_values = e.shap_values(x_test[1:5])
shap.image_plot(shap_values, -x_test[1:5])

Body:
Which Keras version you are using? You can print from your code keras.__version__

When I imported keras under Tensorflow, your code worked as expected. One of the major change is using adam optimizer which works better in your case as it is able to improve accuracy within few epochs. I tried Adadelta but it was slowly optimizing. check the performance yourself.

Check the following code for small modifications (not much). All i did was to import modules under Tensorflow as keas 2.3.1 was throwing some other error.

from __future__ import print_function
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 256
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu', input_shape=input_shape,))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tf.keras.losses.categorical_crossentropy,
          optimizer=tf.keras.optimizers.Adam(0.001),#tf.keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
          steps_per_epoch = x_train.shape[0]//batch_size,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test),validation_steps=x_test.shape[0]//batch_size)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])


来源: stackexchange

问:
Am i violating any NF RULE on my database design?
Good day!

I am a newbie on creating database... I need to create a db for my recruitment web application.

My database schema is as follows:

NOTE: I included the applicant_id on other tables... e.g. exam, interview, exam type.

Am i violating any normalization rule? If i do, what do you recommend to improve my design? Thank you

答: One area where I could see a potential problem is the Interviewer being integrated in interview. Also I would like to point at the source channel in applicant, which could potentially get blobbed (depending of what you're going to store in there).</p>

ContentLicense: CC BY-SA 3.0


问:
Adding a time based trigger using an add-on throws an error that does not exist when running the same code in the editor
I have included the code below. The issue is that when the 'createTestTrigger' function is run from the editor the function runs, creates the trigger, and the trigger runs. However, when I "Test as add-on" with a spreadsheet and run it from the add-on menu it fails with the following error:

Unexpected error while getting the method or property create on object ScriptApp.ClockTriggerBuilder.

This only seems to fail when running as an add-on. I tested it as part of a project in a workbook and that worked fine as well. I cannot find any documentation that would confirm my suspicions that Google simply does not allow add-ons to create triggers but I cannot find anything.

```<code>function onOpen(e) {
  const ui = SpreadsheetApp.getUi();
  var menu = ui.createAddonMenu();
  menu.addItem('Test trigger creattion', 'createTestTrigger')
  menu.addToUi();
}

function createTestTrigger() {
  ScriptApp.newTrigger('toBeTriggered')
  .timeBased()
  .after(5000)
  .create();
}

function toBeTriggered(e) {
  Logger.log('Ran from trigger: ' + e.triggerUid);
}
</code>```

答:
Quote from Google documentation:

Installable triggers aren't supported when testing. Functionality that
  depends on installable triggers are not testable.

https://developers.google.com/gsuite/add-ons/how-tos/testing-editor-addons#testing_details

You can not install a time based trigger when using the "Run - Test as add-on" menu item.

The best way to develop your add-on is by creating a bound script to the document, and running it that way.  For example, if it's a Sheets add-on, from the Sheets menu, click "Tools - Script editor" and a new Apps Script project will open and automatically be bound to the spreadsheet.

The problem with developing an add-on from a bound script, is that if you want to publish your add-on from a stand-alone script, then you need a way to transfer all the files from the bound project to the stand-alone project.  You won't want to manually copy and paste files.  One way to do that is with the Chrome extension:

https://chrome.google.com/webstore/detail/google-apps-script-github/lfjcgcmkmjjlieihflfhjopckgpelofo?hl=en

Upload to GitHub from the bound project then download from GitHub to the stand-alone project.

Related Note:
A time trigger created by an add-on can only run once per hour at most:
https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers

An add-on can not install one time-based trigger, and then 10 minutes later delete the first trigger and then install another time-based trigger.

ContentLicense: CC BY-SA 4.0

Body:
I have included the code below. The issue is that when the 'createTestTrigger' function is run from the editor the function runs, creates the trigger, and the trigger runs. However, when I "Test as add-on" with a spreadsheet and run it from the add-on menu it fails with the following error:

Unexpected error while getting the method or property create on object ScriptApp.ClockTriggerBuilder.

This only seems to fail when running as an add-on. I tested it as part of a project in a workbook and that worked fine as well. I cannot find any documentation that would confirm my suspicions that Google simply does not allow add-ons to create triggers but I cannot find anything.

function onOpen(e) {
  const ui = SpreadsheetApp.getUi();
  var menu = ui.createAddonMenu();
  menu.addItem('Test trigger creattion', 'createTestTrigger')
  menu.addToUi();
}

function createTestTrigger() {
  ScriptApp.newTrigger('toBeTriggered')
  .timeBased()
  .after(5000)
  .create();
}

function toBeTriggered(e) {
  Logger.log('Ran from trigger: ' + e.triggerUid);
}


问:
Search in belongsToMany-relation for item by pivot value
I got these models:

Order

Invoice

An Order can have many Invoices and an Invoice can belong to many Orders.

Example:

Orders:

Order #1

Order #2

Order #3

Invoices:

Invoice #1 -> belongs To Order #1 and Order #2 (so this Invoice contains both Orders)

Invoice #2 -> belongsTo  Order #2 and Order #3

Each belongsTo-relation saves a date as pivot, which defines the last date this order has been invoiced.

Now I'd like to create a isInvoiceable() getter for my Order-Model, which returns, whether the order has been invoiced within the last month or not. If the latest date is older than one month, return true, as this Order should create a new invoice.

So now I need your help: I need to check all invoices, whether there's an Order (belongsToMany) with the order_id of the current Order, and a date-pivot that's older than now - one month. I need to check the order_id because the Invoice could possibly contain information about other Orders, too.

And this is the missing link for me: How can I check the belongsToMany-relation in Invoice for date and order_id?

答:
Asuming you have defined your relation as 'invoices', you may do something like this:</p>

```<code>class Order extends Model {

...

public function isInvoiceable(){
    $lastInvoiceDate = (date('Y-m-d', $this->invoices()->latest()->created_at));
    $today = new Carbon(date('Y-m-d', strtotime(Input::get('startdate'))));
    $diff_months = $lastInvoiceDate->diff($today)->months;

    return $diff_months < 1;
}
</code>```

Body:
Asuming you have defined your relation as 'invoices', you may do something like this:

class Order extends Model {

...

public function isInvoiceable(){
    $lastInvoiceDate = (date('Y-m-d', $this->invoices()->latest()->created_at));
    $today = new Carbon(date('Y-m-d', strtotime(Input::get('startdate'))));
    $diff_months = $lastInvoiceDate->diff($today)->months;

    return $diff_months < 1;
}


问:
How to install git on Windows 10 without Git Bash or GUI?
I am trying to install Git on Windows 10, but without Git Bash or GUI. I want to use Git in PowerShell and I would like not to bloat my PC. I know the install size is small, but that's not the issue.

I've tried going through the installer from git-SMC/Git for Windows a couple times, but it appears I can not opt out of GUI and Bash. Any idea how I can do this? Perhaps Chocolatey is of any use?

Thanks in advance!

答:
The github repo publishes portable and minimum versions of the binary releases which don't require installation. You could prune out the parts you don't want if you need to cut it down further.

https://github.com/git-for-windows/git/releases

Or instalation Using Chocolatey, if that will be ok for you

https://www.jamessturtevant.com/posts/5-Ways-to-install-git-on-Windows/#using-chocolatey


答:
Your database design looks fine to me.

product_l1 (product_l1_id, allocation)

product_l2 (product_l2_id, allocation)

product_l3 (product_l3, allocation)

region (region_id, allocation)

country (country_id, allocation)

One could argue that a product is a product and one table with a product level indicator would suffice, but I consider this model with three tables appropriate. It guarantees that a level 1 product can not be used as a level 2 product for instance.

What's missing is the table holding the combinations you are showing:

combinations (product_l1_id, product_l2_id, product_l3_id, region_id, country_id)

UPDATE:

Looking at your data again, two things come to mind.

A country seems to belong to a region, so the country table should get a region_id.

A region has no fixed allocation.

In your sample data you are using the same combinations with different countries. You may hence want this split in two steps.

This would get something like this:

product_l1 (product_l1_id, name, allocation)

product_l2 (product_l2_id, name, allocation)

product_l3 (product_l3, name, allocation)

region (region_id, name)

country (country_id, name, region_id, allocation)

product_combination (product_combination_id, product_l1_id, product_l2_id, product_l3_id)

region_combination (product_combination_id, region_id, allocation)

final_combination (product_combination_id, country_id)

Title: Is my schema for a financial securities database correct?

Body:
I'm currently using a spreadsheet to calculate monetary allocations between financial products and regions. The table below is a small subset of thhe spreadsheet which has several hundred lines of data and more layers to the hierarchy:

+---------------+------------+---------------+------------+---------------+------------+---------------+------------+------------+------------+----------------+
| product_L1_id | Allocation | product_L2_id | Allocation | product_L3_id | Allocation |   region_id   | Allocation | country_id | Allocation | Net allocation |
+---------------+------------+---------------+------------+---------------+------------+---------------+------------+------------+------------+----------------+
| Bonds         | 100.0%     | Normal        | 60.0%      | Government    | 70.0%      | EMEA          | 80.0%      | UK         | 30.0%      | 10.1%          |
| Bonds         | 100.0%     | Normal        | 60.0%      | Government    | 70.0%      | EMEA          | 80.0%      | France     | 70.0%      | 23.5%          |
| Bonds         | 100.0%     | Normal        | 60.0%      | Government    | 70.0%      | North America | 20.0%      | US         | 0.0%       | 0.0%           |
| Bonds         | 100.0%     | Normal        | 60.0%      | Government    | 70.0%      | North America | 20.0%      | Canada     | 100.0%     | 8.4%           |
| Bonds         | 100.0%     | Normal        | 60.0%      | Corporate     | 30.0%      | EMEA          | 60.0%      | UK         | 80.0%      | 8.6%           |
| Bonds         | 100.0%     | Normal        | 60.0%      | Corporate     | 30.0%      | EMEA          | 60.0%      | France     | 20.0%      | 2.2%           |
| Bonds         | 100.0%     | Normal        | 60.0%      | Corporate     | 30.0%      | North America | 40.0%      | US         | 50.0%      | 3.6%           |
| Bonds         | 100.0%     | Normal        | 60.0%      | Corporate     | 30.0%      | North America | 40.0%      | Canada     | 50.0%      | 3.6%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | High yield    | 80.0%      | EMEA          | 30.0%      | UK         | 60.0%      | 5.8%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | High yield    | 80.0%      | EMEA          | 30.0%      | France     | 40.0%      | 3.8%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | High yield    | 80.0%      | North America | 70.0%      | US         | 30.0%      | 6.7%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | High yield    | 80.0%      | North America | 70.0%      | Canada     | 70.0%      | 15.7%          |
| Bonds         | 100.0%     | Foreign       | 40.0%      | Government    | 20.0%      | EMEA          | 100.0%     | UK         | 0.0%       | 0.0%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | Government    | 20.0%      | EMEA          | 100.0%     | France     | 100.0%     | 8.0%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | Government    | 20.0%      | North America | 0.0%       | US         | 70.0%      | 0.0%           |
| Bonds         | 100.0%     | Foreign       | 40.0%      | Government    | 20.0%      | North America | 0.0%       | Canada     | 30.0%      | 0.0%           |
+---------------+------------+---------------+------------+---------------+------------+---------------+------------+------------+------------+----------------+

Worth me pointing out that the same product_L3 can appear under a different product_L2 - see "Government" as an example.

The key output of the spreadsheet is the Net allocation field which is the product of all the individual allocations.

I'd like to convert this into my first database and I'd like to check my thinking before I spend lots of time implementing it. It seems obvious to me that there's the opportunity to use multiple tables so is my first attempt at a schema(?):

product_L1 table with id and allocation columns

product_L2 table with id and allocation columns

product_L3 table with id and allocation columns

Region table with id and allocation columns

Country table with id and allocation columns

I was then planning on using a foreign key in each table to link it to the previous table in the hierarchy. However, taking the Country table as an example - I think this will need each country to be duplicated multiple times and each record will have to have foreign keys from all the previous tables in order for a query to work out the Net allocation. Is this right/efficient? Is there a different way of thinking about this? I've read about nested sets but am not sure if they'd be the best solution here?

This isn't going to be a database for multiple users - just me.


问:
Elasticsearch Java API - How to get the number of documents without retrieving the documents
I need to get the number of documents in an index. not the documents themselves, but just this "how many" .

What's the best way to do that?

There is https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html. but I'm looking to do this in Java.

There also is https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/count.html, but it seems way old.

I can get all the documents in the given index and come up with "how many". But there must be a better way.

答:
Just an addition to @evanjd's answer

```<code>import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

 SearchResponse response = client.prepareSearch("your_index_goes_here")
   .setTypes("YourTypeGoesHere")
   .setQuery(QueryBuilders.termQuery("some_field", "some_value"))
   .setSize(0) // Don't return any documents, we don't need them.
   .get();

 SearchHits hits = response.getHits();
 long hitsCount = hits.getTotalHits().value;
</code>```

we need to add .value to get long value of total hits otherwise it will be a string value like "6 hits"

```<code>long hitsCount = hits.getTotalHits().value;
</code>```

long hitsCount = hits.getTotalHits().value;

Body:
Just an addition to @evanjd's answer

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

 SearchResponse response = client.prepareSearch("your_index_goes_here")
   .setTypes("YourTypeGoesHere")
   .setQuery(QueryBuilders.termQuery("some_field", "some_value"))
   .setSize(0) // Don't return any documents, we don't need them.
   .get();

 SearchHits hits = response.getHits();
 long hitsCount = hits.getTotalHits().value;

we need to add .value to get long value of total hits otherwise it will be a string value like "6 hits"

long hitsCount = hits.getTotalHits().value;

long hitsCount = hits.getTotalHits().value;


问:
Is there any easy algorithm to do edge coloring on a complete graph
For a given complete graph $G$ having $n$ nodes, how can we build a edge coloring of
$G$ with $n$ colors.</p>

答:
Just color the edge i,j with the color number i+j.
You will need n-1 colors.</p>


问:
osx - How to get a process id (PID) programmatically?
How can I get a process' ID? I require the ID in order to kill that process. I know the name of the process.

Thanks!

答: A quick hack: Spawn a shell call to killall, which kills a process by name.</p>


问:
what is minimum number of operations required to sort an array if:-
In each operation we can either push an element to the end of the array or at the beginning of it
for example an array  3 2 5 1 4 6 would take 4 steps.
after first operation 2 3 5 1 4 6
after second operation 1 2 3 5 4 6
after third operation 2 3 1 4 6 5
after fourth operation 1 2 3 4 5 6</p>

答:
I think in the best case, the array is already sorted - 0 operations needed.
In the worst case, its sorted already, but in the opposite order (eg 6 5 4 3 2 1), you gonna need number of elements-1 operations.</p>


问:
R: plotting - visualizing the common time period of events in a 24 hours timeframe from multiple dataframes
I have dataframes of events captured and i am finding a way to visualize which time period (1hr window) does these events usually occur in a 24 hours timeframe.

I'm only interested in the event starttime.
So x-axis of the plot should be a 24 hours series, breaks at 1hour.
and y-axis would be the different dataframes represented by a geom_point or something
And I like to seek advice how can I do this from multiple dataframes.

df1

```<code>        TimeStamp_start         TimeStamp_end  Fab23.A_start   Fab23.A_end
1   2020-03-01 21:56:00   2020-03-01 21:58:00       38.67555      184.4875
2   2020-03-02 20:48:00   2020-03-02 20:50:00       31.98126      186.0867
3   2020-03-03 18:14:00   2020-03-03 18:16:00       41.42305      189.7806
4   2020-03-04 17:50:00   2020-03-04 17:52:00       36.79726      190.0810
5   2020-03-05 16:58:00   2020-03-05 17:00:00       39.70075      189.8803
.
.
.

</code>```

df2

```<code>        TimeStamp_start         TimeStamp_end    Fab7.A_start    Fab7.A_end
1   2020-03-03 05:20:00   2020-03-03 05:22:00        39.98769      141.9722
2   2020-03-06 02:04:00   2020-03-06 02:06:00        40.59314      189.5027
3   2020-03-08 17:18:00   2020-03-08 17:20:00        47.79272      191.8802
4   2020-03-10 16:00:00   2020-03-10 16:02:00        42.69026      190.4804
.
.
</code>```

I'm wondering if it's possible to look like a dumbbell chart, but instead of the dumbbell it's presented by geom_point in density.

答:
It sounds like you want to plot the starting time of each event. Depending on the frequency and number of events, you might end up overplotting and something like a histogram or density plot would be a better visualization option. However, I use something like this to find periods of missing sampling in my own data. Let's start with just a single dataframe:

library(tidyverse)
library(lubridate)

## generate some random start date/time data
df1 <- tibble(start_time = as.POSIXlt("2020-03-01 21:56:00") + rnorm(100, 0, 604800))

## create a numeric hour/minute variable
df1 <- df1 %>%
  mutate(y_pos = "df1", ## this provides a y variable to map in ggplot
         start_hour = hour(start_time) + (minute(start_time)/60)) ## decimal hour.min

## plot it
ggplot(df1) +
  geom_point(aes(start_hour, y_pos),
             alpha = 0.9,
             shape = 124) +
  scale_x_continuous(limits = c(0,24),
                     breaks = 0:24)
```

<p><img src="https://i.stack.imgur.com/KnNxM.png" alt="rugplot"></p>

<p>If you have multiple dataframes, it is a matter of getting everything tidied up and creating a single dataframe. I would create some kind of categorical variable in each dataframe and just bind the rows.</p>

<pre class="lang-r prettyprint-override"><code>df2 <- tibble(start_time = as.POSIXlt("2020-03-01 21:56:00") + rnorm(100, 0, 604800)) %>%
  mutate(y_pos = "df2",
         start_hour = hour(start_time) + (minute(start_time)/60))

df1 <- df1 %>%
  bind_rows(df2)

ggplot(df1) +
  geom_point(aes(start_hour, y_pos),
             alpha = 0.9,
             shape = 124) +
  scale_x_continuous(limits = c(0,24),
                     breaks = 0:24)
</code>```

Body:
I have dataframes of events captured and i am finding a way to visualize which time period (1hr window) does these events usually occur in a 24 hours timeframe.

I'm only interested in the event starttime.
So x-axis of the plot should be a 24 hours series, breaks at 1hour.
and y-axis would be the different dataframes represented by a geom_point or something
And I like to seek advice how can I do this from multiple dataframes.

df1

        TimeStamp_start         TimeStamp_end  Fab23.A_start   Fab23.A_end
1   2020-03-01 21:56:00   2020-03-01 21:58:00       38.67555      184.4875
2   2020-03-02 20:48:00   2020-03-02 20:50:00       31.98126      186.0867
3   2020-03-03 18:14:00   2020-03-03 18:16:00       41.42305      189.7806
4   2020-03-04 17:50:00   2020-03-04 17:52:00       36.79726      190.0810
5   2020-03-05 16:58:00   2020-03-05 17:00:00       39.70075      189.8803
.
.
.

df2

        TimeStamp_start         TimeStamp_end    Fab7.A_start    Fab7.A_end
1   2020-03-03 05:20:00   2020-03-03 05:22:00        39.98769      141.9722
2   2020-03-06 02:04:00   2020-03-06 02:06:00        40.59314      189.5027
3   2020-03-08 17:18:00   2020-03-08 17:20:00        47.79272      191.8802
4   2020-03-10 16:00:00   2020-03-10 16:02:00        42.69026      190.4804
.
.

I'm wondering if it's possible to look like a dumbbell chart, but instead of the dumbbell it's presented by geom_point in density.

Body:
It sounds like you want to plot the starting time of each event. Depending on the frequency and number of events, you might end up overplotting and something like a histogram or density plot would be a better visualization option. However, I use something like this to find periods of missing sampling in my own data. Let's start with just a single dataframe:

library(tidyverse)
library(lubridate)

## generate some random start date/time data
df1 <- tibble(start_time = as.POSIXlt("2020-03-01 21:56:00") + rnorm(100, 0, 604800))

## create a numeric hour/minute variable
df1 <- df1 %>%
  mutate(y_pos = "df1", ## this provides a y variable to map in ggplot
         start_hour = hour(start_time) + (minute(start_time)/60)) ## decimal hour.min

## plot it
ggplot(df1) +
  geom_point(aes(start_hour, y_pos),
             alpha = 0.9,
             shape = 124) +
  scale_x_continuous(limits = c(0,24),
                     breaks = 0:24)

If you have multiple dataframes, it is a matter of getting everything tidied up and creating a single dataframe. I would create some kind of categorical variable in each dataframe and just bind the rows.

df2 <- tibble(start_time = as.POSIXlt("2020-03-01 21:56:00") + rnorm(100, 0, 604800)) %>%
  mutate(y_pos = "df2",
         start_hour = hour(start_time) + (minute(start_time)/60))

df1 <- df1 %>%
  bind_rows(df2)

ggplot(df1) +
  geom_point(aes(start_hour, y_pos),
             alpha = 0.9,
             shape = 124) +
  scale_x_continuous(limits = c(0,24),
                     breaks = 0:24)


问:
Kivy unable to access an id within the class of a kv file
So I am trying to put a table that I have rendered into a BoxLayout but somehow it seems to be unable to access it, I'm not sure on how to access it. I created a class itemlist(BoxLayout) and within it is a function to run it. I used the self.ids.content which is linked to the id:content in the kv file but somehow I am unable to access it. I either get a AttributeError: 'super' object has no attribute '__getattr__' error (the code as shown) or it doesn't run at all (if i remove the itemlist class from the kv)

PYTHON CODE

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
import sqlite3
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from datetime import datetime
from kivy.uix.boxlayout import BoxLayout
from collections import OrderedDict
from datatable import DataTable
from kivy.uix.widget import Widget

class MainWindow(Screen):
    amount=ObjectProperty(None)
    category=ObjectProperty(None)
    message=ObjectProperty(None)

    def add_expense(self):

        date = str(datetime.now())
        conn = sqlite3.connect("expenditure.db")
        cur = conn.cursor()
        cur.execute(""" INSERT INTO expenses (amount,category,message,date) VALUES (?,?,?,?)""", (self.amount.text,self.category.text,self.message.text,date))
        conn.commit()
        conn.close()
        self.amount.text=""
        self.category.text=""
        self.message.text=""

    def success(self):
        pop = Popup(title='Success!',
                  content=Label(text='Successfully added expense!'),
                  size_hint=(None, None), size=(400, 400))
        pop.open()

class SecondWindow(Screen):
    searched=ObjectProperty(None)
    class itemlist(BoxLayout):
        def __init__(self,**kwargs):
            super().__init__(**kwargs)

            content = self.ids.content
            entry = self.get_items()
            entrytable = DataTable(table=entry)
            content.add_widget(entrytable)

        def get_items(self):
            conn = sqlite3.connect("expenditure.db")
            cur = conn.cursor()

            _entries = OrderedDict(
                amountlist = {},
                categorylist = {},
                messagelist = {},
                datelist = {}
            )
            amountlist = []
            categorylist = []
            messagelist = []
            datelist = []
            sql = ("SELECT * FROM expenses;")
            cur.execute(sql)
            rows = cur.fetchall()
            for amt,cat,price,dt in rows:
                amountlist.append(amt)
                categorylist.append(cat)
                messagelist.append(price)
                datelist.append(dt)
            entrynum = len(amountlist)
            idx = 0
            while idx < entrynum:
                _entries['amountlist'][idx] = amountlist[idx]
                _entries['categorylist'][idx] = categorylist[idx]
                _entries['messagelist'][idx] = messagelist[idx]
                _entries['datelist'][idx] = datelist[idx]

                idx +=1

            return _entries

class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("my.kv")

def view(category=None):

    conn = db.connect("expenditure.db")
    cur = conn.cursor()
    if category:
        sql = '''
        select * from expenses where category = '{}'
        '''.format(category)
        sql2 = '''
        select sum(amount) from expenses where category = '{}'
        '''.format(category)
    else:
        sql = '''
        select * from expenses
        '''.format(category)
        sql2 = '''
        select sum(amount) from expenses
        '''.format(category)
    cur.execute(sql)
    results = cur.fetchall()
    cur.execute(sql2)
    total_amount = cur.fetchone()[0]

    return total_amount, results

class MyMainApp(App):
    def build(self):
        return kv

    conn = sqlite3.connect("expenditure.db")
    cur = conn.cursor()
    sql = '''
    create table if not exists expenses (
        amount number,
        category string,
        message string,
        date string
        )
    '''
    cur.execute(sql)
    conn.commit()

if __name__ == "__main__":
    MyMainApp().run()
</code>```

KV Code

```<code>WindowManager:
    MainWindow:
    SecondWindow:

<MainWindow>:
    name: "main"

    amount : amt
    category : ctgry
    message : msg

    GridLayout:
        cols:1

        Label:
            text: "Input your expenditure"
        GridLayout:
            cols: 2

            Label:
                text: "amount: "

            TextInput:
                id: amt
                multiline: False

            Label:
                text: "Category: "

            TextInput:
                id:ctgry
                multiline:False
            Label:
                text: "Message: "

            TextInput:
                id:msg
                multiline:False

            Button:
                text: "Submit"
                on_press:root.add_expense()
                on_release:root.success()

            Button:
                text: "See your items"
                on_release:
                    app.root.current = "second"
                    root.manager.transition.direction = "left"

<SecondWindow>:
    name: "second"
    searched : categorysearch
    GridLayout:
        cols:1

        GridLayout:
            cols:3
            Label:
                text: "Category: "

            TextInput:
                id:categorysearch
                multiline:False
            Button:
                text: "Search category"

        itemlist:
            BoxLayout:
                id:content

        Button:
            text: "Go Back"
            on_release:
                app.root.current = "main"
                root.manager.transition.direction = "right"
</code>```

I'm not sure if the issue is due to the class level or something. if it is how to fix it? Thank you!

Edit: I have also tried removing the class itemlist(BoxLayout) to make it directly under secondwindow and made minor adjustments to the kv file but it still doesn't work. I have no other idea on how to approach this.

答:
I couldn't find the datatable that you are using, so I couldn't completely run your code. In spite of that problem, I have some suggested changes to your code to make it work as I believe you want. First, I changed the indentation of your itemList class definition so that it is not an inner class of SecondWindow. Like this:

```<code>class SecondWindow(Screen):
    searched=ObjectProperty(None)

class itemlist(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        #content = self.ids.content  # not needed, this is the container
        entry = self.get_items()
        entrytable = DataTable(table=entry)
        #content.add_widget(entrytable)  # replaced with self.add_widget()
        self.add_widget(entrytable)

    def get_items(self):
        conn = sqlite3.connect("expenditure.db")
        cur = conn.cursor()

        _entries = OrderedDict(
            amountlist = {},
            categorylist = {},
            messagelist = {},
            datelist = {}
        )
        amountlist = []
        categorylist = []
        messagelist = []
        datelist = []
        sql = ("SELECT * FROM expenses;")
        cur.execute(sql)
        rows = cur.fetchall()
        for amt,cat,price,dt in rows:
            amountlist.append(amt)
            categorylist.append(cat)
            messagelist.append(price)
            datelist.append(dt)
        entrynum = len(amountlist)
        idx = 0
        while idx < entrynum:
            _entries['amountlist'][idx] = amountlist[idx]
            _entries['categorylist'][idx] = categorylist[idx]
            _entries['messagelist'][idx] = messagelist[idx]
            _entries['datelist'][idx] = datelist[idx]

            idx +=1

        return _entries
</code>```

I have modified the __init__() method. Since the itemList is the BoxLayout, you don't need to query the ids, just use self.

I also removed the extra BoxLayout from your kv, so your SecondWindow rule in kv now looks like:

```<code><SecondWindow>:
    name: "second"
    searched : categorysearch
    GridLayout:
        cols:1

        GridLayout:
            cols:3
            Label:
                text: "Category: "

            TextInput:
                id:categorysearch
                multiline:False
            Button:
                text: "Search category"

        itemlist:
            id:content

        Button:
            text: "Go Back"
            on_release:
                app.root.current = "main"
                root.manager.transition.direction = "right"
</code>```

And the id: content is not needed for your posted code, so that can also be removed.

Body:
So I am trying to put a table that I have rendered into a BoxLayout but somehow it seems to be unable to access it, I'm not sure on how to access it. I created a class itemlist(BoxLayout) and within it is a function to run it. I used the self.ids.content which is linked to the id:content in the kv file but somehow I am unable to access it. I either get a AttributeError: 'super' object has no attribute '__getattr__' error (the code as shown) or it doesn't run at all (if i remove the itemlist class from the kv)

PYTHON CODE

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
import sqlite3
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from datetime import datetime
from kivy.uix.boxlayout import BoxLayout
from collections import OrderedDict
from datatable import DataTable
from kivy.uix.widget import Widget

class MainWindow(Screen):
    amount=ObjectProperty(None)
    category=ObjectProperty(None)
    message=ObjectProperty(None)

    def add_expense(self):

        date = str(datetime.now())
        conn = sqlite3.connect("expenditure.db")
        cur = conn.cursor()
        cur.execute(""" INSERT INTO expenses (amount,category,message,date) VALUES (?,?,?,?)""", (self.amount.text,self.category.text,self.message.text,date))
        conn.commit()
        conn.close()
        self.amount.text=""
        self.category.text=""
        self.message.text=""

    def success(self):
        pop = Popup(title='Success!',
                  content=Label(text='Successfully added expense!'),
                  size_hint=(None, None), size=(400, 400))
        pop.open()

class SecondWindow(Screen):
    searched=ObjectProperty(None)
    class itemlist(BoxLayout):
        def __init__(self,**kwargs):
            super().__init__(**kwargs)

            content = self.ids.content
            entry = self.get_items()
            entrytable = DataTable(table=entry)
            content.add_widget(entrytable)

        def get_items(self):
            conn = sqlite3.connect("expenditure.db")
            cur = conn.cursor()

            _entries = OrderedDict(
                amountlist = {},
                categorylist = {},
                messagelist = {},
                datelist = {}
            )
            amountlist = []
            categorylist = []
            messagelist = []
            datelist = []
            sql = ("SELECT * FROM expenses;")
            cur.execute(sql)
            rows = cur.fetchall()
            for amt,cat,price,dt in rows:
                amountlist.append(amt)
                categorylist.append(cat)
                messagelist.append(price)
                datelist.append(dt)
            entrynum = len(amountlist)
            idx = 0
            while idx < entrynum:
                _entries['amountlist'][idx] = amountlist[idx]
                _entries['categorylist'][idx] = categorylist[idx]
                _entries['messagelist'][idx] = messagelist[idx]
                _entries['datelist'][idx] = datelist[idx]

                idx +=1

            return _entries

class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("my.kv")

def view(category=None):

    conn = db.connect("expenditure.db")
    cur = conn.cursor()
    if category:
        sql = '''
        select * from expenses where category = '{}'
        '''.format(category)
        sql2 = '''
        select sum(amount) from expenses where category = '{}'
        '''.format(category)
    else:
        sql = '''
        select * from expenses
        '''.format(category)
        sql2 = '''
        select sum(amount) from expenses
        '''.format(category)
    cur.execute(sql)
    results = cur.fetchall()
    cur.execute(sql2)
    total_amount = cur.fetchone()[0]

    return total_amount, results

class MyMainApp(App):
    def build(self):
        return kv

    conn = sqlite3.connect("expenditure.db")
    cur = conn.cursor()
    sql = '''
    create table if not exists expenses (
        amount number,
        category string,
        message string,
        date string
        )
    '''
    cur.execute(sql)
    conn.commit()

if __name__ == "__main__":
    MyMainApp().run()

KV Code

WindowManager:
    MainWindow:
    SecondWindow:

<MainWindow>:
    name: "main"

    amount : amt
    category : ctgry
    message : msg

    GridLayout:
        cols:1

        Label:
            text: "Input your expenditure"
        GridLayout:
            cols: 2

            Label:
                text: "amount: "

            TextInput:
                id: amt
                multiline: False

            Label:
                text: "Category: "

            TextInput:
                id:ctgry
                multiline:False
            Label:
                text: "Message: "

            TextInput:
                id:msg
                multiline:False

            Button:
                text: "Submit"
                on_press:root.add_expense()
                on_release:root.success()

            Button:
                text: "See your items"
                on_release:
                    app.root.current = "second"
                    root.manager.transition.direction = "left"

<SecondWindow>:
    name: "second"
    searched : categorysearch
    GridLayout:
        cols:1

        GridLayout:
            cols:3
            Label:
                text: "Category: "

            TextInput:
                id:categorysearch
                multiline:False
            Button:
                text: "Search category"

        itemlist:
            BoxLayout:
                id:content

        Button:
            text: "Go Back"
            on_release:
                app.root.current = "main"
                root.manager.transition.direction = "right"

I'm not sure if the issue is due to the class level or something. if it is how to fix it? Thank you!

Edit: I have also tried removing the class itemlist(BoxLayout) to make it directly under secondwindow and made minor adjustments to the kv file but it still doesn't work. I have no other idea on how to approach this.

Body:
I couldn't find the datatable that you are using, so I couldn't completely run your code. In spite of that problem, I have some suggested changes to your code to make it work as I believe you want. First, I changed the indentation of your itemList class definition so that it is not an inner class of SecondWindow. Like this:

class SecondWindow(Screen):
    searched=ObjectProperty(None)

class itemlist(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        #content = self.ids.content  # not needed, this is the container
        entry = self.get_items()
        entrytable = DataTable(table=entry)
        #content.add_widget(entrytable)  # replaced with self.add_widget()
        self.add_widget(entrytable)

    def get_items(self):
        conn = sqlite3.connect("expenditure.db")
        cur = conn.cursor()

        _entries = OrderedDict(
            amountlist = {},
            categorylist = {},
            messagelist = {},
            datelist = {}
        )
        amountlist = []
        categorylist = []
        messagelist = []
        datelist = []
        sql = ("SELECT * FROM expenses;")
        cur.execute(sql)
        rows = cur.fetchall()
        for amt,cat,price,dt in rows:
            amountlist.append(amt)
            categorylist.append(cat)
            messagelist.append(price)
            datelist.append(dt)
        entrynum = len(amountlist)
        idx = 0
        while idx < entrynum:
            _entries['amountlist'][idx] = amountlist[idx]
            _entries['categorylist'][idx] = categorylist[idx]
            _entries['messagelist'][idx] = messagelist[idx]
            _entries['datelist'][idx] = datelist[idx]

            idx +=1

        return _entries

I have modified the __init__() method. Since the itemList is the BoxLayout, you don't need to query the ids, just use self.

I also removed the extra BoxLayout from your kv, so your SecondWindow rule in kv now looks like:

<SecondWindow>:
    name: "second"
    searched : categorysearch
    GridLayout:
        cols:1

        GridLayout:
            cols:3
            Label:
                text: "Category: "

            TextInput:
                id:categorysearch
                multiline:False
            Button:
                text: "Search category"

        itemlist:
            id:content

        Button:
            text: "Go Back"
            on_release:
                app.root.current = "main"
                root.manager.transition.direction = "right"

And the id: content is not needed for your posted code, so that can also be removed.


问:
checkboxes in php - problem with access
i need to reproduce with the code below something like:

```<code>myformdata[languages1]
myformdata[languages2]
myformdata[languages3]
</code>```

But with this code only reproduce myformdata[languages

```<code>    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
    }
    ?>
</code>```

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

答:
Change this line

```<code> echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
</code>```

to

```<code> echo nl2br ("<input type='checkbox' name='myformdata[languages" .$i++. "]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
</code>```

Also I'm not 100% sure whether []'s are allowed for names of elements. If not you could consider change the name to be like

```<code>myformdata_1 ect...
</code>```

Title: checkboxes in php - problem with access

Body:
i need to reproduce with the code below something like:

myformdata[languages1]
myformdata[languages2]
myformdata[languages3]

But with this code only reproduce myformdata[languages

    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data  \n");
    }
    ?>

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

Body:
Change this line

 echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");

to

 echo nl2br ("<input type='checkbox' name='myformdata[languages" .$i++. "]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");

Also I'm not 100% sure whether []'s are allowed for names of elements. If not you could consider change the name to be like

myformdata_1 ect...


问:
Navigation Drawer menu items aren't clickable
Nothing is happening when I'm selecting any option from the navigation drawer. As soon as I click on the navigation drawer the drawer closes. I'll add my GitHub repository link also if you want to try correcting from there you are very much welcome:

https://github.com/tanmay380/andorid-studio-

This is my alphabetBaseShow class which shows the Navigation Drawer (I'll delete some of the lines so that it uses less space)

```<code>package com.example.myapplication.background;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.infront.CharacterSelection;
import com.example.myapplication.infront.SplashScreen;
import com.software.shell.fab.ActionButton;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

public class alphabetBaseShow extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    protected String mPracticeString;
    protected DrawingView mDrawView;
    public SeekBar seekBar;
    Button button;
    public boolean draw = true;
    AudioManager audio;
    protected TextView mScoreTimerView;
    protected TextView mBestScoreView;
    protected boolean mDone;
    public AlertDialog.Builder alertDialog;
    private static final int STORAGE_PERMISSION_CODE = 101;
    public TextView colorset;
    public NavigationView navigationView;
    //private TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            System.gc();
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_alphabet_show);

            Toolbar toolbar = findViewById(R.id.PracticeToolbar);
            setSupportActionBar(toolbar);
            // textToSpeech=new TextToSpeech(this,LanguageSelection);
            drawerLayout = findViewById(R.id.drawerLayout);
            actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.close, R.string.open);
            drawerLayout.addDrawerListener(actionBarDrawerToggle);
            actionBarDrawerToggle.syncState();

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            mDrawView = new DrawingView(this);
            seekBar = findViewById(R.id.size1);
            mDrawView = findViewById(R.id.DrawingView);
            mBestScoreView = (TextView) findViewById(R.id.best_score_View);
            mScoreTimerView = (TextView) findViewById(R.id.score_and_timer_View);
            mPracticeString = getIntent().getStringExtra(getResources().getString(R.string.practice_string));
            mDone = false;
            mScoreTimerView.bringToFront();

            mDrawView.canVibrate(true);
            mDrawView.setBitmapFromText(mPracticeString);

            audio = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

        /*switch (audio.getStreamVolume(AudioManager.STREAM_MUSIC)) {
            case AudioManager.RINGER_MODE_SILENT:
                Toast.makeText(getApplicationContext(), "TURN UP THE VOLUME", Toast.LENGTH_SHORT).show();
        }*/
            if ((audio.getStreamVolume(AudioManager.STREAM_MUSIC) > 1)) {
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
            else if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
                audio.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 1);

                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        catch (Exception e) {
            showErrorDialog(e);
        }

    }

    private void toggleSeekbar() {
        if (seekBar.getVisibility() == View.INVISIBLE) {
            seekBar.setVisibility(View.VISIBLE);
            seekBar.bringToFront();
            mDrawView.candraw(false);
        }
        else {
            seekBar.setVisibility(View.INVISIBLE);
            mDrawView.candraw(true);
        }

    }

    public void clickit() {
        toggleSeekbar();
        setSize();
    }

    public void setSize() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mDrawView.setCurrentWidth(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                toggleSeekbar();
            }
        });
        return;
    }

    public void practiceOnClick(View v) {
        switch (v.getId()) {

            case R.id.reset:
                if (mDone) {
                    mDrawView.init();
                }

                mDrawView.setBitmapFromText(mPracticeString);
                mBestScoreView.setAnimation(Animator.createFadeOutAnimation());
                mDrawView.startAnimation(Animator.createScaleUpAnimation());
                mScoreTimerView.setAnimation(Animator.createFadeOutAnimation());

                Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_done);
                Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
                mDone = false; //implies that the user isn't done
                mDrawView.candraw(true);

                break;

            case R.id.done:
                String result = mDrawView.saveBitmap(mPracticeString, "");
                if (result.charAt(0) == '/')
                    result = "Trace Saved";

                Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); // Toast displayed with the status of saving the trace
                if (!mDone) {
                    float best = SplashScreen.mDbHelper.getScore(mPracticeString);
                    if (best < mDrawView.score()) {
                        best = mDrawView.score();
                        SplashScreen.mDbHelper.writeScore(mPracticeString, best);
                    }

                    //Animations for when the user is done with the trace
                    mDrawView.startAnimation(Animator.createScaleDownAnimation());
                    findViewById(R.id.best_score_View).bringToFront();
                    ((TextView) findViewById(R.id.best_score_View)).setText("Best: " + String.valueOf(best));
                    mScoreTimerView.setText("Score: " + String.valueOf(mDrawView.score()));
                    mScoreTimerView.setAnimation(Animator.createFadeInAnimation());
                    mBestScoreView.setAnimation(Animator.createFadeInAnimation());

                    Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                    ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_save);
                    Animator.createYFlipBackwardAnimation(findViewById(R.id.done));

                    mDrawView.candraw(false);
                    mDone = true;
                }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        if (!mDone) {
            int next = Arrays.asList(SplashScreen.CHARACTER_LIST).indexOf(mPracticeString);
            switch (item.getItemId()) {

                case R.id.action_next:
                    next = (next + 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.action_previous:

                    next = (next + SplashScreen.CHARACTER_LIST.length - 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.setting:
                    clickit();
                    break;
            }

            if (item.getItemId() == R.id.action_next || item.getItemId() == R.id.action_previous) {
                mPracticeString = SplashScreen.CHARACTER_LIST[next];
                mDrawView.setBitmapFromText(mPracticeString);
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    protected void showErrorDialog(final Exception e) {
        new AlertDialog.Builder(this)
                .setTitle("ERROR")
                .setMessage(Log.getStackTraceString(e))
                .setPositiveButton("Save to File", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name));
                            File file = new File(mediaStorageDir.getPath() + File.separator + "error.txt");
                            if (file.exists() || file.createNewFile()) {
                                FileOutputStream fOut = new FileOutputStream(file, true);
                                fOut.write(("\n\n" + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n\n").getBytes());
                                fOut.write(Log.getStackTraceString(e).getBytes());
                                fOut.flush();
                                fOut.close();
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();

        switch (id) {
            case R.id.green:
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
                break;
            case R.id.red:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.black:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.blue:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}
</code>```

This is my XML file (deleted some Textview lines as they were not important hence less space will be required):

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".background.alphabetBaseShow">

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:layout_marginTop="55dp"
        app:headerLayout="@layout/header"
        app:menu="@menu/colors"
        android:clickable="true">

    </android.support.design.widget.NavigationView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/PracticeToolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/ActionbarBg"
            app:title="PRACTICE " />

        <com.example.myapplication.background.DrawingView
            android:id="@+id/DrawingView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/done"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginBottom="0dp"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_done" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_reset" />
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>
</code>```

This is my colors.xml (menu file). I've even tried to add onClick inside item, but it didn't work:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/green"
            android:icon="@drawable/ic_save"
            android:title="GREEN" />
        <item
            android:id="@+id/black"
            android:icon="@drawable/ic_save"
            android:title="BLACK" />
        <item
            android:id="@+id/blue"
            android:icon="@drawable/ic_save"
            android:title="BLUE" />
        <item
            android:id="@+id/red"
            android:icon="@drawable/ic_save"
            android:title="RED"
            android:onClick="toast"/>

    </group>
</menu>
</code>```

答: I just need to put the NAVIGATIONDRAWER part at the end.</p>

Body:
Nothing is happening when I'm selecting any option from the navigation drawer. As soon as I click on the navigation drawer the drawer closes. I'll add my GitHub repository link also if you want to try correcting from there you are very much welcome:

https://github.com/tanmay380/andorid-studio-

This is my alphabetBaseShow class which shows the Navigation Drawer (I'll delete some of the lines so that it uses less space)

package com.example.myapplication.background;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.infront.CharacterSelection;
import com.example.myapplication.infront.SplashScreen;
import com.software.shell.fab.ActionButton;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

public class alphabetBaseShow extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    protected String mPracticeString;
    protected DrawingView mDrawView;
    public SeekBar seekBar;
    Button button;
    public boolean draw = true;
    AudioManager audio;
    protected TextView mScoreTimerView;
    protected TextView mBestScoreView;
    protected boolean mDone;
    public AlertDialog.Builder alertDialog;
    private static final int STORAGE_PERMISSION_CODE = 101;
    public TextView colorset;
    public NavigationView navigationView;
    //private TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            System.gc();
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_alphabet_show);

            Toolbar toolbar = findViewById(R.id.PracticeToolbar);
            setSupportActionBar(toolbar);
            // textToSpeech=new TextToSpeech(this,LanguageSelection);
            drawerLayout = findViewById(R.id.drawerLayout);
            actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.close, R.string.open);
            drawerLayout.addDrawerListener(actionBarDrawerToggle);
            actionBarDrawerToggle.syncState();

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            mDrawView = new DrawingView(this);
            seekBar = findViewById(R.id.size1);
            mDrawView = findViewById(R.id.DrawingView);
            mBestScoreView = (TextView) findViewById(R.id.best_score_View);
            mScoreTimerView = (TextView) findViewById(R.id.score_and_timer_View);
            mPracticeString = getIntent().getStringExtra(getResources().getString(R.string.practice_string));
            mDone = false;
            mScoreTimerView.bringToFront();

            mDrawView.canVibrate(true);
            mDrawView.setBitmapFromText(mPracticeString);

            audio = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

        /*switch (audio.getStreamVolume(AudioManager.STREAM_MUSIC)) {
            case AudioManager.RINGER_MODE_SILENT:
                Toast.makeText(getApplicationContext(), "TURN UP THE VOLUME", Toast.LENGTH_SHORT).show();
        }*/
            if ((audio.getStreamVolume(AudioManager.STREAM_MUSIC) > 1)) {
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
            else if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
                audio.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 1);

                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        catch (Exception e) {
            showErrorDialog(e);
        }

    }

    private void toggleSeekbar() {
        if (seekBar.getVisibility() == View.INVISIBLE) {
            seekBar.setVisibility(View.VISIBLE);
            seekBar.bringToFront();
            mDrawView.candraw(false);
        }
        else {
            seekBar.setVisibility(View.INVISIBLE);
            mDrawView.candraw(true);
        }

    }

    public void clickit() {
        toggleSeekbar();
        setSize();
    }

    public void setSize() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mDrawView.setCurrentWidth(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                toggleSeekbar();
            }
        });
        return;
    }

    public void practiceOnClick(View v) {
        switch (v.getId()) {

            case R.id.reset:
                if (mDone) {
                    mDrawView.init();
                }

                mDrawView.setBitmapFromText(mPracticeString);
                mBestScoreView.setAnimation(Animator.createFadeOutAnimation());
                mDrawView.startAnimation(Animator.createScaleUpAnimation());
                mScoreTimerView.setAnimation(Animator.createFadeOutAnimation());

                Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_done);
                Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
                mDone = false; //implies that the user isn't done
                mDrawView.candraw(true);

                break;

            case R.id.done:
                String result = mDrawView.saveBitmap(mPracticeString, "");
                if (result.charAt(0) == '/')
                    result = "Trace Saved";

                Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); // Toast displayed with the status of saving the trace
                if (!mDone) {
                    float best = SplashScreen.mDbHelper.getScore(mPracticeString);
                    if (best < mDrawView.score()) {
                        best = mDrawView.score();
                        SplashScreen.mDbHelper.writeScore(mPracticeString, best);
                    }

                    //Animations for when the user is done with the trace
                    mDrawView.startAnimation(Animator.createScaleDownAnimation());
                    findViewById(R.id.best_score_View).bringToFront();
                    ((TextView) findViewById(R.id.best_score_View)).setText("Best: " + String.valueOf(best));
                    mScoreTimerView.setText("Score: " + String.valueOf(mDrawView.score()));
                    mScoreTimerView.setAnimation(Animator.createFadeInAnimation());
                    mBestScoreView.setAnimation(Animator.createFadeInAnimation());

                    Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                    ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_save);
                    Animator.createYFlipBackwardAnimation(findViewById(R.id.done));

                    mDrawView.candraw(false);
                    mDone = true;
                }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        if (!mDone) {
            int next = Arrays.asList(SplashScreen.CHARACTER_LIST).indexOf(mPracticeString);
            switch (item.getItemId()) {

                case R.id.action_next:
                    next = (next + 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.action_previous:

                    next = (next + SplashScreen.CHARACTER_LIST.length - 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.setting:
                    clickit();
                    break;
            }

            if (item.getItemId() == R.id.action_next || item.getItemId() == R.id.action_previous) {
                mPracticeString = SplashScreen.CHARACTER_LIST[next];
                mDrawView.setBitmapFromText(mPracticeString);
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    protected void showErrorDialog(final Exception e) {
        new AlertDialog.Builder(this)
                .setTitle("ERROR")
                .setMessage(Log.getStackTraceString(e))
                .setPositiveButton("Save to File", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name));
                            File file = new File(mediaStorageDir.getPath() + File.separator + "error.txt");
                            if (file.exists() || file.createNewFile()) {
                                FileOutputStream fOut = new FileOutputStream(file, true);
                                fOut.write(("\n\n" + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n\n").getBytes());
                                fOut.write(Log.getStackTraceString(e).getBytes());
                                fOut.flush();
                                fOut.close();
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();

        switch (id) {
            case R.id.green:
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
                break;
            case R.id.red:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.black:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.blue:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}

This is my XML file (deleted some Textview lines as they were not important hence less space will be required):

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".background.alphabetBaseShow">

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:layout_marginTop="55dp"
        app:headerLayout="@layout/header"
        app:menu="@menu/colors"
        android:clickable="true">

    </android.support.design.widget.NavigationView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/PracticeToolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/ActionbarBg"
            app:title="PRACTICE " />

        <com.example.myapplication.background.DrawingView
            android:id="@+id/DrawingView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/done"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginBottom="0dp"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_done" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_reset" />
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>

This is my colors.xml (menu file). I've even tried to add onClick inside item, but it didn't work:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/green"
            android:icon="@drawable/ic_save"
            android:title="GREEN" />
        <item
            android:id="@+id/black"
            android:icon="@drawable/ic_save"
            android:title="BLACK" />
        <item
            android:id="@+id/blue"
            android:icon="@drawable/ic_save"
            android:title="BLUE" />
        <item
            android:id="@+id/red"
            android:icon="@drawable/ic_save"
            android:title="RED"
            android:onClick="toast"/>

    </group>
</menu>


问:
Type '{ text: string; }' is not assignable to type 'TitleObject'. in highcharts
When I use HighCharts angular so I get this error,
Type '{ text: string; }' is not assignable to type 'TitleObject'.

```<code>const sampleData: Highcharts.Chart = {
      chart: {
        type: 'column',
      },
      title: { text: 'Total Predected Revenue Vs Actual Revenue' },
      xAxis: {
        categories: [
          '2010',
          '2011',
          '2012',
          '2013',
          '2014',
          '2015',
          '2016',
          '2017',
        ],
        crosshair: true,
      },
      yAxis: {
        min: 0,
      },
      series: [
        {
          name: 'Predected',
          data: [14, 17, 9, 10, 6, 19, 6, 8] ,
        } ,
        {
          name: 'Actual',
          data: [65, 74, 44, 66, 9, 23, 36, 51],
        },
      ],
    };
</code>```

for Title, categories,yaxis, and for data i get the error Type '{  }' is not assignable to type ' '. in highcharts

答:
Try to create an instance of the Chart class.

const sampleData = Highcharts.Chart(options = {...})
```

Body:
When I use HighCharts angular so I get this error,
Type '{ text: string; }' is not assignable to type 'TitleObject'.

const sampleData: Highcharts.Chart = {
      chart: {
        type: 'column',
      },
      title: { text: 'Total Predected Revenue Vs Actual Revenue' },
      xAxis: {
        categories: [
          '2010',
          '2011',
          '2012',
          '2013',
          '2014',
          '2015',
          '2016',
          '2017',
        ],
        crosshair: true,
      },
      yAxis: {
        min: 0,
      },
      series: [
        {
          name: 'Predected',
          data: [14, 17, 9, 10, 6, 19, 6, 8] ,
        } ,
        {
          name: 'Actual',
          data: [65, 74, 44, 66, 9, 23, 36, 51],
        },
      ],
    };

for Title, categories,yaxis, and for data i get the error Type '{  }' is not assignable to type ' '. in highcharts


问:
Add Jira issue number to git commit message automatically in VS Code
We add Jira Issue # to the commit message to link the change with the Jira Issue. As the issue number is added manually, it is pron to human errors. As we always have this number in the git branch, can the commit message have default value of this branch name? Can it be done by vs code extension or git templates?

答: Actually I've found Flow / Jira Commit Prefix extension that does pretty much what I need. One can adjust the sources by it's need.


问:
Why basic_ifstream show me wrong results?
I have a binary file. There are 2288*2288 longitude float values stored in top half section, and the same number of latitude float values occupied the bottom half. I used the following code to load them into a float vector. It can run like a charm, but gave me incorrect results. With regard to my binary file, the float vector should be filled with a total of 2288*2288*2=10469888 elements, but only 159005, all their values are the same 200.0000. Would you please explain what's wrong with my code?

Thank you in advance!

```<code>bool LoadData(const char* pszDataFile)
{
    typedef char_traits<float> traits_type;
    typedef std::codecvt<float, char, mbstate_t> cvt;

    std::basic_ifstream<float, traits_type> input( pszDataFile, std::ios::binary );
    std::locale loc(std::locale(), new cvt());
    input.imbue(loc);

    std::vector<float> fvBuffer;

    // Copies all data into buffer
    std::copy(std::istreambuf_iterator<float>(input),
              std::istreambuf_iterator<float>( ),
              std::back_inserter(fvBuffer));

    long nSzie = fvBuffer.size();  // Wrong vector size (159005)

    return true;
}
</code>```

答:
If you imbue() a file stream after the file is opened the imbue() will silently fail.

You must do the imbue() then open the file:

```<code>std::basic_ifstream<float, traits_type> input;
std::locale loc(std::locale(), new cvt());
input.imbue(loc);

// Open after the imbue()
input.open( pszDataFile, std::ios::binary );
</code>```

Your second problem is you are confusing the terms binary file:

This code reads a stream of text data (i.e. a text file) using the operator >>

```<code>std::copy(std::istreambuf_iterator<float>(input),
          std::istreambuf_iterator<float>( ),
          std::back_inserter(fvBuffer));
</code>```

The use of std::ios::binary when you open the file only affects the how the 'end of line sequence' (EOLS) is generated it has nothing to do with the nature of the file. Though because you specify it the '\n' character is not converted into the EOLS which is useful when you are generating binary files.

So the short answer is you better by reading a text stream from a file.

The reason your vector is shorter than what you expect is because the stream reading encountered an error and as a result stopped responding to read requests.

Additionally I can't get your code to compile.

So you are doing something else non-standard.

Body:
I have a binary file. There are 2288*2288 longitude float values stored in top half section, and the same number of latitude float values occupied the bottom half. I used the following code to load them into a float vector. It can run like a charm, but gave me incorrect results. With regard to my binary file, the float vector should be filled with a total of 2288*2288*2=10469888 elements, but only 159005, all their values are the same 200.0000. Would you please explain what's wrong with my code?

Thank you in advance!

bool LoadData(const char* pszDataFile)
{
    typedef char_traits<float> traits_type;
    typedef std::codecvt<float, char, mbstate_t> cvt;

    std::basic_ifstream<float, traits_type> input( pszDataFile, std::ios::binary );
    std::locale loc(std::locale(), new cvt());
    input.imbue(loc);

    std::vector<float> fvBuffer;

    // Copies all data into buffer
    std::copy(std::istreambuf_iterator<float>(input),
              std::istreambuf_iterator<float>( ),
              std::back_inserter(fvBuffer));

    long nSzie = fvBuffer.size();  // Wrong vector size (159005)

    return true;
}

Body:
If you imbue() a file stream after the file is opened the imbue() will silently fail.

You must do the imbue() then open the file:

std::basic_ifstream<float, traits_type> input;
std::locale loc(std::locale(), new cvt());
input.imbue(loc);

// Open after the imbue()
input.open( pszDataFile, std::ios::binary );

Your second problem is you are confusing the terms binary file:

This code reads a stream of text data (i.e. a text file) using the operator >>

std::copy(std::istreambuf_iterator<float>(input),
          std::istreambuf_iterator<float>( ),
          std::back_inserter(fvBuffer));

The use of std::ios::binary when you open the file only affects the how the 'end of line sequence' (EOLS) is generated it has nothing to do with the nature of the file. Though because you specify it the '\n' character is not converted into the EOLS which is useful when you are generating binary files.

So the short answer is you better by reading a text stream from a file.

The reason your vector is shorter than what you expect is because the stream reading encountered an error and as a result stopped responding to read requests.

Additionally I can't get your code to compile.

So you are doing something else non-standard.