问:
Joining two tables and then selecting only info based on criteria in a third table
So I joined two tables but I only want to select info from that join based on criteria defined in another table. I only want info from the first join where the actors name is in the popactor table. </p>

```<code>select  h.movie,
        h.released,
        a.rating,
        h.actor
  from  hollywood.stars h
    inner join starmovies a on h.movie =a.title
    inner join popactor p on p.actor = h.actor
  where h.movie = a.title and p.actor = h.actor;
</code>```

答:
First your where clause is useless as the 2 conditions are already in the ON clause of your joins so you could get rid of it. Then you have two ways to achieve what you are looking for :
As suggested in comments :

```<code>select
  h.movie,
  h.released,
  a.rating,
  h.actor
from
  hollywood.stars h
  inner join starmovies a on h.movie = a.title
where h.actor IN (select actor FROM popactor)
</code>```

OR as you already did :

```<code>select
  h.movie,
  h.released,
  a.rating,
  h.actor
from
  hollywood.stars h
  inner join starmovies a on h.movie =a.title
  inner join popactor p on p.actor = h.actor
</code>```

Of course, if h.actor nor p.actor is the actor name on which you want to filter, you need to replace these fields in both queries with the right ones.

Body:
So I joined two tables but I only want to select info from that join based on criteria defined in another table. I only want info from the first join where the actors name is in the popactor table.

select  h.movie,
        h.released,
        a.rating,
        h.actor
  from  hollywood.stars h
    inner join starmovies a on h.movie =a.title
    inner join popactor p on p.actor = h.actor
  where h.movie = a.title and p.actor = h.actor;

Body:
First your where clause is useless as the 2 conditions are already in the ON clause of your joins so you could get rid of it. Then you have two ways to achieve what you are looking for :
As suggested in comments :

select
  h.movie,
  h.released,
  a.rating,
  h.actor
from
  hollywood.stars h
  inner join starmovies a on h.movie = a.title
where h.actor IN (select actor FROM popactor)

OR as you already did :

select
  h.movie,
  h.released,
  a.rating,
  h.actor
from
  hollywood.stars h
  inner join starmovies a on h.movie =a.title
  inner join popactor p on p.actor = h.actor

Of course, if h.actor nor p.actor is the actor name on which you want to filter, you need to replace these fields in both queries with the right ones.


来源: stackexchange

问:
How to delete the image from the storage in laravel?
I am currently trying to delete an image when a user updates his/her post before publishing.

Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.

Here is my controller

```<code>public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}
</code>```

I used:

File::delete(public_path('storage/image'.$isExist['image']));

but it didn't do the job

my delete function

```<code>       public function deletePost($id){
        $post = Post::where('id',$id)->first();
//        dd($post);
        if(!$post){
            return response()->json([
                'status' => '500',
                'error' => 'post not found'
            ]);
        }
        Storage::disk('public')->delete('/storage/image'. $post['image']);
        Post::where('id', $id)->delete();
        return response()->json([
            'status'=> '200',
            'response'=> 'Post successfully deleted'
        ]);
    }
</code>```

my storage path snapshot

答:
```<code>use Illuminate\Support\Facades\Storage;

Storage::delete('file.jpg'); // delete file from default disk

Storage::delete(['file.jpg', 'file2.jpg']); // delete multiple files

Storage::disk('your_disk')->delete('file.jpg'); // delete file from specific disk e.g; s3, local etc
</code>```

Please refer link https://laravel.com/docs/6.x/filesystem

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to delete an image when a user updates his/her post before publishing.

Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.

Here is my controller

public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}

I used:

File::delete(public_path('storage/image'.$isExist['image']));

but it didn't do the job

my delete function

       public function deletePost($id){
        $post = Post::where('id',$id)->first();
//        dd($post);
        if(!$post){
            return response()->json([
                'status' => '500',
                'error' => 'post not found'
            ]);
        }
        Storage::disk('public')->delete('/storage/image'. $post['image']);
        Post::where('id', $id)->delete();
        return response()->json([
            'status'=> '200',
            'response'=> 'Post successfully deleted'
        ]);
    }

my storage path snapshot

Body:
use Illuminate\Support\Facades\Storage;

Storage::delete('file.jpg'); // delete file from default disk

Storage::delete(['file.jpg', 'file2.jpg']); // delete multiple files

Storage::disk('your_disk')->delete('file.jpg'); // delete file from specific disk e.g; s3, local etc

Please refer link https://laravel.com/docs/6.x/filesystem


问:
Generate select option entries from variables in ReactJs
I am still not as fluent in ReactJS, Ant Design, Sagas and Reducers as I thought I am: I am trying to maintain/ debug a single-page app and I am not sure which files I have to adjust and how.

The goal is to add the following <select> in their render() function within component.tsx:

<Select showSearch
        style={{ width: 150 }}
        placeholder="Select entity"
        // onChange={(e) => { this.handleSelectorChange("Entity", e) }} // to tackle later
        // value={this.props.selectedEntity.toString()}                 // ------ " ------
>
<Option value="0">Option 0</Option>
   {this.props.availableEntities.map((myEntity) =>
    (<Option key={myEntity.Id.toString()}
             value={myEntity.Id.toString()}>{myEntity.Name}</Option>))}
</Select>
```
<p>In the respective <code>container.tsx</code>, I added:</p>
<pre class="lang-js prettyprint-override"><code>const mapStateToProps = (state ) => ({
    availableEntities: GeneralSelectors.getAvailableEntities(state),
});
</code>```

What I get back is the following is only Option 0 instead of all entities (and even on a wrong place), see screenshot

How do I get my selection options dynamically generated using data from an API? Since I do not see backend being called (using the Network tab of my Chrome debugger), I assume something is wrong with the sagas, but that is just an hypothesis.

Background info

For another single-page-app (SPA) of the same project which already has that <select> inside, I found a urls.ts which looks as follows

import UrlMap from "../UrlMap"
import * as Actions from "./actions"
import * as GeneralActions from "../general/actions"

export const urls = [
    new UrlMap("myWorkingSPA",
        () => [
            Actions.load(),
            GeneralActions.loadEntities(),
            Actions.loadDifferencePositions()
        ])
];
```
<p>I don't know where this file is actually called, and what I have to modify where in order to include it.</p>
<p>In the respective <code>actions.ts</code> of the running SPA I find</p>
```export function loadEntities() : Action {
    return {
        type: LOAD_ENTITIES
    }
}
```
<p>I am not sure whether my SPA is also taking this <code>actions.ts</code> or not.</p>
<p>The <code>sagas.ts</code> is the same for the running SPA and for my component:</p>
```function* loadEntities() {
    const url = config.apiBaseUrl + "/api/Entities";

    try {
        const response: Response = yield fetch(url);
        const json: Interfaces.Entity[] = yield response.json();
        yield put(Actions.setEntities(json));
    } catch (e) {
        notification.error({ message: "Error", description: "Error loading Entities" });
    }
}

function* watchLoadEntities() {
    yield takeEvery(Actions.LOAD_ENTITIES, loadEntities);
}
```

Hope that was not too much information, but I guess it is all related to the problem.

References

populate select option in reactjs

Mapping checkboxes inside checkboxes ReactJS

答:
Eventually I also found another sagas.ts which was also in effect:

function* parseUrl({ payload }) {
    const pathName = payload.location.pathname;

    const myComponentURI: match<{}> = matchPath(pathName, { path: config.uiBaseUrl + "myComponent" });
    if (myComponentURI) {
        yield put(GeneralActions.loadEntities()); // <---
    }

   // ... here are many more const. for various different pages
}
```

The GeneralActions refers to an actions.ts in a directory general.

I solved the issue by putting the marked line. Warning: I believe, this is not the way things should be implemented, I am just saying that it hot-fixed my issue.

As clafou pointed out in a comment, the clean way would be to trigger the yield on startup.

Body:
I am still not as fluent in ReactJS, Ant Design, Sagas and Reducers as I thought I am: I am trying to maintain/ debug a single-page app and I am not sure which files I have to adjust and how.

The goal is to add the following <select> in their render() function within component.tsx:

<Select showSearch
        style={{ width: 150 }}
        placeholder="Select entity"
        // onChange={(e) => { this.handleSelectorChange("Entity", e) }} // to tackle later
        // value={this.props.selectedEntity.toString()}                 // ------ " ------
>
<Option value="0">Option 0</Option>
   {this.props.availableEntities.map((myEntity) =>
    (<Option key={myEntity.Id.toString()}
             value={myEntity.Id.toString()}>{myEntity.Name}</Option>))}
</Select>

In the respective container.tsx, I added:

const mapStateToProps = (state ) => ({
    availableEntities: GeneralSelectors.getAvailableEntities(state),
});

What I get back is the following is only Option 0 instead of all entities (and even on a wrong place), see screenshot

How do I get my selection options dynamically generated using data from an API? Since I do not see backend being called (using the Network tab of my Chrome debugger), I assume something is wrong with the sagas, but that is just an hypothesis.

Background info

For another single-page-app (SPA) of the same project which already has that <select> inside, I found a urls.ts which looks as follows

import UrlMap from "../UrlMap"
import * as Actions from "./actions"
import * as GeneralActions from "../general/actions"

export const urls = [
    new UrlMap("myWorkingSPA",
        () => [
            Actions.load(),
            GeneralActions.loadEntities(),
            Actions.loadDifferencePositions()
        ])
];

I don't know where this file is actually called, and what I have to modify where in order to include it.

In the respective actions.ts of the running SPA I find

export function loadEntities() : Action {
    return {
        type: LOAD_ENTITIES
    }
}

I am not sure whether my SPA is also taking this actions.ts or not.

The sagas.ts is the same for the running SPA and for my component:

