问:
Why the Task.Run give errors?
I tried to follow this tutorial video : https://www.youtube.com/watch?v=ae1_6ELGVYw

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private Task ProcessData(List<string> list, IProgress<ProgressReport> progress)
        {
            int index = 1;
            int totalProcess = list.Count;
            var progressReport = new ProgressReport();

            return Task.Run()) =>
            {

            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private async void btnStart_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            for(int i = 0; i < 1000; i++)
            {
                list.Add(i.ToString());
            }
            lblStatus.Text = "Working...";
            var progress = new Progress<ProgressReport>();
            progress.ProgressChanged += (o, report) =>
            {
                lblStatus.Text = string.Format("Processing...{0}%", report.PercentComplete);
                progressBar.Value = report.PercentComplete;
                progressBar.Update();
            };

            await ProcessData(list, progress);
            lblStatus.Text = "Done !";
        }
    }
}
</code>```

I'm using visual studio 2019 and project target .NET Framework 4.7.2

I'm getting error on the Run :

No overload for method 'Run' takes 0 arguments

but in the video Task.Run is empty without errors.

And error on the closing : });

} Expected

答:
Looking at your code you got mixed up with the parenthesis here:

```<code> return Task.Run(() =>  // should be () => {}
            {

            });
</code>```

What this syntax means is that () => {} is a Action delegate which Encapsulates a method that has a single parameter and does not return a value. (see here: https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=netcore-3.1)

In C# you can declare and pass them as variables, e.g.

```<code>var myFunc = () => { Console.WriteLine("test"); };

Task.Run(myFunc);
</code>```

Title: Why the Task.Run give errors?

Body:
I tried to follow this tutorial video : https://www.youtube.com/watch?v=ae1_6ELGVYw

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private Task ProcessData(List<string> list, IProgress<ProgressReport> progress)
        {
            int index = 1;
            int totalProcess = list.Count;
            var progressReport = new ProgressReport();

            return Task.Run()) =>
            {

            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private async void btnStart_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            for(int i = 0; i < 1000; i++)
            {
                list.Add(i.ToString());
            }
            lblStatus.Text = "Working...";
            var progress = new Progress<ProgressReport>();
            progress.ProgressChanged += (o, report) =>
            {
                lblStatus.Text = string.Format("Processing...{0}%", report.PercentComplete);
                progressBar.Value = report.PercentComplete;
                progressBar.Update();
            };

            await ProcessData(list, progress);
            lblStatus.Text = "Done !";
        }
    }
}

I'm using visual studio 2019 and project target .NET Framework 4.7.2

I'm getting error on the Run :

No overload for method 'Run' takes 0 arguments

but in the video Task.Run is empty without errors.

And error on the closing : });

} Expected

Body:
Looking at your code you got mixed up with the parenthesis here:

 return Task.Run(() =>  // should be () => {}
            {

            });

What this syntax means is that () => {} is a Action delegate which Encapsulates a method that has a single parameter and does not return a value. (see here: https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=netcore-3.1)

In C# you can declare and pass them as variables, e.g.

var myFunc = () => { Console.WriteLine("test"); };

Task.Run(myFunc);


来源: stackexchange

问:
In Python: How can i get my code to print out all the possible words I can spell based on my input?
I think I was close to figuring out how to print out all the possible words based on user input from my set dictionary. it's based on the assumption that the user input is 'ART' so the possible words I have in my dictionary are ART, RAT, TART, and TAR but only the three letter combinations are printing out. can anyone tell me where I am going wrong? Thanks!</p>

```<code>Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)

def characters(word):
    Dictionary = {}
    for i in word:
        Dictionary[i] = Dictionary.get(i, 0) + 1
    return Dictionary

def all_words(StoredLetters, wordSet):
    for word in StoredLetters:
        flag = 1
        words = characters(word)
        for key in words:
            if key not in wordSet:
                flag = 0
            else:
                if wordSet.count(key) != words[key]:
                    flag = 0
        if flag == 1:
            print(word)
if __name__ == "__main__":
    print(all_words(Dictionary, StoredLetters))
</code>```

答:
Based on the follow-up comments, the rule is that we must use all characters in the target word, but we can use each character as many times as we want.

I'd set up the lookup "dictionary" data structure as a Python dict which maps sorted, unique characters as tuples in each dictionary word to a list of the actual words that can be formed from those characters.

Next, I'd handle the lookups as follows:

Sort the unique characters of the user input (target word) and index into the dictionary to get the list of words it could make. Using a set means that we allow repetition and sorting the characters means we normalize for all of the possible permutations of those letters.

The above alone can give false positives, so we filter the resulting word list to remove any actual result words that are shorter than the target word. This ensures that we handle a target word like "artt" correctly and prevent it from matching "art".

Code:

```<code>from collections import defaultdict

class Dictionary:
    def __init__(self, words):
        self.dictionary = defaultdict(list)

        for word in words:
            self.dictionary[tuple(sorted(set(word)))].append(word)

    def search(self, target):
        candidates = self.dictionary[tuple(sorted(set(target)))]
        return [x for x in candidates if len(x) >= len(target)]

if __name__ == "__main__":
    dictionary = Dictionary(["tar", "art", "tart", "rat"])
    tests = ["art", "artt", "ar", "arttt", "aret"]

    for test in tests:
        print(f"{test}\t=> {dictionary.search(test)}")
</code>```

Output:

art     => ['tar', 'art', 'tart', 'rat']
artt    => ['tart']
ar      => []
arttt   => []
aret    => []
```

The issues in the original code have been addressed nicely in the other answers. The logic doesn't seem clear since it's comparing characters to words and variable names often don't match the logic represented by the code.

It's fine to use a frequency counter, but you'll be stuck iterating over the dictionary, and you'll need to check that each count of a character in a dictionary word is greater than the corresponding count in the target word. I doubt the code I'm offering is optimal, but it should be much faster than the counter approach, I think.

ContentLicense: CC BY-SA 4.0

Body:
I think I was close to figuring out how to print out all the possible words based on user input from my set dictionary. it's based on the assumption that the user input is 'ART' so the possible words I have in my dictionary are ART, RAT, TART, and TAR but only the three letter combinations are printing out. can anyone tell me where I am going wrong? Thanks!

Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)

def characters(word):
    Dictionary = {}
    for i in word:
        Dictionary[i] = Dictionary.get(i, 0) + 1
    return Dictionary

def all_words(StoredLetters, wordSet):
    for word in StoredLetters:
        flag = 1
        words = characters(word)
        for key in words:
            if key not in wordSet:
                flag = 0
            else:
                if wordSet.count(key) != words[key]:
                    flag = 0
        if flag == 1:
            print(word)
if __name__ == "__main__":
    print(all_words(Dictionary, StoredLetters))

Body:
Based on the follow-up comments, the rule is that we must use all characters in the target word, but we can use each character as many times as we want.

I'd set up the lookup "dictionary" data structure as a Python dict which maps sorted, unique characters as tuples in each dictionary word to a list of the actual words that can be formed from those characters.

Next, I'd handle the lookups as follows:

Sort the unique characters of the user input (target word) and index into the dictionary to get the list of words it could make. Using a set means that we allow repetition and sorting the characters means we normalize for all of the possible permutations of those letters.

The above alone can give false positives, so we filter the resulting word list to remove any actual result words that are shorter than the target word. This ensures that we handle a target word like "artt" correctly and prevent it from matching "art".

Code:

from collections import defaultdict

class Dictionary:
    def __init__(self, words):
        self.dictionary = defaultdict(list)

        for word in words:
            self.dictionary[tuple(sorted(set(word)))].append(word)

    def search(self, target):
        candidates = self.dictionary[tuple(sorted(set(target)))]
        return [x for x in candidates if len(x) >= len(target)]

if __name__ == "__main__":
    dictionary = Dictionary(["tar", "art", "tart", "rat"])
    tests = ["art", "artt", "ar", "arttt", "aret"]

    for test in tests:
        print(f"{test}\t=> {dictionary.search(test)}")

Output:

art     => ['tar', 'art', 'tart', 'rat']
artt    => ['tart']
ar      => []
arttt   => []
aret    => []

The issues in the original code have been addressed nicely in the other answers. The logic doesn't seem clear since it's comparing characters to words and variable names often don't match the logic represented by the code.

It's fine to use a frequency counter, but you'll be stuck iterating over the dictionary, and you'll need to check that each count of a character in a dictionary word is greater than the corresponding count in the target word. I doubt the code I'm offering is optimal, but it should be much faster than the counter approach, I think.


问:
group zipcode by duplicates and count
I want to group the zipcode by duplicate values. I have an array of zipcodes that contains duplicates.

```<code>var ArrayOfZipCodes = [{"zipCode" : "12345"},{"zipCode" : "24567"}, {"zipCode" : "24567"},
       {"zipCode" : "24567"} , {"zipCode" : "02895"} , {"zipCode" : "02861"} , {"zipCode" : "02895"}]
</code>```

Output Needed:

```<code>sorting the zipCodes and then grouping it.

var finalOutput = [{"zipCode" : "12345", from: "1"},{"zipCode" : "24567", from: "2 - 4"},
           {"zipCode" : "02861", from: "5"}, {"zipCode" : "02895", from: "6-7"} ]
</code>```

Here is my implementation:

