问:
How to disable angle bracket highlighting in Visual Studio Code?
I just want to disable the character highlighting that happens on angle brackets, as I find the square box to be annoying. Is there a way to turn it off?

答:
Unfortunately it's still unconfigurable. Maybe they will improved it.

Here is my ticket in VSCode repo that you can watch - https://github.com/microsoft/vscode/issues/73521.

As long as they do not improve, you have two ways

Solution with addon:

Disable native bracket matching: "editor.matchBrackets": false,

Install addon from https://marketplace.visualstudio.com/items?itemName=rafamel.subtle-brackets

Customize it for better visuality, example:

```<code>    "subtleBrackets.style": {
        "borderStyle": "solid",
        "borderColor": "#CC7832",
        "borderRadius": "3px",
    }
</code>```

Native solution without addon:

You can disable bracket matching highlight only for specific language:

```<code>"[html]": {
   "editor.matchBrackets": false
}
</code>```

Note that this is not a perfect solution, because when using html in php files, angle brackets are still highlighted

Body:
Unfortunately it's still unconfigurable. Maybe they will improved it.

Here is my ticket in VSCode repo that you can watch - https://github.com/microsoft/vscode/issues/73521.

As long as they do not improve, you have two ways

Solution with addon:

Disable native bracket matching: "editor.matchBrackets": false,

Install addon from https://marketplace.visualstudio.com/items?itemName=rafamel.subtle-brackets

Customize it for better visuality, example:

    "subtleBrackets.style": {
        "borderStyle": "solid",
        "borderColor": "#CC7832",
        "borderRadius": "3px",
    }

Native solution without addon:

You can disable bracket matching highlight only for specific language:

"[html]": {
   "editor.matchBrackets": false
}

Note that this is not a perfect solution, because when using html in php files, angle brackets are still highlighted


来源: stackexchange

问:
Call External JavaScript Function
I have an ActionScript program that I want to access some external JavaScript functions. By external, I mean that the ActionScript/swf aren't going to be loaded via the HTML/JavaScript. Everything I see recommends ExternalInterface, but that seems to imply that your JS loads your swf. Is there a way to call a JavaScript function by URL?

答: So your page will contain some JavaScript to execute, but your Flash app will not be running in a browser?  Can't you just use navigateToURL to open an HTML page containing JavaScript that executes on page load?

ContentLicense: CC BY-SA 3.0

Title: Call External JavaScript Function


问:
Routing to Angular components when app is static content hosted in S3
I am currently developing an application with an Angular4 frontend. My goal for production is to have the frontend be served as static content from an AWS S3 bucket.

Everything is working with one exception which is actually a major problem for the application. When users register, they are sent an email with a link to verify their email addresses. The format of the link is as follows:

https://myhostname.com/user/userguid?token=tokenvalue

As the frontend is served as static content, only the page index.html actually exists, so clicking this link generates a 404.

Now, after some research, I have taken the following steps. In S3, I have the following routing rule.

```<code><RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>myhostname.com</HostName>
      <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>
</code>```

I also have a CloudFront rule that redirects all 404 errors to index.html.

Now, when someone navigates to myhostname.com/user/userguid?token=tokenvalue, the URL is re-written to myhostname.com/#!/user/userguid?token=tokenvalue, but then the user is redirected to myhostname.com/home (aka index.html).

What change(s) can I make to my Angular app to take the value of the hash/fragment and actually route to that component (rather that just redirecting, which will send the user back to index.html)?

Note that in development when the frontend is being served via 'npm start', this works just fine. Thanks all.

答: All i had to do was set the error document to index.html in my static website hosting block in the console

Body:
I am currently developing an application with an Angular4 frontend. My goal for production is to have the frontend be served as static content from an AWS S3 bucket.

Everything is working with one exception which is actually a major problem for the application. When users register, they are sent an email with a link to verify their email addresses. The format of the link is as follows:

https://myhostname.com/user/userguid?token=tokenvalue

As the frontend is served as static content, only the page index.html actually exists, so clicking this link generates a 404.

Now, after some research, I have taken the following steps. In S3, I have the following routing rule.

<RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>myhostname.com</HostName>
      <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>

I also have a CloudFront rule that redirects all 404 errors to index.html.

Now, when someone navigates to myhostname.com/user/userguid?token=tokenvalue, the URL is re-written to myhostname.com/#!/user/userguid?token=tokenvalue, but then the user is redirected to myhostname.com/home (aka index.html).

What change(s) can I make to my Angular app to take the value of the hash/fragment and actually route to that component (rather that just redirecting, which will send the user back to index.html)?

Note that in development when the frontend is being served via 'npm start', this works just fine. Thanks all.

ContentLicense: CC BY-SA 4.0


问:
Why isn't the code working (here) when I try to change values of a list using 'for' loop?
Let's say there's this random list:

```<code>st=['smthg','xyz','random','000','666']
</code>```

I want to change the values of the indices 1 to 3 using this for loop:

```<code>for anythg in st:
      st[1:3]='whtevr'
</code>```

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

```<code>'t','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',
</code>```

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

```<code>for i in range(1,4):
    st[i]='whtevr'
</code>```

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

Body:
Let's say there's this random list:

st=['smthg','xyz','random','000','666']

I want to change the values of the indices 1 to 3 using this for loop:

for anythg in st:
      st[1:3]='whtevr'

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

't','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

for i in range(1,4):
    st[i]='whtevr'

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

Body:
The list just keeps on increasing.

>>> st=['smthg','xyz','random','000','666']
>>> st[1:3]='whtevr'
>>> st
['smthg', 'w', 'h', 't', 'e', 'v', 'r', '000', '666']
>>> st[1:3]='whtevr'
>>> st
['smthg', 'w', 'h', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', '000', '666']
>>> st[1:3]='whtevr'
>>> st
['smthg', 'w', 'h', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', '000', '666']
>>> st[1:3]='whtevr'
>>> st
['smthg', 'w', 'h', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', '000', '666']
>>> st[1:3]='whtevr'
>>> st
['smthg', 'w', 'h', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', 't', 'e', 'v', 'r', '000', '666']

The list started with

>>> ['smthg','xyz','random','000','666'][1:3]
['xyz', 'random']

but continues growing forever , and the loop never ends for a growing list.


问:
i want to delete item from listview without restarting actitvity
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

```<code>@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}
</code>```

答:
Please create Custom Array list :-

```<code>List<Integer> al = new ArrayList<>();
    al.add("item 1");
    al.add("item 2");
    al.add("item 3");
    al.add("item 4");
    al.add("item 5");
</code>```

set adapter:-

```<code>StableArrayAdapter adapter = new StableArrayAdapter(this,
            android.R.layout.simple_list_item_1, a1);
    listview.setAdapter(adapter);
</code>```

Remove item from position

```<code>al.remove(position);
</code>```

Now Refresh listview adapter:-

```<code>adapter.notifyDataSetChanged();
</code>```

Body:
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}

Body:
Please create Custom Array list :-

List<Integer> al = new ArrayList<>();
    al.add("item 1");
    al.add("item 2");
    al.add("item 3");
    al.add("item 4");
    al.add("item 5");

set adapter:-

StableArrayAdapter adapter = new StableArrayAdapter(this,
            android.R.layout.simple_list_item_1, a1);
    listview.setAdapter(adapter);

Remove item from position

al.remove(position);

Now Refresh listview adapter:-

adapter.notifyDataSetChanged();


问:
What is the most efficient way to convert list of structs to dictionary?
I have a struct that consists of multiple type elements as follows:

public struct mystruct
{
        int key;
        string value;
}
```

<p>What is the most efficient way to convert list of this struct to a dictionary that its keys are <code>mystruct.key</code> and values are list of <code>mystruct.value</code>?</p>

<p>i implement it as follows</p>

<pre class="lang-cs prettyprint-override"><code>Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }
</code>```

答:
Based on the assumption of having 2 million keys and 20 values per key, already in memory, this is how I would do it:

var d = new Dictionary<int, List<string>>();
foreach (var s in mystruct_list)
{
    if (!d.TryGetValue(s.key, out List<string> list))
    {
        list = new List<string>();
        d[s.key] = list;
    }
    list.Add(s.value);
}
```

This should result in 42 million dictionary index reads: 40 million (20 * 2 million) for TryGetValue, plus 2 million index reads when first storing the list.

Your version does 82 million index reads: for every one of the 20 * 2 million values, it calls both ContainsKey() and mydictionary[item.key], so that's 20 * 2 * 2 million, plus another 2 million to add the list.

(The code should be more or less correct, been a long time since I've written c#)

Body:
I have a struct that consists of multiple type elements as follows:

public struct mystruct
{
        int key;
        string value;
}

What is the most efficient way to convert list of this struct to a dictionary that its keys are mystruct.key and values are list of mystruct.value?

i implement it as follows

Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }

Body:
Based on the assumption of having 2 million keys and 20 values per key, already in memory, this is how I would do it:

var d = new Dictionary<int, List<string>>();
foreach (var s in mystruct_list)
{
    if (!d.TryGetValue(s.key, out List<string> list))
    {
        list = new List<string>();
        d[s.key] = list;
    }
    list.Add(s.value);
}

This should result in 42 million dictionary index reads: 40 million (20 * 2 million) for TryGetValue, plus 2 million index reads when first storing the list.

Your version does 82 million index reads: for every one of the 20 * 2 million values, it calls both ContainsKey() and mydictionary[item.key], so that's 20 * 2 * 2 million, plus another 2 million to add the list.

(The code should be more or less correct, been a long time since I've written c#)


问:
How to calculate the fraction of sequence that matches given datatables with start and end coordinates?
Given two datatables with start and end coordinates for sequences of integers:

```<code>df1 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 1, 21, 41, 1, 11, 21),
              END = c(10, 20, 30, 20, 40, 60, 10, 20, 30)
)
df2 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 31, 41, 51, 1, 11, 21),
              END = c(5, 17, 23, 38, 48, 54, 9, 17, 26)
)
</code>```

How can I count the number of integers in each sequence in df1 that are within the start and end coordinates of any sequence in df2 with matching CAT? I am currently using a for loop:

```<code>seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))
df1$MATCH <- NA
for (i in 1:nrow(df1)){
  df2_sub <- subset(df2, df2$CAT == df1$CAT[i])
  df2_int <- unlist(seq2(from = df2_sub$START, to = df2_sub$END))
  df1_int <- seq(df1$START[i], df1$END[i])
  df1$MATCH[i] <- length(na.omit(match(df1_int, df2_int)))
}
</code>```

which returns

```<code>df1
</code>```

```<code>   CAT START END MATCH
1:   A     1  10     5
2:   A    11  20     7
3:   A    21  30     3
4:   B     1  20     0
5:   B    21  40     8
6:   B    41  60    12
7:   C     1  10     9
8:   C    11  20     7
9:   C    21  30     6
</code>```

However, the datatables and vectors I am applying this to are very large? Is anyone able to suggest a way to improve performance? Perhaps using data.table?

答:
The first things you need to know is that you use for all your line in df1 your function seq2 which is for the perfomance is very bad.

This is the solution I propose, I haven't tested it with an very large dataset for the performance.

```<code>seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))