function* loadEntities() {
    const url = config.apiBaseUrl + "/api/Entities";

    try {
        const response: Response = yield fetch(url);
        const json: Interfaces.Entity[] = yield response.json();
        yield put(Actions.setEntities(json));
    } catch (e) {
        notification.error({ message: "Error", description: "Error loading Entities" });
    }
}

function* watchLoadEntities() {
    yield takeEvery(Actions.LOAD_ENTITIES, loadEntities);
}

Hope that was not too much information, but I guess it is all related to the problem.

References

populate select option in reactjs

Mapping checkboxes inside checkboxes ReactJS

Body:
Eventually I also found another sagas.ts which was also in effect:

function* parseUrl({ payload }) {
    const pathName = payload.location.pathname;

    const myComponentURI: match<{}> = matchPath(pathName, { path: config.uiBaseUrl + "myComponent" });
    if (myComponentURI) {
        yield put(GeneralActions.loadEntities()); // <---
    }

   // ... here are many more const. for various different pages
}

The GeneralActions refers to an actions.ts in a directory general.

I solved the issue by putting the marked line. Warning: I believe, this is not the way things should be implemented, I am just saying that it hot-fixed my issue.

As clafou pointed out in a comment, the clean way would be to trigger the yield on startup.


问:
How can I calculate precision, recall and F1-score in Neural Network models?
I'm using Keras to predict if I'll get an output of 1 or 0. The data looks like this:

```<code>    funded_amnt  emp_length  avg_cur_bal  num_actv_rev_tl    loan_status
    10000       5.60088      19266                 2                  1
    13750       5.60088      2802                  6                  0
    26100       10.0000      19241                17                  1
</code>```

The target is loan_status and the features are the remaining. I've normalized the data before starting to build a Neural Network model.

Here's the shape of my training and testing data:

```<code>    print(X_train.shape,Y_train.shape)
    # Output: (693, 4) (693,)

    print(X_test.shape,Y_test.shape)
    # Output: (149, 4) (149,)
</code>```

The process I followed to build the Neural Network is:

```<code>     # define the keras model
     model = Sequential()
     model.add(Dense(4, input_dim=4,activation='relu'))
     model.add(Dense(4 ,activation='relu'))
     model.add(Dense(1,activation='sigmoid'))

     # compile the keras model
     model.compile(loss='binary_crossentropy',optimizer='adam', metrics=['accuracy'])

     # fit the keras model on the dataset
     hist = model.fit(X_train, Y_train, validation_data=(X_test, Y_test) ,epochs=10, batch_size=2)

</code>```

The output after running hist:

```<code>Epoch 1/20
693/693 [==============================] - 1s 2ms/step - loss: 0.5974 - acc: 0.7605 - val_loss: 0.5499 - val_acc: 0.7785
Epoch 2/20
693/693 [==============================] - 0s 659us/step - loss: 0.5369 - acc: 0.7778 - val_loss: 0.5380 - val_acc: 0.7785
Epoch 3/20
693/693 [==============================] - 0s 700us/step - loss: 0.5330 - acc: 0.7778 - val_loss: 0.5369 - val_acc: 0.7785
Epoch 4/20
693/693 [==============================] - 0s 670us/step - loss: 0.5316 - acc: 0.7778 - val_loss: 0.5355 - val_acc: 0.7785
Epoch 5/20
693/693 [==============================] - 0s 720us/step - loss: 0.5307 - acc: 0.7778 - val_loss: 0.5345 - val_acc: 0.7785
Epoch 6/20
693/693 [==============================] - 0s 668us/step - loss: 0.5300 - acc: 0.7778 - val_loss: 0.5339 - val_acc: 0.7785
Epoch 7/20
</code>```

Now, I would like to calcuate the precision, recall and F1-score instead of just the accuracy. I've tried following this. But I keep getting the following error:

ValueError: Classification metrics can't handle a mix of binary and continuous targets

Is there another way?

答:
Can you try the following:

```<code>import numpy as np
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score

class Metrics(Callback):

    def on_train_begin(self, logs={}):
        self.val_f1s = []
        self.val_recalls = []
        self.val_precisions = []

    def on_epoch_end(self, epoch, logs={}):
        val_predict = (np.asarray(self.model.predict(
            self.model.validation_data[0]))).round()
        val_targ = self.model.validation_data[1]
        _val_f1 = f1_score(val_targ, val_predict)
        _val_recall = recall_score(val_targ, val_predict)
        _val_precision = precision_score(val_targ, val_predict)
        self.val_f1s.append(_val_f1)
        self.val_recalls.append(_val_recall)
        self.val_precisions.append(_val_precision)
        print(f" — val_f1: {_val_f1} — val_precision: {_val_precision} — val_recall _val_recall")
        return

metrics = Metrics()
</code>```

And in your code you need to use it as following:

```<code>hist = model.fit(X_train, Y_train,
                 validation_data=(X_test, Y_test), epochs=10,
                 batch_size=2, callbacks=[metrics])
</code>```

Body:
I'm using Keras to predict if I'll get an output of 1 or 0. The data looks like this:

    funded_amnt  emp_length  avg_cur_bal  num_actv_rev_tl    loan_status
    10000       5.60088      19266                 2                  1
    13750       5.60088      2802                  6                  0
    26100       10.0000      19241                17                  1

The target is loan_status and the features are the remaining. I've normalized the data before starting to build a Neural Network model.

Here's the shape of my training and testing data:

    print(X_train.shape,Y_train.shape)
    # Output: (693, 4) (693,)

    print(X_test.shape,Y_test.shape)
    # Output: (149, 4) (149,)

The process I followed to build the Neural Network is:

     # define the keras model
     model = Sequential()
     model.add(Dense(4, input_dim=4,activation='relu'))
     model.add(Dense(4 ,activation='relu'))
     model.add(Dense(1,activation='sigmoid'))

     # compile the keras model
     model.compile(loss='binary_crossentropy',optimizer='adam', metrics=['accuracy'])

     # fit the keras model on the dataset
     hist = model.fit(X_train, Y_train, validation_data=(X_test, Y_test) ,epochs=10, batch_size=2)

The output after running hist:

Epoch 1/20
693/693 [==============================] - 1s 2ms/step - loss: 0.5974 - acc: 0.7605 - val_loss: 0.5499 - val_acc: 0.7785
Epoch 2/20
693/693 [==============================] - 0s 659us/step - loss: 0.5369 - acc: 0.7778 - val_loss: 0.5380 - val_acc: 0.7785
Epoch 3/20
693/693 [==============================] - 0s 700us/step - loss: 0.5330 - acc: 0.7778 - val_loss: 0.5369 - val_acc: 0.7785
Epoch 4/20
693/693 [==============================] - 0s 670us/step - loss: 0.5316 - acc: 0.7778 - val_loss: 0.5355 - val_acc: 0.7785
Epoch 5/20
693/693 [==============================] - 0s 720us/step - loss: 0.5307 - acc: 0.7778 - val_loss: 0.5345 - val_acc: 0.7785
Epoch 6/20
693/693 [==============================] - 0s 668us/step - loss: 0.5300 - acc: 0.7778 - val_loss: 0.5339 - val_acc: 0.7785
Epoch 7/20

Now, I would like to calcuate the precision, recall and F1-score instead of just the accuracy. I've tried following this. But I keep getting the following error:

ValueError: Classification metrics can't handle a mix of binary and continuous targets

Is there another way?

Body:
Can you try the following:

import numpy as np
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score

class Metrics(Callback):

    def on_train_begin(self, logs={}):
        self.val_f1s = []
        self.val_recalls = []
        self.val_precisions = []

    def on_epoch_end(self, epoch, logs={}):
        val_predict = (np.asarray(self.model.predict(
            self.model.validation_data[0]))).round()
        val_targ = self.model.validation_data[1]
        _val_f1 = f1_score(val_targ, val_predict)
        _val_recall = recall_score(val_targ, val_predict)
        _val_precision = precision_score(val_targ, val_predict)
        self.val_f1s.append(_val_f1)
        self.val_recalls.append(_val_recall)
        self.val_precisions.append(_val_precision)
        print(f" — val_f1: {_val_f1} — val_precision: {_val_precision} — val_recall _val_recall")
        return

metrics = Metrics()

And in your code you need to use it as following:

hist = model.fit(X_train, Y_train,
                 validation_data=(X_test, Y_test), epochs=10,
                 batch_size=2, callbacks=[metrics])


问:
Split values and loop through them
I have two tables:
Table1:

```<code>id | value
1  | val1
2  | val2
3  | val3
</code>```

Table2:

```<code>id | value
1  | val1,val2,val22
2  | val2
3  | val3,val15,
</code>```

The thing that I want to do is to split the values from Table2 by comma (to get separated values), next loop through it and find them in Table1. As a result I need the Table1.id and Table2.id that contains value from Table1 to insert them in the new table.

Is it possible to do it in mysql as there is no SPLIT function?

Edit: MySql version 5.7.27

Edit2: Desired result:

```<code>table1.id  table1.valie  table1.id  table1.valie
        1          val1          1  val1,val2,val22
        2          val2          1  val1,val2,val22
        2          val2          2  val2
        3          val3          3  val3,val15,
</code>```

答:
MySql version 5.7.27

Use (assuming that table2.value contains not more than 10 separate values)