```<code>ArrayOfZipCodes.sort(function(a, b) {
    return a['zipCode'] - b['zipCode'];
});

ArrayOfZipCodes.forEach((item, index) => (item['id'] = index + 1));

const lookup = zipCodes.reduce((a, e) => {
    a[e['zipCode']] = ++a[e['zipCode']] || 0;
    return a;
}, {});

let group = ArrayOfZipCodes.filter(e => lookup[e['zipCode']]);

const filteredArr = group.reduce((acc, current, currentIndex, array) => {
    const x = acc.find(item => item['zipCode'] === current['zipCode']);
    if (x) {
        acc[0]['from'] = x['id'] + "-" + (array.length + 1);
    }
    return acc.concat([current]);

}, []);

var uniq = {}

var arrFiltered = ArrayOfZipCodes.filter(obj => !uniq[obj['zipCode']] && (uniq[obj['zipCode']] = true));

let finalArr = arrFiltered.concat(filteredArr);
console.log("finalArr", finalArr)
</code>```

When I run, I get, [circular object Object] and not the mentioned above output.

答:
I think this should do what you're looking for.

const arrayOfZipCodes = [
  {zipCode: "12345"},
  {zipCode: "24567"},
  {zipCode: "24567"},
  {zipCode: "24567"},
  {zipCode: "02895"},
  {zipCode: "02861"},
  {zipCode: "02895"},
];

const sortedZipCodes = arrayOfZipCodes.map(z => z.zipCode).sort();

const output = [...new Set(sortedZipCodes)].map(zipCode => {
  const first = sortedZipCodes.indexOf(zipCode);
  const last = sortedZipCodes.lastIndexOf(zipCode);
  const from = first === last ? `${first}` : `${first} - ${last}`;
  return {zipCode, from};
});

console.log(output);```

Title: group zipcode by duplicates and count

Body:
I want to group the zipcode by duplicate values. I have an array of zipcodes that contains duplicates.

var ArrayOfZipCodes = [{"zipCode" : "12345"},{"zipCode" : "24567"}, {"zipCode" : "24567"},
       {"zipCode" : "24567"} , {"zipCode" : "02895"} , {"zipCode" : "02861"} , {"zipCode" : "02895"}]

Output Needed:

sorting the zipCodes and then grouping it.

var finalOutput = [{"zipCode" : "12345", from: "1"},{"zipCode" : "24567", from: "2 - 4"},
           {"zipCode" : "02861", from: "5"}, {"zipCode" : "02895", from: "6-7"} ]

Here is my implementation:

ArrayOfZipCodes.sort(function(a, b) {
    return a['zipCode'] - b['zipCode'];
});

ArrayOfZipCodes.forEach((item, index) => (item['id'] = index + 1));

const lookup = zipCodes.reduce((a, e) => {
    a[e['zipCode']] = ++a[e['zipCode']] || 0;
    return a;
}, {});

let group = ArrayOfZipCodes.filter(e => lookup[e['zipCode']]);

const filteredArr = group.reduce((acc, current, currentIndex, array) => {
    const x = acc.find(item => item['zipCode'] === current['zipCode']);
    if (x) {
        acc[0]['from'] = x['id'] + "-" + (array.length + 1);
    }
    return acc.concat([current]);

}, []);

var uniq = {}

var arrFiltered = ArrayOfZipCodes.filter(obj => !uniq[obj['zipCode']] && (uniq[obj['zipCode']] = true));

let finalArr = arrFiltered.concat(filteredArr);
console.log("finalArr", finalArr)

When I run, I get, [circular object Object] and not the mentioned above output.


问:
How to Change GridView Column Color Based on Column Header
How to change GridView column color based on column header in asp.net (vb.net)?
For example, when column header have text starts with "GT_" is will be red for the whole column, whereas header with "CF_" will be green.</p>

答:
Use rowdatabound event like this:

```<code>protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
   {
     DataRowView drv = (DataRowView)e.Row.DataItem;
     for (int i = 0; i < drv.DataView.Table.Columns.Count; i++)
     {
       if (drv.DataView.Table.Columns[i].ColumnName.StartsWith("GT_"))
        {
          e.Row.Cells[i].BackColor = System.Drawing.Color.LawnGreen;
          grdAdd.Columns[i].HeaderStyle.BackColor = System.Drawing.Color.Khaki;
        }
     }
  }
}
</code>```

Output Here

Body:
Use rowdatabound event like this:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
   {
     DataRowView drv = (DataRowView)e.Row.DataItem;
     for (int i = 0; i < drv.DataView.Table.Columns.Count; i++)
     {
       if (drv.DataView.Table.Columns[i].ColumnName.StartsWith("GT_"))
        {
          e.Row.Cells[i].BackColor = System.Drawing.Color.LawnGreen;
          grdAdd.Columns[i].HeaderStyle.BackColor = System.Drawing.Color.Khaki;
        }
     }
  }
}

Output Here


问:
RewriteCond %{REQUEST_FILENAME} !-f not working
I wrote the following rules to redirect to lowercase url if any character in the url is upper case

```<code>RewriteMap lc int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule . https://www.example.com${lc:%{REQUEST_URI}} [R=301,L]
</code>```

The above rule can redirect https://www.example.com/HelloWorld to https://www.example.com/helloworld

This above rule worked perfectly but then I wanted to defer the lowercasing for all urls which corresponds to actual file urls. For example I wanted to defer the above rule for

https://www.example.com/ABC.png if ABC.png file actually exists on the server.

To do this I added the line RewriteCond %{REQUEST_FILENAME} !-f as below

```<code>RewriteMap lc int:tolower
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule . https://www.example.com${lc:%{REQUEST_URI}} [R=301,L]
</code>```

Despite the above change https://www.example.com/ABC.png is getting redirected to ttps://www.example.com/abc.png. This should be very straight forward but its not working.

答:
Fixed it. When you are using RewriteCond %{REQUEST_FILENAME} !-f in the context of virtual host you should write it as RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f. So the overall rule will be in this case

```<code>RewriteMap lc int:tolower
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule . https://www.example.com${lc:%{REQUEST_URI}} [R=301,L]
</code>```

Body:
I wrote the following rules to redirect to lowercase url if any character in the url is upper case

RewriteMap lc int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule . https://www.example.com${lc:%{REQUEST_URI}} [R=301,L]

The above rule can redirect https://www.example.com/HelloWorld to https://www.example.com/helloworld

This above rule worked perfectly but then I wanted to defer the lowercasing for all urls which corresponds to actual file urls. For example I wanted to defer the above rule for

https://www.example.com/ABC.png if ABC.png file actually exists on the server.

To do this I added the line RewriteCond %{REQUEST_FILENAME} !-f as below

RewriteMap lc int:tolower
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule . https://www.example.com${lc:%{REQUEST_URI}} [R=301,L]

Despite the above change https://www.example.com/ABC.png is getting redirected to ttps://www.example.com/abc.png. This should be very straight forward but its not working.

Body:
Fixed it. When you are using RewriteCond %{REQUEST_FILENAME} !-f in the context of virtual host you should write it as RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f. So the overall rule will be in this case

RewriteMap lc int:tolower
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule . https://www.example.com${lc:%{REQUEST_URI}} [R=301,L]


问:
DropDownList can't bind to DbNull
I have a DropDownList trying to bind to DbNull and it's not happy about it. I've seen advice about creating a ListItem with value=" " but this isn't working.

Any help would be much appreciated.

答:
It shouldn't work to bound DBNull while the other items are e.g. of type int.
With a white space or empty string I got problems too. So best way would be to change your DBNull entry with a constant value, that would not appear in your database and have the same data type like the other entries, for example -1.</p>

ContentLicense: CC BY-SA 3.0

Title: DropDownList can't bind to DbNull


问:
Getting latest lines of streaming stdout from a Python subprocess
My goal : To read the latest "chunk" (N lines) of streaming stdout every M seconds from a subprocess.

Current code:

start the subprocess

reads stdout

once I have a chunk of N lines, print it out (or save as current chunk)

wait M seconds

repeat

I have also put code for the moment to terminate the subprocess (which is an endless stream until you hit Ctrl-C)

What I want to achieve is after I wait for M seconds, if for it to always read the latest N lines and not the subsequent N lines in stdout (they can be discarded as I'm only interested in the latest)

My end goal would be to spawn a thread to run the process and keep saving the latest lines and then call from the main process whenever I need the latest results of the stream.

Any help would be greatly appreciated!

```<code>#!/usr/bin/env python3
import signal
import time
from subprocess import Popen, PIPE

sig = signal.SIGTERM

N=9
M=5

countlines=0
p = Popen(["myprogram"], stdout=PIPE, bufsize=1, universal_newlines=True)

chunk=[]

for line in p.stdout:
    countlines+=1
    chunk.append(line)

    if len(chunk)==N:
        print(chunk)
        chunk=[]
        time.sleep(M)

    if countlines>100:
        p.send_signal(sig)
        break

print("done")
</code>```

答:
After much searching, I stumbled upon a solution here:

https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/

Eli's "Launch, interact, get output in real time, terminate" code section worked for me.
So far its the most elegant solution I've found.

Adapted to my problem above, and written within a class (not shown here):

```<code>def output_reader(self,proc):
    chunk=[]
    countlines=0
    for line in iter(proc.stdout.readline, b''):
        countlines+=1
        chunk.append(line.decode("utf-8"))
        if countlines==N:
            self.current_chunk = chunk
            chunk=[]
            countlines=0