df2_sub = df2[, sequence = unlist( seq2(from = START, to = END) ), by = CAT]

f = function(cat, start, end){
  df2_sub[CAT == cat, length( intersect(seq(start, end), sequence) )]
}

df1[, MATCH := f(CAT, START, END), by = 1:nrow(df1)]
</code>```

It work if the two table df1 and df2 are data.table.

Body:
Given two datatables with start and end coordinates for sequences of integers:

df1 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 1, 21, 41, 1, 11, 21),
              END = c(10, 20, 30, 20, 40, 60, 10, 20, 30)
)
df2 <- data.table(CAT = c(rep("A", 3), rep("B", 3), rep("C", 3)),
              START = c(1, 11, 21, 31, 41, 51, 1, 11, 21),
              END = c(5, 17, 23, 38, 48, 54, 9, 17, 26)
)

How can I count the number of integers in each sequence in df1 that are within the start and end coordinates of any sequence in df2 with matching CAT? I am currently using a for loop:

seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))
df1$MATCH <- NA
for (i in 1:nrow(df1)){
  df2_sub <- subset(df2, df2$CAT == df1$CAT[i])
  df2_int <- unlist(seq2(from = df2_sub$START, to = df2_sub$END))
  df1_int <- seq(df1$START[i], df1$END[i])
  df1$MATCH[i] <- length(na.omit(match(df1_int, df2_int)))
}

which returns

df1

   CAT START END MATCH
1:   A     1  10     5
2:   A    11  20     7
3:   A    21  30     3
4:   B     1  20     0
5:   B    21  40     8
6:   B    41  60    12
7:   C     1  10     9
8:   C    11  20     7
9:   C    21  30     6

However, the datatables and vectors I am applying this to are very large? Is anyone able to suggest a way to improve performance? Perhaps using data.table?

Body:
The first things you need to know is that you use for all your line in df1 your function seq2 which is for the perfomance is very bad.

This is the solution I propose, I haven't tested it with an very large dataset for the performance.

seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))

df2_sub = df2[, sequence = unlist( seq2(from = START, to = END) ), by = CAT]

f = function(cat, start, end){
  df2_sub[CAT == cat, length( intersect(seq(start, end), sequence) )]
}

df1[, MATCH := f(CAT, START, END), by = 1:nrow(df1)]

It work if the two table df1 and df2 are data.table.


问:
Is there way to create foreach for sql code with array data
I got one query that takes data about users.

I need to make a 2nd query for each of these users.

I am getting data just for the first user. (with the second query)

First query:

```<code>$query = mysqli_query($conn, "SELECT * FROM tipuser WHERE permissions = '0'");
$ah = mysqli_fetch_array($query);
</code>```

Also when i do for each($query as $x) and inside that i echo first and last name it shows all, when i do the same with $ah it doesn't show anything.

Then I got these variables:

```<code>$firstname = $ah['firstname'];
$lastname = $ah['lastname'];
</code>```

Second query:

```<code>$sqlwork = mysqli_query($conn,
        "SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
                count(projekt) AS celkem,
                SUM(projekt = 0) AS tipsport,
                SUM(projekt = 1) AS slavia,
                SUM(projekt = 2) AS bet
        FROM zapasy
        WHERE komentator1 = '$firstname $lastname'
           OR komentator2 = '$firstname $lastname'
        GROUP BY Monthyear");
</code>```

I think the problem is somewhere in the array but I can't find it.
I am thankful for any help.

UPDATE:
this is how to display it on site:

```<code>         <?php foreach($query AS $usersall) {?>
           <table id="tablePreview" class="table table-hover table-sm table-bordered" style="border-top: 0px solid hsl(0, 0%, 87%);">

    <thead style="color:black; background-color: hsla(0,0%,71%,1.00); border-top: 0px solid hsl(0, 0%, 87%);">
        <tr>
            <th scope="col">Měsíc</th>
            <th scope="col">Zápasů</th>
            <th scope="col">BET</th>
            <th scope="col">TipSport</th>
            <th scope="col">Slavia</th>
            <th scope="col">Brutto</th>
            <th scope="col">Daň</th>
            <th scope="col">Netto</th>
            <th scope="col">Zaplaceno</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($tip = mysqli_fetch_assoc($sqlwork)) {?>
        <tr>
            <td>
                <?=$tip['Monthyear'] ?>
            </td>
            <td>
              <?=$tip['celkem']?>
            </td>
            <td>
                <?=$tip['bet']?>
            </td>
            <td>
                <?=$tip['tipsport']?>
            </td>
            <td>
                <?=$tip['slavia']?>
            </td>
            <td>
                <?php
                        $betx = $tip['bet']*$bet1cena['cena'];
                        $tipx = $tip['tipsport']*$tipcena['cena'];
                        $slax = $tip['slavia']*$slaviacena['cena'];
                        $celkem = $betx+$tipx+$slax;
                        echo "$celkem Kč";
                ?>
            </td>
            <td>
                <?php
                        if($user['fakturuje'] == 0){
                            $dan = $celkem*0.15;
                            echo "$dan Kč";

                        }else{
                            echo "0 Kč";
                        }
                ?>
            </td>
            <td>
                <?php
                   $netto = $celkem-$dan;
                   echo "$netto Kč";
                ?>
            </td>
            <td>
                <input type="checkbox">
            </td>
        </tr>

        <?php } ?>
    </tbody>
</table>
<?php }?>
</code>```

答:
Although it is not completely clear from your question I think you are getting multiple rows from your first query and wanting to run the second query on each row returned by the first query

This is one way, I have taken the liberty of using a prepared query for the second one, this should remove any SQL Injection issues and also any problems with Last Names like O'Toole (the apostrophe issue). It also means you only need compile the query once, but can run it with new parameters as many times as you need.

```<code>$q1 = mysqli_query($conn, "SELECT * FROM tipuser WHERE permissions = '0'");

$q2 = "SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
                count(projekt) AS celkem,
                SUM(projekt = 0) AS tipsport,
                SUM(projekt = 1) AS slavia,
                SUM(projekt = 2) AS bet
        FROM zapasy
        WHERE komentator1 = ?
           OR komentator2 = ?
        GROUP BY Monthyear");

$stmt2 = $conn->prepare($q2);

while ($ah = mysqli_fetch_array($q1) ) {

    // make the full name field
    $name = $ah['firstname'] . ' ' . $ah['lastname'];

    // bind those values to the prepared query
    $stmt2->bind_param('ss', $name, $name );
    $stmt2->execute();

    // present the results of this query
    // however you like
}
</code>```

Body:
I got one query that takes data about users.

I need to make a 2nd query for each of these users.

I am getting data just for the first user. (with the second query)

First query:

$query = mysqli_query($conn, "SELECT * FROM tipuser WHERE permissions = '0'");
$ah = mysqli_fetch_array($query);

Also when i do for each($query as $x) and inside that i echo first and last name it shows all, when i do the same with $ah it doesn't show anything.

Then I got these variables:

$firstname = $ah['firstname'];
$lastname = $ah['lastname'];

Second query:

$sqlwork = mysqli_query($conn,
        "SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
                count(projekt) AS celkem,
                SUM(projekt = 0) AS tipsport,
                SUM(projekt = 1) AS slavia,
                SUM(projekt = 2) AS bet
        FROM zapasy
        WHERE komentator1 = '$firstname $lastname'
           OR komentator2 = '$firstname $lastname'
        GROUP BY Monthyear");

I think the problem is somewhere in the array but I can't find it.
I am thankful for any help.

UPDATE:
this is how to display it on site:

         <?php foreach($query AS $usersall) {?>

            Měsíc
            Zápasů
            BET
            TipSport
            Slavia
            Brutto
            Daň
            Netto
            Zaplaceno

        <?php while ($tip = mysqli_fetch_assoc($sqlwork)) {?>

                <?=$tip['Monthyear'] ?>

              <?=$tip['celkem']?>

                <?=$tip['bet']?>

                <?=$tip['tipsport']?>

                <?=$tip['slavia']?>

                <?php
                        $betx = $tip['bet']*$bet1cena['cena'];
                        $tipx = $tip['tipsport']*$tipcena['cena'];
                        $slax = $tip['slavia']*$slaviacena['cena'];
                        $celkem = $betx+$tipx+$slax;
                        echo "$celkem Kč";
                ?>

                <?php
                        if($user['fakturuje'] == 0){
                            $dan = $celkem*0.15;
                            echo "$dan Kč";

                        }else{
                            echo "0 Kč";
                        }
                ?>

                <?php
                   $netto = $celkem-$dan;
                   echo "$netto Kč";
                ?>

                <input type="checkbox">

        <?php } ?>

<?php }?>

Body:
Although it is not completely clear from your question I think you are getting multiple rows from your first query and wanting to run the second query on each row returned by the first query

This is one way, I have taken the liberty of using a prepared query for the second one, this should remove any SQL Injection issues and also any problems with Last Names like O'Toole (the apostrophe issue). It also means you only need compile the query once, but can run it with new parameters as many times as you need.

$q1 = mysqli_query($conn, "SELECT * FROM tipuser WHERE permissions = '0'");

$q2 = "SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
                count(projekt) AS celkem,
                SUM(projekt = 0) AS tipsport,
                SUM(projekt = 1) AS slavia,
                SUM(projekt = 2) AS bet
        FROM zapasy
        WHERE komentator1 = ?
           OR komentator2 = ?
        GROUP BY Monthyear");

$stmt2 = $conn->prepare($q2);

while ($ah = mysqli_fetch_array($q1) ) {

    // make the full name field
    $name = $ah['firstname'] . ' ' . $ah['lastname'];

    // bind those values to the prepared query
    $stmt2->bind_param('ss', $name, $name );
    $stmt2->execute();

    // present the results of this query
    // however you like
}


问:
When do AVPlayer and AVPlayerItem status change?
I am working on a music player plugin in flutter using AVFoundation and I want to create a uniform interface on iOS and Android.

I want to capture errors that might be thrown by AVPlayer when, for example, the given AVPlayerItem is invalid (contains a URL of file which is unsupported, like a png file).

I would expect the AVPlayer.replace() to throw exception or change in status of AVPlayerItem or AVPlayer or at least some relevant notification on the NSNotificationCeter. I tried listening/observing all of them, but none of them reported any kind of error. In fact, the AVPlayer reported "ready-to-play" state.

```<code>    mediaPlayer = AVPlayer();
    playerItem = AVPlayerItem(url: URL(fileURLWithPath: Bundle.main.path(forResource: "image", ofType: "png")!))

    playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &playerItemContext)
    mediaPlayer?.addObserver(self, forKeyPath: #keyPath(AVPlayer.status), options: [.old, .new], context: &mediaPlayerContext)

    mediaPlayer?.replaceCurrentItem(with: playerItem); // this changes player status to - "ready-to-play"
    mediaPlayer?.play() // this does not report anything
</code>```

I am an android developer and can't understand how AVPlayer works. How can I achieve this?

Note:I can't use AVAudioPlayer because documentation says it shouldn't be used when playing music from the network or sources that may have latency.

```<code>self.mediaPlayer?.replaceCurrentItem(with: nil)
self.mediaPlayer?.play()
</code>```

Even this code doesn't generates error

答:
```<code>private func addObserverPlayerItem()
    {
        if let playerItem = self.player?.currentItem{
            playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil)
            playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
            playerItem.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: nil)
            playerItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new], context: nil)
            self.player?.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.status), options: [.new, .initial], context: nil)
            self.player?.addObserver(self, forKeyPath: #keyPath(AVPlayer.status), options: [.new, .initial], context: nil)
        }
    }