```<code>CREATE TABLE table3
/* or INSERT INTO table3 (value) if this table already exists */
SELECT *
FROM ( SELECT value
       FROM table1
     UNION
       SELECT TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(table2.value, ',', numbers.num), ',', -1)) value
       FROM table2,
            ( SELECT 1 num UNION
              SELECT 2 UNION
              SELECT 3 UNION
              SELECT 4 UNION
              SELECT 5 UNION
              SELECT 6 UNION
              SELECT 7 UNION
              SELECT 8 UNION
              SELECT 9 UNION
              SELECT 10 ) numbers
       WHERE numbers.num <= LENGTH(table2.value) - LENGTH(REPLACE(table2.value, ',', '')) + 1
       HAVING value != '') total;
</code>```

fiddle

Title: Split values and loop through them

Body:
I have two tables:
Table1:

id | value
1  | val1
2  | val2
3  | val3

Table2:

id | value
1  | val1,val2,val22
2  | val2
3  | val3,val15,

The thing that I want to do is to split the values from Table2 by comma (to get separated values), next loop through it and find them in Table1. As a result I need the Table1.id and Table2.id that contains value from Table1 to insert them in the new table.

Is it possible to do it in mysql as there is no SPLIT function?

Edit: MySql version 5.7.27

Edit2: Desired result:

table1.id  table1.valie  table1.id  table1.valie
        1          val1          1  val1,val2,val22
        2          val2          1  val1,val2,val22
        2          val2          2  val2
        3          val3          3  val3,val15,

Body:
MySql version 5.7.27

Use (assuming that table2.value contains not more than 10 separate values)

CREATE TABLE table3
/* or INSERT INTO table3 (value) if this table already exists */
SELECT *
FROM ( SELECT value
       FROM table1
     UNION
       SELECT TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(table2.value, ',', numbers.num), ',', -1)) value
       FROM table2,
            ( SELECT 1 num UNION
              SELECT 2 UNION
              SELECT 3 UNION
              SELECT 4 UNION
              SELECT 5 UNION
              SELECT 6 UNION
              SELECT 7 UNION
              SELECT 8 UNION
              SELECT 9 UNION
              SELECT 10 ) numbers
       WHERE numbers.num <= LENGTH(table2.value) - LENGTH(REPLACE(table2.value, ',', '')) + 1
       HAVING value != '') total;

fiddle


问:
How is c# reflection a runtime event?
Every definition says C# reflections is used to determine type of object in runtime. Can the type of an object change in runtime? Can anybody please provide me an example.</p>

答:
Of course an entity can change its runtime type during runtime. It just can't change its compile type. This is because c# is a type safe language (once a given type, always a given type).

Suppose you have 3 classes - one an abstract class say Animal and two classes that derive from it, say Cat and Dog. Then

```<code>Animal animal = new Dog(); //compile time type is Animal runtime type is Dog
Console.WriteLine(animal.GetType().Name); // Dog
...
animal = new Cat(); // compile time type is still Animal (c# is Type safe)
// but runtime type just changed to Cat;
Console.WriteLine(animal.GetType().Name); // Cat
</code>```

Notice that all the while you are programming your Animal animal will not be "just an object". Being of (compile) type Animal bears great tiding - bool IsAlive property, Breath() method, and more. But when you write your code (i.e. compile time) your "animal" instance won't have a Tail (because not every animal has a tail). You can only access (with intellisense for example) things that you are sure it has (only Animal things). That's still saying a lot, but not as much as it's concrete subclasses. It's a very general thing, and that's a good thing.

Title: How is c# reflection a runtime event?

Body:
Of course an entity can change its runtime type during runtime. It just can't change its compile type. This is because c# is a type safe language (once a given type, always a given type).

Suppose you have 3 classes - one an abstract class say Animal and two classes that derive from it, say Cat and Dog. Then

Animal animal = new Dog(); //compile time type is Animal runtime type is Dog
Console.WriteLine(animal.GetType().Name); // Dog
...
animal = new Cat(); // compile time type is still Animal (c# is Type safe)
// but runtime type just changed to Cat;
Console.WriteLine(animal.GetType().Name); // Cat

Notice that all the while you are programming your Animal animal will not be "just an object". Being of (compile) type Animal bears great tiding - bool IsAlive property, Breath() method, and more. But when you write your code (i.e. compile time) your "animal" instance won't have a Tail (because not every animal has a tail). You can only access (with intellisense for example) things that you are sure it has (only Animal things). That's still saying a lot, but not as much as it's concrete subclasses. It's a very general thing, and that's a good thing.


问:
JavaScript localeCompare() returns different result than Java compareTo()
What I am trying to achieve is to synchronize the outcome of these two functions.
These methods return number indicating whether a reference string comes before or after or is the same as the given string in sort order.

The JavaScript localeCompare has many parameters to be set but nothing from what I have tried worked.

```<code>**Java returns**:      **JavaScript returns**:
Sensor             Sensor
SensorDus          Sensor DUS
SensorEnv          Sensor E
Sensor DUS         SensorDUS
Sensor E           Sensor Env
</code>```

It looks like that the difference it those two methods is how they return the numbers.
A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.

Any ideas if this is somehow possible?

答:
My solution to the problem.
Instead of using localeCompare() I rewrote the Java compareTo() into JavaScript method. The java method returned positive (higher) number for white space as opposed to string without a white space in JavaScript. </p>

```<code>localCompareAsInJava: function(t1,t2)
{
  var len1 = t1.length;
  var len2 = t2.length;
  var lim = Math.min(t1.length, t2.length);

  var v1 = t1;
  var v2 = t2;

  var k = 0;
  while(k < lim)
  {
    var c1 = v1[k];
    var c2 = v2[k];
    if(c1 != c2)
    {
      if(c1.charCodeAt(0) == 32 )
      {
        var charWithSpace = c1.charCodeAt(0) + c2.charCodeAt(0);
        return charWithSpace;
      }
      else{
        return c1.charCodeAt(0) - c2.charCodeAt(0);
      }

    }
    k++;
  }
  return len1 - len2;
}
</code>```

Body:
What I am trying to achieve is to synchronize the outcome of these two functions.
These methods return number indicating whether a reference string comes before or after or is the same as the given string in sort order.

The JavaScript localeCompare has many parameters to be set but nothing from what I have tried worked.

**Java returns**:      **JavaScript returns**:
Sensor             Sensor
SensorDus          Sensor DUS
SensorEnv          Sensor E
Sensor DUS         SensorDUS
Sensor E           Sensor Env

It looks like that the difference it those two methods is how they return the numbers.
A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.

Any ideas if this is somehow possible?

Body:
My solution to the problem.
Instead of using localeCompare() I rewrote the Java compareTo() into JavaScript method. The java method returned positive (higher) number for white space as opposed to string without a white space in JavaScript.

localCompareAsInJava: function(t1,t2)
{
  var len1 = t1.length;
  var len2 = t2.length;
  var lim = Math.min(t1.length, t2.length);

  var v1 = t1;
  var v2 = t2;

  var k = 0;
  while(k < lim)
  {
    var c1 = v1[k];
    var c2 = v2[k];
    if(c1 != c2)
    {
      if(c1.charCodeAt(0) == 32 )
      {
        var charWithSpace = c1.charCodeAt(0) + c2.charCodeAt(0);
        return charWithSpace;
      }
      else{
        return c1.charCodeAt(0) - c2.charCodeAt(0);
      }

    }
    k++;
  }
  return len1 - len2;
}


问:
How to auto-update the ErrorList in the Visual Studio?
I have the VS 2019.

When I build a solution, I get some compile errors in "BuildOnly" mode. However, when I fix several of the errors, I expect the Error List to refresh, but is not the case: I still have the fixed errors in the list, till the next re/build.

I should rebuild the solution to get the list updated. What is the cause and solutions of this VS bug?

I saw people say to remove the .vs file, but should I do that every time I need to update the ErrorList? Why it's not performed automatically?

答:
It depends on which tool is providing those error items, and how it's triggered.  Some tools only run on file save, or when invoked explicitly by some gesture.

In the case of the C# compiler, it should be running a design-time build (your scenario is even mentioned in the documentation's signs of failure).  You might try the steps further down that page to try to diagnose the issue.


问:
Google Play Developer API - "The current user has insufficient permissions to perform the requested operation."
I have a Google dev console process with Google Play Developer API is enabled and the project is linked to Google Play project.
In Google Dev console project, created OAuth Client ID (web application) (I'm an owner of the project). Using "client_id" and "client_secret" to authenticate.
Tried to using google-api-client in Python, Google Developer API Playground to send request to list reviews of our apps but got error: "The current user has insufficient permissions to perform the requested operation."
Details as below:
Request:

```<code>GET /androidpublisher/v2/applications/<package_name>/reviews
</code>```

Response:

```<code>"error": {
    "code": 401,
    "message": "The current user has insufficient permissions to perform the requested operation.",
    "errors": [
      {
        "domain": "androidpublisher",
        "message": "The current user has insufficient permissions to perform the requested operation.",
        "reason": "permissionDenied"
      }
    ]
  }
}
</code>```

Did I miss anything?

答:
If you followed all what @Bikram listed and you still facing the same error. Do this, create 'Managed product' temporary and then delete them. This way, sure you don't have to wait 24 hours.

It works for me.

ContentLicense: CC BY-SA 3.0

Body:
I have a Google dev console process with Google Play Developer API is enabled and the project is linked to Google Play project.
In Google Dev console project, created OAuth Client ID (web application) (I'm an owner of the project). Using "client_id" and "client_secret" to authenticate.
Tried to using google-api-client in Python, Google Developer API Playground to send request to list reviews of our apps but got error: "The current user has insufficient permissions to perform the requested operation."
Details as below:
Request:

GET /androidpublisher/v2/applications/<package_name>/reviews

Response:

"error": {
    "code": 401,
    "message": "The current user has insufficient permissions to perform the requested operation.",
    "errors": [
      {
        "domain": "androidpublisher",
        "message": "The current user has insufficient permissions to perform the requested operation.",
        "reason": "permissionDenied"
      }
    ]
  }
}

Did I miss anything?


问:
Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want)
```<code>   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)
</code>```