def main():
    proc = subprocess.Popen(['myprocess'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    t = threading.Thread(target=output_reader, args=(proc,))
    t.start()

    try:
        time.sleep(0.2)
        for i in range(10):
            time.sleep(1) # waits a while before getting latest lines
            print(self.current_chunk)
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=0.2)
            print('== subprocess exited with rc =', proc.returncode)
        except subprocess.TimeoutExpired:
            print('subprocess did not terminate in time')
    t.join()
</code>```

Body:
My goal : To read the latest "chunk" (N lines) of streaming stdout every M seconds from a subprocess.

Current code:

start the subprocess

reads stdout

once I have a chunk of N lines, print it out (or save as current chunk)

wait M seconds

repeat

I have also put code for the moment to terminate the subprocess (which is an endless stream until you hit Ctrl-C)

What I want to achieve is after I wait for M seconds, if for it to always read the latest N lines and not the subsequent N lines in stdout (they can be discarded as I'm only interested in the latest)

My end goal would be to spawn a thread to run the process and keep saving the latest lines and then call from the main process whenever I need the latest results of the stream.

Any help would be greatly appreciated!

#!/usr/bin/env python3
import signal
import time
from subprocess import Popen, PIPE

sig = signal.SIGTERM

N=9
M=5

countlines=0
p = Popen(["myprogram"], stdout=PIPE, bufsize=1, universal_newlines=True)

chunk=[]

for line in p.stdout:
    countlines+=1
    chunk.append(line)

    if len(chunk)==N:
        print(chunk)
        chunk=[]
        time.sleep(M)

    if countlines>100:
        p.send_signal(sig)
        break

print("done")

Body:
After much searching, I stumbled upon a solution here:

https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/

Eli's "Launch, interact, get output in real time, terminate" code section worked for me.
So far its the most elegant solution I've found.

Adapted to my problem above, and written within a class (not shown here):

def output_reader(self,proc):
    chunk=[]
    countlines=0
    for line in iter(proc.stdout.readline, b''):
        countlines+=1
        chunk.append(line.decode("utf-8"))
        if countlines==N:
            self.current_chunk = chunk
            chunk=[]
            countlines=0

def main():
    proc = subprocess.Popen(['myprocess'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    t = threading.Thread(target=output_reader, args=(proc,))
    t.start()

    try:
        time.sleep(0.2)
        for i in range(10):
            time.sleep(1) # waits a while before getting latest lines
            print(self.current_chunk)
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=0.2)
            print('== subprocess exited with rc =', proc.returncode)
        except subprocess.TimeoutExpired:
            print('subprocess did not terminate in time')
    t.join()


问:
testing conditional rendering that relies on state using react testing library
What would be the way to test a component that relies on the initial state for conditional rendering ?

For example showLessFlag is dependent on state, and testing state in react-testing-library is counter productive.

so how would i test this condition in the CommentList component

```<code>{showLessFlag === true ? (
    // will show most recent comments below
    showMoreComments()
) : (
    <Fragment>
        {/* filter based on first comment, this shows by default */}
        {filterComments.map((comment, i) => (
            <div key={i} className="comment">
                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
            </div>
        ))}
    </Fragment>
)}
</code>```

Should it be test like the following

```<code>  it("should check more comments", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-show-more");
        expect(commentList).toBeNull();
    });
</code>```

But im getting this error because of the conditional rendering

TestingLibraryElementError: Unable to find an element by:
  [data-testid="comment-show-more"]

CommentList.tsx

```<code>import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";

function CommentList(props: any, ref: Ref<HTMLDivElement>) {
    const [showMore, setShowMore] = useState<Number>(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 2 && inc <= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () => {
        setOpenModal(true);
    };
    const handleCloseModal = () => {
        setOpenModal(false);
    };

    const showLessComments = (e) => {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) => {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) => {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () => {
        return filterComments.map((comment, i) => (
            <div data-testid="comment-show-more" key={i} className="comment">
                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
            </div>
        ));
    };

    return (
        <Grid data-testid="comment-list-div">
            <Fragment>
                <div style={{ margin: "30px 0px" }}>
                    {props.comments.length > 2 ? (
                        <Fragment>
                            {min !== -1 && min !== -2 ? (
                                <Fragment>
                                    {min !== 0 ? (
                                        <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                                            View {min !== -1 && min !== -2 ? min : 0} More Comments
                                        </OurSecondaryButton>
                                    ) : (
                                        <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                            Show Less Comments
                                        </OurSecondaryButton>
                                    )}
                                </Fragment>
                            ) : (
                                <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                    Show Less Comments
                                </OurSecondaryButton>
                            )}
                        </Fragment>
                    ) : null}
                </div>
            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) => (
                        <div key={i} className="comment">
                            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
                        </div>
                    ))}
                </Fragment>
            )}
        </Grid>
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
</code>```

CommentList.test.tsx

```<code>import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {
        current: undefined,
    },
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });

    it("should render first comment", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.firstChild).toBeTruthy();
    });

    it("should render second child", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.lastChild).toBeTruthy();
    });

    it("should check comments", () => {
        const rtl = render(<CommentList {...props} />);

        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();

        expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
    });
    it("should match snapshot", () => {
        const rtl = render(<CommentList {...props} />);
        expect(rtl).toMatchSnapshot();
    });

    it("should check more comments", () => {
      const { getByTestId } = render(<CommentList {...props} />);
      const commentList = getByTestId("comment-show-more");
      expect(commentList).toBeNull();
    });
});
</code>```

答:
Any getBy* query in react-testing-library will throw an error if no match is found. If you want to test/assert the absence of an element then you want to use any of the queryBy* queries, they return null if no match is found.

Queries

```<code>it("should check more comments", () => {
  const { queryByTestId } = render(<CommentList {...props} />);
  const commentList = queryByTestId("comment-show-more");
  expect(commentList).toBeNull();
});
</code>```

Body:
What would be the way to test a component that relies on the initial state for conditional rendering ?

For example showLessFlag is dependent on state, and testing state in react-testing-library is counter productive.

so how would i test this condition in the CommentList component

{showLessFlag === true ? (
    // will show most recent comments below
    showMoreComments()
) : (
    <Fragment>
        {/* filter based on first comment, this shows by default */}
        {filterComments.map((comment, i) => (

                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

        ))}
    </Fragment>
)}

Should it be test like the following

  it("should check more comments", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-show-more");
        expect(commentList).toBeNull();
    });

But im getting this error because of the conditional rendering

TestingLibraryElementError: Unable to find an element by:
  [data-testid="comment-show-more"]

CommentList.tsx

import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";

function CommentList(props: any, ref: Ref<HTMLDivElement>) {
    const [showMore, setShowMore] = useState<Number>(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 2 && inc <= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () => {
        setOpenModal(true);
    };
    const handleCloseModal = () => {
        setOpenModal(false);
    };

    const showLessComments = (e) => {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) => {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) => {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () => {
        return filterComments.map((comment, i) => (

                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

        ));
    };

    return (
        <Grid data-testid="comment-list-div">
            <Fragment>

                    {props.comments.length > 2 ? (
                        <Fragment>
                            {min !== -1 && min !== -2 ? (
                                <Fragment>
                                    {min !== 0 ? (
                                        <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                                            View {min !== -1 && min !== -2 ? min : 0} More Comments
                                        </OurSecondaryButton>
                                    ) : (
                                        <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                            Show Less Comments
                                        </OurSecondaryButton>
                                    )}
                                </Fragment>
                            ) : (
                                <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                    Show Less Comments
                                </OurSecondaryButton>
                            )}
                        </Fragment>
                    ) : null}

            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) => (

                            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

                    ))}
                </Fragment>
            )}
        </Grid>
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;

CommentList.test.tsx

import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {
        current: undefined,
    },
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });

    it("should render first comment", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.firstChild).toBeTruthy();
    });

    it("should render second child", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.lastChild).toBeTruthy();
    });

    it("should check comments", () => {
        const rtl = render(<CommentList {...props} />);

        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
        expect(rtl.getByTestId("comment-list-div")).toBeTruthy();

        expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
    });
    it("should match snapshot", () => {
        const rtl = render(<CommentList {...props} />);
        expect(rtl).toMatchSnapshot();
    });

    it("should check more comments", () => {
      const { getByTestId } = render(<CommentList {...props} />);
      const commentList = getByTestId("comment-show-more");
      expect(commentList).toBeNull();
    });
});

Body:
Any getBy* query in react-testing-library will throw an error if no match is found. If you want to test/assert the absence of an element then you want to use any of the queryBy* queries, they return null if no match is found.

Queries

it("should check more comments", () => {
  const { queryByTestId } = render(<CommentList {...props} />);
  const commentList = queryByTestId("comment-show-more");
  expect(commentList).toBeNull();
});


问:
Can I set the default simulator for new projects in Xcode 7.1 or latest?
I've been making a ton of new projects as I'm learning Swift. My development is all on my laptop, so I hate using the default 6s Plus simulator, since the window is too big to easily see. Is there a way to change the default simulator to be a different one for new projects?</p>

答:
open your simulator, choose **File/Open Device/iOS 13.5/iPhone8 ** will change your simulator device to iPhone 8.
When you reopen your simulator, iPhone 8 will be your device simulator.</p>


问:
Show mean values in boxplots in R
```<code>time_pic <- ggplot(data_box, aes(x=Kind, y=TimeTotal, fill=Sitting_Position)) +
  geom_boxplot()