override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if object is AVPlayerItem {
            switch keyPath {

            case "loadedTimeRanges":

                let duration = self.currentItem?.totalBuffer() ?? 0
                let totalduration = currentItem?.asset.duration
                self.videoControll?.slider.bufferEndValue = totalduration?.seconds ?? 0
                self.videoControll?.slider.bufferStartValue = (duration) / (totalduration?.seconds ?? 1)
                print((duration) / (totalduration?.seconds ?? 1))

            case "playbackBufferEmpty":
                // Show loader
                self.activityIndicator?.startAnimating()

            case "playbackLikelyToKeepUp":
                // Hide loader
                self.activityIndicator?.stopAnimating()

            case "playbackBufferFull":
                // Hide loader
                self.activityIndicator?.stopAnimating()
            case #keyPath(AVPlayer.currentItem.status):

                let newStatus: AVPlayerItem.Status
                if let newStatusAsNumber = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
                    newStatus = AVPlayerItem.Status(rawValue: newStatusAsNumber.intValue)!
                } else {
                    newStatus = .unknown
                }
                if newStatus == .failed {
                    NSLog("SA Detected Error: \(String(describing: self.player?.currentItem?.error?.localizedDescription)), error: \(String(describing: self.player?.currentItem?.error))")
                }
            case #keyPath(AVPlayer.status):
                print()
            case .none:
                self.activityIndicator?.stopAnimating()
            case .some(_):
                self.activityIndicator?.stopAnimating()
            }
        }
    }