The output I want is

```<code>s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf
</code>```

the output I get it

```<code>Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
</code>```

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

答:
Learn more about iterating the dictionaries here - How to Iterate Through a Dictionary in Python

contact_emails = {
    'Sue Reyn' : 's.reyn@email.com',
    'Mike Filt': 'mike.filt@bmail.com',
    'Nate Arty': 'narty042@nmail.com'
    }

new_contact = input()

new_email = input()
contact_emails[new_contact] = new_email

for contact in contact_emails:
            print(contact_emails[contact]+ ' is ' + contact)
```

<p>Output:</p>

```>>Alf
>>alf1@hmail.com
s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf
```

Body:
   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)

The output I want is

s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf

the output I get it

Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

Body:
Learn more about iterating the dictionaries here - How to Iterate Through a Dictionary in Python

contact_emails = {
    'Sue Reyn' : 's.reyn@email.com',
    'Mike Filt': 'mike.filt@bmail.com',
    'Nate Arty': 'narty042@nmail.com'
    }

new_contact = input()

new_email = input()
contact_emails[new_contact] = new_email

for contact in contact_emails:
            print(contact_emails[contact]+ ' is ' + contact)

Output:

>>Alf
>>alf1@hmail.com
s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf


问:
how to add tipbox when mouse hover on the text
http://bowser.effectgames.com/~jhuckaby/zeroclipboard/multiple.html

is there a way to add a tipbox  when the mouse hover on the copied text.the tip box say"the text has been copied" thank you.

HTML:code

```<code><body>
<div>
 <div class="example" "></div><div>copied text</div>
 <div class="example" "></div><div>copied text</div>
<div class="example" "></div><div>copied text</div>
<div class="example" "></div><div>copied text</div>
</div>
</body>
</code>```

答:
this is a fully working html file.. you can look what it does, it's pretty simple

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
    <head>
        <title>h4kr.com</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="de" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <link rel="shortcut icon" href="/favicon.ico" />
        <style type="text/css">
            body {
                font-size: 62.5%;
                font-family: Verdana, Arial, Helvetica, sans-serif;
            }
            .error-msg {
                font-size: 12px;
                margin: 10px;
                padding: 10px;
                color: #ffffff;
                border: 1px solid #000000;
                background-color: #990000;
                font-weight: bold;
            }
            textarea {
                width: 450px;
                height: 200px;
                border: 1px solid #669966;
                padding: 5px;
            }
            #output {
                height: 200px;
                width: 99%;
                border: 1px solid #669966;
                padding: 5px;
                overflow: auto;
            }
            #outputContent {
                font-size: 13px;
            }
            button {
                width: 450px;
                height: 40px;
            }
            span.label {
                width: 140px;
                display: block;
                float: left;
            }
            span.hidden {
                display: none;
            }
            div#clipboardcontent{
                display:none;
            }
            div#copyclipboardsuccess{
                position: absolute;
                top: 400px;
                left: 20px;
                border: 1px solid #000000;
                background-color: #009900;
                color: #ffffff;
                font-weight: bold;
                font-size: 18px;
                padding: 20px;
                width: 300px;
                height: 60px;
                text-align: center;
                opacity: 0.5;
                z-index: 9999;
            }
            div#errormsg{
                position: absolute;
                top: 150px;
                left: 20px;
                border: 1px solid #000000;
                background-color: #990000;
                color: #ffffff;
                font-weight: bold;
                font-size: 18px;
                padding: 20px;
                width: 300px;
                height: 60px;
                text-align: center;
                opacity: 0.5;
                z-index: 9999;
            }
        </style>
                <script type="text/javascript" src="ZeroClipboard.js"></script>
        <script type="text/javascript">
        ZeroClipboard.setMoviePath( 'ZeroClipboard.swf' );
        var clip = null;

    function init() {
        clip = new ZeroClipboard.Client();
        clip.setHandCursor( true );

        clip.addEventListener('load', function (client) {
        });

        clip.addEventListener('mouseOver', function (client) {
            // update the text on mouse over
            clip.setText( document.getElementById('clipboardcontent').innerHTML );
        });

        clip.addEventListener('onComplete', function (client) {
            copyclipboardsuccess();
        });

        clip.glue( 'd_clip_button','d_clip_container');
    }

    function copyclipboardsuccess()
    {
        var o = document.getElementById('copyclipboardsuccess');
        if(o.style.display == 'none')
        {
            o.style.display = 'block';
            setTimeout(copyclipboardsuccess,1000);
        }
        else
        {
            o.style.display = 'none';
        }
    }
    function errormsg()
    {
        var o = document.getElementById('errormsg');
        if(o.style.display == 'none')
        {
            o.style.display = 'block';
            setTimeout(errormsg,2500);
        }
        else
        {
            o.style.display = 'none';
        }
    }

     </script>

        </head>
<body onload="init();">
<h1>h4kr.com</h1><div id="errormsg" style="display:none">Error!</div><div id="copyclipboardsuccess" style="display:none">Copied to clipboard!</div><form id="form_cid" method="POST" target="output"><h2>Input</h2><textarea id="input_list" name="input_list"></textarea><br/><button type="submit" value="go">Go</button></form>      <h2>Output</h2>
    <iframe src="about:blank" name="output" id="output"></iframe>
    <div id="d_clip_container" style="position:relative">

        <button id="d_clip_button">Copy to clipboard</button>
    </div>
    <div id="clipboardcontent"></div>
</body>
</code>```

Body:
http://bowser.effectgames.com/~jhuckaby/zeroclipboard/multiple.html

is there a way to add a tipbox  when the mouse hover on the copied text.the tip box say"the text has been copied" thank you.

HTML:code

copied text

copied text

copied text

copied text

Body:
this is a fully working html file.. you can look what it does, it's pretty simple

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
    <head>
        <title>h4kr.com</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="de" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <link rel="shortcut icon" href="/favicon.ico" />
        <style type="text/css">
            body {
                font-size: 62.5%;
                font-family: Verdana, Arial, Helvetica, sans-serif;
            }
            .error-msg {
                font-size: 12px;
                margin: 10px;
                padding: 10px;
                color: #ffffff;
                border: 1px solid #000000;
                background-color: #990000;
                font-weight: bold;
            }
            textarea {
                width: 450px;
                height: 200px;
                border: 1px solid #669966;
                padding: 5px;
            }
            #output {
                height: 200px;
                width: 99%;
                border: 1px solid #669966;
                padding: 5px;
                overflow: auto;
            }
            #outputContent {
                font-size: 13px;
            }
            button {
                width: 450px;
                height: 40px;
            }
            span.label {
                width: 140px;
                display: block;
                float: left;
            }
            span.hidden {
                display: none;
            }
            div#clipboardcontent{
                display:none;
            }
            div#copyclipboardsuccess{
                position: absolute;
                top: 400px;
                left: 20px;
                border: 1px solid #000000;
                background-color: #009900;
                color: #ffffff;
                font-weight: bold;
                font-size: 18px;
                padding: 20px;
                width: 300px;
                height: 60px;
                text-align: center;
                opacity: 0.5;
                z-index: 9999;
            }
            div#errormsg{
                position: absolute;
                top: 150px;
                left: 20px;
                border: 1px solid #000000;
                background-color: #990000;
                color: #ffffff;
                font-weight: bold;
                font-size: 18px;
                padding: 20px;
                width: 300px;
                height: 60px;
                text-align: center;
                opacity: 0.5;
                z-index: 9999;
            }
        </style>
                <script type="text/javascript" src="ZeroClipboard.js"></script>
        <script type="text/javascript">
        ZeroClipboard.setMoviePath( 'ZeroClipboard.swf' );
        var clip = null;

    function init() {
        clip = new ZeroClipboard.Client();
        clip.setHandCursor( true );

        clip.addEventListener('load', function (client) {
        });

        clip.addEventListener('mouseOver', function (client) {
            // update the text on mouse over
            clip.setText( document.getElementById('clipboardcontent').innerHTML );
        });

        clip.addEventListener('onComplete', function (client) {
            copyclipboardsuccess();
        });

        clip.glue( 'd_clip_button','d_clip_container');
    }

    function copyclipboardsuccess()
    {
        var o = document.getElementById('copyclipboardsuccess');
        if(o.style.display == 'none')
        {
            o.style.display = 'block';
            setTimeout(copyclipboardsuccess,1000);
        }
        else
        {
            o.style.display = 'none';
        }
    }
    function errormsg()
    {
        var o = document.getElementById('errormsg');
        if(o.style.display == 'none')
        {
            o.style.display = 'block';
            setTimeout(errormsg,2500);
        }
        else
        {
            o.style.display = 'none';
        }
    }

     </script>

        </head>
<body onload="init();">
<h1>h4kr.com</h1><div id="errormsg" style="display:none">Error!</div><div id="copyclipboardsuccess" style="display:none">Copied to clipboard!</div><form id="form_cid" method="POST" target="output"><h2>Input</h2><textarea id="input_list" name="input_list"></textarea><br/><button type="submit" value="go">Go</button></form>      <h2>Output</h2>
    <iframe src="about:blank" name="output" id="output"></iframe>
    <div id="d_clip_container" style="position:relative">

        <button id="d_clip_button">Copy to clipboard</button>
    </div>
    <div id="clipboardcontent"></div>
</body>


问:
Edge templating express TypeError
Im using edge template engine in my application node.js and I getting back the error; TypeError: app.use() requires middleware function

this is my code the index.js