print(time_pic)

time_pic+labs(title="", x="", y = "Time (Sec)")
</code>```

I ran the above codes to get the following image. But I don't know how to add average value for each boxplot on this image.

updated.
I tried this.

```<code>means <- aggregate(TimeTotal ~ Sitting_Position*Kind, data_box, mean)
ggplot(data=data_box, aes(x=Kind, y=TimeTotal, fill=Sitting_Position)) +
  geom_boxplot() +
  stat_summary(fun=mean, colour="darkred", geom="point", shape=18, size=3,show_guide = FALSE) +
  geom_text(data = means, aes(label = TimeTotal, y = TimeTotal + 0.08))
</code>```

This is what it looks like now. Two dots are on the same line. And two values are overlapping with each other.

答:
As others said, you can share your dataset for more specific help, but in this case I think the point can be made using a dummy dataset.  I'm creating one that looks pretty similar to your own in terms of naming, so theoretically you can just plug in this code and it could work.

The biggest thing you need here is to control how ggplot2 is separating the separate boxplots for the data_box$Sitting_Position that share the same data_box$Kind.  The process of separating and spreading the boxes around that x= axis value is called "dodging".  When you supply a fill= or color= (or other) aesthetic in aes() for that geom, ggplot2 knows enough that it will assume you also want to group the data according to that value.  So, your initial ggplot() call has in aes() that fill=Sitting_Position, which means that geom_boxplot() "works" - it creates the separate boxes that are colored differently and which are "dodged" properly.

When you create the points and the text, ggplot2 has no idea that you want to "dodge" this data, and even if you did want to dodge, on what basis to use for the dodge, since the fill= aesthetic doesn't make sense for a text or point geom.  How to fix this?  The answer is to:

Supply a group= aesthetic, which can override the grouping of a fill= or color= aesthetic, but which also can serve as a basis for the dodging for geoms that do not have a similar aesthetic.

Specify more clearly how you want to dodge.  This will be important for accurate positioning of all things you want to dodge.  Otherwise, you will have things dodged, but maybe not the same distance.

Here's how I combined all that:

```<code># the datasets
set.seed(1234)
data_box <- data.frame(
  Kind=c(rep('Model-free AR',100),rep('Real-world',100)),
  TimeTotal=c(rnorm(50,5.5,1),rnorm(50,5.43,1.1),rnorm(50,4.9,1),rnorm(50,4.7,0.2)),
  Sitting_Position=rep(c(rep('face to face',50),rep('side by side',50)),2)
)
means <- aggregate(TimeTotal ~ Sitting_Position*Kind, data_box, mean)

# the plot
ggplot(data_box, aes(x=Kind, y=TimeTotal)) + theme_bw() +

  # specifying dodge here and width to avoid overlapping boxes
  geom_boxplot(
    aes(fill=Sitting_Position),
    position=position_dodge(0.6), width=0.5
  ) +
  # note group aesthetic and same dodge call for next two objects
  stat_summary(
    aes(group=Sitting_Position),
    position=position_dodge(0.6),
    fun=mean,
    geom='point', color='darkred', shape=18, size=3,
    show.legend = FALSE
  ) +
  geom_text(
    data=means,
    aes(label=round(TimeTotal,2), y=TimeTotal + 0.18, group=Sitting_Position),
    position=position_dodge(0.6)
  )
</code>```

Giving you this:

Title: Show mean values in boxplots in R

Body:
time_pic <- ggplot(data_box, aes(x=Kind, y=TimeTotal, fill=Sitting_Position)) +
  geom_boxplot()

print(time_pic)

time_pic+labs(title="", x="", y = "Time (Sec)")

I ran the above codes to get the following image. But I don't know how to add average value for each boxplot on this image.

updated.
I tried this.

means <- aggregate(TimeTotal ~ Sitting_Position*Kind, data_box, mean)
ggplot(data=data_box, aes(x=Kind, y=TimeTotal, fill=Sitting_Position)) +
  geom_boxplot() +
  stat_summary(fun=mean, colour="darkred", geom="point", shape=18, size=3,show_guide = FALSE) +
  geom_text(data = means, aes(label = TimeTotal, y = TimeTotal + 0.08))

This is what it looks like now. Two dots are on the same line. And two values are overlapping with each other.

Body:
As others said, you can share your dataset for more specific help, but in this case I think the point can be made using a dummy dataset.  I'm creating one that looks pretty similar to your own in terms of naming, so theoretically you can just plug in this code and it could work.

The biggest thing you need here is to control how ggplot2 is separating the separate boxplots for the data_box$Sitting_Position that share the same data_box$Kind.  The process of separating and spreading the boxes around that x= axis value is called "dodging".  When you supply a fill= or color= (or other) aesthetic in aes() for that geom, ggplot2 knows enough that it will assume you also want to group the data according to that value.  So, your initial ggplot() call has in aes() that fill=Sitting_Position, which means that geom_boxplot() "works" - it creates the separate boxes that are colored differently and which are "dodged" properly.

When you create the points and the text, ggplot2 has no idea that you want to "dodge" this data, and even if you did want to dodge, on what basis to use for the dodge, since the fill= aesthetic doesn't make sense for a text or point geom.  How to fix this?  The answer is to:

Supply a group= aesthetic, which can override the grouping of a fill= or color= aesthetic, but which also can serve as a basis for the dodging for geoms that do not have a similar aesthetic.

Specify more clearly how you want to dodge.  This will be important for accurate positioning of all things you want to dodge.  Otherwise, you will have things dodged, but maybe not the same distance.

Here's how I combined all that:

# the datasets
set.seed(1234)
data_box <- data.frame(
  Kind=c(rep('Model-free AR',100),rep('Real-world',100)),
  TimeTotal=c(rnorm(50,5.5,1),rnorm(50,5.43,1.1),rnorm(50,4.9,1),rnorm(50,4.7,0.2)),
  Sitting_Position=rep(c(rep('face to face',50),rep('side by side',50)),2)
)
means <- aggregate(TimeTotal ~ Sitting_Position*Kind, data_box, mean)

# the plot
ggplot(data_box, aes(x=Kind, y=TimeTotal)) + theme_bw() +

  # specifying dodge here and width to avoid overlapping boxes
  geom_boxplot(
    aes(fill=Sitting_Position),
    position=position_dodge(0.6), width=0.5
  ) +
  # note group aesthetic and same dodge call for next two objects
  stat_summary(
    aes(group=Sitting_Position),
    position=position_dodge(0.6),
    fun=mean,
    geom='point', color='darkred', shape=18, size=3,
    show.legend = FALSE
  ) +
  geom_text(
    data=means,
    aes(label=round(TimeTotal,2), y=TimeTotal + 0.18, group=Sitting_Position),
    position=position_dodge(0.6)
  )

Giving you this:


问:
Adding react-helmet into my Gatsby project causes an error: Element type is invalid
I have a component Layout which I used to style the layout of my app and that's where I introduced react-helmet

The component is like this

import React from 'react';
import { Global, css } from '@emotion/core';
import Helmet from 'react-helmet';
import Header from '../components/header';

const Layout = ({ children }) => (
  <>
    <Global
      styles={css`
        // some CSS style
    />

    <Helmet>

      <title>title</title>
      <meta name="description" content="site description" />
    </Helmet>

      {children}

  </>
);

export default Layout;
```

After I added <Helmet />, I have this error poppin up. And if I removed <Helmet /> from my component, the error would be gone. apparently I didn't forgot to export my Layout component so I really have no idea where this came from.

答:
You need to use named import with react-helmet.

```<code>import {Helmet} from "react-helmet";
</code>```

Docs: https://github.com/nfl/react-helmet#example

Body:
I have a component Layout which I used to style the layout of my app and that's where I introduced react-helmet

The component is like this

import React from 'react';
import { Global, css } from '@emotion/core';
import Helmet from 'react-helmet';
import Header from '../components/header';

const Layout = ({ children }) => (
  <>
    <Global
      styles={css`
        // some CSS style
    />

    <Helmet>

      <title>title</title>
      <meta name="description" content="site description" />
    </Helmet>

      {children}

  </>
);

export default Layout;

After I added <Helmet />, I have this error poppin up. And if I removed <Helmet /> from my component, the error would be gone. apparently I didn't forgot to export my Layout component so I really have no idea where this came from.

Body:
You need to use named import with react-helmet.

import {Helmet} from "react-helmet";

Docs: https://github.com/nfl/react-helmet#example


问:
Data not insert in MySQL databae
I'm Try to connect with MySQL database with qt by using this code. I'm successfully Build the MySQL plugin for Qt.  But when I try insert data QT it display message box data not inserted. Is any problem with query or something?

This is register.h

```<code>#ifndef REGISTER_H
#define REGISTER_H

#include <QDialog>
#include <QtSql>
#include <QSqlDatabase>
#include <QMessageBox>

namespace Ui {
class Register;
}

 class Register : public QDialog
  {
   Q_OBJECT

public:
explicit Register(QWidget *parent = nullptr);
~Register();

 private slots:
   void on_pushButton_clicked();

private:
  Ui::Register *ui;
   QSqlDatabase database;
};

 #endif
</code>```

and this is register.cpp