</code>```

Body:
I am working on a music player plugin in flutter using AVFoundation and I want to create a uniform interface on iOS and Android.

I want to capture errors that might be thrown by AVPlayer when, for example, the given AVPlayerItem is invalid (contains a URL of file which is unsupported, like a png file).

I would expect the AVPlayer.replace() to throw exception or change in status of AVPlayerItem or AVPlayer or at least some relevant notification on the NSNotificationCeter. I tried listening/observing all of them, but none of them reported any kind of error. In fact, the AVPlayer reported "ready-to-play" state.

    mediaPlayer = AVPlayer();
    playerItem = AVPlayerItem(url: URL(fileURLWithPath: Bundle.main.path(forResource: "image", ofType: "png")!))

    playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &playerItemContext)
    mediaPlayer?.addObserver(self, forKeyPath: #keyPath(AVPlayer.status), options: [.old, .new], context: &mediaPlayerContext)

    mediaPlayer?.replaceCurrentItem(with: playerItem); // this changes player status to - "ready-to-play"
    mediaPlayer?.play() // this does not report anything

I am an android developer and can't understand how AVPlayer works. How can I achieve this?

Note:I can't use AVAudioPlayer because documentation says it shouldn't be used when playing music from the network or sources that may have latency.

self.mediaPlayer?.replaceCurrentItem(with: nil)
self.mediaPlayer?.play()

Even this code doesn't generates error


问:
AWS S3 Bucket name already exists
I know this question has been asked before, but replies didn't really help my case.
I am trying to create a bucket in S3 and I always receive the 'Bucket name already exists' error. I tried any possible combination but no luck, also the format is compliant to the docs.

Any idea of what I am doing wrong?

Thanks

答:
According to the AWS docs:

An Amazon S3 bucket name is globally unique, and the namespace is shared by all AWS accounts. This means that after a bucket is created, the name of that bucket cannot be used by another AWS account in any AWS Region until the bucket is deleted.

Someone else has already created a bucket with this name.

Title: AWS S3 Bucket name already exists


问:
When I run command phpunit in terminal, I got php warning
When I run a phpunit command in terminal console, I got Php warning.

I've tried to run vendor/bin/phpunit but the result is the same.

This is an error:

PHP Warning:  "continue" targeting switch is equivalent to "break". Did
   you mean to use "continue 2"? in D:\xampp\php\pear\PHPUnit\TextUI\Command.php
   on line 277
   Warning: "continue" targeting switch is equivalent to "break". Did you mean
   to use "continue 2"? in D:\xampp\php\pear\PHPUnit\TextUI\Command.php on line
   277
   PHP Warning:  "continue" targeting switch is equivalent to "break". Did you
   mean to use "continue 2"? in D:\xampp\php\pear\PHPUnit\TextUI\Command.php on
   line 285

Warning: "continue" targeting switch is equivalent to "break". Did you mean
   to use
   "continue 2"? in D:\xampp\php\pear\PHPUnit\TextUI\Command.php on line 285
   PHPUnit 3.7.21 by Sebastian Bergmann.

答:
PHPUnit 3.7.21 was released in July 2013, meanwhile PHP has been improved and there was some changes in the codebase.

I suggest you to update PHPUnit for your project.

BTW if you google your error you can find a lot of discussion on that topic.


问:
Building Fiware Orion context broker on LinuxOne docker (s390x)
I am trying to build Fiware Orion context broker using Dockerfile at:

https://hub.docker.com/r/fiware/orion/

As a first step I have tried replacing the FROM image with the "supposed" equivalent of Centos for s390x, ClefOS: https://hub.docker.com/_/clefos :

```<code>FROM s390x/clefos:7.6.1810
</code>```

It takes a long time and seems to go OK but ends up with the error below. Any ideas? Anybody has successfully built any Orion version docker image on IBM Z? (s390x)

Update: I have added those four libraries in the yum install command in Dockerfile and they are correctly installed but the problem is still there. It seems not just a problem of those boost_* libs missing but some configuration fix needed to "ld" locates them.

```<code>[ 97%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/mongoRegistrationCreate.cpp.o
[ 97%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/mongoRegistrationDelete.cpp.o
[ 97%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/connectionOperations.cpp.o
[ 97%] [ 98%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/mongoSubCache.cpp.o
Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/safeMongo.cpp.o
[ 98%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/compoundResponses.cpp.o
[ 98%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/location.cpp.o
[ 99%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/compoundValueBson.cpp.o
[ 99%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/dateExpiration.cpp.o
Linking CXX static library libmongoBackend.a
make[3]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
[ 99%] Built target mongoBackend
make[3]: Entering directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
Scanning dependencies of target contextBroker
make[3]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make[3]: Entering directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
[100%] Building CXX object src/app/contextBroker/CMakeFiles/contextBroker.dir/contextBroker.cpp.o
[100%] Building CXX object src/app/contextBroker/CMakeFiles/contextBroker.dir/orionRestServices.cpp.o
Linking CXX executable contextBroker
/usr/bin/ld: cannot find -lboost_thread-mt
/usr/bin/ld: cannot find -lboost_filesystem-mt
/usr/bin/ld: cannot find -lboost_system-mt
/usr/bin/ld: cannot find -lboost_regex-mt
collect2: error: ld returned 1 exit status
make[3]: *** [src/app/contextBroker/contextBroker] Error 1
make[3]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make[2]: *** [src/app/contextBroker/CMakeFiles/contextBroker.dir/all] Error 2
make[2]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make: *** [release] Error 2
The command '/bin/sh -c adduser --comment "${ORION_USER}" ${ORION_USER} &&     yum -y install epel-release &&     yum -y install       boost-devel       bzip2       cmake       gnutls-devel       libgcrypt-devel       libcurl-devel       openssl-devel       libuuid-devel       make       nc       git       gcc-c++       scons       tar       which       cyrus-sasl-devel &&     curl -kOL http://ftp.gnu.org/gnu/libmicrohttpd/libmicrohttpd-0.9.48.tar.gz &&     tar xvf libmicrohttpd-0.9.48.tar.gz &&     cd libmicrohttpd-0.9.48 &&     ./configure --disable-messages --disable-postprocessor --disable-dauth &&     make &&     make install &&     ldconfig &&     curl -kOL https://github.com/mongodb/mongo-cxx-driver/archive/legacy-1.1.2.tar.gz &&     tar xfz legacy-1.1.2.tar.gz &&     cd mongo-cxx-driver-legacy-1.1.2 &&     scons --use-sasl-client --ssl &&     scons install --prefix=/usr/local --use-sasl-client --ssl &&     curl -kOL https://github.com/miloyip/rapidjson/archive/v1.0.2.tar.gz &&     tar xfz v1.0.2.tar.gz &&     mv rapidjson-1.0.2/include/rapidjson/ /usr/local/include &&     git clone https://github.com/telefonicaid/fiware-orion &&     cd fiware-orion &&     git checkout ${GIT_REV_ORION} &&     make &&     make install &&     strip /usr/bin/contextBroker &&     mkdir -p /var/log/contextBroker &&     mkdir -p /var/run/contextBroker &&     chown ${ORION_USER} /var/log/contextBroker &&     chown ${ORION_USER} /var/run/contextBroker &&     cd /opt &&     if [ ${CLEAN_DEV_TOOLS} -eq 0 ] ; then yum clean all && exit 0 ; fi &&     rm -rf /opt/libmicrohttpd-0.9.48.tar.gz            /usr/local/include/microhttpd.h            /usr/local/lib/libmicrohttpd.*            /opt/libmicrohttpd-0.9.48            /opt/legacy-1.1.2.tar.gz            /opt/mongo-cxx-driver-legacy-1.1.2            /usr/local/include/mongo            /usr/local/lib/libmongoclient.a            /opt/rapidjson-1.0.2            /opt/v1.0.2.tar.gz            /usr/local/include/rapidjson            /opt/fiware-orion            /usr/share/cracklib            /usr/share/i18n /usr/{lib,lib64}/gconv            &&     yum -y erase git perl* rsync         cmake libarchive         gcc-c++ cloog-ppl cpp gcc glibc-devel glibc-headers         kernel-headers libgomp libstdc++-devel mpfr ppl         scons boost-devel libcurl-devel gnutls-devel libgcrypt-devel         clang llvm llvm-libs         CUnit-devel CUnit         autoconf automake m4 libidn-devel         boost-wave boost-serialization boost-python         boost-iostreams boost boost-date-time         boost-test boost-graph boost-signals         boost-program-options boost-math         openssh openssh-clients libedit hwdata dbus-glib fipscheck* *devel sysvinit-tools         &&     rpm -qa groff | xargs -r rpm -e --nodeps &&     yum clean all && rm -rf /var/lib/yum/yumdb && rm -rf /var/lib/yum/history &&     rpm -vv --rebuilddb &&     find /usr/share/locale -mindepth 1 -maxdepth 1 ! -name 'en_US' ! -name 'locale.alias' | xargs -r rm -r &&     bash -c 'localedef --list-archive | grep -v -e "en_US" | xargs localedef --delete-from-archive' &&     /bin/cp -f /usr/lib/locale/locale-archive /usr/lib/locale/locale-archive.tmpl &&     build-locale-archive &&     rm -f /var/log/*log' returned a non-zero code: 2
</code>```

答:
By

```<code>/usr/bin/ld: cannot find -lboost_thread-mt
/usr/bin/ld: cannot find -lboost_filesystem-mt
/usr/bin/ld: cannot find -lboost_system-mt
/usr/bin/ld: cannot find -lboost_regex-mt
</code>```

I guess some required dependencies are missing. The solution would be to install them as part of the Dockefile script. However, not sure how to do it in s390x/clefos (in CentOS is a matter of installing the package that contains the dependency using yum, the Dockerfile does that).

Body:
I am trying to build Fiware Orion context broker using Dockerfile at:

https://hub.docker.com/r/fiware/orion/

As a first step I have tried replacing the FROM image with the "supposed" equivalent of Centos for s390x, ClefOS: https://hub.docker.com/_/clefos :

FROM s390x/clefos:7.6.1810

It takes a long time and seems to go OK but ends up with the error below. Any ideas? Anybody has successfully built any Orion version docker image on IBM Z? (s390x)

Update: I have added those four libraries in the yum install command in Dockerfile and they are correctly installed but the problem is still there. It seems not just a problem of those boost_* libs missing but some configuration fix needed to "ld" locates them.

[ 97%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/mongoRegistrationCreate.cpp.o
[ 97%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/mongoRegistrationDelete.cpp.o
[ 97%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/connectionOperations.cpp.o
[ 97%] [ 98%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/mongoSubCache.cpp.o
Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/safeMongo.cpp.o
[ 98%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/compoundResponses.cpp.o
[ 98%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/location.cpp.o
[ 99%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/compoundValueBson.cpp.o
[ 99%] Building CXX object src/lib/mongoBackend/CMakeFiles/mongoBackend.dir/dateExpiration.cpp.o
Linking CXX static library libmongoBackend.a
make[3]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
[ 99%] Built target mongoBackend
make[3]: Entering directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
Scanning dependencies of target contextBroker
make[3]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make[3]: Entering directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
[100%] Building CXX object src/app/contextBroker/CMakeFiles/contextBroker.dir/contextBroker.cpp.o
[100%] Building CXX object src/app/contextBroker/CMakeFiles/contextBroker.dir/orionRestServices.cpp.o
Linking CXX executable contextBroker
/usr/bin/ld: cannot find -lboost_thread-mt
/usr/bin/ld: cannot find -lboost_filesystem-mt
/usr/bin/ld: cannot find -lboost_system-mt
/usr/bin/ld: cannot find -lboost_regex-mt
collect2: error: ld returned 1 exit status
make[3]: *** [src/app/contextBroker/contextBroker] Error 1
make[3]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make[2]: *** [src/app/contextBroker/CMakeFiles/contextBroker.dir/all] Error 2
make[2]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/opt/libmicrohttpd-0.9.48/mongo-cxx-driver-legacy-1.1.2/fiware-orion/BUILD_RELEASE'
make: *** [release] Error 2
The command '/bin/sh -c adduser --comment "${ORION_USER}" ${ORION_USER} &&     yum -y install epel-release &&     yum -y install       boost-devel       bzip2       cmake       gnutls-devel       libgcrypt-devel       libcurl-devel       openssl-devel       libuuid-devel       make       nc       git       gcc-c++       scons       tar       which       cyrus-sasl-devel &&     curl -kOL http://ftp.gnu.org/gnu/libmicrohttpd/libmicrohttpd-0.9.48.tar.gz &&     tar xvf libmicrohttpd-0.9.48.tar.gz &&     cd libmicrohttpd-0.9.48 &&     ./configure --disable-messages --disable-postprocessor --disable-dauth &&     make &&     make install &&     ldconfig &&     curl -kOL https://github.com/mongodb/mongo-cxx-driver/archive/legacy-1.1.2.tar.gz &&     tar xfz legacy-1.1.2.tar.gz &&     cd mongo-cxx-driver-legacy-1.1.2 &&     scons --use-sasl-client --ssl &&     scons install --prefix=/usr/local --use-sasl-client --ssl &&     curl -kOL https://github.com/miloyip/rapidjson/archive/v1.0.2.tar.gz &&     tar xfz v1.0.2.tar.gz &&     mv rapidjson-1.0.2/include/rapidjson/ /usr/local/include &&     git clone https://github.com/telefonicaid/fiware-orion &&     cd fiware-orion &&     git checkout ${GIT_REV_ORION} &&     make &&     make install &&     strip /usr/bin/contextBroker &&     mkdir -p /var/log/contextBroker &&     mkdir -p /var/run/contextBroker &&     chown ${ORION_USER} /var/log/contextBroker &&     chown ${ORION_USER} /var/run/contextBroker &&     cd /opt &&     if [ ${CLEAN_DEV_TOOLS} -eq 0 ] ; then yum clean all && exit 0 ; fi &&     rm -rf /opt/libmicrohttpd-0.9.48.tar.gz            /usr/local/include/microhttpd.h            /usr/local/lib/libmicrohttpd.*            /opt/libmicrohttpd-0.9.48            /opt/legacy-1.1.2.tar.gz            /opt/mongo-cxx-driver-legacy-1.1.2            /usr/local/include/mongo            /usr/local/lib/libmongoclient.a            /opt/rapidjson-1.0.2            /opt/v1.0.2.tar.gz            /usr/local/include/rapidjson            /opt/fiware-orion            /usr/share/cracklib            /usr/share/i18n /usr/{lib,lib64}/gconv            &&     yum -y erase git perl* rsync         cmake libarchive         gcc-c++ cloog-ppl cpp gcc glibc-devel glibc-headers         kernel-headers libgomp libstdc++-devel mpfr ppl         scons boost-devel libcurl-devel gnutls-devel libgcrypt-devel         clang llvm llvm-libs         CUnit-devel CUnit         autoconf automake m4 libidn-devel         boost-wave boost-serialization boost-python         boost-iostreams boost boost-date-time         boost-test boost-graph boost-signals         boost-program-options boost-math         openssh openssh-clients libedit hwdata dbus-glib fipscheck* *devel sysvinit-tools         &&     rpm -qa groff | xargs -r rpm -e --nodeps &&     yum clean all && rm -rf /var/lib/yum/yumdb && rm -rf /var/lib/yum/history &&     rpm -vv --rebuilddb &&     find /usr/share/locale -mindepth 1 -maxdepth 1 ! -name 'en_US' ! -name 'locale.alias' | xargs -r rm -r &&     bash -c 'localedef --list-archive | grep -v -e "en_US" | xargs localedef --delete-from-archive' &&     /bin/cp -f /usr/lib/locale/locale-archive /usr/lib/locale/locale-archive.tmpl &&     build-locale-archive &&     rm -f /var/log/*log' returned a non-zero code: 2

Body:
By

/usr/bin/ld: cannot find -lboost_thread-mt
/usr/bin/ld: cannot find -lboost_filesystem-mt
/usr/bin/ld: cannot find -lboost_system-mt
/usr/bin/ld: cannot find -lboost_regex-mt

I guess some required dependencies are missing. The solution would be to install them as part of the Dockefile script. However, not sure how to do it in s390x/clefos (in CentOS is a matter of installing the package that contains the dependency using yum, the Dockerfile does that).


问:
How to sort a regex match in PowerShell by a value of the groups array
I have an array of strings and each string includes a number which represents the sprint (scrum) number. Now, I want to sort the array by the sprint number using regular expressions in Powershell.

Example of the array

a.sprint-100

a.sprint-99

a.sprint-49

a.sprint-98

```<code># define the array
$a = @("a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98")

# escape hard defined string in regex
$escapedString = [regex]::escape(".sprint-")

# create regex which matches <AnyCharacter>.sprint-<SprintNumber>
[regex]$regex = "(.+)$escapedString([0-9]{2,3})"

# process the regex on all strings and print out the sprint number
$a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{$_.Groups[2].value}

# output: 100 99 49 98

# but my sort logic doesn't work
 $a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | Sort-Object -Property {$_.Groups[2].value} -Descending | %{$_.Groups[2].value}

# output: 99 98 49 100
</code>```

I am sorting on a string. So, this could be the main problem.
Have anyone an idea to parse the match value to an int?

If I try to do it, then I'm getting 'value' is a ReadOnly property.".
Or is there a better way to get to my desired sorting result?

For simplification, I used here a string array. But in the real scenario, it is an array including custom objects with a bunch of data. This array should be sorted after my regex pipe.

Thanks in advance!

答:
You need to sort on the numeric part of the strings, converted to [int] first, because otherwise, the sort will still be alphanumeric:

```<code># define the array
$a = "a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98"
# sort on the numeric part of the strings, converted to [int]
$a | Sort-Object {[int]($_ -split '-')[-1]}
</code>```

Result:

```<code>a.sprint-49
a.sprint-98
a.sprint-99
a.sprint-100
</code>```

Body:
I have an array of strings and each string includes a number which represents the sprint (scrum) number. Now, I want to sort the array by the sprint number using regular expressions in Powershell.

Example of the array

a.sprint-100

a.sprint-99

a.sprint-49

a.sprint-98

# define the array
$a = @("a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98")

# escape hard defined string in regex
$escapedString = [regex]::escape(".sprint-")

# create regex which matches <AnyCharacter>.sprint-<SprintNumber>
[regex]$regex = "(.+)$escapedString([0-9]{2,3})"

# process the regex on all strings and print out the sprint number
$a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{$_.Groups[2].value}

# output: 100 99 49 98

# but my sort logic doesn't work
 $a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | Sort-Object -Property {$_.Groups[2].value} -Descending | %{$_.Groups[2].value}

# output: 99 98 49 100

I am sorting on a string. So, this could be the main problem.
Have anyone an idea to parse the match value to an int?

If I try to do it, then I'm getting 'value' is a ReadOnly property.".
Or is there a better way to get to my desired sorting result?

For simplification, I used here a string array. But in the real scenario, it is an array including custom objects with a bunch of data. This array should be sorted after my regex pipe.

Thanks in advance!

Body:
You need to sort on the numeric part of the strings, converted to [int] first, because otherwise, the sort will still be alphanumeric:

# define the array
$a = "a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98"
# sort on the numeric part of the strings, converted to [int]
$a | Sort-Object {[int]($_ -split '-')[-1]}

Result:

a.sprint-49
a.sprint-98
a.sprint-99
a.sprint-100


问:
sed command to append string inside the double qoutes
I want to update a file on remote linux server. For this i am using sed command. in that i have to first search that line then update value

i have file with following content:

```<code>GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur"
GRUB_DISABLE_RECOVERY="true"
</code>```

so using sed command i have to append sharma in double qoutes
means after execution line will be  grub_cmdline_linux = "ankur sharma"

i have tried this command

```<code>sed -i 's+\(GRUB_CMDLINE_LINUX.*\)+\1 sharma+g' '/etc/default/grub.bak'
</code>```

by this command sharma is appending at the end of the line but it should be append inside the double qoutes

Expected output:

```<code>GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur sharma"
GRUB_DISABLE_RECOVERY="true"
</code>```

答:
Wouldn't it be something like

```<code>sed '/^GRUB_CMDLINE_LINUX=/s/"$/ sharma"/' /etc/default/grub.bak
</code>```

?

Body:
I want to update a file on remote linux server. For this i am using sed command. in that i have to first search that line then update value

i have file with following content:

GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur"
GRUB_DISABLE_RECOVERY="true"

so using sed command i have to append sharma in double qoutes
means after execution line will be  grub_cmdline_linux = "ankur sharma"

i have tried this command

sed -i 's+\(GRUB_CMDLINE_LINUX.*\)+\1 sharma+g' '/etc/default/grub.bak'

by this command sharma is appending at the end of the line but it should be append inside the double qoutes

Expected output:

GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="ankur sharma"
GRUB_DISABLE_RECOVERY="true"

Body:
Wouldn't it be something like

sed '/^GRUB_CMDLINE_LINUX=/s/"$/ sharma"/' /etc/default/grub.bak

?


问:
Disabling SSL Certificate Validation in Spring RestTemplate
I am having two Spring-based web apps A and B, on two different machines.

I want to make an HTTPS call from web app A to web app B, however, I am using a self-signed certificate in Machine B. So my HTTPS request fails.

How can I disable HTTPS certificate validation when using RestTemplate in Spring? I want to disable validation because both web app A and B are within the internal network, but data transfer has to happen over HTTPS

答:
To overrule the default strategy you can create a simple method in the class where you are wired your restTemplate:

```<code> protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    };

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
            HttpClientBuilder
                    .create()
                    .setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
                    .build()));
}
</code>```

Note: Surely you need to handle exceptions since this method only throws them further!

Body:
To overrule the default strategy you can create a simple method in the class where you are wired your restTemplate:

 protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    };

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
            HttpClientBuilder
                    .create()
                    .setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
                    .build()));
}

Note: Surely you need to handle exceptions since this method only throws them further!


问:
How can I combine the Properties of two arrays?
I have made a for loop that makes dots. Now I want to color them in a specific way. Like the first 200 are black and the next 326 are blue. I already managed that, but now I have so many rows of code and I wonder if there is a cleaner way to do it. For example make an array for the colors and then make an array for the values? </p>

```<code>let circleColor = 'Lavender ';
const secondColor = 'burlyWood ';
const numberFirstColor = 493;
const numberSecondColor = numberFirstColor+578;
for (let i = 0; i < circleCount; i++) {
if (i > numberFirstColor) circleColor = secondColor;
if ( i > numberSecondColor) circleColor= thirdColor;
</code>```

答:
You could keep an array of objects, then iterate over that:</p>

```<code> for(const { color, count } of [{ color: "Lavender", count: 200 }, { color: "burlyWood", count: 326 } /*..*/]) {
   for(let i = 0; i < count; i++) {
     circleColor = color;
     //...
   }
 }
</code>```

Body:
I have made a for loop that makes dots. Now I want to color them in a specific way. Like the first 200 are black and the next 326 are blue. I already managed that, but now I have so many rows of code and I wonder if there is a cleaner way to do it. For example make an array for the colors and then make an array for the values?

let circleColor = 'Lavender ';
const secondColor = 'burlyWood ';
const numberFirstColor = 493;
const numberSecondColor = numberFirstColor+578;
for (let i = 0; i < circleCount; i++) {
if (i > numberFirstColor) circleColor = secondColor;
if ( i > numberSecondColor) circleColor= thirdColor;

Body:
You could keep an array of objects, then iterate over that:

 for(const { color, count } of [{ color: "Lavender", count: 200 }, { color: "burlyWood", count: 326 } /*..*/]) {
   for(let i = 0; i < count; i++) {
     circleColor = color;
     //...
   }
 }


问:
Writing a Factory method for STL random number generators
I'm trying to provide an interface — through a config file — for my users to choose a distribution for some of the parameters that they are using. I would like to use STL random number generator algorithms for this purpose.

Let's assume that my program reads a JSON from a command line. For the JSON provided below, the program needs to realize that it should generate a random number from the normal distribution with given mean and standard variation. (I'm using the same parameter names as STL library for clearance.)

```<code>{
    "dist": "normal_distribution",
    "mean": 0.1,
    "stddev": 0.5
}
</code>```

So far, I can parse the JSON easily, and use each distribution's param_type to initialize the distribution. I use the name to decide which distribution to decide the param_type and the distribution.

What I don't know is how to implement this nicely. I know that I should provide some sort of factory method for this, pass the JSON, and spit out a function or a class. If I want to return an instance of a class, let's say a unique_ptr of the generator, I need to define an abstract class, e.g., RandDist and write some sort of adaptor to incorporate my input, .... I generally don't need a lot from the class, just a gen() method should be enough.

I'm wondering if anyone have thoughts on this. Or, if anyone knows a library that can do this.

P.S. Input doesn't have to be a JSON object, any hash table would work per se.

答:
You described a pretty standard way to deal with this situation - to have abstract RandomGenerator class with just one virtual method gen().

Then, it will have implementations like NormalDistributionGenerator, UniformDistributionGenerator etc. with constructors accepting appropriate distribution parameter set and initializing STL stuff as members.
These concrete classes will be used directly only in generator creation routine, and used in other places as abstract RandomGenerator.

So creation routine will look something like this

```<code>std::unique_ptr<RandomGenerator> CreateRandomGenerator(const Info& info) {
    switch (info.type) {
    case Type::Normal:
        return std::make_unique<NormalDistributionGenerator>(info.mean(), info.stddev());
    case Type::Uniform:
        return std::make_unique<UniformDistributionGenerator>(info.a(), info.b());
    // ...
    }
}
</code>```

Info - is a class which holds distribution info (some JSON wrapper, of map/hash_table - whatever works best in your case).

So you will definitely need to write some boilerplate code to make it work, but it will make a usage of your RandomGenerator simple and clear, and adding new types of distributions will be easy enough and require code modification in single place only - factory method.

Body:
I'm trying to provide an interface — through a config file — for my users to choose a distribution for some of the parameters that they are using. I would like to use STL random number generator algorithms for this purpose.

Let's assume that my program reads a JSON from a command line. For the JSON provided below, the program needs to realize that it should generate a random number from the normal distribution with given mean and standard variation. (I'm using the same parameter names as STL library for clearance.)

{
    "dist": "normal_distribution",
    "mean": 0.1,
    "stddev": 0.5
}

So far, I can parse the JSON easily, and use each distribution's param_type to initialize the distribution. I use the name to decide which distribution to decide the param_type and the distribution.

What I don't know is how to implement this nicely. I know that I should provide some sort of factory method for this, pass the JSON, and spit out a function or a class. If I want to return an instance of a class, let's say a unique_ptr of the generator, I need to define an abstract class, e.g., RandDist and write some sort of adaptor to incorporate my input, .... I generally don't need a lot from the class, just a gen() method should be enough.

I'm wondering if anyone have thoughts on this. Or, if anyone knows a library that can do this.

P.S. Input doesn't have to be a JSON object, any hash table would work per se.

Body:
You described a pretty standard way to deal with this situation - to have abstract RandomGenerator class with just one virtual method gen().

Then, it will have implementations like NormalDistributionGenerator, UniformDistributionGenerator etc. with constructors accepting appropriate distribution parameter set and initializing STL stuff as members.
These concrete classes will be used directly only in generator creation routine, and used in other places as abstract RandomGenerator.

So creation routine will look something like this

std::unique_ptr<RandomGenerator> CreateRandomGenerator(const Info& info) {
    switch (info.type) {
    case Type::Normal:
        return std::make_unique<NormalDistributionGenerator>(info.mean(), info.stddev());
    case Type::Uniform:
        return std::make_unique<UniformDistributionGenerator>(info.a(), info.b());
    // ...
    }
}

Info - is a class which holds distribution info (some JSON wrapper, of map/hash_table - whatever works best in your case).

So you will definitely need to write some boilerplate code to make it work, but it will make a usage of your RandomGenerator simple and clear, and adding new types of distributions will be easy enough and require code modification in single place only - factory method.


问:
How to fix "Could not find method" error?
I'm working on home work on Android studio, every thing was Ok, and I shut down my pc till next day, when i opened android studio i found this error message

ERROR: Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13-beta-3'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.0.0-alpha1'

    // Displaying images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'

    // Realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}
</code>```

答:
This error because of Glide library:

add following dependency too with glide dependency:

```<code>annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
</code>```

also if you are using androidx then you need to add :

```<code>annotationProcessor 'androidx.annotation:annotation:1.0.2'
</code>```

Hope it will helps you.

Body:
I'm working on home work on Android studio, every thing was Ok, and I shut down my pc till next day, when i opened android studio i found this error message

ERROR: Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13-beta-3'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.0.0-alpha1'

    // Displaying images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'

    // Realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}

Body:
This error because of Glide library:

add following dependency too with glide dependency:

annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

also if you are using androidx then you need to add :

annotationProcessor 'androidx.annotation:annotation:1.0.2'

Hope it will helps you.


问:
With the pose between two images, how do you project a point from one scene into another?
If you have the full relative-3D values of two images looking at the same scene (relative x,y,z), along with the extrinsic/intrinsic parameters between them, how do you project the points from one scene into the other scene, in opencv?</p>

答: Let the extrinsic parameters be R and t such that camera 1 is [I|0] and camera 2 is [R|t]. So all you have to do is rotate and the translate point cloud 1 with R and t to have it in the same coordinate system as point cloud 2.


问:
Pandas dataframe total row
I have a dataframe, something like:

```<code>     foo  bar  qux
0    a    1    3.14
1    b    3    2.72
2    c    2    1.62
3    d    9    1.41
4    e    3    0.58
</code>```

and I would like to add a 'total' row to the end of dataframe:

```<code>     foo  bar  qux
0    a    1    3.14
1    b    3    2.72
2    c    2    1.62
3    d    9    1.41
4    e    3    0.58
5  total  18   9.47
</code>```

I've tried to use the sum command but I end up with a Series, which although I can convert back to a Dataframe, doesn't maintain the data types:

```<code>tot_row = pd.DataFrame(df.sum()).T
tot_row['foo'] = 'tot'
tot_row.dtypes:
     foo    object
     bar    object
     qux    object
</code>```

I would like to maintain the data types from the original data frame as I need to apply other operations to the total row, something like:

```<code>baz = 2*tot_row['qux'] + 3*tot_row['bar']
</code>```

答:
Building on answer from Matthias Kauer.

To add row total:

```<code>df.loc["Row_Total"] = df.sum()
</code>```

To add column total,

```<code>df.loc[:,"Column_Total"] = df.sum(axis=1)
</code>```

Title: Pandas dataframe total row

Body:
I have a dataframe, something like:

     foo  bar  qux
0    a    1    3.14
1    b    3    2.72
2    c    2    1.62
3    d    9    1.41
4    e    3    0.58

and I would like to add a 'total' row to the end of dataframe:

     foo  bar  qux
0    a    1    3.14
1    b    3    2.72
2    c    2    1.62
3    d    9    1.41
4    e    3    0.58
5  total  18   9.47

I've tried to use the sum command but I end up with a Series, which although I can convert back to a Dataframe, doesn't maintain the data types:

tot_row = pd.DataFrame(df.sum()).T
tot_row['foo'] = 'tot'
tot_row.dtypes:
     foo    object
     bar    object
     qux    object

I would like to maintain the data types from the original data frame as I need to apply other operations to the total row, something like:

baz = 2*tot_row['qux'] + 3*tot_row['bar']

Body:
Building on answer from Matthias Kauer.

To add row total:

df.loc["Row_Total"] = df.sum()

To add column total,

df.loc[:,"Column_Total"] = df.sum(axis=1)


问:
Collection of array objects being pushed into existing array in the same index

```<code>ipRecords: any;

 this.auth.fileUpload(fd).subscribe((res: any)=>{
        if(res.status==="Success"){
          this.toastr.success("File Uploaded");
          this.ipRecords.push(JSON.parse(JSON.stringify(res.data)));
});
</code>```

in the iprecords array when i push the new data it gets pushed in the same index 10. I want that items inside it should be pushed. this.ipRecords = res.data works fine but it overwrites the existing items

答:
That's it:) use Array.prototype.concat or spread operator.<br>
And why are you using so tricky stuff (JSON.parse(JSON.stringify))? </p>

```<code> this.auth.fileUpload(fd).subscribe((res: any)=>{
        if(res.status==="Success"){
          this.toastr.success("File Uploaded");
          this.ipRecords.push(...JSON.parse(JSON.stringify(res.data)));
});
</code>```

Body:
ipRecords: any;

 this.auth.fileUpload(fd).subscribe((res: any)=>{
        if(res.status==="Success"){
          this.toastr.success("File Uploaded");
          this.ipRecords.push(JSON.parse(JSON.stringify(res.data)));
});

in the iprecords array when i push the new data it gets pushed in the same index 10. I want that items inside it should be pushed. this.ipRecords = res.data works fine but it overwrites the existing items

Body:
That's it:) use Array.prototype.concat or spread operator.

And why are you using so tricky stuff (JSON.parse(JSON.stringify))?

 this.auth.fileUpload(fd).subscribe((res: any)=>{
        if(res.status==="Success"){
          this.toastr.success("File Uploaded");
          this.ipRecords.push(...JSON.parse(JSON.stringify(res.data)));
});


问:
How to change the chart line color to custom color code value in Flutter
I am using chart_flutter plug in https://pub.dartlang.org/packages/charts_flutter and I want to change the line color of my TimeSeriesChart?

The code I have right now is this:

```<code>final chartdata = [
  charts.Series<VolumePerDay, DateTime>(
    id: 'Workout',
    colorFn: (_, __) => charts.MaterialPalette.lime.shadeDefault,
    // colorFn: (_, __) => Theme.of(context).accentColor,
    domainFn: (VolumePerDay workout, _) => workout.time,
    measureFn: (VolumePerDay workout, _) => workout.volume,
    data: data,
  )
];
return charts.TimeSeriesChart(
  chartdata,
  animate: false,
);
</code>```

I thought that changing the colorFn property would change the color, but if I comment the line with MaterialPalette and uncomment the Theme color line, it gives me an error. How can I set the chart's line color to a color of my choice using color codes?

答:
I am new to flutter and was also facing the same issue, So, as far as I came to know is that may be we cant use the MaterialColor for the charts Color and So a workaround to this was to replace your charts.MaterialPalette.lime.shadeDefault code with charts.Color.fromHex(code: '#f2f2f2').

This was discussed in this GitHub issue.

Body:
I am using chart_flutter plug in https://pub.dartlang.org/packages/charts_flutter and I want to change the line color of my TimeSeriesChart?

The code I have right now is this:

final chartdata = [
  charts.Series<VolumePerDay, DateTime>(
    id: 'Workout',
    colorFn: (_, __) => charts.MaterialPalette.lime.shadeDefault,
    // colorFn: (_, __) => Theme.of(context).accentColor,
    domainFn: (VolumePerDay workout, _) => workout.time,
    measureFn: (VolumePerDay workout, _) => workout.volume,
    data: data,
  )
];
return charts.TimeSeriesChart(
  chartdata,
  animate: false,
);

I thought that changing the colorFn property would change the color, but if I comment the line with MaterialPalette and uncomment the Theme color line, it gives me an error. How can I set the chart's line color to a color of my choice using color codes?


问:
How to get caret/cursor position in RichTextBox in WPF?
I want to get the Caret position in RichTextBox in WPF when I change my cursor with Left Click Mouse Button and this picture below shows this.

答:
Get position:

```<code>TextPointer tp = EditMessageRTB.Selection.Start;
</code>```

Set position:

```<code>RichTextBox.CaretPosition = tp;
</code>```

If want to set position to end:

```<code>RichTextBox.CaretPosition = RichTextBox.Document.Blocks.LastBlock.ContentEnd;
</code>```

Body:
Get position:

TextPointer tp = EditMessageRTB.Selection.Start;

Set position:

RichTextBox.CaretPosition = tp;

If want to set position to end:

RichTextBox.CaretPosition = RichTextBox.Document.Blocks.LastBlock.ContentEnd;


问:
Spring Boot, MySQL, Tomcat can't create intital connections of pool in Eclipse
I have created a webapp using Spring Boot and REST APIs in Eclipse. When I try to run it using Tomcat 8, it gives the error
"o.a.tomcat.jdbc.pool.ConnectionPool: Unable to create initial connections of pool."

I tried using the solutions provided but nothing seemed to work, it always gives the same error.

This is my application.properties file -

```<code>spring.datasource.url = jdbc:mysql://localhost:3306/dbase?autoReconnect=true&useSSL=false
spring.datasource.username = 1234
spring.datasource.password = 1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.hibernate.ddl-auto = update
</code>```

and this is the pom.xml file -

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.springboot</groupId>
  <artifactId>springbootrestapi</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springbootrestapiexample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>
  <build>
    <finalName>springbootrestapiexample</finalName>
  </build>
</project>
</code>```

This is the stack trace -

```<code>16:33:43.182 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
16:33:43.206 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
16:33:43.207 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/Amber%20Bhanarkar/eclipse-workspace/springbootrestapi/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2019-05-29 16:33:43.767  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : Starting StudentApplication on LAPTOP-BV6107FE with PID 13396 (started by Amber Bhanarkar in C:\Users\Amber Bhanarkar\eclipse-workspace\springbootrestapi)
2019-05-29 16:33:43.768  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : No active profile set, falling back to default profiles: default
2019-05-29 16:33:43.892  INFO 13396 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@754391d8: startup date [Wed May 29 16:33:43 IST 2019]; root of context hierarchy
2019-05-29 16:33:49.463  INFO 13396 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-05-29 16:33:49.552  INFO 13396 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-29 16:33:49.554  INFO 13396 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6188 ms
2019-05-29 16:33:50.354  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-05-29 16:33:50.359  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-05-29 16:33:55.529 ERROR 13396 --- [  restartedMain] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
</code>```

Here is StudentApplication.java -

```<code>package com.springboot.springbootrestapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing
public class StudentApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentApplication.class, args);
    }

}
</code>```

答:
These are the things to check

Verify if the database server up and running, and your connection details are working fine in a standalone test.

Grant access if not present, visit :

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Why are you running spring boot within tomcat in the first place and not as a fat jar ?
Secondly, the mysql client JAR should be included in tomcat library

Increase mySQL max connection count, if server is running out of available connections

Body:
I have created a webapp using Spring Boot and REST APIs in Eclipse. When I try to run it using Tomcat 8, it gives the error
"o.a.tomcat.jdbc.pool.ConnectionPool: Unable to create initial connections of pool."

I tried using the solutions provided but nothing seemed to work, it always gives the same error.

This is my application.properties file -

spring.datasource.url = jdbc:mysql://localhost:3306/dbase?autoReconnect=true&useSSL=false
spring.datasource.username = 1234
spring.datasource.password = 1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.hibernate.ddl-auto = update

and this is the pom.xml file -

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.springboot</groupId>
  <artifactId>springbootrestapi</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springbootrestapiexample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>
  <build>
    <finalName>springbootrestapiexample</finalName>
  </build>
</project>

This is the stack trace -

16:33:43.182 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
16:33:43.206 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
16:33:43.207 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/Amber%20Bhanarkar/eclipse-workspace/springbootrestapi/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2019-05-29 16:33:43.767  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : Starting StudentApplication on LAPTOP-BV6107FE with PID 13396 (started by Amber Bhanarkar in C:\Users\Amber Bhanarkar\eclipse-workspace\springbootrestapi)
2019-05-29 16:33:43.768  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : No active profile set, falling back to default profiles: default
2019-05-29 16:33:43.892  INFO 13396 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@754391d8: startup date [Wed May 29 16:33:43 IST 2019]; root of context hierarchy
2019-05-29 16:33:49.463  INFO 13396 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-05-29 16:33:49.552  INFO 13396 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-29 16:33:49.554  INFO 13396 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6188 ms
2019-05-29 16:33:50.354  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-05-29 16:33:50.359  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-05-29 16:33:55.529 ERROR 13396 --- [  restartedMain] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.

Here is StudentApplication.java -

package com.springboot.springbootrestapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing
public class StudentApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentApplication.class, args);
    }

}


问:
Vue + TypeScript - Recommended folder structure convention for placing custom typings?
Is there a recommended convention in where to place your custom type definition files in a Vue project?

I've been using a folder named ./src/types with this kind of tsconfig:

```<code>{
  "compilerOptions": {
    ...
    "typeRoots": [
      "node_modules/@types",
      "types"
    ]
  }
}
</code>```

Somebody told me that Vue or Webpack would pick up files in ./@types/ folder automatically without needing to add this to ./tsconfig.json - however, I did not find a reference to such information?

答:
According to TypeScript website, TypeScript automatically loads types in folders if you have referenced them in your code.

@types, typeRoots and types

By default all visible “@types” packages are included in your
  compilation. Packages in node_modules/@types of any enclosing folder
  are considered visible; specifically, that means packages within
  ./node_modules/@types/, ../node_modules/@types/,
  ../../node_modules/@types/, and so on.

If typeRoots is specified, only packages under typeRoots will be
  included. For example:

```<code>{
   "compilerOptions": {
       "typeRoots" : ["./typings"]
   }
}
</code>```

This config file will include all packages under ./typings, and no
  packages from ./node_modules/@types

You can easily test it like:

```<code>tc --init
</code>```

Create a index.d.ts file inside @types/index.d.ts, and put code below in it:

```<code>declare interface Foo {
    Bar: string;
}
</code>```

In the root folder, create a new index.ts file and inside your code-editor (Eg. VSCode), test it:

```<code>let foo:Foo;
foo. // you can see code-completion
</code>```

p.s:
It doesn't matter if you put your code inside @types or not, TypeScript automatically will find them. You can manually define the path for typeRoots as well but don't forget to configure it to looks for @types inside node_modules.

Body:
Is there a recommended convention in where to place your custom type definition files in a Vue project?

I've been using a folder named ./src/types with this kind of tsconfig:

{
  "compilerOptions": {
    ...
    "typeRoots": [
      "node_modules/@types",
      "types"
    ]
  }
}

Somebody told me that Vue or Webpack would pick up files in ./@types/ folder automatically without needing to add this to ./tsconfig.json - however, I did not find a reference to such information?

Body:
According to TypeScript website, TypeScript automatically loads types in folders if you have referenced them in your code.

@types, typeRoots and types

By default all visible “@types” packages are included in your
  compilation. Packages in node_modules/@types of any enclosing folder
  are considered visible; specifically, that means packages within
  ./node_modules/@types/, ../node_modules/@types/,
  ../../node_modules/@types/, and so on.

If typeRoots is specified, only packages under typeRoots will be
  included. For example:

{
   "compilerOptions": {
       "typeRoots" : ["./typings"]
   }
}

This config file will include all packages under ./typings, and no
  packages from ./node_modules/@types

You can easily test it like:

tc --init

Create a index.d.ts file inside @types/index.d.ts, and put code below in it:

declare interface Foo {
    Bar: string;
}

In the root folder, create a new index.ts file and inside your code-editor (Eg. VSCode), test it:

let foo:Foo;
foo. // you can see code-completion

p.s:
It doesn't matter if you put your code inside @types or not, TypeScript automatically will find them. You can manually define the path for typeRoots as well but don't forget to configure it to looks for @types inside node_modules.


问:
Problems when creating a huge matrix
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

```<code>#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}
</code>```

Thanks in advance for all your help!

答:
You have allocated the array on the stack which is usually have very limited size. For Windows it is about 1Mb by default.

You can allocate the array on the heap instead.

Title: Problems when creating a huge matrix

Body:
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}

Thanks in advance for all your help!