```<code>const path = require('path');
const express = require('express');
const expressEdge = require('express-edge');

const app = new express();

app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');

app.get('/', (req, res) => {
  res.render('index');
});
app.get('/about',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/about.html'));
});
app.get('/post',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/post.html'));
});

app.get('/contact',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/contact.html'));
});

app.listen(4000,() =>{
  console.log('App listening on port 4000')
});
</code>```

This is how I set up the folder in my application
enter image description here

答:
From the docs, you are supposed to pass expressEdge.engine as the middleware to app.use not the entire expressEdge object. So this is what your index.js code should be like:

```<code>const path = require('path');
const express = require('express');
// Use the config method to configure express-edge if needed
const { config, engine } = require('express-edge');

const app = new express();

app.use(express.static('public'));
// Pass in the engine not the entire express-edge object
app.use(engine);
app.set('views', __dirname + '/views');

app.get('/', (req, res) => {
  res.render('index');
});
app.get('/about',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/about.html'));
});
app.get('/post',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/post.html'));
});

app.get('/contact',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/contact.html'));
});

app.listen(4000,() =>{
  console.log('App listening on port 4000')
});
</code>```

More details in the usage documentation here.

Title: Edge templating express TypeError

Body:
Im using edge template engine in my application node.js and I getting back the error; TypeError: app.use() requires middleware function

this is my code the index.js

const path = require('path');
const express = require('express');
const expressEdge = require('express-edge');

const app = new express();

app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');

app.get('/', (req, res) => {
  res.render('index');
});
app.get('/about',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/about.html'));
});
app.get('/post',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/post.html'));
});

app.get('/contact',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/contact.html'));
});

app.listen(4000,() =>{
  console.log('App listening on port 4000')
});

This is how I set up the folder in my application
enter image description here

Body:
From the docs, you are supposed to pass expressEdge.engine as the middleware to app.use not the entire expressEdge object. So this is what your index.js code should be like:

const path = require('path');
const express = require('express');
// Use the config method to configure express-edge if needed
const { config, engine } = require('express-edge');

const app = new express();

app.use(express.static('public'));
// Pass in the engine not the entire express-edge object
app.use(engine);
app.set('views', __dirname + '/views');

app.get('/', (req, res) => {
  res.render('index');
});
app.get('/about',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/about.html'));
});
app.get('/post',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/post.html'));
});

app.get('/contact',(req,res)=>{
  res.sendFile(path.resolve(__dirname,'pages/contact.html'));
});

app.listen(4000,() =>{
  console.log('App listening on port 4000')
});

More details in the usage documentation here.


问:
Apache guacamole create user using postgres
Im using apache guacamole latest from docker hub and postgres 12  as database,
I want to create a login user using postgres but its not working.

This is how to create user from docs:

```<code>-- Generate salt
SET @salt = UNHEX(SHA2(UUID(), 256));

-- Create user and hash password with salt
INSERT INTO guacamole_user (username, password_salt, password_hash)
     VALUES ('myuser', @salt, UNHEX(SHA2(CONCAT('mypassword', HEX(@salt)), 256)));
</code>```

But here the first command gives me an error :

```<code>guacamole_db=# SET @salt = UNHEX(SHA2(UUID(), 256));
ERROR:  syntax error at or near "@"
LINE 1: SET @salt = UNHEX(SHA2(UUID(), 256));
            ^
</code>```

From docs this is how they created the defult user in postgres: "guacadmin"

```<code>INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
    entity_id,
    decode('CA458A7D494E3BE824F5E1E175A1556C0F8EEF2C2D7DF3633BEC4A29C4411960', 'hex'),  -- 'guacadmin'
    decode('FE24ADC5E11E2B25288D1704ABE67A79E342ECC26064CE69C5B3177795A82264', 'hex'),
    CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';

-- Grant admin permission to read/update/administer self
INSERT INTO guacamole_user_permission (entity_id, affected_user_id, permission)
SELECT guacamole_entity.entity_id, guacamole_user.user_id, permission::guacamole_object_permission_type
FROM (
    VALUES
        ('guacadmin', 'guacadmin', 'READ'),
        ('guacadmin', 'guacadmin', 'UPDATE'),
        ('guacadmin', 'guacadmin', 'ADMINISTER')
) permissions (username, affected_username, permission)
JOIN guacamole_entity          ON permissions.username = guacamole_entity.name AND guacamole_entity.type = 'USER'
JOIN guacamole_entity affected ON permissions.affected_username = affected.name AND guacamole_entity.type = 'USER'
JOIN guacamole_user            ON guacamole_user.entity_id = affected.entity_id;
</code>```

How can i translate this to create new user, "test" with password "123456" and only READ premmision?

this is how the related tables looks like :

guacamole_entity :

```<code> entity_id |   name    | type
-----------+-----------+------
         1 | guacadmin | USER
</code>```

guacamole_user:

```<code> user_id | entity_id |                           password_hash                            |                           password_salt                            |        pass
word_date         | disabled | expired | access_window_start | access_window_end | valid_from | valid_until | timezone | full_name | email_address | organization | organiza
tional_role
---------+-----------+--------------------------------------------------------------------+--------------------------------------------------------------------+------------
------------------+----------+---------+---------------------+-------------------+------------+-------------+----------+-----------+---------------+--------------+---------
------------
       1 |         1 | \xca458a7d494e3be824f5e1e175a1556c0f8eef2c2d7df3633bec4a29c4411960 | \xfe24adc5e11e2b25288d1704abe67a79e342ecc26064ce69c5b3177795a82264 | 2020-01-13
09:10:56.73947+00 | f        | f       |                     |                   |            |             |          |           |               |              |
</code>```

guacamole_user_permission :

```<code> entity_id | affected_user_id | permission
-----------+------------------+------------
         1 |                1 | READ
         1 |                1 | UPDATE
         1 |                1 | ADMINISTER
</code>```

答:
I ended up creating a user using POST request in python:
First part is that we need to get a token for all the requests we want to send to guacamole api:

import requests

```<code>url = "http://guacamoleipornginx/api"
headers ={
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'}
res = requests.post(url + "/tokens", headers=headers, data={'username': 'guacadmin', 'password': 'guacadmin'})
authToken = res.json()['authToken']
</code>```

And with that token we can send a request for creating a user: fill USERNAME nad USERPASSWORD with your values.

```<code>headers ={
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8'}

uri = "session/data/postgresql/users?token=" + authToken
data = {
        "username": $USERNAME,
        "password": $USERPASSWORD,
        "attributes":{"disabled":"","expired":"","access-window-start":"","access-window-end":"","valid-from":"","valid-until":"","timezone":None}}
res = requests.post(url + "/" + uri, headers=headers, json=data)
</code>```

The last part here is giving the user you created above a permission to see a connection,
you dont have to use it if you dont need to.
for this request we will need connection id of a connection you created.
my guacamole is docker guacamole that i got here:
https://github.com/boschkundendienst/guacamole-docker-compose

And it uses nginx + gouacamole and postgreSql, so in the postgrs you can see connection id under guacamole_connection. and then you can add the connection premission to the created user :

```<code>uri = "session/data/postgresql/users/" + $USERNAME+ "/permissions?token=" + authToken
ID = 52 # here is the connection id of some connection created in guoacamole psql db.
data = [
            {"op":"add",
            "path": '/connectionPermissions/' + str(ID),
            "value":"READ"}]
res = requests.patch(url + "/" + uri, headers=headers, json=data)
</code>```

You can add a connection also to guacamole using this method. you will need simply to open F12 and see the values it sends when it creats a connection and use it with the same methode above.

Ill add another cool thing - this is how you can see active connections :

```<code>url = "http://guacamoleipornginx/api"
uri = "/session/data/postgresql/activeConnections?token=" + authToken
res = requests.get(url + "/" + uri)
</code>```

I hope this helps i had a lot of trouble getting all this information.

Body:
Im using apache guacamole latest from docker hub and postgres 12  as database,
I want to create a login user using postgres but its not working.

This is how to create user from docs:

-- Generate salt
SET @salt = UNHEX(SHA2(UUID(), 256));

-- Create user and hash password with salt
INSERT INTO guacamole_user (username, password_salt, password_hash)
     VALUES ('myuser', @salt, UNHEX(SHA2(CONCAT('mypassword', HEX(@salt)), 256)));

But here the first command gives me an error :

guacamole_db=# SET @salt = UNHEX(SHA2(UUID(), 256));
ERROR:  syntax error at or near "@"
LINE 1: SET @salt = UNHEX(SHA2(UUID(), 256));
            ^

From docs this is how they created the defult user in postgres: "guacadmin"

INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
    entity_id,
    decode('CA458A7D494E3BE824F5E1E175A1556C0F8EEF2C2D7DF3633BEC4A29C4411960', 'hex'),  -- 'guacadmin'
    decode('FE24ADC5E11E2B25288D1704ABE67A79E342ECC26064CE69C5B3177795A82264', 'hex'),
    CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';

-- Grant admin permission to read/update/administer self
INSERT INTO guacamole_user_permission (entity_id, affected_user_id, permission)
SELECT guacamole_entity.entity_id, guacamole_user.user_id, permission::guacamole_object_permission_type
FROM (
    VALUES
        ('guacadmin', 'guacadmin', 'READ'),
        ('guacadmin', 'guacadmin', 'UPDATE'),
        ('guacadmin', 'guacadmin', 'ADMINISTER')
) permissions (username, affected_username, permission)
JOIN guacamole_entity          ON permissions.username = guacamole_entity.name AND guacamole_entity.type = 'USER'
JOIN guacamole_entity affected ON permissions.affected_username = affected.name AND guacamole_entity.type = 'USER'
JOIN guacamole_user            ON guacamole_user.entity_id = affected.entity_id;