```<code>    #include "register.h"
#include "ui_register.h"

Register::Register(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
}

Register::~Register()
{
    delete ui;
}

void Register::on_pushButton_clicked()
{
    //database connection
    database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName("localhost");
    database.setUserName("root");
    database.setPassword("");
    database.setDatabaseName("electricity");

    if(database.open()){

                QString username = ui ->lineEdit ->text();
                QString password = ui ->lineEdit_2 ->text();
                QString fullname = ui ->lineEdit_3 ->text();
                QString adress = ui ->lineEdit_4 ->text();
                QString telephone = ui ->lineEdit_5 ->text();

                // insert query
                QSqlQuery qry;

                qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
                            "VALUES (:username, :password, :fullname, :adress, :telephone)");

                qry.bindValue(":lineEdit", username);
                qry.bindValue(":lineEdit_2", password);
                qry.bindValue(":lineEdit_3", fullname);
                qry.bindValue(":lineEdit_4", adress);
                qry.bindValue(":lineEdit_5", telephone);

                if(qry.exec()){

                QMessageBox::information(this, "Data Insetrted", "Data Enter sucess");
                }

                else {
                            QMessageBox::information(this, "Data not inserted", "Not Sucessfully");
                }

    }
                else{

                QMessageBox::information(this, "ERROR","Database Not Connected Sucessfully. Please CheckYyour Internet Connection");

}

}
</code>```

I got This error. Is anything have to modified?

答:
You are using the wrong names to bind to

```<code>qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
                        "VALUES (:username, :password, :fullname, :adress, :telephone)");

qry.bindValue(":lineEdit", username);
</code>```

should be

```<code>qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
                        "VALUES (:username, :password, :fullname, :adress, :telephone)");

qry.bindValue(":username", username);
</code>```

etc. etc.

The name used in bindValue should match the name used in the query.

Title: Data not insert in MySQL databae

Body:
I'm Try to connect with MySQL database with qt by using this code. I'm successfully Build the MySQL plugin for Qt.  But when I try insert data QT it display message box data not inserted. Is any problem with query or something?

This is register.h

#ifndef REGISTER_H
#define REGISTER_H

#include <QDialog>
#include <QtSql>
#include <QSqlDatabase>
#include <QMessageBox>

namespace Ui {
class Register;
}

 class Register : public QDialog
  {
   Q_OBJECT

public:
explicit Register(QWidget *parent = nullptr);
~Register();

 private slots:
   void on_pushButton_clicked();

private:
  Ui::Register *ui;
   QSqlDatabase database;
};

 #endif

and this is register.cpp

    #include "register.h"
#include "ui_register.h"

Register::Register(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
}

Register::~Register()
{
    delete ui;
}

void Register::on_pushButton_clicked()
{
    //database connection
    database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName("localhost");
    database.setUserName("root");
    database.setPassword("");
    database.setDatabaseName("electricity");

    if(database.open()){

                QString username = ui ->lineEdit ->text();
                QString password = ui ->lineEdit_2 ->text();
                QString fullname = ui ->lineEdit_3 ->text();
                QString adress = ui ->lineEdit_4 ->text();
                QString telephone = ui ->lineEdit_5 ->text();

                // insert query
                QSqlQuery qry;

                qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
                            "VALUES (:username, :password, :fullname, :adress, :telephone)");

                qry.bindValue(":lineEdit", username);
                qry.bindValue(":lineEdit_2", password);
                qry.bindValue(":lineEdit_3", fullname);
                qry.bindValue(":lineEdit_4", adress);
                qry.bindValue(":lineEdit_5", telephone);

                if(qry.exec()){

                QMessageBox::information(this, "Data Insetrted", "Data Enter sucess");
                }

                else {
                            QMessageBox::information(this, "Data not inserted", "Not Sucessfully");
                }

    }
                else{

                QMessageBox::information(this, "ERROR","Database Not Connected Sucessfully. Please CheckYyour Internet Connection");

}

}

I got This error. Is anything have to modified?

Body:
You are using the wrong names to bind to

qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
                        "VALUES (:username, :password, :fullname, :adress, :telephone)");

qry.bindValue(":lineEdit", username);

should be

qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
                        "VALUES (:username, :password, :fullname, :adress, :telephone)");

qry.bindValue(":username", username);

etc. etc.

The name used in bindValue should match the name used in the query.


问:
Error accessing the Cache in the Application_Start method of Global.asax
I am trying to access the Cache in the Application_Start method of Global.asax. I am trying to accdess Context.Cache. When I run the code from visual studio it works just fine but when I run it on the server from IIS I get: Session state is not available in this context. I want to seed some values in the cache when the application starts. How can I get at the cache from Application_Start?</p>

答:
Yes, this changed in IIS7 with the switch to integrated mode. Application_Start executes earlier so the HttpContext is not available.

Visual Studio uses Cassini which differs from full IIS in several ways. Check out the newly released IIS Express which can also be used with Visual Studio. It's a self-contained version of IIS 7.5 so you won't hit problems in production that didn't exist when testing using Cassini.

OwnerDisplayName: minty

ContentLicense: CC BY-SA 2.5


问:
How to publish on Azure AD my MDM App in the MDM and MAM gallery?
We have a MDM solution where clients that utilize Azure AD can join and enroll (to our MDM) Windows 10 devices. The clients configure in their Tenants an On-Premise MDM app (that is selected from the Mobility MDM and MAM app gallery) in order to set and use our MDM.

We would like to have our MDM App showed in that gallery such as the image below. Does anyone can help me and show me some hints to make our MDM to appear in that Gallery?

I know that one step is that our MDM has to have its own Tenant in Azure AD and there create an App (my organization is developing) and set it as Multi-Tenant. But after that I am lost, I don't know what are the next steps.

Thanks in advance.

答:
according to https://learn.microsoft.com/en-us/windows/client-management/mdm/azure-active-directory-integration-with-mdm#publish-your-mdm-app-to-azure-ad-app-gallery

to publish a on-prem based mdm, is no different than adding a normal app to the app gallery, in which case, in which case follow this documentation:
https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/howto-app-gallery-listing

they mention a portal that you can use and request access to submit request.


问:
Check if ActiveRecord::Relation alread includes JOIN
I'm inside method that adds filter (user.type) to my query/relation.

Sometimes if grouping by the user (which needs INNER join to users table in another module) is selected before filtering I receive an error:

PostgreSQL: PG::DuplicateAlias: ERROR: table name "users" specified more than once

Before error happen JOIN is already in query -

```<code>$ pry> relation.to_sql
SELECT \"posts\".* FROM \"posts\"
INNER JOIN users ON users.id = posts.user_id
WHERE \"posts\".\"created_at\" BETWEEN '2019-05-01 00:00:00'
AND '2020-05-01 23:59:59' AND \"users\".\"type\" = 'Guest'"
</code>```

I wanna fix it, by checking if the table is already joined inside my ActiveRecord::Relation object. I added:

```<code>def join_users
  return relation if /JOIN users/.match? relation.to_sql

  relation.joins('LEFT JOIN users ON users.id = posts.user_id')
end
</code>```

This solution works, but I wonder - is there any better way to check if JOIN is inside relation?

答:
Perhaps you can use joins_values, which isn't documented, but is an ActiveRecord_Relation public method that returns an array containing the name of the table the current query (object) is constructed with:

```<code>Post.joins(:user).joins_values # [:user]
Post.all.joins_values          # []
</code>```

Body:
I'm inside method that adds filter (user.type) to my query/relation.

Sometimes if grouping by the user (which needs INNER join to users table in another module) is selected before filtering I receive an error:

PostgreSQL: PG::DuplicateAlias: ERROR: table name "users" specified more than once

Before error happen JOIN is already in query -

$ pry> relation.to_sql
SELECT \"posts\".* FROM \"posts\"
INNER JOIN users ON users.id = posts.user_id
WHERE \"posts\".\"created_at\" BETWEEN '2019-05-01 00:00:00'
AND '2020-05-01 23:59:59' AND \"users\".\"type\" = 'Guest'"

I wanna fix it, by checking if the table is already joined inside my ActiveRecord::Relation object. I added:

def join_users
  return relation if /JOIN users/.match? relation.to_sql

  relation.joins('LEFT JOIN users ON users.id = posts.user_id')
end

This solution works, but I wonder - is there any better way to check if JOIN is inside relation?

Body:
Perhaps you can use joins_values, which isn't documented, but is an ActiveRecord_Relation public method that returns an array containing the name of the table the current query (object) is constructed with:

Post.joins(:user).joins_values # [:user]
Post.all.joins_values          # []


问:
XGBoost - select tree with the highest accuracy
I need to visualize XGBoost's effects and I want to extract a single tree from it that has the highest accuracy on the test set. Is is built in in any way, or do I have to test by hand all of the trees? I'm using the Python version.</p>

答:
If you'd like to inspect individual trees in a tree ensemble model, then you should consider switching from a boosting-type algorithm (eg. XGBoost, LightGBM, GBM) to a bagging-type algorithm (eg. Random Forest).

By definition, the bagging algorithm grows trees in decreasing "smartness" order. In this case, the highest accuracy tree model is probably the first one in the XGBoost tree ensemble.


问:
Unable to echo rows
I have been stuck on something for quite a while now, I am creating a take-away system (pure as self learning). Although i'm trying to keep the learning curve go upwards by browsing the internet and look for solutions but I haven't found a solution for now.

