Title: How to concatenate a series of smaller size to the bottom of a pandas dataframe

Body:
I'm trying to concatenate a Series onto the right side of a dataframe with the column name 'RSI'.  However, because the Series is of shorter length than the other columns in the dataframe, I need to ensure that NaN values are appended to the top of the column and not the bottom.  Right now, I've used the following code but I can't find an argument that would allow me to have the desired output.

RSI = pd.Series(RSI)
df = pd.concat((df, RSI.rename('RSI'), axis='columns')

So far, this is my output:

      Dates  Prices   Volumes      RSI
0    2013-02-08  201.68   2893254  47.7357
1    2013-02-11  200.16   2944651  53.3967
2    2013-02-12  200.04   2461779  56.3866
3    2013-02-13  200.09   2169757  60.1845
4    2013-02-14  199.65   3294126  62.1784
5    2013-02-15  200.98   3627887  63.9720
6    2013-02-19  200.32   2998317  62.9671
7    2013-02-20  199.31   3715311  63.9232
8    2013-02-21  198.33   3923051  66.8817
9    2013-02-22  201.09   3107876  72.8258
10   2013-02-25  197.51   3845276  69.6578
11   2013-02-26  199.14   3391562  63.8458
12   2013-02-27  202.33   4185545  64.2776
13   2013-02-28  200.83   4689698  67.2445
14   2013-03-01  202.91   3308544  58.2408
15   2013-03-04  205.19   3693365  57.7058
16   2013-03-05  206.53   3807706  53.7482
17   2013-03-06  208.38   3594899  57.5396
18   2013-03-07  209.42   3884317  53.2722
19   2013-03-08  210.38   3700086  58.6824
20   2013-03-11  210.08   3048901  56.0161
21   2013-03-12  210.55   3591261  60.2066
22   2013-03-13  212.06   3355969  55.3322
23   2013-03-14  215.80   5505484  51.7492
24   2013-03-15  214.92   7935024  47.1241
25   2013-03-18  213.21   3006125  46.9102
26   2013-03-19  213.44   3198577  46.6569
27   2013-03-20  215.06   3019153  54.0822
28   2013-03-21  212.26   5830566  56.2525
29   2013-03-22  212.08   3015847  51.8359
...         ...     ...       ...      ...
1229 2017-12-26  152.83   2479017  80.1930
1230 2017-12-27  153.13   2149257  80.7444
1231 2017-12-28  154.04   2687624  56.4425
1232 2017-12-29  153.42   3327087  56.9183
1233 2018-01-02  154.25   4202503  63.6958
1234 2018-01-03  158.49   9441567  61.1962
1235 2018-01-04  161.70   7556249  61.3816
1236 2018-01-05  162.49   5195764  64.7724
1237 2018-01-08  163.47   5237523  63.0508
1238 2018-01-09  163.83   4341810  53.9559
1239 2018-01-10  164.18   4174105  54.1351
1240 2018-01-11  164.20   3794453  50.6824
1241 2018-01-12  163.14   5031886  43.0222
1242 2018-01-16  163.85   7794195  32.7428
1243 2018-01-17  168.65  11710033  39.4754
1244 2018-01-18  169.12  14259345  37.3409
1245 2018-01-19  162.37  21172488      NaN
1246 2018-01-22  162.60   8480795      NaN
1247 2018-01-23  166.25   7466232      NaN
1248 2018-01-24  165.37   5645003      NaN
1249 2018-01-25  165.47   3302520      NaN
1250 2018-01-26  167.34   3787913      NaN
1251 2018-01-29  166.80   3516995      NaN
1252 2018-01-30  163.62   4902341      NaN
1253 2018-01-31  163.70   4072830      NaN
1254 2018-02-01  162.40   4434242      NaN
1255 2018-02-02  159.03   5251938      NaN
1256 2018-02-05  152.53   8746599      NaN
1257 2018-02-06  155.34   9867678      NaN
1258 2018-02-07  153.85   6149207      NaN

However, I need it to look like this:

          Dates  Prices   Volumes      RSI
0    2013-02-08  201.68   2893254  NaN
1    2013-02-11  200.16   2944651  NaN
2    2013-02-12  200.04   2461779  NaN
3    2013-02-13  200.09   2169757  NaN
4    2013-02-14  199.65   3294126  NaN
5    2013-02-15  200.98   3627887  NaN
6    2013-02-19  200.32   2998317  NaN
7    2013-02-20  199.31   3715311  NaN
8    2013-02-21  198.33   3923051  NaN
9    2013-02-22  201.09   3107876  NaN
10   2013-02-25  197.51   3845276  NaN
11   2013-02-26  199.14   3391562  NaN
12   2013-02-27  202.33   4185545  NaN
13   2013-02-28  200.83   4689698  NaN
14   2013-03-01  202.91   3308544  NaN
15   2013-03-04  205.19   3693365  57.7058
16   2013-03-05  206.53   3807706  53.7482
17   2013-03-06  208.38   3594899  57.5396
18   2013-03-07  209.42   3884317  53.2722
19   2013-03-08  210.38   3700086  58.6824
20   2013-03-11  210.08   3048901  56.0161
21   2013-03-12  210.55   3591261  60.2066
22   2013-03-13  212.06   3355969  55.3322
23   2013-03-14  215.80   5505484  51.7492
24   2013-03-15  214.92   7935024  47.1241
25   2013-03-18  213.21   3006125  46.9102
26   2013-03-19  213.44   3198577  46.6569
27   2013-03-20  215.06   3019153  54.0822
28   2013-03-21  212.26   5830566  56.2525
29   2013-03-22  212.08   3015847  51.8359
...         ...     ...       ...      ...
1229 2017-12-26  152.83   2479017  80.1930
1230 2017-12-27  153.13   2149257  80.7444
1231 2017-12-28  154.04   2687624  56.4425
1232 2017-12-29  153.42   3327087  56.9183
1233 2018-01-02  154.25   4202503  63.6958
1234 2018-01-03  158.49   9441567  61.1962
1235 2018-01-04  161.70   7556249  61.3816
1236 2018-01-05  162.49   5195764  64.7724
1237 2018-01-08  163.47   5237523  63.0508
1238 2018-01-09  163.83   4341810  53.9559
1239 2018-01-10  164.18   4174105  54.1351
1240 2018-01-11  164.20   3794453  50.6824
1241 2018-01-12  163.14   5031886  43.0222
1242 2018-01-16  163.85   7794195  32.7428
1243 2018-01-17  168.65  11710033  39.4754
1244 2018-01-18  169.12  14259345  36.9999
1245 2018-01-19  162.37  21172488  41.1297
1246 2018-01-22  162.60   8480795  12.1231
1247 2018-01-23  166.25   7466232  39.0977
1248 2018-01-24  165.37   5645003  63.6958
1249 2018-01-25  165.47   3302520  56.4425
1250 2018-01-26  167.34   3787913  80.7444
1251 2018-01-29  166.80   3516995  61.1962
1252 2018-01-30  163.62   4902341  58.6824
1253 2018-01-31  163.70   4072830  53.7482
1254 2018-02-01  162.40   4434242  43.0222
1255 2018-02-02  159.03   5251938  61.1962
1256 2018-02-05  152.53   8746599  56.4425
1257 2018-02-06  155.34   9867678  36.0978
1258 2018-02-07  153.85   6149207  41.1311

Thanks for the help.

Body:
We can get the difference in rows between the Series and the dataframe.

Then append the difference in NaN to the series (on top) with np.repeat

Finally append the new series with NaN to your original dataframe over axis=1 (columns)

diff = df.shape[0] - RSI.shape[0]
rpts = np.repeat(np.NaN, diff)

RSI = pd.concat([pd.Series(rpts, name='RSI'), RSI], ignore_index=True)

pd.concat([df, RSI['RSI']], axis=1).head(20)

         Dates  Prices  Volumes      RSI
0   2013-02-08  201.68  2893254      NaN
1   2013-02-11  200.16  2944651      NaN
2   2013-02-12  200.04  2461779      NaN
3   2013-02-13  200.09  2169757      NaN
4   2013-02-14  199.65  3294126      NaN
5   2013-02-15  200.98  3627887      NaN
6   2013-02-19  200.32  2998317      NaN
7   2013-02-20  199.31  3715311      NaN
8   2013-02-21  198.33  3923051      NaN
9   2013-02-22  201.09  3107876      NaN
10  2013-02-25  197.51  3845276      NaN
11  2013-02-26  199.14  3391562      NaN
12  2013-02-27  202.33  4185545      NaN
13  2013-02-28  200.83  4689698  47.7357
14  2013-03-01  202.91  3308544  53.3967
15  2013-03-04  205.19  3693365  56.3866
16  2013-03-05  206.53  3807706  60.1845
17  2013-03-06  208.38  3594899  62.1784
18  2013-03-07  209.42  3884317  63.9720
19  2013-03-08  210.38  3700086  62.9671


来源: stackexchange

问:
How to navigate to next page taking params from current page and persist it even after browser refresh in react
I have to navigate to next page on click of a link with parameters from current page and also want to persist that param if browser refresh in reactjs</p>

答:
localStorage is the answer.
before sending the client to the link, transform the data to a json string, then save it on local storage, th
en redirect the client, then get the previous data and parse it.

```<code>const data = your-data
const stringData = JSON.stringify(data)
localStorage.set("prevdata", stringData)
</code>```

Redirect the client, and then

```<code>const prevData = JSON.parse(localStorage.get("prevdata"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
localStorage is the answer.
before sending the client to the link, transform the data to a json string, then save it on local storage, th
en redirect the client, then get the previous data and parse it.

const data = your-data
const stringData = JSON.stringify(data)
localStorage.set("prevdata", stringData)

Redirect the client, and then

const prevData = JSON.parse(localStorage.get("prevdata"))


问:
Parsing a json file using python
I have this json file which has the image name(medical images-around 7500) and its corresponding medical reports.
It is of the format:

```<code>{"IMAGE_NAME1.png": "MEDICAL_REPORT1_IN_TEXT", "IMAGE_NAME2.png": "MEDICAL_REPORT2_IN_TEXT", ...and so on for all images ...}
</code>```

What I want is all the image names in the JSON file so that I can take all the images(From a database of images which is a super set of the image names in the JSON file) and make its own folder. Can someone help me with this?

答:
I think you're looking for the json library.  I haven't tested this, but I am pretty confident it will work.

```<code>import json

with open("path/to/json.json", 'r') as file:
    json_data = json.load(file)
</code>```

to get image names from what you described the data to look like.

```<code>image_names = list(json_data.keys())
</code>```

Title: Parsing a json file using python

Body:
I have this json file which has the image name(medical images-around 7500) and its corresponding medical reports.
It is of the format:

{"IMAGE_NAME1.png": "MEDICAL_REPORT1_IN_TEXT", "IMAGE_NAME2.png": "MEDICAL_REPORT2_IN_TEXT", ...and so on for all images ...}

What I want is all the image names in the JSON file so that I can take all the images(From a database of images which is a super set of the image names in the JSON file) and make its own folder. Can someone help me with this?

Body:
I think you're looking for the json library.  I haven't tested this, but I am pretty confident it will work.

import json

with open("path/to/json.json", 'r') as file:
    json_data = json.load(file)

to get image names from what you described the data to look like.

image_names = list(json_data.keys())


问:
difference between let inside and outside a lambda expression
Consider a module with the following procedures:

```<code>(define-module (test test)
  #:export     (proc1 proc2 proc3))

(define proc1
  (let ((module (current-module)))
    (lambda ()
      (format #t "~s\n" module))))

(define proc2
  (lambda ()
    (let ((module (current-module)))
      (format #t "~s\n" module))))

(define (proc3)
  (let ((module (current-module)))
    (format #t "~s\n" module)))
</code>```

I was under the impression that all these were equivalent, but they are not.

```<code>scheme@(guile-user)> (use-modules (test test))
scheme@(guile-user)> (proc1)
#<directory (test test) 562a062152d0>
$1 = #t
scheme@(guile-user)> (proc2)
#<directory (guile-user) 562a05b8bbd0>
$2 = #t
scheme@(guile-user)> (proc3)
#<directory (guile-user) 562a05b8bbd0>
$3 = #t
</code>```

Only in proc1 the module symbol inside the lambda expression is bound to the module were the procedure is defined.

Can somebody explain this? Does it mean I always have to use the first form, if I want to create a closure?

答:
proc1 evaluates (current-module) only once, when the procedure is defined, so module inside the lambda is bound to that value at definition-time.

proc2 does not evaluate (current-module) until the procedure is called.

It also evaluates it every time.

It is equivalent to proc3.

Body:
Consider a module with the following procedures:

(define-module (test test)
  #:export     (proc1 proc2 proc3))

(define proc1
  (let ((module (current-module)))
    (lambda ()
      (format #t "~s\n" module))))

(define proc2
  (lambda ()
    (let ((module (current-module)))
      (format #t "~s\n" module))))

(define (proc3)
  (let ((module (current-module)))
    (format #t "~s\n" module)))

I was under the impression that all these were equivalent, but they are not.

scheme@(guile-user)> (use-modules (test test))
scheme@(guile-user)> (proc1)
#<directory (test test) 562a062152d0>
$1 = #t
scheme@(guile-user)> (proc2)
#<directory (guile-user) 562a05b8bbd0>
$2 = #t
scheme@(guile-user)> (proc3)
#<directory (guile-user) 562a05b8bbd0>
$3 = #t

Only in proc1 the module symbol inside the lambda expression is bound to the module were the procedure is defined.

Can somebody explain this? Does it mean I always have to use the first form, if I want to create a closure?


问:
Populate a Combo Box with Pivot Table Values
I have a combo box with a list of names, that filters a pivot table.

Each name I select changes the values shown at the pivot table.

I need a code that populates a second combo box with those pivot tables values. When I choose a name on the first combo box, the options at the second one will be the ones filtered by that name on the pivot table.

I have done that before in a simpler manner with fixed tables, but now the values are going to change constantly, and that's why I need to use a pivot table for that.

答:
You can use the DataRange of your PivotField as source for your ComboBox.

You may either add each cell's value to the ComboBox items ...

```<code>Dim aCell As Range
For Each aCell In ActiveSheet.PivotTables(1).RowFields(1).DataRange.Cells
    ActiveSheet.ComboBox1.AddItem aCell.Value
Next aCell
</code>```

... or the whole ComboBox.List in one by a simple assignment:

```<code>ActiveSheet.ComboBox1.List = ActiveSheet.PivotTables(1).RowFields(1).DataRange.Value
</code>```

I guess you used your "TIMBRA..."-list as the only row field in your pivot table.

If not, you can address the DataRange by names instead, e. g.

```<code>ActiveWorkbook.Sheets("...").PivotTables("...").PivotFields("...").DataRange
</code>```

Body:
You can use the DataRange of your PivotField as source for your ComboBox.

You may either add each cell's value to the ComboBox items ...

Dim aCell As Range
For Each aCell In ActiveSheet.PivotTables(1).RowFields(1).DataRange.Cells
    ActiveSheet.ComboBox1.AddItem aCell.Value
Next aCell

... or the whole ComboBox.List in one by a simple assignment:

ActiveSheet.ComboBox1.List = ActiveSheet.PivotTables(1).RowFields(1).DataRange.Value

I guess you used your "TIMBRA..."-list as the only row field in your pivot table.

If not, you can address the DataRange by names instead, e. g.

ActiveWorkbook.Sheets("...").PivotTables("...").PivotFields("...").DataRange


问:
How to get a sales order ID and set it in a Custom Record in netsuite?
I am very new to netsuite. I want to redirect a user from sales order to a custom record I created on button click, I want to get sales order ID and set it in the custom form where the user is being redirected by clicking a button the way fulfillment works in netsuite. I am using client script to redirect user when the button is clicked. Is there a way to pass the sale order id to the next form/Record?

Like this
https://i.stack.imgur.com/QghDv.png

I tried to use the saved search feature but I couldn't fully understand it. If indeed it can be done through saved search, it would be a great help if someone could guide me.

答:
In your Client Script you can use the N/currentRecord module to retrieve the ID of the record in context. It will allow you to retrieve a reference to the CurrentRecord object, which will have an id property.

See the Help page for N/currentRecord for details.


问:
Converting Strings into the numeric unicode equivalent for each letter in the word using a loop using Java?
I've been trying to figure out how to convert Strings into numeric Unicode that is from the user input. From the assignment, I know I'm suppose to use loops to transfer the words to Unicode but I'm uncertain how to do this.

I'm pretty sure it's suppose to be either a while or for loop. They said the while loop if for when you don't have a set iteration which I don't think this one does.

I have looked up Unicode and I'm still confused but I think this might be Unicode site: http://www.unicodetables.com/

Which lead me to the Basic Latin:
http://www.unicode.org/charts/PDF/U0000.pdf

But I have no idea what to do with it.

I also saw another question that was similar to mine but used ord() but that was for Python so I don't know if Java has an equivalent.

The code that I have so far is here:
package calculate;

```<code>import java.util.Scanner;

public class UniCal {
    public static void main(String[] args) {

        String word1;
        String word2;

        String resultFullWord;
        int resultAbsVal = 0;

        Scanner scanner = new Scanner(System.in);

        System.out.println("What is your first word?");
        word1 = scanner.nextLine();

        System.out.println("And your second word?");
        word2 = scanner.nextLine();

        resultFullWord = (word1 + " " + word2);
        System.out.println(resultFullWord);

        word = input("Enter a word: ")
                for letter in word:
                    print(letter + ': ', ord(letter));
    }

    // while (resultFullWord.equals(resultFullWord)) {
            // Do something ...
            // Get input into userChar
    // }

        // Math.abs
        System.out.println("Your absolute value based on your word is : " + resultAbsVal);
        scanner.close();

    }

}
</code>```

答:
You are missing the key point that Java char values already provide a numeric encoding of Unicode, and also that Java Strings have methods for extracting Unicode "code points" -- the numeric values that Unicode assigns to characters.

It's unclear exactly what the expectation of the assignment is.  If the "numeric unicode equivalent" means the UTF-16 code unit value, then you can just iterate over the chars of the string.  Depending on what method you use to print them, you may need to cast them to type int to get numeric results instead of numbers.

I suspect that the above is what the assignment expects you to do, since you seem to have had little or no introduction to Unicode concepts or terminology.  However, evantually you will need to be aware that UTF-16, and therefore Java Strings, encode the majority of Unicode characters as two-char "surrogate pairs".  If you're intended to print the numeric value of each Unicode character encoded by a String, as opposed to each Java char, then you need a different approach: you want to iterate over the code points represented by the String, not the chars.

To iterate over all the Unicode code points of a String, I would be inclined to use String.codePoints(), but that provides them to you in the form of an IntStream.  That's a really convenient form, except that it's not conducive to performing an explicit iteration via a for or while loop, and if you're new to Java then you may not have learned about streams yet.  In that case, you can use String.codePointCount() to find out how many code points the string contains, then use a for loop to iterate over the code point indexes, extracting each one via String.codePointAt().

Body:
I've been trying to figure out how to convert Strings into numeric Unicode that is from the user input. From the assignment, I know I'm suppose to use loops to transfer the words to Unicode but I'm uncertain how to do this.

I'm pretty sure it's suppose to be either a while or for loop. They said the while loop if for when you don't have a set iteration which I don't think this one does.

I have looked up Unicode and I'm still confused but I think this might be Unicode site: http://www.unicodetables.com/

Which lead me to the Basic Latin:
http://www.unicode.org/charts/PDF/U0000.pdf

But I have no idea what to do with it.

I also saw another question that was similar to mine but used ord() but that was for Python so I don't know if Java has an equivalent.

The code that I have so far is here:
package calculate;

import java.util.Scanner;

public class UniCal {
    public static void main(String[] args) {

        String word1;
        String word2;

        String resultFullWord;
        int resultAbsVal = 0;

        Scanner scanner = new Scanner(System.in);

        System.out.println("What is your first word?");
        word1 = scanner.nextLine();

        System.out.println("And your second word?");
        word2 = scanner.nextLine();

        resultFullWord = (word1 + " " + word2);
        System.out.println(resultFullWord);

        word = input("Enter a word: ")
                for letter in word:
                    print(letter + ': ', ord(letter));
    }

    // while (resultFullWord.equals(resultFullWord)) {
            // Do something ...
            // Get input into userChar
    // }

        // Math.abs
        System.out.println("Your absolute value based on your word is : " + resultAbsVal);
        scanner.close();

    }

}


问:
How to remove gameobject from list referencing by raycast
Hi I I'm trying to create a card game and I have a class called hand, this hand has a public List<GameObject> cards; and a methods:

```<code>public void AddCard(GameObject card)
{
   cards.Add(card);
   GameObject cardObject = Instantiate(card, startPosition, actualCardRotation);
}

public GameObject RemoveCard(GameObject card)
{
        cards.Remove(card);
        return card;
 }
</code>```

then I have a cardGameController attributes public Hand playerHand, computerHand; that has a function to select a card for play and call RemoveCard function but its not working here is the code:

```<code>public void SelectCardToPlay()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

        RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
        if (hit.collider != null && hit.collider.CompareTag("Card"))
        {
            Console.text = hit.collider.gameObject.GetComponent<Card>().description;

            if (Input.GetMouseButtonDown(0))
            {
                playedPlayerCard = playerHand.RemoveCard(hit.collider.gameObject);
                playerSelectedCardBoard.AddCard(playedPlayerCard, 3);

                playedComputerCard = computerHand.PickRandomCard();
                computerSelectedCardBoard.AddCard(playedComputerCard, 3);

                gameState = 5;
            }
        }
    }
</code>```

Seems like the object i get by hit.collider isn't the same as the hand list or something like that, any hints?

答:
In your AddCard you're adding the input card, which I assume is a prefab - since you use it to spawn a new card. I then assume it's this spawned card that you want to remove from the list, since that's probably the object you're hitting?

Simply change your AddCard to:

```<code>public void AddCard(GameObject card)
{
   GameObject cardObject = Instantiate(card, startPosition, actualCardRotation);
   cards.Add(cardObject);
}
</code>```

And see if that works.

If that wasn't the issue, make sure you debug exactly what object it is you're getting att all points. Add some Debug.Log(gameObject.name); here and there to see.

Body:
Hi I I'm trying to create a card game and I have a class called hand, this hand has a public List<GameObject> cards; and a methods:

public void AddCard(GameObject card)
{
   cards.Add(card);
   GameObject cardObject = Instantiate(card, startPosition, actualCardRotation);
}

public GameObject RemoveCard(GameObject card)
{
        cards.Remove(card);
        return card;
 }

then I have a cardGameController attributes public Hand playerHand, computerHand; that has a function to select a card for play and call RemoveCard function but its not working here is the code:

public void SelectCardToPlay()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

        RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
        if (hit.collider != null && hit.collider.CompareTag("Card"))
        {
            Console.text = hit.collider.gameObject.GetComponent<Card>().description;

            if (Input.GetMouseButtonDown(0))
            {
                playedPlayerCard = playerHand.RemoveCard(hit.collider.gameObject);
                playerSelectedCardBoard.AddCard(playedPlayerCard, 3);

                playedComputerCard = computerHand.PickRandomCard();
                computerSelectedCardBoard.AddCard(playedComputerCard, 3);

                gameState = 5;
            }
        }
    }

Seems like the object i get by hit.collider isn't the same as the hand list or something like that, any hints?

Body:
In your AddCard you're adding the input card, which I assume is a prefab - since you use it to spawn a new card. I then assume it's this spawned card that you want to remove from the list, since that's probably the object you're hitting?

Simply change your AddCard to:

public void AddCard(GameObject card)
{
   GameObject cardObject = Instantiate(card, startPosition, actualCardRotation);
   cards.Add(cardObject);
}

And see if that works.

If that wasn't the issue, make sure you debug exactly what object it is you're getting att all points. Add some Debug.Log(gameObject.name); here and there to see.


问:
Input parameters validation and response
I want to validate operation parameters sent from the client (using IParameterInspector) in my service and in case of wrong parameter input I would like to send response code as a part of the response object instead of throwing fault exception.
Please let me know how I can achieve this.

UPDATE :
If it is not possible with IParameterInspector, what other options you will suggest ?

答: Inspector intercepts calls to service operations and performs logic for validating the parameters passed to that operation. If the parameters are found invalid the actual service operation never gets executed, and the only way to notify client is exception (better be part of FaultContract).</p>

ContentLicense: CC BY-SA 3.0


问:
KeyError: "The name 'loss:0' refers to a Tensor which does not exist. The operation, 'loss', does not exist in the graph."

KeyError: "The name 'loss:0' refers to a Tensor which does not exist. The operation, 'loss', does not exist in the graph."

Hey guys, i'm facing an issue while using the tensorflow model. The code is running fine when it compiled in terminal but when i try to make it an python API it shows the above error

```<code>output_layer = 'loss:0'
input_node = 'Placeholder:0'

# Crop the center for the specified network_input_Size
augmented_image = crop_center(augmented_image, network_input_size, network_input_size)

with tf.Session() as sess:
    prob_tensor = sess.graph.get_tensor_by_name(output_layer)
    predictions = sess.run(prob_tensor, {input_node: [augmented_image] })
</code>```

The above code is saying an error at

prob_tensor = sess.graph.get_tensor_by_name(output_layer)

答:
I had the same problem when exporting my Custom Vision model. When I use model_outputs:0 it runs. However the predictions array doen't make sense. When I test the model within Custom Vision I get 4 objects
Three cars and a truck

but the predicition array shape is 13X13X40

Body:
KeyError: "The name 'loss:0' refers to a Tensor which does not exist. The operation, 'loss', does not exist in the graph."

Hey guys, i'm facing an issue while using the tensorflow model. The code is running fine when it compiled in terminal but when i try to make it an python API it shows the above error

output_layer = 'loss:0'
input_node = 'Placeholder:0'

# Crop the center for the specified network_input_Size
augmented_image = crop_center(augmented_image, network_input_size, network_input_size)

with tf.Session() as sess:
    prob_tensor = sess.graph.get_tensor_by_name(output_layer)
    predictions = sess.run(prob_tensor, {input_node: [augmented_image] })

The above code is saying an error at

prob_tensor = sess.graph.get_tensor_by_name(output_layer)


问:
How exactly CSS works?
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  border: 1px solid red;
}
</code>```

Example-2:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  color: red;
}
</code>```

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.

答:
In CSS, inheritance controls what happens when no value is specified for a property on an element. Refer to any CSS property definition to see whether a specific property inherits by default ("Inherited: yes") or not ("Inherited: no").

From Inheritance - CSS: Cascading Style Sheets | MDN

Not all properties are inherited by defaults, color for instance is, but border is not. You have to refer to documentations (like MDN or w3schools) to know whether a property is set to inherit by default.

You can however explicitly set an element property to inherit the value of its parent property using the keyword value inherit, like so:

.parent {
  border: 1px solid red;
}

.child {
  border: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  Some text
  <div class="child">Child element</div>
  <div class="child">Child element</div>
</div></code>```

/!\ Inheritance is not to be confused with the cascade, which is the mechanism defining the style declarations applied to elements being targeted by several selectors.

Title: How exactly CSS works?

Body:
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  border: 1px solid red;
}

Example-2:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  color: red;
}

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.

Body:
In CSS, inheritance controls what happens when no value is specified for a property on an element. Refer to any CSS property definition to see whether a specific property inherits by default ("Inherited: yes") or not ("Inherited: no").

From Inheritance - CSS: Cascading Style Sheets | MDN

Not all properties are inherited by defaults, color for instance is, but border is not. You have to refer to documentations (like MDN or w3schools) to know whether a property is set to inherit by default.

You can however explicitly set an element property to inherit the value of its parent property using the keyword value inherit, like so:

.parent {
  border: 1px solid red;
}

.child {
  border: inherit;
}

<div class="parent">
  Some text
  <div class="child">Child element</div>
  <div class="child">Child element</div>
</div>

/!\ Inheritance is not to be confused with the cascade, which is the mechanism defining the style declarations applied to elements being targeted by several selectors.


问:
How to create a Column that defaults to a ListView as fallback if the content widgets are too large?
I have some widgets that I want to display on a screen.

If the screen is large enough, the widgets should be centered on it like this:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [...],
)
```

<p>On small screens, I don't want the <code>Column</code> to overflow (black & yellow stripes) but instead, let the user scroll through them, as if they were in a <code>ListView</code>, like this:</p>

<pre class="lang-dart prettyprint-override"><code>ListView(
  children: [...],
)
</code>```

If I knew the dimensions of the widgets beforehand, I could change the layout to one of the above in a LayoutBuilder based on the incoming constraints.
However, I don't know how their dimensions, so is there any easy way to achieve this on the widget layer?

答:
Use SingleChildScrollView with physics: ClampingScrollPhysics() to avoid unwanted scrolling, wrapped in Center widget.

e.g.

Center(
  child: SingleChildScrollView(
    physics: ClampingScrollPhysics(), // To prevent the content from being always scrollable even when overall height is smaller than the screen.
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [/*...*/],
    )
  )
)
```

Body:
I have some widgets that I want to display on a screen.

If the screen is large enough, the widgets should be centered on it like this:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [...],
)

On small screens, I don't want the Column to overflow (black & yellow stripes) but instead, let the user scroll through them, as if they were in a ListView, like this:

ListView(
  children: [...],
)

If I knew the dimensions of the widgets beforehand, I could change the layout to one of the above in a LayoutBuilder based on the incoming constraints.
However, I don't know how their dimensions, so is there any easy way to achieve this on the widget layer?


问:
GitLab remote: HTTP Basic: Access denied and fatal Authentication
Unlike this post, I am on macOS.

I have the password configured in GitLab. I also have an SSL key created after the project was made on GitLab.

When I use an existing folder for a new project and follow the steps below, I am prompted to enter my GitLab username and password.

Existing folder

```<code>cd existing_folder
git init
git remote add origin https://gitlab.com/sobopla/Geronimod.git
git add .
git commit -m "Initial commit"
git push -u origin master
</code>```

After the password is entered I get the following error.

remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/myname/myproject'

答:
It happens if you change your login or password of git service account (GitHub or GitLab, Bitbacket, etc). You need to change it in Windows Credentials Manager too.

So, type "Credential Manager" (rus. "Диспетчер Учетных Данных") in Windows Search menu and go to your git service account and change data too.

Body:
Unlike this post, I am on macOS.

I have the password configured in GitLab. I also have an SSL key created after the project was made on GitLab.

When I use an existing folder for a new project and follow the steps below, I am prompted to enter my GitLab username and password.

Existing folder

cd existing_folder
git init
git remote add origin https://gitlab.com/sobopla/Geronimod.git
git add .
git commit -m "Initial commit"
git push -u origin master

After the password is entered I get the following error.

remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/myname/myproject'


问:
Mathematica - How to execute a function inside a while loop?
I'm new to Mathematica, and am trying to get a function to execute in a while loop. I think the best way to explain this is by using an example.
So, say you have a normal, simply while loop like the following:

```<code>In[1]:= x = 5;
While[x > 0, Print[x]; x--];
</code>```

This outputs the following:
5
4
3
2
1 as one would expect.
However, why doesn't this work:

```<code>x=5;

While[x > 0, g[]; x--];
g[] = Print[x];
</code>```

When I try something like the above, it just outputs 5 and then stops. I'm used to Python and something like that would work in Python - how can I make it work in Mathematica. Thanks

答:
The first time you run this

```<code>x=5;
While[x > 0, g[]; x--];
g[]:= Print[x];
</code>```

it prints nothing because the function g has not been defined before it is used.

The second time you run it it prints your desired 5,4,3,2,1 because it has previously seen the definition of g.

You can make this work every time if you define g before first use, like this

```<code>g[]:= Print[x];
x=5;
While[x > 0, g[]; x--];
</code>```

Body:
I'm new to Mathematica, and am trying to get a function to execute in a while loop. I think the best way to explain this is by using an example.
So, say you have a normal, simply while loop like the following:

In[1]:= x = 5;
While[x > 0, Print[x]; x--];

This outputs the following:
5
4
3
2
1 as one would expect.
However, why doesn't this work:

x=5;

While[x > 0, g[]; x--];
g[] = Print[x];

When I try something like the above, it just outputs 5 and then stops. I'm used to Python and something like that would work in Python - how can I make it work in Mathematica. Thanks

Body:
The first time you run this

x=5;
While[x > 0, g[]; x--];
g[]:= Print[x];

it prints nothing because the function g has not been defined before it is used.

The second time you run it it prints your desired 5,4,3,2,1 because it has previously seen the definition of g.

You can make this work every time if you define g before first use, like this

g[]:= Print[x];
x=5;
While[x > 0, g[]; x--];


问:
Angular HttpClient get method returns object with wrongly named attributes
I have a web controller with a GET method Products. This method returns Enumerable of type Product.

```<code>        public class Product
        {
            public float Price;
            public string Name;
            public string ImageURL;
            public int Quantity;

            public Product()
            {
                this.Quantity = 1;
            }
        }
</code>```

I have created an Angular component which reads data provided by the controller method as follows:

```<code>constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.grandTotal = 0;
    this.httpClient = http;
    this.url = baseUrl;
    http.get<Product[]>(baseUrl + 'api/SampleData/Products').subscribe(result => {
      this.products = result;
      this.slicedProducts = new Array<Product[]>();
      for (let i = 0; i < this.products.length / 3; i++) {
        this.slicedProducts[i] = this.products.slice(i * 3, i * 3 + 3);
      }

    }, error => console.error(error));
  }
</code>```

My problem is that property names in the objects at Angular side are incorrectly named, e.g.: Product.Quantity is Product.quantity, so when I try to use these properties later on in my functions, I have an error that Quantity does not exist. When I use quantity, the code works.

答: If you are using Java. Check your settings for the object conversion from Java object to Json object. Assuming you are using Spring Boot on the backend, you may need to configure your Jackson to keep the field names as is. I assume the fields are converted to Camel case by default.</p>

Body:
I have a web controller with a GET method Products. This method returns Enumerable of type Product.

        public class Product
        {
            public float Price;
            public string Name;
            public string ImageURL;
            public int Quantity;

            public Product()
            {
                this.Quantity = 1;
            }
        }

I have created an Angular component which reads data provided by the controller method as follows:

constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.grandTotal = 0;
    this.httpClient = http;
    this.url = baseUrl;
    http.get<Product[]>(baseUrl + 'api/SampleData/Products').subscribe(result => {
      this.products = result;
      this.slicedProducts = new Array<Product[]>();
      for (let i = 0; i < this.products.length / 3; i++) {
        this.slicedProducts[i] = this.products.slice(i * 3, i * 3 + 3);
      }

    }, error => console.error(error));
  }

My problem is that property names in the objects at Angular side are incorrectly named, e.g.: Product.Quantity is Product.quantity, so when I try to use these properties later on in my functions, I have an error that Quantity does not exist. When I use quantity, the code works.


问:
converting with the same quality
ffmpeg -i cam2.DAT -qscale:v cam2.avi
When run, this returns "At least one output file must be specified", what am I missing?
Probably, there is another method to convert with the same quality?

答:
As said user:5726027 there must be a number description for value
Finally ffmpeg -i cam2.DAT -qscale:v 7 cam2.avi worked

Title: converting with the same quality


问:
When is it necessary to implement Fabric high-throughput to avoid key collisions?
I am trying to implement a token in Fabric with low TPS. According to high-troughput sample I must consider key collisions and try to avoid using the same keys for accounts. Due to the difficulty of implementation, I want to know that is it necessary to implement high-throughput? For how many TPS I need to implement that?</p>

答:
If a transaction with a new value of an asset is submitted before the previous one hasn't been committed yet to the ledger, an MVCC conflict occurs.
This happens because multiple transactions are trying to update at the same asset before they are committed to the ledger.

If your solution needs to update an asset at the same time you should follow the best practice suggested in the high-throughput chaincode example by using composite keys.


问:
How to upgrade a password storage scheme (change hashing-algorithm)
I've been asked to implement some changes/updates to an intranet-site; make it 'future proof' as they call it.

We found that the passwords are hashed using the MD5 algorithm. (the system has been around since 2001 so it was adequate at time).

We would now like to upgrade the hashing-algorithm to a stronger one (BCrypt-hash or SHA-256).

We obviously do not know the plaintext-passwords and creating a new password for the userbase is not an option*).

So, my question is:

What is the accepted way to change hashing-algorithm without having access to the plaintext passwords?

The best solution would be a solution that is entirely 'behind the scenes'.

*) we tried; tried to convince them, we used the argument of 'password age', tried to bribe them with coffee, tried to bribe them with cake, etc. etc. But it is not an option.

Update

I was hoping for some sort of automagic solution for solving the problem, but apparently there are no other options than just 'wait for the user to log in, then convert'.

Well, at least now I now there is no other solution available.

答:
The best answer is from an actual cryptography expert
https://paragonie.com/blog/2016/02/how-safely-store-password-in-2016#legacy-hashes

This post also helps explain which hashing you should use. It's still current even if it says 2016. If in doubt use bcrypt.

Add a column to your user accounts table, called legacy_password (or equivalent). This is just a Boolean

Calculate the new stronger hash of the existing password hashes and store them in the database.

Modify your authentication code to handle the legacy flag.

When a user attempts to login, first check if the legacy_password flag is set. If it is, first pre-hash their password with your old password hashing algorithm, then use this prehashed value in place of their password. Afterwards (md5), recalculate the new hash and store the new hash in the database, disabling the legacy_password flag in the process.

ContentLicense: CC BY-SA 2.5


问:
Video re-streaming server (video output format)
I need to develop a video streaming server which would stream a live video to multiple users. It needs to support the following "video" sources for the re-stream server:

web-camera

surveillance camera (already supports MJPG stream)

scanner

I understand that I would need a different driver for adding support to each video input device.

I also need to support the video-display in:

web-browsers

Mozilla Firefox 3.6

Internet Explorer 8

desktop applications developed in C++ / QT 4.6

My questions:

What would be a good video output format that can be used to support the required browsers/applications?

Is there a similar Open-Source, Commercial, etc. solution which I could use to make my work easier and faster?

答:
I managed to complete the video re-streaming server and I've used the following:

MJPG format for video stream, as it is basically a standard which is natively supported in modern browsers, except in IE, but there are free ActiveX controls, allowing IE to properly display MJPG streams.

Solutions, libraries:

For the Web Camera I've used the TVideoGrabber from Datastead Software, it is a commercial solution, but it works great, and it can be used with a lot of environments (Visual Studio, Delphi, C++Builder).

For the Scanner, I used WIA 2.0 library.

Security Camera already supported MJPG, so I basically forwarded the stream from the camera as my server's output.


问:
I need a helper function to loop through complex object arrays with ngFor
I'm working on setting up a loop in angular and I'm quite new to this. Normally I'd be able to do it no problem but since I was given a weird data object to work with I'm terribly stuck. My code is as follows.

So far I can get the list from "children" at the top of the object but I cant go any further.

Here is my data

```<code>{
   "type": "categoryGroup",
   "children": [
       "Apples",
       "Bananas",
       "Oranges"
   ],
   "Apples": {
       "type": "categorySubgroup",
       "children": [
           "Golden Delicious",
           "Granny Smith",
           "Macintosh"
       ],
       "Golden Delicious": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Granny Smith": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Macintosh": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Bananas": {
       "type": "categorySubgroup",
       "children": [
           "Lady's Finger",
           "Cavendish Bananas"
       ],
       "Lady's Finger": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Cavendish Bananas": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Oranges": {
       "type": "categorySubgroup",
       "children": [
           "Blood Orange"
       ],
       "Blood Orange": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   }
}

</code>```

Here is the HTML part of my code (which is failing miserably)

{{ category }}

{{ categoryGroup }}

{{ categoryItem.name }}

```

I would like some help looping down the object arrays, maybe as a helper function using the "children" array. Any thoughts or help would be greatly appreciated. Thanks!

答:
You could get at the data using methods in the component to keep things quite clear. Here's an example object that could be used for testing:

```<code>export const data = {
  "type": "categoryGroup",
  "children": [
    "Apples",
    "Bananas",
    "Oranges"
  ],
  "Apples": {
    "type": "categorySubgroup",
    "children": [
      "Golden Delicious",
      "Granny Smith",
      "Macintosh"
    ],
    "Golden Delicious": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    },
    "Granny Smith": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    },
    "Macintosh": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    }
  },
  "Bananas": {
    "type": "categorySubgroup",
    "children": [
      "Lady's Finger",
      "Cavendish Bananas"
    ],
    "Lady's Finger": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    },
    "Cavendish Bananas": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    }
  },
  "Oranges": {
    "type": "categorySubgroup",
    "children": [
      "Blood Orange"
    ],
    "Blood Orange": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    }
  }
}
</code>```

Now, we could import this data and create some getters (in app.component.ts for example):

```<code>import { Component } from '@angular/core'
import { data } from './data'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  data = data

  getFruits() {
    return data.children
  }

  getFruit(fruit: string) {
    return data[fruit]
  }

  getVarieties(fruit) {
    return data[fruit].children
  }

  getVariety(fruit, variety) {
    return data[fruit][variety]
  }

  getArticles(fruit, variety) {
    return data[fruit][variety].articles
  }

  getArticle(fruit, variety, article) {
    return data[fruit][variety][article]
  }
}
</code>```

In the template, the properties could now be used like this:

```<code><h1>Fruit Data</h1>
<p><span class="key">type:</span> {{ data.type }}</p>
<p><span class="key">children:</span> {{ data.children }}</p>
<hr>
<div class="fruit" *ngFor="let fruit of getFruits()">
    <h2>{{ fruit }}</h2>
    <p><span class="key">type:</span> {{ getFruit(fruit).type }}</p>
    <p><span class="key">children:</span> {{ getFruit(fruit).children }}</p>
    <div class="variety" *ngFor="let variety of getVarieties(fruit)">
        <h3>{{ variety }}</h3>
        <p><span class="key">type:</span> {{ getVariety(fruit, variety).type }}</p>
        <p><span class="key">articles:</span> {{ getArticles(fruit, variety) | json }}</p>
        <div class="article" *ngFor="let article of getArticles(fruit, variety)">
            <p><span class="key">key:</span> {{ article.key }}</p>
            <p><span class="key">name:</span> {{ article.name }}</p>
        </div>
    </div>
</div>
</code>```

Body:
I'm working on setting up a loop in angular and I'm quite new to this. Normally I'd be able to do it no problem but since I was given a weird data object to work with I'm terribly stuck. My code is as follows.

So far I can get the list from "children" at the top of the object but I cant go any further.

Here is my data

{
   "type": "categoryGroup",
   "children": [
       "Apples",
       "Bananas",
       "Oranges"
   ],
   "Apples": {
       "type": "categorySubgroup",
       "children": [
           "Golden Delicious",
           "Granny Smith",
           "Macintosh"
       ],
       "Golden Delicious": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Granny Smith": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Macintosh": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Bananas": {
       "type": "categorySubgroup",
       "children": [
           "Lady's Finger",
           "Cavendish Bananas"
       ],
       "Lady's Finger": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Cavendish Bananas": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Oranges": {
       "type": "categorySubgroup",
       "children": [
           "Blood Orange"
       ],
       "Blood Orange": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   }
}

Here is the HTML part of my code (which is failing miserably)

{{ category }}

{{ categoryGroup }}

{{ categoryItem.name }}

I would like some help looping down the object arrays, maybe as a helper function using the "children" array. Any thoughts or help would be greatly appreciated. Thanks!

Body:
You could get at the data using methods in the component to keep things quite clear. Here's an example object that could be used for testing:

export const data = {
  "type": "categoryGroup",
  "children": [
    "Apples",
    "Bananas",
    "Oranges"
  ],
  "Apples": {
    "type": "categorySubgroup",
    "children": [
      "Golden Delicious",
      "Granny Smith",
      "Macintosh"
    ],
    "Golden Delicious": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    },
    "Granny Smith": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    },
    "Macintosh": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    }
  },
  "Bananas": {
    "type": "categorySubgroup",
    "children": [
      "Lady's Finger",
      "Cavendish Bananas"
    ],
    "Lady's Finger": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    },
    "Cavendish Bananas": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    }
  },
  "Oranges": {
    "type": "categorySubgroup",
    "children": [
      "Blood Orange"
    ],
    "Blood Orange": {
      "type": "articleList",
      "articles": [
        {
          "key": "article-1",
          "name": "Article 1"
        },
        {
          "key": "article-2",
          "name": "Article 2"
        }
      ]
    }
  }
}

Now, we could import this data and create some getters (in app.component.ts for example):

import { Component } from '@angular/core'
import { data } from './data'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  data = data

  getFruits() {
    return data.children
  }

  getFruit(fruit: string) {
    return data[fruit]
  }

  getVarieties(fruit) {
    return data[fruit].children
  }

  getVariety(fruit, variety) {
    return data[fruit][variety]
  }

  getArticles(fruit, variety) {
    return data[fruit][variety].articles
  }

  getArticle(fruit, variety, article) {
    return data[fruit][variety][article]
  }
}

In the template, the properties could now be used like this:

<h1>Fruit Data</h1>
<p><span class="key">type:</span> {{ data.type }}</p>
<p><span class="key">children:</span> {{ data.children }}</p>
<hr>
<div class="fruit" *ngFor="let fruit of getFruits()">
    <h2>{{ fruit }}</h2>
    <p><span class="key">type:</span> {{ getFruit(fruit).type }}</p>
    <p><span class="key">children:</span> {{ getFruit(fruit).children }}</p>
    <div class="variety" *ngFor="let variety of getVarieties(fruit)">
        <h3>{{ variety }}</h3>
        <p><span class="key">type:</span> {{ getVariety(fruit, variety).type }}</p>
        <p><span class="key">articles:</span> {{ getArticles(fruit, variety) | json }}</p>
        <div class="article" *ngFor="let article of getArticles(fruit, variety)">
            <p><span class="key">key:</span> {{ article.key }}</p>
            <p><span class="key">name:</span> {{ article.name }}</p>
        </div>
    </div>
</div>


问:
Cant overwrite the custom stylesheet
I am trying to overwrite the CSS of react range slider.It uses the custom style sheet of which i need to add in the head section.My project is built on next.js

```<code> <link rel="stylesheet" href="https://unpkg.com/react-rangeslider/umd/rangeslider.min.css" />
</code>```

Otherwise, the slider doesn't show anything if i don't add the link in head even though I installed the library. It's not even overwriting the CSS. I want  to change the background color.This is my code:

```<code>import React, { Component } from 'react'
import 'react-rangeslider/lib/index.css';
import './slider.css';
import Slider from 'react-rangeslider'
class Horizontal extends Component {
    constructor (props, context) {
        super(props, context)
        this.state = {
            value: 850
        }
    }
    handleChangeStart = () => {
        console.log('Change event started')
    };
    handleChange = value => {
        this.setState({
            value: value
        })
    };

    handleChangeComplete = () => {
        console.log('Change event completed')
    };
    render () {
        const { value } = this.state
        return (
            <div>
                <div className='slider'  style={{ marginTop:'165px',marginLeft:'319px',width:'700px',backgroundColor:'EF5350'}} >

                    <div style={{ textAlign:'center',color:'gray',fontSize:'35px',marginBottom:'82px'}}>
                        <p> What is the size of your property?</p>
                    </div>
                    <Slider
                        min={850}
                        max={5000}
                        value={value}
                        onChangeStart={this.handleChangeStart}
                        onChange={this.handleChange}
                        onChangeComplete={this.handleChangeComplete}
                    />
                    <div className='value'>{value}</div>

                </div>
            </div>
        )
    }
}
export default Horizontal
</code>```

I tried to change the background color in slider.css.

```<code>.rangeslider-horizontal .rangeslider__fill {
    background-color: red;
}
</code>```

The library needs to be installed first:

```<code>npm install react-rangeslider --save
</code>```

答:
It doesn't work as the slider stylesheet overwrite yours. Include the style like

```<code>// To include the default styles
import 'react-rangeslider/lib/index.css'
// import your css
import './style.css';
</code>```

Demo

Title: Cant overwrite the custom stylesheet

Body:
I am trying to overwrite the CSS of react range slider.It uses the custom style sheet of which i need to add in the head section.My project is built on next.js

 <link rel="stylesheet" href="https://unpkg.com/react-rangeslider/umd/rangeslider.min.css" />

Otherwise, the slider doesn't show anything if i don't add the link in head even though I installed the library. It's not even overwriting the CSS. I want  to change the background color.This is my code:

import React, { Component } from 'react'
import 'react-rangeslider/lib/index.css';
import './slider.css';
import Slider from 'react-rangeslider'
class Horizontal extends Component {
    constructor (props, context) {
        super(props, context)
        this.state = {
            value: 850
        }
    }
    handleChangeStart = () => {
        console.log('Change event started')
    };
    handleChange = value => {
        this.setState({
            value: value
        })
    };

    handleChangeComplete = () => {
        console.log('Change event completed')
    };
    render () {
        const { value } = this.state
        return (

 What is the size of your property?

                    <Slider
                        min={850}
                        max={5000}
                        value={value}
                        onChangeStart={this.handleChangeStart}
                        onChange={this.handleChange}
                        onChangeComplete={this.handleChangeComplete}
                    />

{value}

        )
    }
}
export default Horizontal

I tried to change the background color in slider.css.

.rangeslider-horizontal .rangeslider__fill {
    background-color: red;
}

The library needs to be installed first:

npm install react-rangeslider --save

Body:
It doesn't work as the slider stylesheet overwrite yours. Include the style like

// To include the default styles
import 'react-rangeslider/lib/index.css'
// import your css
import './style.css';

Demo


问:
ImportError: No module named 'Queue'
I am trying to import requests module, but I got this error
my python version is 3.4 running on ubuntu 14.04

```<code>>>> import requests
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 10, in <module>
    from queue import LifoQueue, Empty, Full
ImportError: cannot import name 'LifoQueue'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/requests/__init__.py", line 58, in <module>
   from . import utils
  File "/usr/local/lib/python3.4/dist-packages/requests/utils.py", line 26, in <module>
    from .compat import parse_http_list as _parse_list_header
  File "/usr/local/lib/python3.4/dist-packages/requests/compat.py", line 7, in <module>
    from .packages import chardet
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/__init__.py", line 3, in <module>
    from . import urllib3
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/__init__.py", line 10, in <module>
    from .connectionpool import (
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 12, in <module>
    from Queue import LifoQueue, Empty, Full
ImportError: No module named 'Queue'
</code>```

答:
It's because of the Python version. In Python 2.x it's import Queue as queue; on the contrary in Python 3 it's import queue. If you want it for both environments you may use something below as mentioned here

```<code>try:
   import queue
except ImportError:
   import Queue as queue
</code>```

Title: ImportError: No module named 'Queue'

Body:
I am trying to import requests module, but I got this error
my python version is 3.4 running on ubuntu 14.04

>>> import requests
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 10, in <module>
    from queue import LifoQueue, Empty, Full
ImportError: cannot import name 'LifoQueue'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/requests/__init__.py", line 58, in <module>
   from . import utils
  File "/usr/local/lib/python3.4/dist-packages/requests/utils.py", line 26, in <module>
    from .compat import parse_http_list as _parse_list_header
  File "/usr/local/lib/python3.4/dist-packages/requests/compat.py", line 7, in <module>
    from .packages import chardet
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/__init__.py", line 3, in <module>
    from . import urllib3
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/__init__.py", line 10, in <module>
    from .connectionpool import (
  File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 12, in <module>
    from Queue import LifoQueue, Empty, Full
ImportError: No module named 'Queue'

Body:
It's because of the Python version. In Python 2.x it's import Queue as queue; on the contrary in Python 3 it's import queue. If you want it for both environments you may use something below as mentioned here

try:
   import queue
except ImportError:
   import Queue as queue


问:
Adding a loader/spinner to yii2 interface
I have a view in which I have two buttons. While clicking on any of the two buttons, a certain request is made.

View

```<code><?php Pjax::begin(); ?>
        <?=Html::beginForm(['process'],'post');?>
        <?=Html::submitButton('Disconnect', ['id'=>'d','name'=>'dco','class' => 'btn btn-primary']);?>
        <?=Html::submitButton('Connect', ['id'=>'r','name'=>'rco','class' => 'btn btn-info']);?>
        <br><br>
        <div class="pre-scrollable">
        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [

        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],

        'customer_id',
       // 'dept_code:ntext',
        'dept_name:ntext',
        'sub_div_name',
        [
            'label' => 'Sub Division Name',
            'value' => function ($d) {
                return $d->subdiv->name;
            },
            'filter' => Html::activeDropDownList($searchModel, 'sub_div_code', \common\models\SurveyHescoSubdivision::toArrayList(), ['prompt' => "Sub-Div", 'class' => 'form-control']),

        ],
        'division_name',
        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'active_energy_total_m',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
        </div>
        <?= Html::endForm();?>
        <?php Pjax::end(); ?>
</code>```

Controller

```<code> public function actionProcess()
{

 $soapUrl = "http://ip:port/HES/services/Request";
    $userName = "user";
    $password = "123456";

 if (isset($_POST['dco']))
    {
        if(Yii::$app->request->isPost)
        {
            $data = Yii::$app->request->post('selection'); //checkbox (array)

            foreach($data as $value)
            {

                $msn = $value;

                $xml_post_string = /** @lang text */
                    '//soap request';

                $headers = array(
                    "Content-type: text/xml;charset=\"utf-8\"",
                    "Accept: text/xml",
                    "Cache-Control: no-cache",
                    "Pragma: no-cache",
                    "Content-length: ".strlen($xml_post_string),
                ); //SOAPAction: your op URL

                $url = $soapUrl;

                // PHP cURL  for https connection

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                // converting
                $response = curl_exec($ch);
                curl_close($ch);
                $domd=new DOMDocument();

                var_dump($response);
                if(!$domd->loadXML($response)){
                    throw new \RuntimeException("failed to parse XML!");
                }
                $inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;
                if(!($domd2=@DOMDocument::loadXML($inner_xml))){
                    throw new \RuntimeException("failed to parse inner_xml!");
                }
                $AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;

                if ($AsyncReplyFlag =='true')
                {
                    $ds = 1;

                    $disconnected_at = date('Y-m-d H:i:s');

                    try {
                        Yii::$app->db->createCommand(/** @lang text */
                            "update
  `accurate_mam`.`daily_log`
set
  `disconnected` = '$ds',
  `diconnected_at` = '$disconnected_at',
  `reconnected_at` = NULL
where `msn` = '$msn' ;

")->execute(); //update master table

                        Yii::$app->db->createCommand(/** @lang text */
                            "update
                        `accurate_mam`.`log_disconnected`
                         set

                        `disconnected_at` = '$disconnected_at'
                         where `msn` = '$msn'")->execute();// update log disconnected table
                    } catch (Exception $e) {
                    } // updating the master table
                }

            }

        }
    }
    }
</code>```

What I want to do?

On button click, I want to show a spinner/loader that will start when the request is made and stop when the request is completed.

Note

I don't want to add a default time for spinner/loader. It should starts when the request is sent and stop when it's completed i.e. when the process is completed

I have searched many articles but can't find the complete implementation details.

Update 1

I have found a solution here and tried to implement it by doing the following

```<code><style>
#loader {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    background: rgba(0, 0, 0, 0.05) url("<?php \yii\helpers\Url::to('@web/images/25.png', true);  ?>") no-repeat center center;
    z-index: 10000;
}
</style>
</code>```

JS

```<code>$(document).ready(function () {

      $('form').submit(function(e) {
       e.preventDefault();

        spinner.show();
        $.ajax({
            url:'$url',
            data: $(this).serialize()
            type: 'POST',
            dataType: 'JSON'
        }).done(function(resp) {
            spinner.hide();
          //alert(resp.status);
        });

  });

});
</code>```

Problem Facing

Now I am able to see a spinner but the process is not completed. After further debugging, I observed that I am getting bool(false) in var_dump(isset($_POST['dco']));
        die(); while submitting the request

Update 2

I have found one more solution and tried to do the same

Updating both buttons

```<code><?= Html::submitButton(Yii::t('app', '<i class="fa fa-times"></i> Disconnect'), ['class' => 'btn red', 'name' => 'dco', 'value' => '0']) ?>
<?= Html::submitButton(Yii::t('app', '<i class="fa fa-check"></i> Connect'), ['class' => 'btn blue', 'name' => 'rco', 'value' => '1']) ?>
</code>```

JS

```<code> $('form').submit(function(e) {
       e.preventDefault();
        var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
       strValue = this.value;

});

        spinner.show();
        $.ajax({
            url:'$url',
            data: {data :strValue},
            type: 'POST',
            dataType: 'JSON'
        }).done(function(resp) {
            spinner.hide();
          //alert(resp.status);
        });

  });
</code>```

Controller

```<code>if (Yii::$app->request->post()) {

   if (Yii::$app->request->post('dco') == 0) {
    //Code for value 0
 }

   if (Yii::$app->request->post('rco') == 1) {
    //Code for value 1
  }

 }
</code>```

Problem Facing

When I click any of the two buttons it always hit the dco check i.e. if (Yii::$app->request->post('dco') == 0) it's not hitting the rco condition

There must be something that I am missing.

Any help would be highly appreciated.

答:
```<code><?php
$this->registerJs(<<<JS
$(document).on('pjax:send', function() {
   $('#loading').show();
});
$(document).on('pjax:complete', function() {
  $('#loading').hide();
});
JS
);
?>
</code>```

example: with fontawesome( or can use image ....)

```<code><i id='loading' class='fa fa-spinner fa-pulse' style='display:none;'></i>
</code>```

You can also do this by a variable (in the controller).

Body:
I have a view in which I have two buttons. While clicking on any of the two buttons, a certain request is made.

View

<?php Pjax::begin(); ?>
        <?=Html::beginForm(['process'],'post');?>
        <?=Html::submitButton('Disconnect', ['id'=>'d','name'=>'dco','class' => 'btn btn-primary']);?>
        <?=Html::submitButton('Connect', ['id'=>'r','name'=>'rco','class' => 'btn btn-info']);?>

        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [

        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],

        'customer_id',
       // 'dept_code:ntext',
        'dept_name:ntext',
        'sub_div_name',
        [
            'label' => 'Sub Division Name',
            'value' => function ($d) {
                return $d->subdiv->name;
            },
            'filter' => Html::activeDropDownList($searchModel, 'sub_div_code', \common\models\SurveyHescoSubdivision::toArrayList(), ['prompt' => "Sub-Div", 'class' => 'form-control']),

        ],
        'division_name',
        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '' : '';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'active_energy_total_m',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

        <?= Html::endForm();?>
        <?php Pjax::end(); ?>

Controller

 public function actionProcess()
{

 $soapUrl = "http://ip:port/HES/services/Request";
    $userName = "user";
    $password = "123456";

 if (isset($_POST['dco']))
    {
        if(Yii::$app->request->isPost)
        {
            $data = Yii::$app->request->post('selection'); //checkbox (array)

            foreach($data as $value)
            {

                $msn = $value;

                $xml_post_string = /** @lang text */
                    '//soap request';

                $headers = array(
                    "Content-type: text/xml;charset=\"utf-8\"",
                    "Accept: text/xml",
                    "Cache-Control: no-cache",
                    "Pragma: no-cache",
                    "Content-length: ".strlen($xml_post_string),
                ); //SOAPAction: your op URL

                $url = $soapUrl;

                // PHP cURL  for https connection

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                // converting
                $response = curl_exec($ch);
                curl_close($ch);
                $domd=new DOMDocument();

                var_dump($response);
                if(!$domd->loadXML($response)){
                    throw new \RuntimeException("failed to parse XML!");
                }
                $inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;
                if(!($domd2=@DOMDocument::loadXML($inner_xml))){
                    throw new \RuntimeException("failed to parse inner_xml!");
                }
                $AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;

                if ($AsyncReplyFlag =='true')
                {
                    $ds = 1;

                    $disconnected_at = date('Y-m-d H:i:s');

                    try {
                        Yii::$app->db->createCommand(/** @lang text */
                            "update
  `accurate_mam`.`daily_log`
set
  `disconnected` = '$ds',
  `diconnected_at` = '$disconnected_at',
  `reconnected_at` = NULL
where `msn` = '$msn' ;

")->execute(); //update master table

                        Yii::$app->db->createCommand(/** @lang text */
                            "update
                        `accurate_mam`.`log_disconnected`
                         set

                        `disconnected_at` = '$disconnected_at'
                         where `msn` = '$msn'")->execute();// update log disconnected table
                    } catch (Exception $e) {
                    } // updating the master table
                }

            }

        }
    }
    }

What I want to do?

On button click, I want to show a spinner/loader that will start when the request is made and stop when the request is completed.

Note

I don't want to add a default time for spinner/loader. It should starts when the request is sent and stop when it's completed i.e. when the process is completed

I have searched many articles but can't find the complete implementation details.

Update 1

I have found a solution here and tried to implement it by doing the following

JS

$(document).ready(function () {

      $('form').submit(function(e) {
       e.preventDefault();

        spinner.show();
        $.ajax({
            url:'$url',
            data: $(this).serialize()
            type: 'POST',
            dataType: 'JSON'
        }).done(function(resp) {
            spinner.hide();
          //alert(resp.status);
        });

  });

});

Problem Facing

Now I am able to see a spinner but the process is not completed. After further debugging, I observed that I am getting bool(false) in var_dump(isset($_POST['dco']));
        die(); while submitting the request

Update 2

I have found one more solution and tried to do the same

Updating both buttons

<?= Html::submitButton(Yii::t('app', ' Disconnect'), ['class' => 'btn red', 'name' => 'dco', 'value' => '0']) ?>
<?= Html::submitButton(Yii::t('app', ' Connect'), ['class' => 'btn blue', 'name' => 'rco', 'value' => '1']) ?>

JS

 $('form').submit(function(e) {
       e.preventDefault();
        var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
       strValue = this.value;

});

        spinner.show();
        $.ajax({
            url:'$url',
            data: {data :strValue},
            type: 'POST',
            dataType: 'JSON'
        }).done(function(resp) {
            spinner.hide();
          //alert(resp.status);
        });

  });

Controller

if (Yii::$app->request->post()) {

   if (Yii::$app->request->post('dco') == 0) {
    //Code for value 0
 }

   if (Yii::$app->request->post('rco') == 1) {
    //Code for value 1
  }

 }

Problem Facing

When I click any of the two buttons it always hit the dco check i.e. if (Yii::$app->request->post('dco') == 0) it's not hitting the rco condition

There must be something that I am missing.

Any help would be highly appreciated.

Body:
<?php
$this->registerJs(<<<JS
$(document).on('pjax:send', function() {
   $('#loading').show();
});
$(document).on('pjax:complete', function() {
  $('#loading').hide();
});
JS
);
?>

example: with fontawesome( or can use image ....)

<i id='loading' class='fa fa-spinner fa-pulse' style='display:none;'></i>

You can also do this by a variable (in the controller).


问:
Passing javascript loop value to Laravel Controller
I want to get values from multiple select and pass them to Laravel controller.

Getting all values from multiple select:

```<code><script>
    function redirect() {
        $("#sbtwo > option").each(function() {
            if(document.getElementById("report1").checked == true)
                window.open (+this.value+"/report1", 'w1');
        });
    }
</script>
</code>```

I want to get +this.value+ and pass it to Laravel controller.

```<code><form action="/teachers/printreports" method="POST">
    {{ csrf_field() }}
    <input type="checkbox" name="report1[]"  id="report1"> Basic Data</div>
    <input type="submit" class="btn btn-primary " value="Print" >
</form>
</code>```

How to store javascript +this.value+ in to form element name= report1[]?

答:
Use multi-select with checkbox

In blade file:

```<code><link rel="stylesheet" href="https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js"></script>

<form action="/teachers/printreports" method="POST">
    @csrf

    <select name="reports[]" id="select" multiple="multiple">
        <option value="1">Report-1</option>
        <option value="2">Report-2</option>
        <option value="3">Report-3</option>
        <option value="4">Report-4</option>
        <option value="5">Report-5</option>
        <option value="6">Report-6</option>
        <option value="7">Report-7</option>
        <option value="8">Report-8</option>
    </select>

    <input type="submit" class="btn btn-primary " value="Print" >
</form>

<script>
    $(document).ready(function(){
        $(function () {
            $('.select').multipleSelect({
                width: 500
            })
        })
    });
</script>
</code>```

In Controller:

```<code>public function yourFunction(Request $request){
    $post = $request->all();

    // dump your selected reports
    dd($post);
}
</code>```

Result:

```<code>array:3 [▼
  "_token" => "WXs56rP5fWWw3D4B1H8I1wibT23Dko2AfFPmFRiZ"
  "reports" => array:5 [▼
    0 => "1"
    1 => "2"
    2 => "4"
    3 => "6"
    4 => "7"
  ]
]
</code>```

Body:
I want to get values from multiple select and pass them to Laravel controller.

Getting all values from multiple select:

I want to get +this.value+ and pass it to Laravel controller.

<form action="/teachers/printreports" method="POST">
    {{ csrf_field() }}
    <input type="checkbox" name="report1[]"  id="report1"> Basic Data

    <input type="submit" class="btn btn-primary " value="Print" >
</form>

How to store javascript +this.value+ in to form element name= report1[]?

Body:
Use multi-select with checkbox

In blade file:

<link rel="stylesheet" href="https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js"></script>

<form action="/teachers/printreports" method="POST">
    @csrf

    <select name="reports[]" id="select" multiple="multiple">
        <option value="1">Report-1</option>
        <option value="2">Report-2</option>
        <option value="3">Report-3</option>
        <option value="4">Report-4</option>
        <option value="5">Report-5</option>
        <option value="6">Report-6</option>
        <option value="7">Report-7</option>
        <option value="8">Report-8</option>
    </select>

    <input type="submit" class="btn btn-primary " value="Print" >
</form>

<script>
    $(document).ready(function(){
        $(function () {
            $('.select').multipleSelect({
                width: 500
            })
        })
    });
</script>

In Controller:

public function yourFunction(Request $request){
    $post = $request->all();

    // dump your selected reports
    dd($post);
}

Result:

array:3 [▼
  "_token" => "WXs56rP5fWWw3D4B1H8I1wibT23Dko2AfFPmFRiZ"
  "reports" => array:5 [▼
    0 => "1"
    1 => "2"
    2 => "4"
    3 => "6"
    4 => "7"
  ]
]


问:
Catch2 - output to console and file
I can run a Catch executable with -o junit --output catch_results.xml to generate an xml report.

Is there some way to both generate an xml report, and also have the console output?

答:
Assuming you are asking for having a JUnit output in a file and the standard console reporter at stdout, there is no way to do that.

Catch2 used to support multiple reporters, but there was no support for having them write their output to separate files/outputs, which meant that the feature was unusable and was removed until some point in the future.

Title: Catch2 - output to console and file


问:
how to merge two array into one php
I have two array , one is codeigniter query result array and other is created inside foreach. My code is,

```<code>$items = array();
$seats_available = 0;
$available_seats = array();

$query = 'SELECT * FROM tbl_buses';
$result = $this->db->query($query);

foreach ($result->result() as $results) {
    $query1 = 'SELECT * FROM tbl_booking WHERE buses_id = '.$results->buses_id.' AND booking_date = "'.$results->buses_date.'" AND booking_status = 1';
    $result1 = $this->db->query($query1);
    $total = $result1->num_rows();
    $seats_available = $results->buses_tot_seat - $total;
    $available_seats[] = array('available_seats' => $seats_available);

    $items[] = $results;
}

return array_merge($items, $available_seats);
</code>```

now the result for the above code is,

[{"buses_id":"1","buses_title":"Sugama Tourist Route No - 31","buses_dept":"20:20","buses_type":"Non A\/C Seater\/Sleeper (2+1)","buses_arr":"05:56","buses_fare":"760","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-25","buses_tot_seat":"30"},{"buses_id":"2","buses_title":"test buses","buses_dept":"18:20","buses_type":"test type","buses_arr":"05:56","buses_fare":"1000","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-26","buses_tot_seat":"100"},{"available_seats":30},{"available_seats":100}]

But I want the result as

[{"buses_id":"1","buses_title":"Sugama Tourist Route No - 31","buses_dept":"20:20","buses_type":"Non A\/C Seater\/Sleeper (2+1)","buses_arr":"05:56","buses_fare":"760","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-25","buses_tot_seat":"30","available_seats":30},{"buses_id":"2","buses_title":"test buses","buses_dept":"18:20","buses_type":"test type","buses_arr":"05:56","buses_fare":"1000","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-26","buses_tot_seat":"100","available_seats":100}]

How to acheive the above result. Please help.

答:
I think a join query would be more efficient in your circumstance.</p>

```<code>$query = "SELECT buses.*, booking.buses_tot_seat as available_seats FROM tbl_buses as buses LEFT JOIN tbl_booking as booking ON booking.buses_id = buses.buses_id AND booking.booking_status = 1";

$q = $this->db->query($query);

if ($q && $q->num_rows() > 0) {
    $res = $q->result();
    echo '```';
    print_r($res);
} else {
    echo 'query failed or returned no rows!'; exit;
}
</code>```

Title: how to merge two array into one php

Body:
I have two array , one is codeigniter query result array and other is created inside foreach. My code is,

$items = array();
$seats_available = 0;
$available_seats = array();

$query = 'SELECT * FROM tbl_buses';
$result = $this->db->query($query);

foreach ($result->result() as $results) {
    $query1 = 'SELECT * FROM tbl_booking WHERE buses_id = '.$results->buses_id.' AND booking_date = "'.$results->buses_date.'" AND booking_status = 1';
    $result1 = $this->db->query($query1);
    $total = $result1->num_rows();
    $seats_available = $results->buses_tot_seat - $total;
    $available_seats[] = array('available_seats' => $seats_available);

    $items[] = $results;
}

return array_merge($items, $available_seats);

now the result for the above code is,

[{"buses_id":"1","buses_title":"Sugama Tourist Route No - 31","buses_dept":"20:20","buses_type":"Non A\/C Seater\/Sleeper (2+1)","buses_arr":"05:56","buses_fare":"760","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-25","buses_tot_seat":"30"},{"buses_id":"2","buses_title":"test buses","buses_dept":"18:20","buses_type":"test type","buses_arr":"05:56","buses_fare":"1000","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-26","buses_tot_seat":"100"},{"available_seats":30},{"available_seats":100}]

But I want the result as

[{"buses_id":"1","buses_title":"Sugama Tourist Route No - 31","buses_dept":"20:20","buses_type":"Non A\/C Seater\/Sleeper (2+1)","buses_arr":"05:56","buses_fare":"760","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-25","buses_tot_seat":"30","available_seats":30},{"buses_id":"2","buses_title":"test buses","buses_dept":"18:20","buses_type":"test type","buses_arr":"05:56","buses_fare":"1000","from_place":"Ernakulam","to_place":"Mangalore","buses_date":"2019-04-26","buses_tot_seat":"100","available_seats":100}]

How to acheive the above result. Please help.

Body:
I think a join query would be more efficient in your circumstance.

$query = "SELECT buses.*, booking.buses_tot_seat as available_seats FROM tbl_buses as buses LEFT JOIN tbl_booking as booking ON booking.buses_id = buses.buses_id AND booking.booking_status = 1";

$q = $this->db->query($query);

if ($q && $q->num_rows() > 0) {
    $res = $q->result();
    echo '<pre>';
    print_r($res);
} else {
    echo 'query failed or returned no rows!'; exit;
}


问:
i have created a custom class which can get date and time as strings i want to access the object and set data to the class any suggestions
i have created a custom class which can get date and time as strings i want to access the object and set data to the class any suggestions
here is my code

```<code>public class DateTime {
private String Date;
private String Time;

public DateTime(String Date,String Time) {
    this.Date=Date;
    this.Time=Time;

}

public void showDateAndTime() {

    System.out.println("entery Date is :");
    System.out.println(Date);
    System.out.println("entery time is :");
    System.out.println(Time);

}
}

public class Vehicle {

        public int ID;
        public String Brand;
            public String type;
        public DateTime entryTimeDate;

}

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        Vehicle v1=new Vehicle();
        v1.entryTimeDate**********
}
</code>```

i want to set date time value to v1 object any suggestions?

答:
Instead of having public fields in Vehicle class, make them private and then  use accessor and mutator methods in order to gain access to them. Then vehicle.getEntryTimeDate() will be enough to give you the DateTime object of the vehicle. With other words:

```<code>public class Vehicle {
    private int id;
    public String brand;
    public String type;
    public DateTime entryTimeDate;

    public Vehicle()
    {
        setId(0);
        setBrand("");
        setType("");
        setEntryTimeDate(new DateTime("DATE", "TIME"));
    }

    public Vehicle(int id, String brand, String type, DateTime entryTimeDate) {
        this.id = id;
        this.brand = brand;
        this.type = type;
        this.entryTimeDate = entryTimeDate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public DateTime getEntryTimeDate() {
        return entryTimeDate;
    }

    public void setEntryTimeDate(DateTime entryTimeDate) {
        this.entryTimeDate = entryTimeDate;
    }

    public static class DateTime{
        private String date;
        private String time;

        public DateTime(String date,String time) {
            this.setDate(date);
            this.setTime(time);

        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }
    }

    public static void main(String[] args) {
        Vehicle v1 = new Vehicle();
        v1.getEntryTimeDate().setTime("Time of the vehicle");
        v1.getEntryTimeDate().setDate("Date of the vehicle.");
    }
}
</code>```

Some notes: Ignore the static keyword in DateTime class. I did it in order to create an SSCCE. Also notice the field naming convention i followed (camel-case). It is the most used naming convention by Java programmers.

Body:
i have created a custom class which can get date and time as strings i want to access the object and set data to the class any suggestions
here is my code

public class DateTime {
private String Date;
private String Time;

public DateTime(String Date,String Time) {
    this.Date=Date;
    this.Time=Time;

}

public void showDateAndTime() {

    System.out.println("entery Date is :");
    System.out.println(Date);
    System.out.println("entery time is :");
    System.out.println(Time);

}
}

public class Vehicle {

        public int ID;
        public String Brand;
            public String type;
        public DateTime entryTimeDate;

}

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        Vehicle v1=new Vehicle();
        v1.entryTimeDate**********
}

i want to set date time value to v1 object any suggestions?

Body:
Instead of having public fields in Vehicle class, make them private and then  use accessor and mutator methods in order to gain access to them. Then vehicle.getEntryTimeDate() will be enough to give you the DateTime object of the vehicle. With other words:

public class Vehicle {
    private int id;
    public String brand;
    public String type;
    public DateTime entryTimeDate;

    public Vehicle()
    {
        setId(0);
        setBrand("");
        setType("");
        setEntryTimeDate(new DateTime("DATE", "TIME"));
    }

    public Vehicle(int id, String brand, String type, DateTime entryTimeDate) {
        this.id = id;
        this.brand = brand;
        this.type = type;
        this.entryTimeDate = entryTimeDate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public DateTime getEntryTimeDate() {
        return entryTimeDate;
    }

    public void setEntryTimeDate(DateTime entryTimeDate) {
        this.entryTimeDate = entryTimeDate;
    }

    public static class DateTime{
        private String date;
        private String time;

        public DateTime(String date,String time) {
            this.setDate(date);
            this.setTime(time);

        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }
    }

    public static void main(String[] args) {
        Vehicle v1 = new Vehicle();
        v1.getEntryTimeDate().setTime("Time of the vehicle");
        v1.getEntryTimeDate().setDate("Date of the vehicle.");
    }
}

Some notes: Ignore the static keyword in DateTime class. I did it in order to create an SSCCE. Also notice the field naming convention i followed (camel-case). It is the most used naming convention by Java programmers.