How can i translate this to create new user, "test" with password "123456" and only READ premmision?

this is how the related tables looks like :

guacamole_entity :

 entity_id |   name    | type
-----------+-----------+------
         1 | guacadmin | USER

guacamole_user:

 user_id | entity_id |                           password_hash                            |                           password_salt                            |        pass
word_date         | disabled | expired | access_window_start | access_window_end | valid_from | valid_until | timezone | full_name | email_address | organization | organiza
tional_role
---------+-----------+--------------------------------------------------------------------+--------------------------------------------------------------------+------------
------------------+----------+---------+---------------------+-------------------+------------+-------------+----------+-----------+---------------+--------------+---------
------------
       1 |         1 | \xca458a7d494e3be824f5e1e175a1556c0f8eef2c2d7df3633bec4a29c4411960 | \xfe24adc5e11e2b25288d1704abe67a79e342ecc26064ce69c5b3177795a82264 | 2020-01-13
09:10:56.73947+00 | f        | f       |                     |                   |            |             |          |           |               |              |

guacamole_user_permission :

 entity_id | affected_user_id | permission
-----------+------------------+------------
         1 |                1 | READ
         1 |                1 | UPDATE
         1 |                1 | ADMINISTER

Body:
I ended up creating a user using POST request in python:
First part is that we need to get a token for all the requests we want to send to guacamole api:

import requests