I have two MYSQL tables named ; "Menu_Category" and "Menu_Dishes". I want to have a drop down menu when you're adding a dish, it gives you all the categories from Menu_category.

Menu_Category has the following columns
Cat_id
Category
Comments
Image
State
Created_by
Created_at
Updated_on
Updated_by

Menu_Dishes has the following columns
Dish_id
Dish_name
Dish_price
Dish_comments
Dish_image
Dish_state
Dish_Category

So technically speaking, should a inner join be used or should I twice use SELECT to two different databases? I'm currently completely lost..

```<code>        <?php
        $Category = $db->getValue ("Menu_Category", "Category");
        // select login from users
            echo $Category;
        ?>
</code>```

This echo works and it shows one row, which is logic since the foreach isn't programmed, but I can't seem to get it to work..

Thanks for your help!

Darry

UPDATE

```<code><?php $rows = $db->arraybuilder('Menu_Category');?>
<?php foreach ($rows as $row): ?>
<?php echo $row['Category']; ?>
<?php endforeach; ?>
</code>```

I now have the following error code: Warning: Illegal string offset 'Category' in customers/5/0/d/mardesk.be/httpd.www/new/forms/dishes_form.php

答: There must also be the cat_id value in the menu_dishes table. Then a left join solves the job.</p>

Title: Unable to echo rows

Body:
I have been stuck on something for quite a while now, I am creating a take-away system (pure as self learning). Although i'm trying to keep the learning curve go upwards by browsing the internet and look for solutions but I haven't found a solution for now.

I have two MYSQL tables named ; "Menu_Category" and "Menu_Dishes". I want to have a drop down menu when you're adding a dish, it gives you all the categories from Menu_category.

Menu_Category has the following columns
Cat_id
Category
Comments
Image
State
Created_by
Created_at
Updated_on
Updated_by

Menu_Dishes has the following columns
Dish_id
Dish_name
Dish_price
Dish_comments
Dish_image
Dish_state
Dish_Category

So technically speaking, should a inner join be used or should I twice use SELECT to two different databases? I'm currently completely lost..

        <?php
        $Category = $db->getValue ("Menu_Category", "Category");
        // select login from users
            echo $Category;
        ?>

This echo works and it shows one row, which is logic since the foreach isn't programmed, but I can't seem to get it to work..

Thanks for your help!

Darry

UPDATE

<?php $rows = $db->arraybuilder('Menu_Category');?>
<?php foreach ($rows as $row): ?>
<?php echo $row['Category']; ?>
<?php endforeach; ?>

I now have the following error code: Warning: Illegal string offset 'Category' in customers/5/0/d/mardesk.be/httpd.www/new/forms/dishes_form.php


问:
Why does this code not calculate tax minus income to print take home pay? Tax Lab
It's supposed to be a simple tax lab, but I'm stuck calculating Income - Tax and printing the result. What am I doing wrong?</p>

```<code>package com.company;
import java.util.Scanner;
public class Main {

// IRS Take Home Pay Lab

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        //Get input for filing status

        System.out.println("Please select a filing status Below: \n1 for Single, 2 for Married ");

        int status = input.nextInt();

        //Get input for taxable income

        System.out.println("\nPlease Enter Your Income");

        double income = input.nextDouble();

        //Compute tax

        double tax = computedTaxResult(status, income); // this computes my income and marital status

        // computing take home pay

        //double TakeHomePay = ComputeedTakeHomePay(income, - tax);

        //Output filing status, income, and tax result

        //System.out.printf("\nFiling status: " + status + "\n" + " income: %9.2f" + "\n" + " tax: %12.2f" + "\n" + " TakeHome: %12.2f"); //Frack Try 1

         System.out.printf("\nFiling status: " + status + "\n" + " Your Gross Income is: %9.12f" + "\n" + " You must pay:  %12.2f");

                 System.exit(0);
    }

    public static double computedTaxResult(int status, double income){

        double computedTaxResult = 0;

        if (status == 1) {
            if (income <= 9325)
                computedTaxResult = (income * .10);

            else if (income <= 37950)
                computedTaxResult = (932.50 + (income - 27050) * .15);

            else if (income <= 91900)
                computedTaxResult = (14645.0 + (income - 65550) * .25);

            else if (income <=191650)
                computedTaxResult = (36361 + (income - 136750) * .28);

            else if (income <=416700)
                computedTaxResult = (36361 + (income - 136750) * .33);

            else if (income <=418400)
                computedTaxResult = (36361 + (income - 136750) * .35);

            else computedTaxResult = (121505.25 + (income - 418400) * .39);
        }
        if (status == 2) {
            if (income <= 18650)
                computedTaxResult = (income * .10);

            else if (income <= 75000)
                computedTaxResult = (6780.0 + (income - 45200) * .15);

            else if (income <= 153100)
                computedTaxResult = (24393.75 + (income - 109250) * .25);

            else if (income <= 233350)
                computedTaxResult = (41855 + (income - 166500) * .28);
            else if (income <= 416700)
                computedTaxResult = (52222.50 + (income - 166500) * .33);
            else if (income <= 470700)
                computedTaxResult = (112728 + (income - 166500) * .35);
            else if (income > 470700)
             computedTaxResult = (131628 + (income - 297350) * .396);
        }

        return computedTaxResult;
    }

}
</code>```

答: There does not appear to be an implementation in your code of the following method that returns a double ComputeedTakeHomePay(income, - tax)

Body:
It's supposed to be a simple tax lab, but I'm stuck calculating Income - Tax and printing the result. What am I doing wrong?

package com.company;
import java.util.Scanner;
public class Main {

// IRS Take Home Pay Lab

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        //Get input for filing status

        System.out.println("Please select a filing status Below: \n1 for Single, 2 for Married ");

        int status = input.nextInt();

        //Get input for taxable income

        System.out.println("\nPlease Enter Your Income");

        double income = input.nextDouble();

        //Compute tax

        double tax = computedTaxResult(status, income); // this computes my income and marital status

        // computing take home pay

        //double TakeHomePay = ComputeedTakeHomePay(income, - tax);

        //Output filing status, income, and tax result

        //System.out.printf("\nFiling status: " + status + "\n" + " income: %9.2f" + "\n" + " tax: %12.2f" + "\n" + " TakeHome: %12.2f"); //Frack Try 1

         System.out.printf("\nFiling status: " + status + "\n" + " Your Gross Income is: %9.12f" + "\n" + " You must pay:  %12.2f");

                 System.exit(0);
    }

    public static double computedTaxResult(int status, double income){

        double computedTaxResult = 0;

        if (status == 1) {
            if (income <= 9325)
                computedTaxResult = (income * .10);

            else if (income <= 37950)
                computedTaxResult = (932.50 + (income - 27050) * .15);

            else if (income <= 91900)
                computedTaxResult = (14645.0 + (income - 65550) * .25);

            else if (income <=191650)
                computedTaxResult = (36361 + (income - 136750) * .28);

            else if (income <=416700)
                computedTaxResult = (36361 + (income - 136750) * .33);

            else if (income <=418400)
                computedTaxResult = (36361 + (income - 136750) * .35);

            else computedTaxResult = (121505.25 + (income - 418400) * .39);
        }
        if (status == 2) {
            if (income <= 18650)
                computedTaxResult = (income * .10);

            else if (income <= 75000)
                computedTaxResult = (6780.0 + (income - 45200) * .15);

            else if (income <= 153100)
                computedTaxResult = (24393.75 + (income - 109250) * .25);

            else if (income <= 233350)
                computedTaxResult = (41855 + (income - 166500) * .28);
            else if (income <= 416700)
                computedTaxResult = (52222.50 + (income - 166500) * .33);
            else if (income <= 470700)
                computedTaxResult = (112728 + (income - 166500) * .35);
            else if (income > 470700)
             computedTaxResult = (131628 + (income - 297350) * .396);
        }

        return computedTaxResult;
    }

}


问:
Java for Iphone App Development?
I have been primarily using Java and have experience with it. I want to develop some iphone apps and wanted to know if there a way to develop iphone app using Java or iphone development can be only done using Objective-C?

Also if Objective-C is the only way to go then would really appreciate if you can recommend some books or links where I can get started on Iphone Development, my background is completely based on Java and I have not work with C or C++ professionally in the past.

Any recommendations/suggestions would highly help.

Can we have quick comparison of Objective-C vs Java or its like comparing oranges with Apple, am just trying to get some similarities in objective-c from java perspective so that I have some knowledge to leverage on while learning Objective-C, any suggestions?

答:
From your comments, here is a book found through a quick google search for java developers to learn objective C.  I used other books in this series (Learn Objective-C on the Mac, and Beginning iPhone Development) to learn iPhone development, so I assume it is good.

And here is a link to a well done powerpoint presentation given on comparing Java to Objective-C (about halfway is where the syntax differences start with examples!) as well as some of the cool features of Objective-C.

Title: Java for Iphone App Development?


问:
Can't connect to Oracle 19.3 with 19.3 JDBC driver
We have a project running with an Oracle 19.3 database, and a Java application using the Oracle 19.3 JDBC driver (which is available on Maven Central). On Windows with JRE 1.8, everything is fine, but when I run either on our build server or in WSL Ubuntu with OpenJDK 11.0.3 it refuses to connect to the database. Specifically:

```<code>ERROR: Unexpected error
java.sql.SQLRecoverableException:
Unable to obtain connection from database (jdbc:oracle:thin:@//<host>:<port>/<db>) for user '<user>': IO Error: Invalid argument, Authentication lapse 0 ms.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
SQL State  : 08006
Error Code : 17002
Message    : IO Error: Invalid argument, Authentication lapse 0 ms.

        at JuliasApplication.openConnection(JdbcUtils.java:60)
        ...
Caused by: java.sql.SQLRecoverableException: IO Error: Invalid argument, Authentication lapse 0 ms.
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:874)
        at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:793)
        at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:57)
        at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:747)
        at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:562)
        ...
Caused by: java.io.IOException: Invalid argument, Authentication lapse 0 ms.
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:870)
        ... 12 more
Caused by: java.io.IOException: Invalid argument
        at java.base/sun.nio.ch.SocketChannelImpl.sendOutOfBandData(Native Method)
        at java.base/sun.nio.ch.SocketChannelImpl.sendOutOfBandData(SocketChannelImpl.java:521)
        at java.base/sun.nio.ch.SocketAdaptor.sendUrgentData(SocketAdaptor.java:323)
        at oracle.net.nt.TcpNTAdapter.sendUrgentByte(TcpNTAdapter.java:433)
        at oracle.net.ns.NSProtocolNIO.negotiateConnection(NSProtocolNIO.java:159)
        at oracle.net.ns.NSProtocol.connect(NSProtocol.java:340)
        at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1596)
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:588)
        ... 12 more
</code>```

If I switch in the 18.3 JDBC driver everything is fine in both environments; if I switch in an 18.3 database everything is fine in both environments. That does give us a workaround for now, but it feels very uncomfortable that we don't understand what's going on. And I can't find anything online about an "Authentication lapse". Can anyone see any clues which would explain the failure?

答:
It looks like the underlying Socket implementation is not allowing OOB.
As a workaround, you can disable the OOB check by setting the connection property CONNECTION_PROPERTY_THIN_NET_DISABLE_OUT_OF_BAND_BREAK to "true".
Please refer this link : https://docs.oracle.com/en/database/oracle/oracle-database/20/jajdb/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_THIN_NET_DISABLE_OUT_OF_BAND_BREAK

The link above no longer mentions the "out of band break" issue, so here's some alternatives:

put DISABLE_OOB=on in your sqlnet.ora file, per this article.

for your java apps put -Doracle.net.disableOob=true on the command line

for apps like SQL Developer you can add AddVMOption -Doracle.net.disableOob=true to your sqldeveloper.conf.

Body:
We have a project running with an Oracle 19.3 database, and a Java application using the Oracle 19.3 JDBC driver (which is available on Maven Central). On Windows with JRE 1.8, everything is fine, but when I run either on our build server or in WSL Ubuntu with OpenJDK 11.0.3 it refuses to connect to the database. Specifically:

ERROR: Unexpected error
java.sql.SQLRecoverableException:
Unable to obtain connection from database (jdbc:oracle:thin:@//<host>:<port>/<db>) for user '<user>': IO Error: Invalid argument, Authentication lapse 0 ms.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
SQL State  : 08006
Error Code : 17002
Message    : IO Error: Invalid argument, Authentication lapse 0 ms.

        at JuliasApplication.openConnection(JdbcUtils.java:60)
        ...
Caused by: java.sql.SQLRecoverableException: IO Error: Invalid argument, Authentication lapse 0 ms.
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:874)
        at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:793)
        at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:57)
        at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:747)
        at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:562)
        ...
Caused by: java.io.IOException: Invalid argument, Authentication lapse 0 ms.
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:870)
        ... 12 more
Caused by: java.io.IOException: Invalid argument
        at java.base/sun.nio.ch.SocketChannelImpl.sendOutOfBandData(Native Method)
        at java.base/sun.nio.ch.SocketChannelImpl.sendOutOfBandData(SocketChannelImpl.java:521)
        at java.base/sun.nio.ch.SocketAdaptor.sendUrgentData(SocketAdaptor.java:323)
        at oracle.net.nt.TcpNTAdapter.sendUrgentByte(TcpNTAdapter.java:433)
        at oracle.net.ns.NSProtocolNIO.negotiateConnection(NSProtocolNIO.java:159)
        at oracle.net.ns.NSProtocol.connect(NSProtocol.java:340)
        at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1596)
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:588)
        ... 12 more

If I switch in the 18.3 JDBC driver everything is fine in both environments; if I switch in an 18.3 database everything is fine in both environments. That does give us a workaround for now, but it feels very uncomfortable that we don't understand what's going on. And I can't find anything online about an "Authentication lapse". Can anyone see any clues which would explain the failure?


问:
How to run Azure virtual machine from PowerShell script in C#
I want to run my virtual machine from C# script, if i try to do this from PowerShell(5.1.18362.752 version) it works,
i put first command

Import-AzureRmContext -Path "C:\Program Files(x86)\WindowsPowerShell\azureprofile.json"

and then second command

$PowerState = ((Get-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska -Status).Statuses[1]).code
If ( $PowerState -contains "PowerState/running")
{
Write-Host "PowerState1: running"
}
ElseIf ( $PowerState -contains "PowerState/deallocated")
{
Start-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska
$PowerState = ((Get-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska -Status).Statuses[1]).code
}
Write-Host "PowerState2: $PowerState"

but if i try to do this in C# .Net Core ,Visual Studio it's doesn't work

```<code>static void  Main(string[] args)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {

                string text = System.IO.File.ReadAllText(@"C:\Users\Krute\Desktop\Inżynierka\PowerShellScriptRunning\FirstScript.txt");
                PowerShellInstance.AddScript(text);

                IAsyncResult result = PowerShellInstance.BeginInvoke();
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Pierwsze Zapytanie");
                    Thread.Sleep(1000);

                }
            }
            using (PowerShell PowerShellInstance1 = PowerShell.Create())
            {

                string text1 = System.IO.File.ReadAllText(@"C:\Users\Krute\Desktop\Inżynierka\PowerShellScriptRunning\SecondScript.txt");
                PowerShellInstance1.AddScript(text1);

                IAsyncResult result = PowerShellInstance1.BeginInvoke();

                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Drugie Zapytanie");
                    Thread.Sleep(1000);

                }

                Console.WriteLine("Finished!");
            }
            Console.Read();
</code>```

I check what is inside text and text1 and script is read correct.
Can somebody explain me what is wrong with my code or why it doesn't work? and what i can do to run this PowerShell script from C# ?

Thanks

答:
You can run PowerShell script from C# like this

```<code>PowerShell ps = PowerShell.Create();
ps.AddScript(@"D:\PSScripts\MyScript.ps1", true).Invoke();
</code>```

Reference:

Adding and invoking commands

Body:
I want to run my virtual machine from C# script, if i try to do this from PowerShell(5.1.18362.752 version) it works,
i put first command

Import-AzureRmContext -Path "C:\Program Files(x86)\WindowsPowerShell\azureprofile.json"

and then second command

$PowerState = ((Get-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska -Status).Statuses[1]).code
If ( $PowerState -contains "PowerState/running")
{
Write-Host "PowerState1: running"
}
ElseIf ( $PowerState -contains "PowerState/deallocated")
{
Start-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska
$PowerState = ((Get-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska -Status).Statuses[1]).code
}
Write-Host "PowerState2: $PowerState"

but if i try to do this in C# .Net Core ,Visual Studio it's doesn't work

static void  Main(string[] args)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {

                string text = System.IO.File.ReadAllText(@"C:\Users\Krute\Desktop\Inżynierka\PowerShellScriptRunning\FirstScript.txt");
                PowerShellInstance.AddScript(text);

                IAsyncResult result = PowerShellInstance.BeginInvoke();
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Pierwsze Zapytanie");
                    Thread.Sleep(1000);

                }
            }
            using (PowerShell PowerShellInstance1 = PowerShell.Create())
            {

                string text1 = System.IO.File.ReadAllText(@"C:\Users\Krute\Desktop\Inżynierka\PowerShellScriptRunning\SecondScript.txt");
                PowerShellInstance1.AddScript(text1);

                IAsyncResult result = PowerShellInstance1.BeginInvoke();

                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Drugie Zapytanie");
                    Thread.Sleep(1000);

                }

                Console.WriteLine("Finished!");
            }
            Console.Read();

I check what is inside text and text1 and script is read correct.
Can somebody explain me what is wrong with my code or why it doesn't work? and what i can do to run this PowerShell script from C# ?

Thanks

Body:
You can run PowerShell script from C# like this

PowerShell ps = PowerShell.Create();
ps.AddScript(@"D:\PSScripts\MyScript.ps1", true).Invoke();

Reference:

Adding and invoking commands


问:
Find style properties of element that I'm creating dynamically
If I have a CSS style:

.myClass {
    width: 1234px;
}
```

<p>And an element that I add dynamically with JS thus:</p>

<pre class="lang-js prettyprint-override"><code>document.onload = function(){
    myParent = document.getElementById("parent");
    let myNewElmt = document.createElement("div");
    myNewElmt.className = "myClass";
    myParent.appendChild(MyNewElmt);
    console.log(myNewElmt.style.width);//expect "1234px" returns ""
}
</code>```

I can't access the style properties. It renders fine, and if I subsequently look at myNewElmt.style.width, say in a document.onmousedown function it works, but not when it's created.

How do I access css styles of a dynamically created element, at the time that it is created?