url = "http://guacamoleipornginx/api"
headers ={
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'}
res = requests.post(url + "/tokens", headers=headers, data={'username': 'guacadmin', 'password': 'guacadmin'})
authToken = res.json()['authToken']

And with that token we can send a request for creating a user: fill USERNAME nad USERPASSWORD with your values.

headers ={
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8'}

uri = "session/data/postgresql/users?token=" + authToken
data = {
        "username": $USERNAME,
        "password": $USERPASSWORD,
        "attributes":{"disabled":"","expired":"","access-window-start":"","access-window-end":"","valid-from":"","valid-until":"","timezone":None}}
res = requests.post(url + "/" + uri, headers=headers, json=data)

The last part here is giving the user you created above a permission to see a connection,
you dont have to use it if you dont need to.
for this request we will need connection id of a connection you created.
my guacamole is docker guacamole that i got here:
https://github.com/boschkundendienst/guacamole-docker-compose

And it uses nginx + gouacamole and postgreSql, so in the postgrs you can see connection id under guacamole_connection. and then you can add the connection premission to the created user :

uri = "session/data/postgresql/users/" + $USERNAME+ "/permissions?token=" + authToken
ID = 52 # here is the connection id of some connection created in guoacamole psql db.
data = [
            {"op":"add",
            "path": '/connectionPermissions/' + str(ID),
            "value":"READ"}]
res = requests.patch(url + "/" + uri, headers=headers, json=data)

You can add a connection also to guacamole using this method. you will need simply to open F12 and see the values it sends when it creats a connection and use it with the same methode above.

Ill add another cool thing - this is how you can see active connections :

url = "http://guacamoleipornginx/api"
uri = "/session/data/postgresql/activeConnections?token=" + authToken
res = requests.get(url + "/" + uri)

I hope this helps i had a lot of trouble getting all this information.


问:
Get specific URL in Controller .NET CORE
So this is my controller :

```<code> [HttpGet("Home/Project-Name/Dashboard")]
  public IActionResult Index()
  {
    ViewBag.Current = "Dashboard";
    return View();
  }
</code>```

The question is, how do I get the "Project-Name" Value ?

答:
```<code>var projectName = HttpContext.Request.Path.Value.Split('/',StringSplitOptions.RemoveEmptyEntries)[1]
</code>```

Body:
So this is my controller :

 [HttpGet("Home/Project-Name/Dashboard")]
  public IActionResult Index()
  {
    ViewBag.Current = "Dashboard";
    return View();
  }

The question is, how do I get the "Project-Name" Value ?


问:
how to fill multiline associative array in bash
I am trying to fill associative array in bash from following example file

```<code>interface GigabitEthernet1/0/1
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/2
 mls qos trust dscp
interface GigabitEthernet1/0/3
interface GigabitEthernet1/0/4
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/5
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/6
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/7
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/8
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
</code>```

interface GigabitEthernet1/0/1 or  GigabitEthernet1/0/1 should be the array key and anything between interface sections should be array key value.

```<code> srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
</code>```

Expected output should be:

```<code> $echo ${array[GigabitEthernet1/0/4]}
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
</code>```

There will be multiple different files with similar format, so this need to be done by loop, the text between interfaces should be 0 to 5-6 lines. The reason behind is I need to do logical test on each interface, if it is correct or not. Below text is correct, anything else, or empty field is incorrect.

```<code> srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
</code>```

So far i have stuck with formatting of IFS and multilines as the value of array key. I was able to fill non-associative array, but in not the cleanest form.

```<code>$ cat test_compare_interface | sed 's/interface.*$/*\n&/g' > test_compare_interface_sed
</code>```

test_compare_interface is file with interfaces

```<code>$ IFS=$'*' && array=($(cat test_compare_interface_sed))
$ echo ${array[4]}

interface GigabitEthernet1/0/4
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
</code>```

With associative array loop, i am still strugling

```<code>while IFS='*' read -r interface value; do array[$interface]=$value ; done < test_compare_interface_sed
</code>```

Thank you for all the suggestions.

答:
Would you please try the following:

```<code>declare -A array

# assign "${val[*]}" to the assciative array "array" keying with $1
store() {
    if [[ -n $1 ]]; then        # will skip the 1st line which is not ready
        array[$1]=$(IFS=$'\n'; echo "${val[*]}")
                                # join "val" with newline
        unset val               # empty the queue
    fi
}

while IFS= read -r line; do
    if [[ $line =~ ^interface ]]; then
        store "$interface"      # assign to the associative array
        interface="$line"       # for the next iteration
    else
        val+=("${line# }")      # append to the queue
    fi
done < file.txt

store "$interface"              # flush the last entry

for i in "${!array[@]}"; do     # print the array elements to test
    echo "$i"
    echo "${array[$i]}"
done
</code>```

It just read the input line by line without modifying IFS.

If the line starts with "interface", it flushes the queue (array val)
into the associative array and updates the interface name for next iteration.

If the line does not start with "interface", the line is accumulated
in the queue (array val)

Body:
I am trying to fill associative array in bash from following example file

interface GigabitEthernet1/0/1
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/2
 mls qos trust dscp
interface GigabitEthernet1/0/3
interface GigabitEthernet1/0/4
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/5
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/6
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/7
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp
interface GigabitEthernet1/0/8
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp

interface GigabitEthernet1/0/1 or  GigabitEthernet1/0/1 should be the array key and anything between interface sections should be array key value.

 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp

Expected output should be:

 $echo ${array[GigabitEthernet1/0/4]}
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp

There will be multiple different files with similar format, so this need to be done by loop, the text between interfaces should be 0 to 5-6 lines. The reason behind is I need to do logical test on each interface, if it is correct or not. Below text is correct, anything else, or empty field is incorrect.

 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp

So far i have stuck with formatting of IFS and multilines as the value of array key. I was able to fill non-associative array, but in not the cleanest form.

$ cat test_compare_interface | sed 's/interface.*$/*\n&/g' > test_compare_interface_sed

test_compare_interface is file with interfaces

$ IFS=$'*' && array=($(cat test_compare_interface_sed))
$ echo ${array[4]}

interface GigabitEthernet1/0/4
 srr-queue bandwidth share 10 10 60 20
 priority-queue out
 mls qos trust dscp

With associative array loop, i am still strugling

while IFS='*' read -r interface value; do array[$interface]=$value ; done < test_compare_interface_sed

Thank you for all the suggestions.

Body:
Would you please try the following:

declare -A array

# assign "${val[*]}" to the assciative array "array" keying with $1
store() {
    if [[ -n $1 ]]; then        # will skip the 1st line which is not ready
        array[$1]=$(IFS=$'\n'; echo "${val[*]}")
                                # join "val" with newline
        unset val               # empty the queue
    fi
}

while IFS= read -r line; do
    if [[ $line =~ ^interface ]]; then
        store "$interface"      # assign to the associative array
        interface="$line"       # for the next iteration
    else
        val+=("${line# }")      # append to the queue
    fi
done < file.txt

store "$interface"              # flush the last entry

for i in "${!array[@]}"; do     # print the array elements to test
    echo "$i"
    echo "${array[$i]}"
done

It just read the input line by line without modifying IFS.

If the line starts with "interface", it flushes the queue (array val)
into the associative array and updates the interface name for next iteration.

If the line does not start with "interface", the line is accumulated
in the queue (array val)


问:
How to Create OLAP cubes programmatically using Visual Studio
I am new to SQL Server Data Tools. After browsing the internet to learn the BI suite I found out that SSIS SSAS SSRS has more than just drag and drop. People are actually creating cubes and databases programmatically. Unfortunately, I couldn't find any resources on internet to learn how to code like this. Kindly guide me or share some links to learn to create cubes and databases programmatically.</p>

答:
Using BIML you can create SSIS packages programmatically. Combining BIML and TMSL allows you to script cube creation and processing. If you're set on creating multidimensional cubes and not tabular cubes then look at MDX.

Start by downloading BIML express for Visual Studio Data Tools.
Then start to look at the connector for Analysis Server and the AnalysisServicesExecuteDdl element which allows you to write TMSL inside the component. Now, using TMSL you can create a cube.
Why not just use BIML for everything and skip TMSL? Using TMSL instead of the available BIML elements for handling cubes removes the need to have BIML Studio ($$$) installed.


问:
Serial port reading loop in background
Have an STM32 device, that send over Serial port an AES encrypted Hex data any 2 seconds. All messages are finished with newline. My program (with User Interface, not a console one) is able to read from serial and to decrypt the data, even in loop still working good, but the problem is that in loop i can't use the disconnect function, so my program stay in "infinite loop".
Here is a code:

```<code>public void button1_Click(object sender, EventArgs e)
{
    try
    {
        serialPort1.PortName = cBoxComPort.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.DtrEnable = true;
        serialPort1.ReadTimeout = 5000;
        serialPort1.WriteTimeout = 500;
        serialPort1.Open();
        lblStatusCom.Text = "Connected";
        lblMessage.Text = "I am on!";

        while (serialPort1.IsOpen)
        {
            string mgs1 = serialPort1.ReadLine();
            byte[] key = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
            byte[] enc = StringToByteArray(mgs1);
            byte[] dec = Decrypt(enc, key);
            lblMessage.Text = getString(dec);
        }
    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //lblStatusCom.Text = "Disconnected";
    }
}
</code>```

How can i "put to background" this loop process, so that a user can click to disconnect, if he wish to quit the reading?

答:
Here is a version that would use the DataReceived event:

With the button click you would open the port and register the event

```<code>public void button1_Click(object sender, EventArgs e)
{
    try
    {
        serialPort1.PortName = cBoxComPort.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.DtrEnable = true;
        serialPort1.ReadTimeout = 5000;
        serialPort1.WriteTimeout = 500;
        serialPort1.Open();
        lblStatusCom.Text = "Connected";
        lblMessage.Text = "I am on!";

        serialPort1.DataReceived += portDataReceived;

    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //lblStatusCom.Text = "Disconnected";
    }
}

private void portDataReceived(object sender, EventArgs args)
{
    SerialPort port = sender as SerialPort;

    if (port == null)
    {
        return;
    }

    string mgs1 = port.ReadLine();
    byte[] key = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
    byte[] enc = StringToByteArray(mgs1);
    byte[] dec = Decrypt(enc, key);
    if (lblMessage.InvokeRequired)
    {
        lblMessage.Invoke(new Action(()=> lblMessage.Text = getString(dec)));
    }
    else
    {
        lblMessage.Text = getString(dec);
    }
}
</code>```

Title: Serial port reading loop in background

Body:
Have an STM32 device, that send over Serial port an AES encrypted Hex data any 2 seconds. All messages are finished with newline. My program (with User Interface, not a console one) is able to read from serial and to decrypt the data, even in loop still working good, but the problem is that in loop i can't use the disconnect function, so my program stay in "infinite loop".
Here is a code:

public void button1_Click(object sender, EventArgs e)
{
    try
    {
        serialPort1.PortName = cBoxComPort.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.DtrEnable = true;
        serialPort1.ReadTimeout = 5000;
        serialPort1.WriteTimeout = 500;
        serialPort1.Open();
        lblStatusCom.Text = "Connected";
        lblMessage.Text = "I am on!";

        while (serialPort1.IsOpen)
        {
            string mgs1 = serialPort1.ReadLine();
            byte[] key = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
            byte[] enc = StringToByteArray(mgs1);
            byte[] dec = Decrypt(enc, key);
            lblMessage.Text = getString(dec);
        }
    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //lblStatusCom.Text = "Disconnected";
    }
}

How can i "put to background" this loop process, so that a user can click to disconnect, if he wish to quit the reading?

Body:
Here is a version that would use the DataReceived event:

With the button click you would open the port and register the event

public void button1_Click(object sender, EventArgs e)
{
    try
    {
        serialPort1.PortName = cBoxComPort.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.DtrEnable = true;
        serialPort1.ReadTimeout = 5000;
        serialPort1.WriteTimeout = 500;
        serialPort1.Open();
        lblStatusCom.Text = "Connected";
        lblMessage.Text = "I am on!";

        serialPort1.DataReceived += portDataReceived;

    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //lblStatusCom.Text = "Disconnected";
    }
}

private void portDataReceived(object sender, EventArgs args)
{
    SerialPort port = sender as SerialPort;

    if (port == null)
    {
        return;
    }

    string mgs1 = port.ReadLine();
    byte[] key = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
    byte[] enc = StringToByteArray(mgs1);
    byte[] dec = Decrypt(enc, key);
    if (lblMessage.InvokeRequired)
    {
        lblMessage.Invoke(new Action(()=> lblMessage.Text = getString(dec)));
    }
    else
    {
        lblMessage.Text = getString(dec);
    }
}


问:
Silverlight crashes FireFox 3.5, IE7, & IE8
One of my users has an HP Pavilion DV4-1430us laptop running Windows Vista Professional 64-bit. She is using the latest version of the Silverlight Plug-In, downloaded on 24 July from microsoft.com/silverlight.

While typing in a text box in a silverlight web application my company developed, all three browsers will occasionally crash. Nine times out of ten, she can go back to the page where the crash occurred and pick up from where she left off, only to have it crash again several minutes later.

This only occurs while she is typing in a text box, and it only occurs on her laptop. I have watched her to confirm there is no user error.

Any thoughts?

Edit 1: I replicated the error. In Firefox 3.5, the window in which I was working closed with no warning, and the Mozilla Crash Reporter popped up. I'm pasting the crash report code:

Add-ons: {20a82645-c095-46ed-80e3-08825760534b}:1.1,{972ce4c6-7e08-4474-a285-3208198ce6fd}:3.5.1

BuildID: 20090715094852

CrashTime: 1248713784

InstallTime: 1248455260

ProductName: Firefox

SecondsSinceLastCrash: 245055

StartupTime: 1248713511

Theme: classic/1.0

Throttleable: 1

URL: [redacted]
Vendor: Mozilla

Version: 3.5.1

Edit 2: I replicated the error in IE8. I highlighted the text in a text box and began to type. Instantly,

Internet Explorer has stopped working

A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.
appeared.

Here is the event log entry:

>Log Name:      Application

>Source:        Application Error

>Date:          7/27/2009 1:06:10 PM
>Event ID:      1000

>Task Category: (100)

>Level:         Error

>Keywords:      Classic

>User:          N/A

>Computer:      [computer name]

>Description:

>Faulting application iexplore.exe, version 8.0.6001.18702, time stamp 0x49b3ad2e, faulting module kernel32.dll, version 6.0.6000.16820, time stamp 0x4995210a, exception code 0xe0434352, fault offset 0x0001e05c, process id 0x1a54, application start time 0x01ca0edc4c7c0054.

>Event Xml:

><Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">

>  <System>

>    <Provider Name="Application Error" />

>    <EventID Qualifiers="0">1000</EventID>

>    <Level>2</Level>

>    <Task>100</Task>

>    <Keywords>0x80000000000000</Keywords>

>    <TimeCreated SystemTime="2009-07-27T17:06:10.000Z" />

>    <EventRecordID>2636</EventRecordID>

>    <Channel>Application</Channel>

>    <Computer>[computer name]</Computer>

>    <Security />

>  </System>

>  <EventData>

>    <Data>iexplore.exe</Data>

>    <Data>8.0.6001.18702</Data>

>    <Data>49b3ad2e</Data>

>    <Data>kernel32.dll</Data>

>    <Data>6.0.6000.16820</Data>

>    <Data>4995210a</Data>

>    <Data>e0434352</Data>

>    <Data>0001e05c</Data>

>    <Data>1a54</Data>

>    <Data>01ca0edc4c7c0054</Data>

>  </EventData>

></Event>

答: You should look at FireFox's bugzilla for issues in firefox.  You'll get a lot better idea of what todo.  If you look, you will see quite a number of simular faults.</p>

ContentLicense: CC BY-SA 2.5


问:
TypeError: Cannot read property 'UserName' of undefined with Angular 2
I would like to display a username of the current user in my angular 2 application. The backend is developed with .net core web api.

I write this code but obtain in console this error :

TypeError: Cannot read property 'UserName' of undefined

class AuthService

```<code>import {Injectable, EventEmitter} from "@angular/core";
import {Http, Headers, Response, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Injectable()

export class AuthService {
    authKey = "auth";

    constructor(private http: AuthHttp) {
    }

    // Persist auth into localStorage or removes it if a NULL argument is given
    setAuth(auth: any): boolean {
        if (auth) {
            localStorage.setItem(this.authKey, JSON.stringify(auth));
        }
        else {
            localStorage.removeItem(this.authKey);
        }
        return true;
    }

    // Retrieves the auth JSON object (or NULL if none)
    getAuth(): any {
        var i = localStorage.getItem(this.authKey);
        if (i) {
            return JSON.parse(i);
        }
        else {
            return null;
        }
    }

    // Returns TRUE if the user is logged in, FALSE otherwise.

    isLoggedIn(): boolean {
        return localStorage.getItem(this.authKey) != null;
    }

    **get() {
        return this.http.get("api/Accounts")
            .map(response => <User>response.json());
    }**

}
</code>```

I'm sure that the user is logged in because I can read the his token.

Web api method

```<code> /// <summary>
        /// GET: api/accounts
        /// </summary>
        /// <returns>A Json-serialized object representing the current account.</returns>
        [HttpGet()]
        public IActionResult Get()
        {
            var id = GetCurrentUserId();
            //var id = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var user = DbContext.Users.Where(i => i.Id == id).FirstOrDefault();
            if (user != null) return new JsonResult(new UserViewModel()
            {
                Type = user.Type,
                UserName = user.UserName,
                Email = user.Email,
                DisplayName = user.DisplayName,
                PhoneNumber = user.PhoneNumber,
                DisplayPhoneNumber = user.DisplayPhoneNumber,
                Description = user.Description

            }, DefaultJsonSettings);
            else return NotFound(new { error = String.Format("User ID {0} has not been found", id) });
        }
</code>```

class user in typescript

```<code>export class User {
    constructor(
        public Type: number,
        public UserName: string,
        public DisplayName: string,
        public PhoneNumber: string,
        public DisplayPhoneNumber: boolean,
        public Description: string,
        public Password: string,
        public PasswordNew: string,
        public Email: string
    ) {
    }
}
</code>```

Code of component in angular 2

```<code>import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {AuthService} from "./auth.service";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Component({
    selector: "home",
    templateUrl: "templates/home.component.html",
    //template: `<h1>Home Component</h1>`
})

export class HomeComponent {

    isRegister: boolean;
    currentUser: User;
    constructor(
        public router: Router,
        public authService: AuthService,
        private activatedRoute: ActivatedRoute
    ) {

        //this.isRegister = this.authService.isLoggedIn();
        //console.log(this.isRegister);
    }
    ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.get().subscribe(
                User => this.currentUser = User
            );
            console.log(this.isRegister);
            console.log(this.currentUser.UserName);
        }
    }
}
</code>```

Code template html

```<code> <div *ngIf="currentUser"><h1>{{currentUser.UserName}}</h1></div>
</code>```

I don't understand why this doesn't work.

答:
try to replace:

currentUser: User;

as

currentUser = new User();

Undefined error in console is disappeared.

Body:
I would like to display a username of the current user in my angular 2 application. The backend is developed with .net core web api.

I write this code but obtain in console this error :

TypeError: Cannot read property 'UserName' of undefined

class AuthService

import {Injectable, EventEmitter} from "@angular/core";
import {Http, Headers, Response, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Injectable()

export class AuthService {
    authKey = "auth";

    constructor(private http: AuthHttp) {
    }

    // Persist auth into localStorage or removes it if a NULL argument is given
    setAuth(auth: any): boolean {
        if (auth) {
            localStorage.setItem(this.authKey, JSON.stringify(auth));
        }
        else {
            localStorage.removeItem(this.authKey);
        }
        return true;
    }

    // Retrieves the auth JSON object (or NULL if none)
    getAuth(): any {
        var i = localStorage.getItem(this.authKey);
        if (i) {
            return JSON.parse(i);
        }
        else {
            return null;
        }
    }

    // Returns TRUE if the user is logged in, FALSE otherwise.

    isLoggedIn(): boolean {
        return localStorage.getItem(this.authKey) != null;
    }

    **get() {
        return this.http.get("api/Accounts")
            .map(response => <User>response.json());
    }**

}

I'm sure that the user is logged in because I can read the his token.

Web api method

 ///
        /// GET: api/accounts
        ///
        /// <returns>A Json-serialized object representing the current account.</returns>
        [HttpGet()]
        public IActionResult Get()
        {
            var id = GetCurrentUserId();
            //var id = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var user = DbContext.Users.Where(i => i.Id == id).FirstOrDefault();
            if (user != null) return new JsonResult(new UserViewModel()
            {
                Type = user.Type,
                UserName = user.UserName,
                Email = user.Email,
                DisplayName = user.DisplayName,
                PhoneNumber = user.PhoneNumber,
                DisplayPhoneNumber = user.DisplayPhoneNumber,
                Description = user.Description

            }, DefaultJsonSettings);
            else return NotFound(new { error = String.Format("User ID {0} has not been found", id) });
        }

class user in typescript

export class User {
    constructor(
        public Type: number,
        public UserName: string,
        public DisplayName: string,
        public PhoneNumber: string,
        public DisplayPhoneNumber: boolean,
        public Description: string,
        public Password: string,
        public PasswordNew: string,
        public Email: string
    ) {
    }
}

Code of component in angular 2

import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {AuthService} from "./auth.service";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Component({
    selector: "home",
    templateUrl: "templates/home.component.html",
    //template: `<h1>Home Component</h1>`
})

export class HomeComponent {

    isRegister: boolean;
    currentUser: User;
    constructor(
        public router: Router,
        public authService: AuthService,
        private activatedRoute: ActivatedRoute
    ) {

        //this.isRegister = this.authService.isLoggedIn();
        //console.log(this.isRegister);
    }
    ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.get().subscribe(
                User => this.currentUser = User
            );
            console.log(this.isRegister);
            console.log(this.currentUser.UserName);
        }
    }
}

Code template html

{{currentUser.UserName}}

I don't understand why this doesn't work.


问:
Typescript flexible types
How can I enforce a value to exist within a list in typescript specifically w/ enums. Is this accomplishable w/ typescript type definitions?</p>

```<code>enum Friend {
  JOHN,
  SALLY,
  PAUL,
}

type MyFriends = {
   friends: Friend[],
   bestFriend: <> //How can I enforce that this value exists within the supplied list of friends?
}
</code>```

答:
```<code>enum Friend {
  JOHN,
  SALLY,
  PAUL,
}

// solution at type level
// type constructor
type MyFriends<F extends Friend[]> = {
   friends: F,
   bestFriend: F[number]
}

// make specific instance of it:
type JohnFriends = MyFriends<[Friend.SALLY,Friend.PAUL]>
const johnFriends: JohnFriends = {
    friends: [Friend.SALLY,Friend.PAUL],
    bestFriend: Friend.SALLY // can be only a member of friends array
}
const errorJohnFriends: JohnFriends = {
    friends: [Friend.SALLY,Friend.PAUL],
    bestFriend: Friend.JOHN // error as it should!
}

// solution at value level with value constructor
// additionaly we can make value constructor for proper creating such type of value
const makeFriends = <A extends Friend[], BF extends A[number]>(friends: A, bestFriend: BF): MyFriends<A> => ({
    friends,
    bestFriend
})

// propelry created value of MyFriends
const johnFriends2 = makeFriends([Friend.PAUL, Friend.JOHN], Friend.JOHN);
const errorJohnFriends2 = makeFriends([Friend.PAUL, Friend.JOHN], Friend.SALLY); // error as it should
</code>```

What we did here is:

MyFriends generic type which has argument of Friend, it means we pass which exactly elements from Friends enum will be available in friends property

bestFriend: F[number] - we say second field can be only value which exists in the friends array, thanks to that we cannot use Enum member which is not provided in the first one

Title: Typescript flexible types

Body:
How can I enforce a value to exist within a list in typescript specifically w/ enums. Is this accomplishable w/ typescript type definitions?

enum Friend {
  JOHN,
  SALLY,
  PAUL,
}

type MyFriends = {
   friends: Friend[],
   bestFriend: <> //How can I enforce that this value exists within the supplied list of friends?
}

Body:
enum Friend {
  JOHN,
  SALLY,
  PAUL,
}

// solution at type level
// type constructor
type MyFriends<F extends Friend[]> = {
   friends: F,
   bestFriend: F[number]
}

// make specific instance of it:
type JohnFriends = MyFriends<[Friend.SALLY,Friend.PAUL]>
const johnFriends: JohnFriends = {
    friends: [Friend.SALLY,Friend.PAUL],
    bestFriend: Friend.SALLY // can be only a member of friends array
}
const errorJohnFriends: JohnFriends = {
    friends: [Friend.SALLY,Friend.PAUL],
    bestFriend: Friend.JOHN // error as it should!
}

// solution at value level with value constructor
// additionaly we can make value constructor for proper creating such type of value
const makeFriends = <A extends Friend[], BF extends A[number]>(friends: A, bestFriend: BF): MyFriends<A> => ({
    friends,
    bestFriend
})

// propelry created value of MyFriends
const johnFriends2 = makeFriends([Friend.PAUL, Friend.JOHN], Friend.JOHN);
const errorJohnFriends2 = makeFriends([Friend.PAUL, Friend.JOHN], Friend.SALLY); // error as it should

What we did here is:

MyFriends generic type which has argument of Friend, it means we pass which exactly elements from Friends enum will be available in friends property

bestFriend: F[number] - we say second field can be only value which exists in the friends array, thanks to that we cannot use Enum member which is not provided in the first one


问:
Add prism to summernote
Is there any way to add a button for prism in summernote editor?

I have prism css and js file included in my view but i don't know how to add button for it in editor:

```<code>$(document).ready(function() {
  $('.summernote').summernote({
      minHeight: 200,
      toolbar: [
         ['style', ['style', 'bold', 'italic', 'underline', 'clear']],
         ['font', ['strikethrough', 'superscript', 'subscript']],
         ['fontsize', ['fontsize', 'fontname', 'fontsizeunit', 'height']],
         ['color', ['color']],
         ['para', ['ul', 'ol', 'paragraph']],
         ['table', ['table']],
         ['insert', ['link', 'emoji', 'picture', 'video']],
         ['view', ['fullscreen', 'codeview', 'help']]
      ]
  });
});
</code>```

Any idea?

答:
Solved

I fixed my issue by creating a plugin for summernote as well as package for others to use

Screenshots

editor

view

Package links

NPM

GitHub

Hope it help others as well.

Title: Add prism to summernote

Body:
Is there any way to add a button for prism in summernote editor?

I have prism css and js file included in my view but i don't know how to add button for it in editor:

$(document).ready(function() {
  $('.summernote').summernote({
      minHeight: 200,
      toolbar: [
         ['style', ['style', 'bold', 'italic', 'underline', 'clear']],
         ['font', ['strikethrough', 'superscript', 'subscript']],
         ['fontsize', ['fontsize', 'fontname', 'fontsizeunit', 'height']],
         ['color', ['color']],
         ['para', ['ul', 'ol', 'paragraph']],
         ['table', ['table']],
         ['insert', ['link', 'emoji', 'picture', 'video']],
         ['view', ['fullscreen', 'codeview', 'help']]
      ]
  });
});

Any idea?