答:
Please note that element.style.propName is only used to access the inline style properties that we set using style attribute like:

```<code><div style="height: 200px;">
</code>```

To access the CSS property value which we set using the class names, we need to use getComputedStyle() for it like:

```<code>let compStyles = window.getComputedStyle(myNewElmt);
console.log( compStyles.width );
</code>```

Working Demo:

myParent = document.getElementById("parent");
let myNewElmt = document.createElement("div");

myNewElmt.style.height = '200px';       // Set iniline height here
myNewElmt.className = "myClass";
myParent.appendChild(myNewElmt);

console.log( myNewElmt.style.height );  // Returns 200px
console.log( myNewElmt.style.width );   // Returns ''

let compStyles = window.getComputedStyle(myNewElmt);
console.log( compStyles.width );        // Returns 1234px```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myClass { width: 1234px; }</code>```

```
</div>
</div>
</p>

<p><strong>Explanation:</strong></p>

<p>In this demo, you can see using:</p>

```console.log( myNewElmt.style.height );
```

we get the correct height as 200px, as we have set the inline height using myNewElmt.style.height = '200px';, but myNewElmt.style.width returns empty string, as the width is set here using the class and by using window.getComputedStyle(myNewElmt) we are able to access the width properly.

Body:
If I have a CSS style:

.myClass {
    width: 1234px;
}

And an element that I add dynamically with JS thus:

document.onload = function(){
    myParent = document.getElementById("parent");
    let myNewElmt = document.createElement("div");
    myNewElmt.className = "myClass";
    myParent.appendChild(MyNewElmt);
    console.log(myNewElmt.style.width);//expect "1234px" returns ""
}

I can't access the style properties. It renders fine, and if I subsequently look at myNewElmt.style.width, say in a document.onmousedown function it works, but not when it's created.

How do I access css styles of a dynamically created element, at the time that it is created?

Body:
Please note that element.style.propName is only used to access the inline style properties that we set using style attribute like:

<div style="height: 200px;">

To access the CSS property value which we set using the class names, we need to use getComputedStyle() for it like:

let compStyles = window.getComputedStyle(myNewElmt);
console.log( compStyles.width );

Working Demo:

myParent = document.getElementById("parent");
let myNewElmt = document.createElement("div");

myNewElmt.style.height = '200px';       // Set iniline height here
myNewElmt.className = "myClass";
myParent.appendChild(myNewElmt);

console.log( myNewElmt.style.height );  // Returns 200px
console.log( myNewElmt.style.width );   // Returns ''

let compStyles = window.getComputedStyle(myNewElmt);
console.log( compStyles.width );        // Returns 1234px

.myClass { width: 1234px; }

<div id="parent"></div>

Explanation:

In this demo, you can see using:

console.log( myNewElmt.style.height );

we get the correct height as 200px, as we have set the inline height using myNewElmt.style.height = '200px';, but myNewElmt.style.width returns empty string, as the width is set here using the class and by using window.getComputedStyle(myNewElmt) we are able to access the width properly.


问:
In Python: How can i get my code to print out all the possible words I can spell based on my input?
I think I was close to figuring out how to print out all the possible words based on user input from my set dictionary. it's based on the assumption that the user input is 'ART' so the possible words I have in my dictionary are ART, RAT, TART, and TAR but only the three letter combinations are printing out. can anyone tell me where I am going wrong? Thanks!</p>

```<code>Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)

def characters(word):
    Dictionary = {}
    for i in word:
        Dictionary[i] = Dictionary.get(i, 0) + 1
    return Dictionary

def all_words(StoredLetters, wordSet):
    for word in StoredLetters:
        flag = 1
        words = characters(word)
        for key in words:
            if key not in wordSet:
                flag = 0
            else:
                if wordSet.count(key) != words[key]:
                    flag = 0
        if flag == 1:
            print(word)
if __name__ == "__main__":
    print(all_words(Dictionary, StoredLetters))
</code>```

答:
It appears there are a few things that could contribute to this.

You are swapping the parameters on all words def allwords(Dictionary, StoredLetters): when you call it in main allwords(StoredLetters, Dictionary). Without specifying the name (look up named parameters in python) you would be swapping the input.

In the characters function it would appear you are resetting the dictionary variable. Try using unique names when creating new variables. This is causing the dictionary of words you set at the top to be emptied out when characters(word) is called

Body:
I think I was close to figuring out how to print out all the possible words based on user input from my set dictionary. it's based on the assumption that the user input is 'ART' so the possible words I have in my dictionary are ART, RAT, TART, and TAR but only the three letter combinations are printing out. can anyone tell me where I am going wrong? Thanks!

Dictionary = ["tar","art","tart","rat"] #creates dictionary of set words
StoredLetters = input('input your word here: ') #allows the user to input any word
list(StoredLetters)

def characters(word):
    Dictionary = {}
    for i in word:
        Dictionary[i] = Dictionary.get(i, 0) + 1
    return Dictionary

def all_words(StoredLetters, wordSet):
    for word in StoredLetters:
        flag = 1
        words = characters(word)
        for key in words:
            if key not in wordSet:
                flag = 0
            else:
                if wordSet.count(key) != words[key]:
                    flag = 0
        if flag == 1:
            print(word)
if __name__ == "__main__":
    print(all_words(Dictionary, StoredLetters))


问:
shell_exec with PHP
I am attempting to run apktool (just a tool to unpackage android applications) over the web using PHP shell_exec but it isn't working.  Does anyone know why this might be?

This is what the line of code actually looks like:

```<code>   $output = `apktool d -f $file_name`;
</code>```

Any suggestions would help I'm totally at a loss why I run the php and nothing happens.
Thanks!

答:
check if you web server (probably apache) has sufficient permissions to execute apktool. Include the whole path to the apktool binary. Use single quotes if there are spaces in your file name.

Check your web server's logs if there is any detail why the command is not executed.

Title: shell_exec with PHP

Body:
I am attempting to run apktool (just a tool to unpackage android applications) over the web using PHP shell_exec but it isn't working.  Does anyone know why this might be?

This is what the line of code actually looks like:

   $output = `apktool d -f $file_name`;

Any suggestions would help I'm totally at a loss why I run the php and nothing happens.
Thanks!


问:
How to change BottomNavigationBarItem icon when selected, Flutter
I am new to Flutter. I have a BottomNavigationBar with 4 items. I want to change icon of the item when pressed. Please help.

This is what I have done so far.

```<code>bottomNavigationBar : new BottomNavigationBar(
        currentIndex: index,
        onTap: (int index) {
          setState(() {
            this.index = index;
          }
          );
          _navigateToScreens(index);
        },
        type: BottomNavigationBarType.fixed,
        items: [
          new BottomNavigationBarItem(
              backgroundColor: Colors.white,
              icon: new Image.asset('images/1.0x/icon1.png'),
              title: new Text("Route1", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0))),
          new BottomNavigationBarItem(
              icon: new Image.asset('images/1.0x/icon2.png'),
              title: new Text("Route2", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0))),
          new BottomNavigationBarItem(
              icon: new Image.asset('images/1.0x/icon3.png'),
              title: new Text("Route3", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0),)),
          new BottomNavigationBarItem(
              icon: new Image.asset('images/1.0x/icon4.png'),
              title: new Text("Route4", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0),))
        ]);
</code>```

答:
```<code>color: _selectedIndex == ThisIndex?SelectedColor:normalColor,
</code>```

Body:
I am new to Flutter. I have a BottomNavigationBar with 4 items. I want to change icon of the item when pressed. Please help.

This is what I have done so far.

bottomNavigationBar : new BottomNavigationBar(
        currentIndex: index,
        onTap: (int index) {
          setState(() {
            this.index = index;
          }
          );
          _navigateToScreens(index);
        },
        type: BottomNavigationBarType.fixed,
        items: [
          new BottomNavigationBarItem(
              backgroundColor: Colors.white,
              icon: new Image.asset('images/1.0x/icon1.png'),
              title: new Text("Route1", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0))),
          new BottomNavigationBarItem(
              icon: new Image.asset('images/1.0x/icon2.png'),
              title: new Text("Route2", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0))),
          new BottomNavigationBarItem(
              icon: new Image.asset('images/1.0x/icon3.png'),
              title: new Text("Route3", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0),)),
          new BottomNavigationBarItem(
              icon: new Image.asset('images/1.0x/icon4.png'),
              title: new Text("Route4", style: new TextStyle(
                  color: const Color(0xFF06244e), fontSize: 14.0),))
        ]);


问:
Angular 2 contenteditable
In Angular 2 how can I make two way data binding with a contenteditable div?</p>

```<code><div class="editable" contenteditable="true">
    <h1>Text Field</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra felis in sem porta feugiat.</p>
 </div>
</code>```

答:
the blur event and innerHTML attribute.

In .ts:

```<code>getContent(innerText){
  this.content = innerText;
}
</code>```

in .html:

```<code><div (blur)="getContent($event.target.innerHTML)" contenteditable [innerHTML]="content"></div>
</code>```

Title: Angular 2 contenteditable

Body:
In Angular 2 how can I make two way data binding with a contenteditable div?

Text Field

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra felis in sem porta feugiat.

Body:
the blur event and innerHTML attribute.

In .ts:

getContent(innerText){
  this.content = innerText;
}

in .html:

<div (blur)="getContent($event.target.innerHTML)" contenteditable [innerHTML]="content"></div>