问:
Canonical URLs and Google
As far as Google and canonical URLs go - is there any advantage to adding a 301 redirect from:

http://www.mydomain.com/index.php

to

http://www.mydomain.com/

答:
No the default page to open when no page name is specified is either "index.html" or "index.php", with the priority given to the latter by default. So there will not be any advantage as such & moreover, it's not needed.

For any other page (except the Home page or the "index" named pages), if you specify the Redirect Header 301, then you are notifying Google & other search engines to store the target URL as the active & the latest one (not the first one), in their database. It's like setting a permalink in the databases of the search engines with your latest active URLs.

There will be one big advantage, however. When you are specifying "http://www.mydomain.com/index.php", you are notifying search engines to load the "index.php" page only all the times. However, if you just specify "http://www.mydomain.com/" to the search engines, then it's upto the (mydomain.com) server's interpretation (after understanding that server's HTAccess rules & other Redirection rules, if any) to show the user the correct file - it may be "index.php" (first priority), or "index.html", or "index.htm" - although that correct file may or may not be present in that server's hosting space.

If the correct file is not present, then a 404 Not Found page is shown. And it's the responsibility of the owner of that server to have the correct file in his server's root folder, so that never a 404 Not Found page is shown to any user.

So I will say that it's a big advantage mentioning "http://www.mydomain.com/" instead of "http://www.mydomain.com/index.php".

Hope it helps.

Title: Canonical URLs and Google


来源: stackexchange

问:
Change background-color with different shades of color
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

```<code>background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)
</code>```

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

答:
try using transition-timing-function like step-start and step-end.

```<code>transition-timing-function: step-start;
transition-timing-function: step-end;
</code>```

See the fiddle for understanding: https://jsfiddle.net/9bcgw7x4/5/

In the code at fiddle replace the background colours with your desired ones.

Updated

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

Body:
try using transition-timing-function like step-start and step-end.

transition-timing-function: step-start;
transition-timing-function: step-end;

See the fiddle for understanding: https://jsfiddle.net/9bcgw7x4/5/

In the code at fiddle replace the background colours with your desired ones.

Updated


问:
Values Separated in Excel
I have a dataframe in R which contains values like:

```<code>Sales officer        2      3
Therapy Specialist   4      9
Quality,Assurance    3      5
Training Manager     5      4
</code>```

But when I write this data into Excel, the 3rd row  Quality,Assurance is treated separately i.e Excel looks like this:

```<code>Sales officer        2      3
Therapy Specialist   4      9
Quality          Assurance  3      5
Training Manager     5      4
</code>```

This is just a sample example. I have a lot of such fields which have commas due to which they are shifted by one column while writing in Excel.

How to stop this?

答:
In Excel 2007, you can use fixed width to format data.
Steps

click Data

click Text to column (in Data Tools Ribbon)

select fixed width

Then you get your data as is

Title: Values Separated in Excel

Body:
I have a dataframe in R which contains values like:

Sales officer        2      3
Therapy Specialist   4      9
Quality,Assurance    3      5
Training Manager     5      4

But when I write this data into Excel, the 3rd row  Quality,Assurance is treated separately i.e Excel looks like this:

Sales officer        2      3
Therapy Specialist   4      9
Quality          Assurance  3      5
Training Manager     5      4

This is just a sample example. I have a lot of such fields which have commas due to which they are shifted by one column while writing in Excel.

How to stop this?


问:
Need Help Creating Multiple Directories in Makefile
I have the following block of code in a makefile:

```<code>param_test_dir:

    @if test -d $(BUILD_DIR); then \
        echo Build exists...; \
    else \
    echo Build directory does not exist, making build dir...; \
mkdir $(BUILD_DIR); \
fi
@if test -d $(TEST_DIR); then \
    echo Tests exists...; \
else \
    echo Tests directory does not exist, making tests dir...; \
mkdir $(TEST_DIR); \
fi
@if test -d $(TEST_DIR)/param_unit_test; then \
    echo Param unit test directory exists...; \
else \
    echo Param unit test directory does \
    not exist, making build dir...; \
    mkdir $(TEST_DIR)/param_unit_test; \
fi
@if test -d $(TEST_DIR)/param_unit_test/source; then \
    echo Param unit test source directory exists...; \
else \
    echo Param unit test source directory does \
    not exist, making build dir...; \
    mkdir $(TEST_DIR)/param_unit_test/source; \
fi
@if test -d $(TEST_DIR)/param_unit_test/obj; then \
    echo Param unit test object directory exists...; \
else \
    echo Param unit test object directory does \
    not exist, making object dir...; \
    mkdir $(TEST_DIR)/param_unit_test/obj; \
fi
@if test -d $(TEST_DIR)/param_unit_test/bin; then \
    echo Param unit test executable directory exists...; \
else \
    echo Param unit test executable directory does \
    not exist, making executable dir...; \
    mkdir $(TEST_DIR)/param_unit_test/bin; \
fi
</code>```

Basically, this is necessitated as I don't my makefile to crash and die if the build directory doesn't exist -- I want it to recreate the missing parts of the directory tree.  The nesting is due to the fact that I have a build directory, a tests directory inside the build (for module tests vs. full programs) and then within that tests directory individual directories for tests, each of which need a source, obj, and bin directory.  So a lot of stuff to create!

Here's my question.  Is there a way to take advantage of makefile "magic" to feed it some single variable like:

```<code>PATH=./build/tests/param_test/bin
</code>```

and have it create all the directories I need with like a one or two liner rather than that humongous if statement?

Thanks in advance!!

答:
If you need to write a portable makefile (e.g. that work also on Windows), you may consider a solution where you can use the same command for all platforms. The solution by @Sjoerd works fine on unixish machines, but there is a small difference for Windows (I tried it on XP, Vista and Windows 7):

```<code># Unix solution
mkdir -p build/tests/param_test/bin
# Windows solution
mkdir build\tests\param_test\bin
</code>```

No -p option, and you need backslashes.

It does create the directories recursively, but it complains if the directory already exists. There is no 'silent' option to suppress the complaint.

What I'm using is a solution using a Perl one-liner. Other build steps in our system mandate Perl, so this is portable for us. YMMV.

```<code>perl "-MFile::Path" -e "mkpath 'build/tests/param_test/bin'"
</code>```

Note that with Perl you can use forward slashes also on Windows.

ContentLicense: CC BY-SA 2.5

Body:
I have the following block of code in a makefile:

param_test_dir:

    @if test -d $(BUILD_DIR); then \
        echo Build exists...; \
    else \
    echo Build directory does not exist, making build dir...; \
mkdir $(BUILD_DIR); \
fi
@if test -d $(TEST_DIR); then \
    echo Tests exists...; \
else \
    echo Tests directory does not exist, making tests dir...; \
mkdir $(TEST_DIR); \
fi
@if test -d $(TEST_DIR)/param_unit_test; then \
    echo Param unit test directory exists...; \
else \
    echo Param unit test directory does \
    not exist, making build dir...; \
    mkdir $(TEST_DIR)/param_unit_test; \
fi
@if test -d $(TEST_DIR)/param_unit_test/source; then \
    echo Param unit test source directory exists...; \
else \
    echo Param unit test source directory does \
    not exist, making build dir...; \
    mkdir $(TEST_DIR)/param_unit_test/source; \
fi
@if test -d $(TEST_DIR)/param_unit_test/obj; then \
    echo Param unit test object directory exists...; \
else \
    echo Param unit test object directory does \
    not exist, making object dir...; \
    mkdir $(TEST_DIR)/param_unit_test/obj; \
fi
@if test -d $(TEST_DIR)/param_unit_test/bin; then \
    echo Param unit test executable directory exists...; \
else \
    echo Param unit test executable directory does \
    not exist, making executable dir...; \
    mkdir $(TEST_DIR)/param_unit_test/bin; \
fi

Basically, this is necessitated as I don't my makefile to crash and die if the build directory doesn't exist -- I want it to recreate the missing parts of the directory tree.  The nesting is due to the fact that I have a build directory, a tests directory inside the build (for module tests vs. full programs) and then within that tests directory individual directories for tests, each of which need a source, obj, and bin directory.  So a lot of stuff to create!

Here's my question.  Is there a way to take advantage of makefile "magic" to feed it some single variable like:

PATH=./build/tests/param_test/bin

and have it create all the directories I need with like a one or two liner rather than that humongous if statement?

Thanks in advance!!

Body:
If you need to write a portable makefile (e.g. that work also on Windows), you may consider a solution where you can use the same command for all platforms. The solution by @Sjoerd works fine on unixish machines, but there is a small difference for Windows (I tried it on XP, Vista and Windows 7):

# Unix solution
mkdir -p build/tests/param_test/bin
# Windows solution
mkdir build\tests\param_test\bin

No -p option, and you need backslashes.

It does create the directories recursively, but it complains if the directory already exists. There is no 'silent' option to suppress the complaint.

What I'm using is a solution using a Perl one-liner. Other build steps in our system mandate Perl, so this is portable for us. YMMV.

perl "-MFile::Path" -e "mkpath 'build/tests/param_test/bin'"

Note that with Perl you can use forward slashes also on Windows.


问:
HTML5 date input width
So i am having an issue trying to force a size on a date input. Has anyone else had this issue or know how to get around it?

```<code><input style="width:50px;" type="date" value="">
</code>```

It is pretty simple, the width only changes the textarea, the actual control does not change, it is fixed at about 125 px width or so.

I have also tried width="" and max-width in the css, neither work.

答:
```<code><input type="date" name="tanggal" style="width:231px">
</code>```

Hope this works!
It doesn't change anything except the width.

Title: HTML5 date input width

Body:
So i am having an issue trying to force a size on a date input. Has anyone else had this issue or know how to get around it?

<input style="width:50px;" type="date" value="">

It is pretty simple, the width only changes the textarea, the actual control does not change, it is fixed at about 125 px width or so.

I have also tried width="" and max-width in the css, neither work.

Body:
<input type="date" name="tanggal" style="width:231px">

Hope this works!
It doesn't change anything except the width.


问:
Displaying an error message in PHP
I want to display an error message to the user if the credentials entered by them are incorrect(do not return a match with anything in my database), such as in a login form.
What is the easiest way to do that?
Here's what I have till now-

```<code><?php
require 'includes/common.php';
?>

<!DOCTYPE html>
<!--
Login page of Lifestyle Store
-->
<html>
<head>
    <title>Log In</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!---- External css file index.css placed in the folder css is linked-->
<link href="css/index.css" rel="stylesheet" type="text/css"/>
</head>
<body>

    <?php
    include 'includes/header.php';
    ?>
    <div class="row login">
        <div class="col-xs-4"></div>
        <div class="col-xs-4">
    <div class="panel panel-primary">
        <div class="panel-body">
            <p class="text-warning">Login to make a purchase-</p>
            <form action="login_submit.php" method="POST">
                <div class="form-group">
                    <label for="email">E-mail:</label>
                    <input type="text" class="form-control" name="email" value="Email">
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="text" class="form-control" name="password" value="Password">
                </div>
            </form>
             <button class="btn btn-primary" type="submit" name="submit">Log-in</button>
        </div>
        <div class="panel-footer">Don't have an account? <a class="a2" href="signup.html">Register!</a></div>
    </div>
        </div>
        <div class="col-xs-4"></div>
    </div>

    <?php
    include 'includes/footer.php';
    ?>
</body>
</code>```

答:
If you are using mysql to search the database for matches, then use something like below </p>

```<code>$email = $mysqli->escape_string($_POST['email']);
$password  = $mysqli->escape_string($_POST['password']):
$result = $mysqli->query("SELECT * FROM users WHERE email='$email' AND password='$password'");
//check whether the user exists and redirecting if not exists
if ($result-> num_rows == 0){
$_SESSION['messege']= "You have entered Either Wrong Username or Password ";
header("location: error.php");
}
</code>```

Title: Displaying an error message in PHP

Body:
I want to display an error message to the user if the credentials entered by them are incorrect(do not return a match with anything in my database), such as in a login form.
What is the easiest way to do that?
Here's what I have till now-

<?php
require 'includes/common.php';
?>

<!DOCTYPE html>

    <title>Log In</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

<link href="css/index.css" rel="stylesheet" type="text/css"/>

    <?php
    include 'includes/header.php';
    ?>

Login to make a purchase-

            <form action="login_submit.php" method="POST">

                    E-mail:
                    <input type="text" class="form-control" name="email" value="Email">

                    Password:
                    <input type="text" class="form-control" name="password" value="Password">

            </form>
             <button class="btn btn-primary" type="submit" name="submit">Log-in</button>

Don't have an account? Register!

    <?php
    include 'includes/footer.php';
    ?>

Body:
If you are using mysql to search the database for matches, then use something like below

$email = $mysqli->escape_string($_POST['email']);
$password  = $mysqli->escape_string($_POST['password']):
$result = $mysqli->query("SELECT * FROM users WHERE email='$email' AND password='$password'");
//check whether the user exists and redirecting if not exists
if ($result-> num_rows == 0){
$_SESSION['messege']= "You have entered Either Wrong Username or Password ";
header("location: error.php");
}


问:
Issues with Python Threading and Code in general
Given the following Python3 code, with threading:

```<code>class main:
    def __init__(self):
        self.text = open(os.getcwd()+"/FileScanLogs.txt", "a+")
        self.hashlist = queue.Queue()
        self.filelist = queue.Queue()
        self.top = '/home/'
        for y in range(12):
            self.u = threading.Thread(target=self.md5hash)
            self.u.daemon = True
            self.u.start()
        for x in range(4):
            self.t = threading.Thread(target=self.threader)
            self.t.daemon = True
            self.t.start()
        main.body(self)

    def body(self):
        start = time.time()
        self.text.write("Time now is " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\n")
        for root, dirs, files in os.walk(self.top):
            for f in files:
                path = os.path.join(root,f)
                self.filelist.put(path)
        self.t.join()
        self.u.join()
        self.text.write("Total time taken     : " + str(time.time() - start) + "\n")
        print("Log file is created as " + os.getcwd() + "/FileScanLogs.txt")

    def md5hash(self):
        while True:
            entry = self.filelist.get()
            //hashing//
            lists = finalhash + ',' + entry
            self.hashlist.put(lists)
            self.filelist.task_done()

    def compare(self, hashed, path):
        f = open(os.getcwd() + "/database.csv", 'r')
        for row in f:
            if row.split(':')[1] == hashed:
                print("Suspicious File!")
                print("Suspecfs: " + row.split(':')[2] + "File name : " + path)

    def threader(self):
        while True:
            item = self.hashlist.get()
            hashes = item.split(',')[0]
            path = item.split(',')[1]
            self.compare(hashes, path)
            self.hashlist.task_done()

main()
</code>```

Problem 1: In def body(self), there exist the line self.text.write("Time now is ..."). This line does not appear in the Log File that is created.

Problem 2: In def compare(self, hashed, path), there exist a line that prints "Suspicious File!" and the file path every time there is a hash collision. This line always prints out of order as the 4 threads t are fighting over who will print first. For this, I think I need to know how to let Python threads run print commands sequentially instead of however they like -- how?

Problem 3: In def body(self), there exist lines self.u.join() and self.t.join(). The command join(), according to the best of my knowledge, is a command waiting for the thread to terminate before continuing. The threads are both not terminating.

Additional information 1: I am writing multi-threading as I need the code to be converted to multi-processing later.

Additional information 2: Please do let me know if I have misunderstood any commands/syntax in my code as you are skimming through.

答:
Problem 1: You're writing to your file buffer - it gets flushed to the actual file only when the buffer is full, the file handle is closed or you explicitly call flush() on it (i.e. self.text.flush())

Problem 2: You either want your code to execute in parallel (and it's not, but we'll get to that) but you lose the order of execution, or you execute serially keeping the order. If you want to run multiple threads it makes little sense to have them execute one after another because then you're not executing your code in parallel and you might as well execute everything in the main thread.

If you only want to control the output to STDOUT, provided it doesn't interfere with the thread execution, you can capture what you want to print and have it printed out in the end under a mutex (so only one thread writes at the time) or even pipe it back to the main thread and have it manage access to STDOUT. A simple mutex example would be:

```<code>PRINT_MUTEX = threading.Lock()

def compare(self, hashed, path):  # never mind the inefficiency, we'll get to that later
    out = []  # hold our output buffer
    with open(os.getcwd() + "/database.csv", 'r') as f:
        for row in f:
            row = row.split(':')
            if row[1] == hashed:
                out.append("Suspicious File!")
                out.append("Suspecfs: " + row[2] + "File name : " + path)
    if out:
        with self.PRINT_MUTEX:  # use a lock to print out the results
            print("\n".join(out))
</code>```

This will not keep in order the thread execution (nor should you attempt to least you want to defeat the purpose of 'parallel' execution) but at least the threads will output their compare results one at a time instead of interspersing their results. If you want to have your main thread/process control the STDOUT, especially since you want to transform this into a multi-processing code, check this answer.

Problem 3: Your threads are never exiting because they are stuck in a while True loop - until you break away from it the threads will keep running. I don't know what's the reason behind the way you've structured the code, but if you're trying to parallelize file listing (main thread), reading, hashing (md5hash threads) and comparing (threader threads) you presumably want to stop hashing when there are no more files, and stop comparing when there are no more hashes. To do so, you cannot really use Queue.task_done() as it's there to signal other 'listeners' (if they are blocked by a Queue.join() call which yours are not) that you're done with queue modifications.

You should use a threading.Event signal for that, but if you want to keep it queue.Queue only you can create a special property to denote the end of your queue and then place it in a queue when there's nothing more to process, then have your threads exit their loops when they encounter this special property. Let's first fix a big overlook in your code - you're not storing a reference to your threads at all, you're overwriting it with the last thread so you cannot really control the execution flow - instead of storing the last thread reference in a variable, store all the references in a list. Also, if you're going to wait for everything to close don't use daemon threads:

```<code>def __init__(self):
    self.text = open(os.getcwd()+"/FileScanLogs.txt", "a+")  # consider os.path.join()
    self.hashlist = queue.Queue()
    self.filelist = queue.Queue()
    self.hashers = []  # hold the md5hash thread references
    self.comparators = []  # hold the threader thread references
    self.top = '/home/'
    for _ in range(12):  # you might want to consider a ThreadPool instead
        t = threading.Thread(target=self.md5hash)
        t.start()
        self.hashers.append(t)
    for _ in range(4):
        t = threading.Thread(target=self.threader)
        t.start()
        self.comparators.append(t)
    main.body(self)
</code>```

Now we can modify the main.body() method so that it adds the aforementioned special values to the end of our queues so that the worker threads know when to stop:

```<code>QUEUE_CLOSE = object()  # a 'special' object to denote end-of-data in our queues

def body(self):
    start = time.time()
    self.text.write("Time:  " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\n")
    for root, dirs, files in os.walk(self.top):
        for f in files:
            path = os.path.join(root, f)
            self.filelist.put(path)
    self.filelist.put(self.QUEUE_CLOSE)  # no more files, signal the end of the filelist
    for t in self.hashers:  # let's first wait for our hashing threads to exit
        t.join()
    # since we're not going to be receiving any new hashes, we can...
    self.hashlist.put(self.QUEUE_CLOSE)  # ... signal the end of the hashlist as well
    for t in self.comparators:  # let's wait for our comparator threads to exit
        t.join()
    self.text.write("Total: " + str(time.time() - start) + "\n")
    self.text.close()  # close the log file (this will also flush the previous content)
    print("Log file is created as " + os.getcwd() + "/FileScanLogs.txt")
</code>```

And consequently we need to modify the worker threads to exit when they encounter the end of the queue:

```<code>def md5hash(self):
    while self.filelist:
        entry = self.filelist.get()
        if entry is self.QUEUE_CLOSE:  # end of queue encountered
            self.filelist.put(self.QUEUE_CLOSE)  # put it back for the other threads
            break  # break away the processing
        finalhash = whatever_is_your_hash_code(entry)
        lists = finalhash + ',' + entry
        self.hashlist.put(lists)

def threader(self):
    while True:
        item = self.hashlist.get()
        if item is self.QUEUE_CLOSE:  # end of queue encountered
            self.hashlist.put(self.QUEUE_CLOSE)  # put it back for the other threads
            break  # break away the queue
        hashes = item.split(',')[0]
        path = item.split(',')[1]
        self.compare(hashes, path)
</code>```

Now if you run it, provided your unlisted hashing part works properly, everything should eventually exit.

Apart from the awkward setup, one thing you definitely should do is optimize away the main.compare() method - since the CSV file doesn't change during the execution (and if it does you should handle it in-memory) loading the whole CSV and looping through it for every files' hash you want to compare is ludicrous. Load the whole CSV as hash<=>whatever dict and then do comparisons on the spot (i.e. if hashed in your_map) instead.

And lastly, as I mentioned above, time to, hmm, rain on your parade - all of this was for nothing! Due to the dreaded GIL none of your threads here execute in parallel (actually, only the file loading does to an extent, but any advantage is probably thwarted by the time it takes to hash the data). They do run as a separate, honest-to-god system threads but the GIL ensures that only one of those threads is running at a time so this code, processing wise, is most likely slower than if you were running everything in one thread. This won't help you much in the process of multiprocessing either because you cannot share a local instance state (well, you can, check this answer, but it's just a major PITA and most of the time not worth going through the trouble).

Body:
Given the following Python3 code, with threading:

class main:
    def __init__(self):
        self.text = open(os.getcwd()+"/FileScanLogs.txt", "a+")
        self.hashlist = queue.Queue()
        self.filelist = queue.Queue()
        self.top = '/home/'
        for y in range(12):
            self.u = threading.Thread(target=self.md5hash)
            self.u.daemon = True
            self.u.start()
        for x in range(4):
            self.t = threading.Thread(target=self.threader)
            self.t.daemon = True
            self.t.start()
        main.body(self)

    def body(self):
        start = time.time()
        self.text.write("Time now is " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\n")
        for root, dirs, files in os.walk(self.top):
            for f in files:
                path = os.path.join(root,f)
                self.filelist.put(path)
        self.t.join()
        self.u.join()
        self.text.write("Total time taken     : " + str(time.time() - start) + "\n")
        print("Log file is created as " + os.getcwd() + "/FileScanLogs.txt")

    def md5hash(self):
        while True:
            entry = self.filelist.get()
            //hashing//
            lists = finalhash + ',' + entry
            self.hashlist.put(lists)
            self.filelist.task_done()

    def compare(self, hashed, path):
        f = open(os.getcwd() + "/database.csv", 'r')
        for row in f:
            if row.split(':')[1] == hashed:
                print("Suspicious File!")
                print("Suspecfs: " + row.split(':')[2] + "File name : " + path)

    def threader(self):
        while True:
            item = self.hashlist.get()
            hashes = item.split(',')[0]
            path = item.split(',')[1]
            self.compare(hashes, path)
            self.hashlist.task_done()

main()

Problem 1: In def body(self), there exist the line self.text.write("Time now is ..."). This line does not appear in the Log File that is created.

Problem 2: In def compare(self, hashed, path), there exist a line that prints "Suspicious File!" and the file path every time there is a hash collision. This line always prints out of order as the 4 threads t are fighting over who will print first. For this, I think I need to know how to let Python threads run print commands sequentially instead of however they like -- how?

Problem 3: In def body(self), there exist lines self.u.join() and self.t.join(). The command join(), according to the best of my knowledge, is a command waiting for the thread to terminate before continuing. The threads are both not terminating.

Additional information 1: I am writing multi-threading as I need the code to be converted to multi-processing later.

Additional information 2: Please do let me know if I have misunderstood any commands/syntax in my code as you are skimming through.

Body:
Problem 1: You're writing to your file buffer - it gets flushed to the actual file only when the buffer is full, the file handle is closed or you explicitly call flush() on it (i.e. self.text.flush())

Problem 2: You either want your code to execute in parallel (and it's not, but we'll get to that) but you lose the order of execution, or you execute serially keeping the order. If you want to run multiple threads it makes little sense to have them execute one after another because then you're not executing your code in parallel and you might as well execute everything in the main thread.

If you only want to control the output to STDOUT, provided it doesn't interfere with the thread execution, you can capture what you want to print and have it printed out in the end under a mutex (so only one thread writes at the time) or even pipe it back to the main thread and have it manage access to STDOUT. A simple mutex example would be:

PRINT_MUTEX = threading.Lock()

def compare(self, hashed, path):  # never mind the inefficiency, we'll get to that later
    out = []  # hold our output buffer
    with open(os.getcwd() + "/database.csv", 'r') as f:
        for row in f:
            row = row.split(':')
            if row[1] == hashed:
                out.append("Suspicious File!")
                out.append("Suspecfs: " + row[2] + "File name : " + path)
    if out:
        with self.PRINT_MUTEX:  # use a lock to print out the results
            print("\n".join(out))

This will not keep in order the thread execution (nor should you attempt to least you want to defeat the purpose of 'parallel' execution) but at least the threads will output their compare results one at a time instead of interspersing their results. If you want to have your main thread/process control the STDOUT, especially since you want to transform this into a multi-processing code, check this answer.

Problem 3: Your threads are never exiting because they are stuck in a while True loop - until you break away from it the threads will keep running. I don't know what's the reason behind the way you've structured the code, but if you're trying to parallelize file listing (main thread), reading, hashing (md5hash threads) and comparing (threader threads) you presumably want to stop hashing when there are no more files, and stop comparing when there are no more hashes. To do so, you cannot really use Queue.task_done() as it's there to signal other 'listeners' (if they are blocked by a Queue.join() call which yours are not) that you're done with queue modifications.

You should use a threading.Event signal for that, but if you want to keep it queue.Queue only you can create a special property to denote the end of your queue and then place it in a queue when there's nothing more to process, then have your threads exit their loops when they encounter this special property. Let's first fix a big overlook in your code - you're not storing a reference to your threads at all, you're overwriting it with the last thread so you cannot really control the execution flow - instead of storing the last thread reference in a variable, store all the references in a list. Also, if you're going to wait for everything to close don't use daemon threads:

def __init__(self):
    self.text = open(os.getcwd()+"/FileScanLogs.txt", "a+")  # consider os.path.join()
    self.hashlist = queue.Queue()
    self.filelist = queue.Queue()
    self.hashers = []  # hold the md5hash thread references
    self.comparators = []  # hold the threader thread references
    self.top = '/home/'
    for _ in range(12):  # you might want to consider a ThreadPool instead
        t = threading.Thread(target=self.md5hash)
        t.start()
        self.hashers.append(t)
    for _ in range(4):
        t = threading.Thread(target=self.threader)
        t.start()
        self.comparators.append(t)
    main.body(self)

Now we can modify the main.body() method so that it adds the aforementioned special values to the end of our queues so that the worker threads know when to stop:

QUEUE_CLOSE = object()  # a 'special' object to denote end-of-data in our queues

def body(self):
    start = time.time()
    self.text.write("Time:  " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\n")
    for root, dirs, files in os.walk(self.top):
        for f in files:
            path = os.path.join(root, f)
            self.filelist.put(path)
    self.filelist.put(self.QUEUE_CLOSE)  # no more files, signal the end of the filelist
    for t in self.hashers:  # let's first wait for our hashing threads to exit
        t.join()
    # since we're not going to be receiving any new hashes, we can...
    self.hashlist.put(self.QUEUE_CLOSE)  # ... signal the end of the hashlist as well
    for t in self.comparators:  # let's wait for our comparator threads to exit
        t.join()
    self.text.write("Total: " + str(time.time() - start) + "\n")
    self.text.close()  # close the log file (this will also flush the previous content)
    print("Log file is created as " + os.getcwd() + "/FileScanLogs.txt")

And consequently we need to modify the worker threads to exit when they encounter the end of the queue:

def md5hash(self):
    while self.filelist:
        entry = self.filelist.get()
        if entry is self.QUEUE_CLOSE:  # end of queue encountered
            self.filelist.put(self.QUEUE_CLOSE)  # put it back for the other threads
            break  # break away the processing
        finalhash = whatever_is_your_hash_code(entry)
        lists = finalhash + ',' + entry
        self.hashlist.put(lists)

def threader(self):
    while True:
        item = self.hashlist.get()
        if item is self.QUEUE_CLOSE:  # end of queue encountered
            self.hashlist.put(self.QUEUE_CLOSE)  # put it back for the other threads
            break  # break away the queue
        hashes = item.split(',')[0]
        path = item.split(',')[1]
        self.compare(hashes, path)

Now if you run it, provided your unlisted hashing part works properly, everything should eventually exit.

Apart from the awkward setup, one thing you definitely should do is optimize away the main.compare() method - since the CSV file doesn't change during the execution (and if it does you should handle it in-memory) loading the whole CSV and looping through it for every files' hash you want to compare is ludicrous. Load the whole CSV as hash<=>whatever dict and then do comparisons on the spot (i.e. if hashed in your_map) instead.

And lastly, as I mentioned above, time to, hmm, rain on your parade - all of this was for nothing! Due to the dreaded GIL none of your threads here execute in parallel (actually, only the file loading does to an extent, but any advantage is probably thwarted by the time it takes to hash the data). They do run as a separate, honest-to-god system threads but the GIL ensures that only one of those threads is running at a time so this code, processing wise, is most likely slower than if you were running everything in one thread. This won't help you much in the process of multiprocessing either because you cannot share a local instance state (well, you can, check this answer, but it's just a major PITA and most of the time not worth going through the trouble).


问:
Asynchronous Data in tableView Firebase Swift
I have an issue with my least favourite part in Firebase. I want to pull a post from user's following list (every user has one and only one post). First, I created a completion handler to get a list of all followers from Firebase and store it in userArray array of strings:

```<code>func GetUsersInFollowing(completion: @escaping (Bool) -> ()) {
    ref.child("following").queryOrdered(byChild: FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
        for group in snapshot.children {
            self.userArray.append((group as AnyObject).key)
        }
        completion(true)
    })
}
</code>```

Now the plan is to pull a post from every element of userArray.
Here is where the problem starts. I call CreatePosts() immediately after GetUsersInFollowing() completes.

```<code>func CreatePosts() {
    for x in userArray {
        var thePost = Post()
        print("1")
        self.ref.child("users").child(x).observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? NSDictionary
            thePost.fullName = value?["fullname"] as? String ?? ""
            thePost.username = value?["username"] as? String ?? ""
            thePost.profileImageURL = value?["photourl"] as? String ?? ""
            print("2")
        })

        self.ref.child("posts").child(x).observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? NSDictionary
            thePost.description = value?["description"] as? String ?? ""
            thePost.info = value?["location"] as? String ?? ""
            thePost.postImageURL = value?["photoURL"] as? String ?? ""
            thePost.timePost = value?["timestamp"] as? NSDate
            thePost.upVotes = value?["upvotes"] as? Int ?? 0
        })

        self.postArray.append(thePost)
        self.tableView.reloadData()
    }
}
</code>```

Everything looks ok to me, but it surely isn't. Here's how I create cells:

```<code>func configureCell(post: Post) {
    self.post = post
    self.username.text = post.username
    self.profileImage = post.profileImageURL
    print("3")
    self.fullname.text = post.fullName
    self.timestamp.text = post.timePost
    self.upvotes.text = post.upVotes
    self.location.text = post.location
    self.descriptionText.text = post.description
}
</code>```

The output in the console varies, but usually I get:
1
1
3
3
2
2

The idea is to first retrieve all data from Firebase, add it to post object, append the object to the array and then create cell for that object with data downloaded. Cell is already created even though data is not retrieved. I think that is the problem. Thank you, every suggestion is appreciated.

答:
You need to inner query for combining both user profile data and post data.
Like this -</p>

```<code>    func CreatePosts() {

        //Using userPostArrayObjFetched as a counter to check the number of data fetched.
        //Remove this code, if you don't want to wait till all the user data is fetched.
        var userPostArrayObjFetched = 0

        for (index,userID) in userArray.enumerated() {

            print("1" + userID)

            self.ref.child("users").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in

                var thePost = Post()

                let value = snapshot.value as? NSDictionary
                thePost.fullName = value?["fullname"] as? String ?? ""
                thePost.username = value?["username"] as? String ?? ""
                thePost.profileImageURL = value?["photourl"] as? String ?? ""
                print("2" + userID)

                self.ref.child("posts").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
                    let value = snapshot.value as? NSDictionary
                    thePost.description = value?["description"] as? String ?? ""
                    thePost.info = value?["location"] as? String ?? ""
                    thePost.postImageURL = value?["photoURL"] as? String ?? ""
                    thePost.timePost = value?["timestamp"] as? NSDate
                    thePost.upVotes = value?["upvotes"] as? Int ?? 0
                    print("3" + userID)

                    self.postArray.append(thePost)

//                      Uncomment if you want to reload data as fetched from Firebase without waiting for all the data to be fetched.
//                    self.tableView.reloadData()

                    userPostArrayObjFetched += 1

                    if userPostArrayObjFetched == userArray.count{
                         self.tableView.reloadData()
                    }
                })
            })
        }
    }
</code>```

Body:
I have an issue with my least favourite part in Firebase. I want to pull a post from user's following list (every user has one and only one post). First, I created a completion handler to get a list of all followers from Firebase and store it in userArray array of strings:

func GetUsersInFollowing(completion: @escaping (Bool) -> ()) {
    ref.child("following").queryOrdered(byChild: FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
        for group in snapshot.children {
            self.userArray.append((group as AnyObject).key)
        }
        completion(true)
    })
}

Now the plan is to pull a post from every element of userArray.
Here is where the problem starts. I call CreatePosts() immediately after GetUsersInFollowing() completes.

func CreatePosts() {
    for x in userArray {
        var thePost = Post()
        print("1")
        self.ref.child("users").child(x).observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? NSDictionary
            thePost.fullName = value?["fullname"] as? String ?? ""
            thePost.username = value?["username"] as? String ?? ""
            thePost.profileImageURL = value?["photourl"] as? String ?? ""
            print("2")
        })

        self.ref.child("posts").child(x).observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? NSDictionary
            thePost.description = value?["description"] as? String ?? ""
            thePost.info = value?["location"] as? String ?? ""
            thePost.postImageURL = value?["photoURL"] as? String ?? ""
            thePost.timePost = value?["timestamp"] as? NSDate
            thePost.upVotes = value?["upvotes"] as? Int ?? 0
        })

        self.postArray.append(thePost)
        self.tableView.reloadData()
    }
}

Everything looks ok to me, but it surely isn't. Here's how I create cells:

func configureCell(post: Post) {
    self.post = post
    self.username.text = post.username
    self.profileImage = post.profileImageURL
    print("3")
    self.fullname.text = post.fullName
    self.timestamp.text = post.timePost
    self.upvotes.text = post.upVotes
    self.location.text = post.location
    self.descriptionText.text = post.description
}

The output in the console varies, but usually I get:
1
1
3
3
2
2

The idea is to first retrieve all data from Firebase, add it to post object, append the object to the array and then create cell for that object with data downloaded. Cell is already created even though data is not retrieved. I think that is the problem. Thank you, every suggestion is appreciated.

Body:
You need to inner query for combining both user profile data and post data.
Like this -

    func CreatePosts() {

        //Using userPostArrayObjFetched as a counter to check the number of data fetched.
        //Remove this code, if you don't want to wait till all the user data is fetched.
        var userPostArrayObjFetched = 0

        for (index,userID) in userArray.enumerated() {

            print("1" + userID)

            self.ref.child("users").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in

                var thePost = Post()

                let value = snapshot.value as? NSDictionary
                thePost.fullName = value?["fullname"] as? String ?? ""
                thePost.username = value?["username"] as? String ?? ""
                thePost.profileImageURL = value?["photourl"] as? String ?? ""
                print("2" + userID)

                self.ref.child("posts").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
                    let value = snapshot.value as? NSDictionary
                    thePost.description = value?["description"] as? String ?? ""
                    thePost.info = value?["location"] as? String ?? ""
                    thePost.postImageURL = value?["photoURL"] as? String ?? ""
                    thePost.timePost = value?["timestamp"] as? NSDate
                    thePost.upVotes = value?["upvotes"] as? Int ?? 0
                    print("3" + userID)

                    self.postArray.append(thePost)

//                      Uncomment if you want to reload data as fetched from Firebase without waiting for all the data to be fetched.
//                    self.tableView.reloadData()

                    userPostArrayObjFetched += 1

                    if userPostArrayObjFetched == userArray.count{
                         self.tableView.reloadData()
                    }
                })
            })
        }
    }


问:
Incorrect syntax near the keyword 'JOIN'. using asp.net
Kindly help me on identifying the cause of this error

Incorrect syntax near the keyword 'JOIN'

Here is the code:

```<code>Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");

string queryGuitarItems = "DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)";

using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
    using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
    {
        connectionGuitarItems.Open();
        commandGuitarItems.Connection = connectionGuitarItems;
        commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
        commandGuitarItems.ExecuteNonQuery();

        connectionGuitarItems.Close();
        commandGuitarItems.Parameters.Clear();
    }
}
</code>```

答:
Here is the right to do delete from join syntax

DELETE S  --missing alias name
FROM stringInstrumentItem S
JOIN brand B
  ON S.brandId = B.brandId
WHERE B.name = @brand
```

Note : You don't need the sub-query, since Brand table is already joined

Body:
Kindly help me on identifying the cause of this error

Incorrect syntax near the keyword 'JOIN'

Here is the code:

Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");

string queryGuitarItems = "DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)";

using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
    using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
    {
        connectionGuitarItems.Open();
        commandGuitarItems.Connection = connectionGuitarItems;
        commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
        commandGuitarItems.ExecuteNonQuery();

        connectionGuitarItems.Close();
        commandGuitarItems.Parameters.Clear();
    }
}

Body:
Here is the right to do delete from join syntax

DELETE S  --missing alias name
FROM stringInstrumentItem S
JOIN brand B
  ON S.brandId = B.brandId
WHERE B.name = @brand

Note : You don't need the sub-query, since Brand table is already joined


问:
How can I update files on Amazon's CDN (CloudFront)?
Is there any way to update files stored on Amazon CloudFront (Amazon's CDN service)?
Seems like it won't take any update of a file we make (e.g. removing the file and storing the new one with the same file name as before).
Do I have to explicitly trigger an update process to remove the files from the edge servers to get the new file contents published?

Thanks for your help

答: Cyberduck for Mac & Windows provides a user interface for object invalidation. Refer to http://trac.cyberduck.ch/wiki/help/en/howto/cloudfront.</p>


问:
platformUniversalDynamic not found after update to angular 4
i updated my project to angular4. but now i get an error in my boot-client file. I think it comes from webpack/HMR, but i dosn't really know. Before the error, i don't know something about this file.

The error: cannot find module angular2-universal.

I searched many days for a bugfix, but i dont find something.

```<code>import 'angular2-universal-polyfills/browser';
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
import 'bootstrap';

// Enable either Hot Module Reloading or production mode
if (module['hot']) {
    module['hot'].accept();
    module['hot'].dispose(() => { platform.destroy(); });
} else {
    enableProdMode();
}

// Boot the application, either now or when the DOM content is loaded
const platform = platformUniversalDynamic();
//const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
    bootApplication();
} else {
    document.addEventListener('DOMContentLoaded', bootApplication);
}
</code>```

答:
I think angular2-universal is no more relevant in Angular4 like Richards said.
Maybe the workaround is to use

```<code>    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

    const platform = platformBrowserDynamic();
    platform.bootstrapModule(AppModule);
</code>```

BTW that's the initial code when you create a new Angular project from scratch using @angular/cli.

Body:
i updated my project to angular4. but now i get an error in my boot-client file. I think it comes from webpack/HMR, but i dosn't really know. Before the error, i don't know something about this file.

The error: cannot find module angular2-universal.

I searched many days for a bugfix, but i dont find something.

import 'angular2-universal-polyfills/browser';
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
import 'bootstrap';

// Enable either Hot Module Reloading or production mode
if (module['hot']) {
    module['hot'].accept();
    module['hot'].dispose(() => { platform.destroy(); });
} else {
    enableProdMode();
}

// Boot the application, either now or when the DOM content is loaded
const platform = platformUniversalDynamic();
//const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
    bootApplication();
} else {
    document.addEventListener('DOMContentLoaded', bootApplication);
}

Body:
I think angular2-universal is no more relevant in Angular4 like Richards said.
Maybe the workaround is to use

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

    const platform = platformBrowserDynamic();
    platform.bootstrapModule(AppModule);

BTW that's the initial code when you create a new Angular project from scratch using @angular/cli.


问:
Bootstrap - Adding a pixel border to the active link on a menu
I'm styling my navigation menu but I'm having some trouble. On mobile mode, I have home selected, and gallery is hovered, as per the image below.

However, I want there to be a 1 pixel border running between them. I have the following CSS:

```<code>/* Small Devices, Tablets */
@media only screen and (max-width: 766px) {
.collapsing, .in {background-color: #transparent;  border: 1px; border-color: #7A292A;}
.collapsing .in ul li a {color: #DEE0A3!important;}
.collapsing ul li a:hover, .in ul li a:hover {color: #9D343D!important; border: 1px; border-color: #7A292A;}
.collapsing ul li a:focus, .in ul li a:focus {background-color: #000 !important;}
}
</code>```

But it's not working. Any ideas? I think I want a 1px border at the bottom of the current active navigation link, which I thought was the focus link.

答:
Add this and see if that works :</p>

```<code> .collapsing ul li a:active, .in ul li a:active {border-bottom: 1px solid #000 !important;}
</code>```

Body:
I'm styling my navigation menu but I'm having some trouble. On mobile mode, I have home selected, and gallery is hovered, as per the image below.

However, I want there to be a 1 pixel border running between them. I have the following CSS:

/* Small Devices, Tablets */
@media only screen and (max-width: 766px) {
.collapsing, .in {background-color: #transparent;  border: 1px; border-color: #7A292A;}
.collapsing .in ul li a {color: #DEE0A3!important;}
.collapsing ul li a:hover, .in ul li a:hover {color: #9D343D!important; border: 1px; border-color: #7A292A;}
.collapsing ul li a:focus, .in ul li a:focus {background-color: #000 !important;}
}

But it's not working. Any ideas? I think I want a 1px border at the bottom of the current active navigation link, which I thought was the focus link.

Body:
Add this and see if that works :

 .collapsing ul li a:active, .in ul li a:active {border-bottom: 1px solid #000 !important;}


问:
Java - Pausing Akka Scheduler
So I have this scheduler, which is not doing anything right now except incrementing a number . When it gets to 5, I want to pause it and afterwards reset the number tries. I get to the point where totalTries reached 5, and then it stops for 30 seconds. But after those 30 seconds have passed, it instantly logs the next 5 totalTries and pauses again. Clearly, something more is going on behind the curtains.

Am I misunderstanding how this is used? What I want to do is pause the ActorSystem system entirely for that period of time. Any hints greatly appreciated.

```<code>system.scheduler().schedule(
    Duration.create(5, TimeUnit.SECONDS),
    Duration.create(1, TimeUnit.SECONDS),
    new Runnable() {

        public void run() {

                int totalTries = incrementTries(1);
                logger.info("tries: " + totalTries);

                if(totalTries >= 5) {
                    logger.info("5 tries reached, waiting 30 seconds.");
                    try {
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        logger.info("Sleep interrupted" + e);
                    }
                    resetTries();
                }
            }
        }
    }, system.dispatcher());
</code>```

答:
You cannot pause the ActorSystem as far as I know. What your code does by calling Thread.sleep(30000) is blocking the scheduler thread, when it wakes up, it tries to catch up on its schedule by issuing pending notifications - that's correct behaviour.

Using Thread.sleep to block a thread in an actor system is not recommended.

What I'd do is:

Once your counter reaches 5:

cancel the schedule

schedule a new one-off notification in 30 seconds with a handler that will schedule the original notification all over again

Alternatively, you can keep the original schedule going and once your counter reaches 5:

set a flag to ignore further notifications

schedule a new one-off notification in 30 seconds with a handler that will unset the flag set in the above step

Title: Java - Pausing Akka Scheduler

Body:
So I have this scheduler, which is not doing anything right now except incrementing a number . When it gets to 5, I want to pause it and afterwards reset the number tries. I get to the point where totalTries reached 5, and then it stops for 30 seconds. But after those 30 seconds have passed, it instantly logs the next 5 totalTries and pauses again. Clearly, something more is going on behind the curtains.

Am I misunderstanding how this is used? What I want to do is pause the ActorSystem system entirely for that period of time. Any hints greatly appreciated.

system.scheduler().schedule(
    Duration.create(5, TimeUnit.SECONDS),
    Duration.create(1, TimeUnit.SECONDS),
    new Runnable() {

        public void run() {

                int totalTries = incrementTries(1);
                logger.info("tries: " + totalTries);

                if(totalTries >= 5) {
                    logger.info("5 tries reached, waiting 30 seconds.");
                    try {
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        logger.info("Sleep interrupted" + e);
                    }
                    resetTries();
                }
            }
        }
    }, system.dispatcher());


问:
Create CLR assembly and available group?
I created a CLR stored procedure in C# and I will need to deploy it to SQL server available group cluster.

Can I just copy the assembly DLL to the hard drive of the primary server and run "create assembly" on the primary server?

Or I will need to copy the DLL to all the server and run create assembly separately on the server in the cluster?

答: You need to do this only once per database, regardless of whether it's in an availability group or not. Once you run the create assembly statement, the bits are inside the database so you don't even need the dll file anymore.


问:
How can I make ffmpeg executable file separately by using gcc command?
actually, my goal is to use ffmpeg on Qt platform. But tow of them is unfamiliar with me..
I tried command on ./ffmpeg directory after build (./configure, make, sudo make install) as below on Mac (os x) 10.12.4 (Sierra)

$ gcc ffmpeg.c -o a.out -I /usr/local/include -I /Users/koseonjae/ffmpeg -L /usr/local/lib -lavdevice -lavutil -lavformat -lavcodec -lavutil -lx264 -lvpx -lvorbisenc -lvorbis -ltheoraenc -ltheoradec -logg -lmp3lame -lbz2 -lz -lxslt -lfdk-aac -liconv -lopus -lx265 -lxvidcore -lpng16 -lswresample -framework CoreFoundation -framework CoreServices -framework AudioUnit -framework AudioToolbox -framework CoreAudio -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework CoreAudio -framework Foundation -framework Security -framework VideoDecodeAcceleration -framework VideoToolbox

I added many library, but result is as below

/Users/koseonjae/ffmpeg/ffmpeg2.h:157:8: error: unknown type name 'BOOL'
static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType);

/Users/koseonjae/ffmpeg/ffmpeg2.h:157:19: error: expected ';' after top level declarator
static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType);

what library should I add?? thank you!

答:
This question is not about Qt, but about compiling ffmpeg on a Mac.
Read on about detailed installation of ffmpeg dependencies: https://trac.ffmpeg.org/wiki/CompilationGuide/MacOSX .</p>


问:
Firebase : How to add new attribute in existing table
I am working on a project in swift and having firebase as backend for managing data.

```<code>FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
</code>```

This is what I have set in app delegate file. Now in my chat module, I have added message information in firebase database through below code.

```<code>    let messageData = ["text": text, "senderId": senderId, "senderName": senderDisplayName, "MediaType": "TEXT"]
    self.messageSentRef?.child("Messages").childByAutoId().setValue(messageData)
</code>```

Now I want to add one new attribute named TimeStamp in messages table.

Anyone can help me how to do that?

答:
In Firebase, data can be represented by a dictionary of key:value pairs. The key is always a string, but the value can be a number of different things, a String, Int etc.

The value can also be another dictionary of key: value pairs.

In your case, this line of code generates a key: value pair of a string: and another string (messsageData)

self.messageSentRef?.child("Messages").childByAutoId().setValue(messageData)

which looks like this

```<code>app_node
   Messages
      -y88hj3-39i9isdf: "some message data"
</code>```

If you want to also have a timestamp child, instead of writing the single string, you can write an entire dictionary of key: value pairs - like this

```<code>let messageDictionary = [
   "text": "some text",
   "senderId": "the sender Id",
   "senderDisplayName": "the sender display name",
   "mediaType": "a media type",
   "timestamp": "170708"
]

let messageItemRef = self.ref.child("Messages")
messageItemRef.childByAutoId().setValue(messageDictionary)
</code>```

which creates the following node:

```<code>app_node
   Messages
      -Y9js9s9m494jms:
          text: "some text"
          senderId: "the sender Id"
          senderDisplayName: "the sender display name"
          mediaType: "a media type"
          timestamp: :170708"
</code>```

Body:
I am working on a project in swift and having firebase as backend for managing data.

FirebaseApp.configure()
Database.database().isPersistenceEnabled = true

This is what I have set in app delegate file. Now in my chat module, I have added message information in firebase database through below code.

    let messageData = ["text": text, "senderId": senderId, "senderName": senderDisplayName, "MediaType": "TEXT"]
    self.messageSentRef?.child("Messages").childByAutoId().setValue(messageData)

Now I want to add one new attribute named TimeStamp in messages table.

Anyone can help me how to do that?

Body:
In Firebase, data can be represented by a dictionary of key:value pairs. The key is always a string, but the value can be a number of different things, a String, Int etc.

The value can also be another dictionary of key: value pairs.

In your case, this line of code generates a key: value pair of a string: and another string (messsageData)

self.messageSentRef?.child("Messages").childByAutoId().setValue(messageData)

which looks like this

app_node
   Messages
      -y88hj3-39i9isdf: "some message data"

If you want to also have a timestamp child, instead of writing the single string, you can write an entire dictionary of key: value pairs - like this

let messageDictionary = [
   "text": "some text",
   "senderId": "the sender Id",
   "senderDisplayName": "the sender display name",
   "mediaType": "a media type",
   "timestamp": "170708"
]

let messageItemRef = self.ref.child("Messages")
messageItemRef.childByAutoId().setValue(messageDictionary)

which creates the following node:

app_node
   Messages
      -Y9js9s9m494jms:
          text: "some text"
          senderId: "the sender Id"
          senderDisplayName: "the sender display name"
          mediaType: "a media type"
          timestamp: :170708"


问:
XCOPY batch file
I’m looking to create a batch file that transfers all my music from my external drive to my Samsung note 3. The idea is just to click the batch file and for it to update any song on my external on my phone.

Heres what I’ve got

```<code>XCOPY "E:\Music\*.*" "Computer\SAMSUNG-SM-N900A\Phone\Music\" /e /c /r /k /y /v
</code>```

The problem I see is that it’s creating a folder on my desktop with that path, the directory on my desktop being computer with the following subfolders.

I’m not sure why it won’t recognize the path, any ideas?

答:
You can't directly copy files from windows to an android device, its a different file system. You can probably do it manually with this program:
https://android-file-manager.en.softonic.com/</p>

Title: XCOPY batch file

Body:
I’m looking to create a batch file that transfers all my music from my external drive to my Samsung note 3. The idea is just to click the batch file and for it to update any song on my external on my phone.

Heres what I’ve got

XCOPY "E:\Music\*.*" "Computer\SAMSUNG-SM-N900A\Phone\Music\" /e /c /r /k /y /v

The problem I see is that it’s creating a folder on my desktop with that path, the directory on my desktop being computer with the following subfolders.

I’m not sure why it won’t recognize the path, any ideas?


问:
Getting jQuery ajax and asp.net webmethod xml response to work
I have an asp.net WebMethod that returns an XmlDocument object.
I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error').

To reproduce, Asp.net C#:

```<code>[WebMethod]
public static XmlDocument test(string name)
{
    XmlDocument result = new XmlDocument();
    XmlElement root = result.CreateElement("Data");
    result.AppendChild(root);

    XmlElement element = result.CreateElement("AnElement");
    element.SetAttribute("Name", name);
    root.AppendChild(element);

    return result;
}
</code>```

JavaScript:

```<code>function CallForData(name) {
    $.ajax({
        type: "POST",
        url: "AppName.aspx/test",
        data: "{'name': " + name+ "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function (response) { ParseXML(response); },
        error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
    });
}
</code>```

If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure.
I want an XML response that I can parse using jQuery.

I think I possibly need to add some format identification to the XML document but aren't sure. Can anyone point out the problem?

答:
Fixed by adding

```<code>[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]
</code>```

to the web method.

Credit to riteshtandon23 in
this thread

Body:
I have an asp.net WebMethod that returns an XmlDocument object.
I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error').

To reproduce, Asp.net C#:

[WebMethod]
public static XmlDocument test(string name)
{
    XmlDocument result = new XmlDocument();
    XmlElement root = result.CreateElement("Data");
    result.AppendChild(root);

    XmlElement element = result.CreateElement("AnElement");
    element.SetAttribute("Name", name);
    root.AppendChild(element);

    return result;
}

JavaScript:

function CallForData(name) {
    $.ajax({
        type: "POST",
        url: "AppName.aspx/test",
        data: "{'name': " + name+ "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function (response) { ParseXML(response); },
        error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
    });
}

If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure.
I want an XML response that I can parse using jQuery.

I think I possibly need to add some format identification to the XML document but aren't sure. Can anyone point out the problem?

Body:
Fixed by adding

[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]

to the web method.

Credit to riteshtandon23 in
this thread


问:
Angular2 Http POST header argument type error
This service should perform a HTTP post request to my PHP backend api, but ng2 won't compile the project, it throws the following error:

ERROR in login-service.ts (25,9): Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'.
    Types of property 'headers' are incompatible.
      Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated.
        Property 'keys' is missing in type 'Headers'.

My snippet looks like:

```<code>import { HttpModule }     from '@angular/http';
import { Injectable }     from '@angular/core';
import { Http }           from '@angular/http';
import { Response }       from '@angular/http';
import { Headers }        from '@angular/http';

@Injectable()
export class LoginService {
  constructor(private http: Http) {

  }
  login(username, password){
    var body = 'foo=bar&foo1=bar1';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http
    .post('http://127.0.0.1/server.php', body, { headers: headers })
    .subscribe((data:Response) => {
       let res = data.text();
       console.log('Result: ',res);
     }, error => {
       console.log('Error: ', JSON.stringify(error.json()));
     });
  }
}
</code>```

This code works perfectly in a different ng2 app.

答:
You have to use:

```<code>let options = new RequestOptions({ headers: headers });
</code>```

Updated Login Method:

```<code> login(username, password){
    var body = 'foo=bar&foo1=bar1';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({ headers: headers });
    this.http
    .post('http://127.0.0.1/server.php', body, options)
    .subscribe((data:Response) => {
       let res = data.text();
       console.log('Result: ',res);
     }, error => {
       console.log('Error: ', JSON.stringify(error.json()));
     });
  }
</code>```

Body:
This service should perform a HTTP post request to my PHP backend api, but ng2 won't compile the project, it throws the following error:

ERROR in login-service.ts (25,9): Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'.
    Types of property 'headers' are incompatible.
      Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated.
        Property 'keys' is missing in type 'Headers'.

My snippet looks like:

import { HttpModule }     from '@angular/http';
import { Injectable }     from '@angular/core';
import { Http }           from '@angular/http';
import { Response }       from '@angular/http';
import { Headers }        from '@angular/http';

@Injectable()
export class LoginService {
  constructor(private http: Http) {

  }
  login(username, password){
    var body = 'foo=bar&foo1=bar1';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http
    .post('http://127.0.0.1/server.php', body, { headers: headers })
    .subscribe((data:Response) => {
       let res = data.text();
       console.log('Result: ',res);
     }, error => {
       console.log('Error: ', JSON.stringify(error.json()));
     });
  }
}

This code works perfectly in a different ng2 app.

Body:
You have to use:

let options = new RequestOptions({ headers: headers });

Updated Login Method:

 login(username, password){
    var body = 'foo=bar&foo1=bar1';
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({ headers: headers });
    this.http
    .post('http://127.0.0.1/server.php', body, options)
    .subscribe((data:Response) => {
       let res = data.text();
       console.log('Result: ',res);
     }, error => {
       console.log('Error: ', JSON.stringify(error.json()));
     });
  }


问:
Change background-color with different shades of color
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

```<code>background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)
</code>```

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

答:
Below is an example of the code you're looking for. If you want it to apply to the whole page then you should add it to the body tag. I used http://www.colorzilla.com/gradient-editor/ to generate this code snippet. </p>

```<code>body { /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#6db3f2+0,f9e759+0,f9e759+0,f9e759+0,f2f257+16,e85353+16,e85353+57,4239a0+57,4239a0+57,4239a0+83,66ff5b+83,66ff5b+83 */
background: #6db3f2; /* Old browsers */
background: -moz-linear-gradient(left, #6db3f2 0%, #f9e759 0%, #f9e759 0%, #f9e759 0%, #f2f257 16%, #e85353 16%, #e85353 57%, #4239a0 57%, #4239a0 57%, #4239a0 83%, #66ff5b 83%, #66ff5b 83%); /* FF3.6-15 */
background: -webkit-linear-gradient(left, #6db3f2 0%,#f9e759 0%,#f9e759 0%,#f9e759 0%,#f2f257 16%,#e85353 16%,#e85353 57%,#4239a0 57%,#4239a0 57%,#4239a0 83%,#66ff5b 83%,#66ff5b 83%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, #6db3f2 0%,#f9e759 0%,#f9e759 0%,#f9e759 0%,#f2f257 16%,#e85353 16%,#e85353 57%,#4239a0 57%,#4239a0 57%,#4239a0 83%,#66ff5b 83%,#66ff5b 83%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#6db3f2', endColorstr='#66ff5b',GradientType=1 ); /* IE6-9 */ }
</code>```

<p>Here is an example with the colors you mentioned. </p>

```<code>linear-gradient(to left, red 15%, orange 15%, orange 30%, yellow 30%, yellow 45%, green 45%, green 60%, blue 60%, blue 75%, indigo 75%, indigo 90%, violet 90%, violet)
</code>```

Body:
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

Body:
Below is an example of the code you're looking for. If you want it to apply to the whole page then you should add it to the body tag. I used http://www.colorzilla.com/gradient-editor/ to generate this code snippet.

body { /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#6db3f2+0,f9e759+0,f9e759+0,f9e759+0,f2f257+16,e85353+16,e85353+57,4239a0+57,4239a0+57,4239a0+83,66ff5b+83,66ff5b+83 */
background: #6db3f2; /* Old browsers */
background: -moz-linear-gradient(left, #6db3f2 0%, #f9e759 0%, #f9e759 0%, #f9e759 0%, #f2f257 16%, #e85353 16%, #e85353 57%, #4239a0 57%, #4239a0 57%, #4239a0 83%, #66ff5b 83%, #66ff5b 83%); /* FF3.6-15 */
background: -webkit-linear-gradient(left, #6db3f2 0%,#f9e759 0%,#f9e759 0%,#f9e759 0%,#f2f257 16%,#e85353 16%,#e85353 57%,#4239a0 57%,#4239a0 57%,#4239a0 83%,#66ff5b 83%,#66ff5b 83%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, #6db3f2 0%,#f9e759 0%,#f9e759 0%,#f9e759 0%,#f2f257 16%,#e85353 16%,#e85353 57%,#4239a0 57%,#4239a0 57%,#4239a0 83%,#66ff5b 83%,#66ff5b 83%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#6db3f2', endColorstr='#66ff5b',GradientType=1 ); /* IE6-9 */ }

Here is an example with the colors you mentioned.

linear-gradient(to left, red 15%, orange 15%, orange 30%, yellow 30%, yellow 45%, green 45%, green 60%, blue 60%, blue 75%, indigo 75%, indigo 90%, violet 90%, violet)


问:
Angular 2 declare global css or js frameworks
I have a simple question more about best practice/performance.

When you have to include a CSS or Javascript framework (bootstrap, jquery, ...) to your project, do you include them on the index.html or declare it on the .angular-cli.json?

I know that bouth aproaches work, but is there a best practice on this? Is there an advantage of using one or other?

Thanks for your comments.

答:
The best approach is to install them using npm or yarn package managers and then add them to your .angular-cli.json

The advantage here is that you just have to look at one place to find all your dependencies, the package.json file. You can also easily upgrade to the latest version and the package manager will warn you if the version is not compatible with your other packages.


问:
How to extract an assembly from the GAC?
There is a package I have to deal with which installs assemblies straight into the GAC (e.g. somewhere deep in %windows%/assembly).

How do I exorcise the actual assembly (the DLL) from the GAC into the normal file system?

Thanks.

答: Open RUN then type %windir%\assembly\GAC_MSIL, this will open your dlls in folders' view you can then navigate to your dll named folder and open it, you will find your dll file and copy it easily

OwnerDisplayName: AngryHacker


问:
XmlReader skipping adjoined elements
Whilst trying to minimise the memory footprint of an XML parsing program, specifically avoiding the loading hundreds of megabytes using XElement.Load(), I came across articles suggesting using the older XmlReader e.g. here.

I need to internally reconstruct each major element as an XElement to avoid major refactoring.  However, I discovered that if my source elements are directly adjoining, this approach skips every 2nd element.

I've torn down the problem to this unit-test (MSTest2 with FluentAssertions):

[DataTestMethod]
[DataRow("<data><entry>1</entry><entry>2</entry><entry>3</entry><entry>4</entry></data>")]
[DataRow("<data><entry>1</entry> <entry>2</entry> <entry>3</entry> <entry>4</entry></data>")]
public void XmlReaderCount(string input)
{
    var sr = new StringReader(input);
    var xml = XmlReader.Create(sr);
    xml.MoveToContent();

    var data = new List<string>();
    while (xml.Read())
    {
        if (xml.LocalName == "entry" && xml.NodeType == XmlNodeType.Element)
        {
            var element = (XElement)System.Xml.Linq.XNode.ReadFrom(xml);
            data.Add(element.Value);
        }
    }

    data.Should()
        .HaveCount(4);
}
```

<p>The first (data-driven) test fails with:</p>

<blockquote>
  <p>Expected collection to contain 4 item(s), but found 2.</p>
</blockquote>

<p>As it puts 1 and 3 into the data collection.  It does loop 4 times, but every other element has an <code>xml.NodeType</code> of <code>Text</code>, not <code>Element</code>.  The second test (with spaces between the <code></entry></code> and <code><entry></code> passes by processing all 4.  </p>

<p>In my real world example, I can't easily change the source. I do already have a solution, inspired by another StackOverflow question so I can do the following, but it seems strange - is something wrong?</p>

<pre class="lang-cs prettyprint-override"><code>[DataTestMethod]
[DataRow("<data><entry>1</entry><entry>2</entry><entry>3</entry><entry>4</entry></data>")]
[DataRow("<data><entry>1</entry> <entry>2</entry> <entry>3</entry> <entry>4</entry></data>")]
public void XmlReaderCountSubtree(string input)
{
    var data = new List<string>();

    var sr = new StringReader(input);
    var xml = XmlReader.Create(sr);
    xml.MoveToContent();

    while (xml.Read())
    {
        if (xml.LocalName == "entry" && xml.NodeType == XmlNodeType.Element)
        {
            using (var subtree = xml.ReadSubtree())
            {
                subtree.MoveToContent();
                var content = subtree.ReadOuterXml();
                var element = XElement.Parse(content);
                data.Add(element.Value);
            }
         }
     }

     data.Should()
         .HaveCount(4);
}
</code>```

答:
When you call ReadFrom(xml) , the state of xml is changed. Its cursor is moved forward to the next element. Your code then moves on to while (xml.Read()) and so ignores that new element completely.

With the second data set, the ignored (and uninspected) elements are the whitespace nodes so you get away with it. But basically, you reading algorithm is wrong.

A fix for your first approach, not pretty but it works:

```<code>xml.Read();
while (! xml.EOF)
{
    if (xml.LocalName == "entry" && xml.NodeType == XmlNodeType.Element)
    {
        //using (var subtree = xml.ReadSubtree())
        {
            var element = (XElement)XNode.ReadFrom(xml);
            data.Add(element.Value);
        }
    }
    else
    {
        xml.Read();
    }
}
</code>```

Title: XmlReader skipping adjoined elements

Body:
Whilst trying to minimise the memory footprint of an XML parsing program, specifically avoiding the loading hundreds of megabytes using XElement.Load(), I came across articles suggesting using the older XmlReader e.g. here.

I need to internally reconstruct each major element as an XElement to avoid major refactoring.  However, I discovered that if my source elements are directly adjoining, this approach skips every 2nd element.

I've torn down the problem to this unit-test (MSTest2 with FluentAssertions):

[DataTestMethod]
[DataRow("<data><entry>1</entry><entry>2</entry><entry>3</entry><entry>4</entry></data>")]
[DataRow("<data><entry>1</entry> <entry>2</entry> <entry>3</entry> <entry>4</entry></data>")]
public void XmlReaderCount(string input)
{
    var sr = new StringReader(input);
    var xml = XmlReader.Create(sr);
    xml.MoveToContent();

    var data = new List<string>();
    while (xml.Read())
    {
        if (xml.LocalName == "entry" && xml.NodeType == XmlNodeType.Element)
        {
            var element = (XElement)System.Xml.Linq.XNode.ReadFrom(xml);
            data.Add(element.Value);
        }
    }

    data.Should()
        .HaveCount(4);
}

The first (data-driven) test fails with:

Expected collection to contain 4 item(s), but found 2.

As it puts 1 and 3 into the data collection.  It does loop 4 times, but every other element has an xml.NodeType of Text, not Element.  The second test (with spaces between the </entry> and <entry> passes by processing all 4.

In my real world example, I can't easily change the source. I do already have a solution, inspired by another StackOverflow question so I can do the following, but it seems strange - is something wrong?

[DataTestMethod]
[DataRow("<data><entry>1</entry><entry>2</entry><entry>3</entry><entry>4</entry></data>")]
[DataRow("<data><entry>1</entry> <entry>2</entry> <entry>3</entry> <entry>4</entry></data>")]
public void XmlReaderCountSubtree(string input)
{
    var data = new List<string>();

    var sr = new StringReader(input);
    var xml = XmlReader.Create(sr);
    xml.MoveToContent();

    while (xml.Read())
    {
        if (xml.LocalName == "entry" && xml.NodeType == XmlNodeType.Element)
        {
            using (var subtree = xml.ReadSubtree())
            {
                subtree.MoveToContent();
                var content = subtree.ReadOuterXml();
                var element = XElement.Parse(content);
                data.Add(element.Value);
            }
         }
     }

     data.Should()
         .HaveCount(4);
}

Body:
When you call ReadFrom(xml) , the state of xml is changed. Its cursor is moved forward to the next element. Your code then moves on to while (xml.Read()) and so ignores that new element completely.

With the second data set, the ignored (and uninspected) elements are the whitespace nodes so you get away with it. But basically, you reading algorithm is wrong.

A fix for your first approach, not pretty but it works:

xml.Read();
while (! xml.EOF)
{
    if (xml.LocalName == "entry" && xml.NodeType == XmlNodeType.Element)
    {
        //using (var subtree = xml.ReadSubtree())
        {
            var element = (XElement)XNode.ReadFrom(xml);
            data.Add(element.Value);
        }
    }
    else
    {
        xml.Read();
    }
}


问:
Return from list the double value that has the highest absolute value, without making the return value absolute
Short of iterating the collection, is there a way to return the double in a set that has the highest absolute value without making the values in the set actually absolute?</p>

```<code>double[] vals = new double[] { 2.3, 1.7, -3.8};

vals.Max(v => Math.Abs(v)); // This returns 3.8 instead of -3.8
</code>```

答:
One approach to consider:

```<code>var max = vals
    .OrderByDescending(z => Math.Abs(z))
    .FirstOrDefault();
</code>```

Alternatively, consider using MoreLinq's MaxBy. It is faster than both my and Samvel's solution, especially for larger sets of inputs.

```<code>var max = vals.MaxBy(z => Math.Abs(z));
</code>```

Body:
Short of iterating the collection, is there a way to return the double in a set that has the highest absolute value without making the values in the set actually absolute?

double[] vals = new double[] { 2.3, 1.7, -3.8};

vals.Max(v => Math.Abs(v)); // This returns 3.8 instead of -3.8

Body:
One approach to consider:

var max = vals
    .OrderByDescending(z => Math.Abs(z))
    .FirstOrDefault();

Alternatively, consider using MoreLinq's MaxBy. It is faster than both my and Samvel's solution, especially for larger sets of inputs.

var max = vals.MaxBy(z => Math.Abs(z));


答:
You have to give the table you want to delete an alias. I just named the table "sII". Furthermore you don't need an WHERE-clause. You could restrict the delete in the join-conditions too.

```<code>   DELETE sII
     FROM stringInstrumentItem  sII
INNER JOIN brand b
        ON sII.brandId = b.brandId
       AND b.name = @brand
</code>```

Title: Incorrect syntax near the keyword 'JOIN'. using asp.net

Body:
Kindly help me on identifying the cause of this error

Incorrect syntax near the keyword 'JOIN'

Here is the code:

Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");

string queryGuitarItems = "DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)";

using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
    using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
    {
        connectionGuitarItems.Open();
        commandGuitarItems.Connection = connectionGuitarItems;
        commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
        commandGuitarItems.ExecuteNonQuery();

        connectionGuitarItems.Close();
        commandGuitarItems.Parameters.Clear();
    }
}

Body:
You have to give the table you want to delete an alias. I just named the table "sII". Furthermore you don't need an WHERE-clause. You could restrict the delete in the join-conditions too.

   DELETE sII
     FROM stringInstrumentItem  sII
INNER JOIN brand b
        ON sII.brandId = b.brandId
       AND b.name = @brand


问:
PHP - Is this the factory method pattern?
I saw a resource online
http://www.labelmedia.co.uk/blog/posts/design-patterns-factory-method.html

From what I know this is not really the pattern. It's more of a mix between the the Simple Factory Idiom and Simple Factory Method.

Did they get it wrong ?

答: Hmm, yes. It looks more like a Simple Factory indeed. However, it might be they are refering to what is sometimes called "Static Factory Method".</p>


问:
codeigniter An uncaught Exception was encountered Type: RuntimeException not working in Linux server
Am creating a website using codeigniter. All the codes are working in localhost(XAMPP).

But same code not working in Linuxserver showing error like

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to locate the model you have specified: Admin_user

Filename: /home/capitalw/public_html/domain/system/core/Loader.php

Line Number: 344

Backtrace:

File: /home/capitalw/public_html/domain/application/controllers/Admin.php
  Line: 10
  Function: model

File: /home/capitalw/public_html/domain/index.php
  Line: 315
  Function: require_once

Here my codes are

application/controller/Admin.php

```<code>class Admin extends CI_Controller {

    public function __construct(){
        parent::__construct();
        //$this->load->library('common');
        $this->load->library('form_validation');
        $this->load->model('admin_user');

    }
}
</code>```

application/models/admin_user.php

```<code>class Admin_user extends CI_Model {

    function __construct()
    {
        parent::__construct();

    }
//some inser update codes here

}
</code>```

答:
Make sure your filenames and classes start with First Letter Only Upper Case The rest lower case.
https://www.codeigniter.com/user_guide/general/styleguide.html#file-naming

Admin_user.php

Not

admin_user.php

https://www.codeigniter.com/user_guide/general/styleguide.html#class-and-method-naming

Body:
Am creating a website using codeigniter. All the codes are working in localhost(XAMPP).

But same code not working in Linuxserver showing error like

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to locate the model you have specified: Admin_user

Filename: /home/capitalw/public_html/domain/system/core/Loader.php

Line Number: 344

Backtrace:

File: /home/capitalw/public_html/domain/application/controllers/Admin.php
  Line: 10
  Function: model

File: /home/capitalw/public_html/domain/index.php
  Line: 315
  Function: require_once

Here my codes are

application/controller/Admin.php

class Admin extends CI_Controller {

    public function __construct(){
        parent::__construct();
        //$this->load->library('common');
        $this->load->library('form_validation');
        $this->load->model('admin_user');

    }
}

application/models/admin_user.php

class Admin_user extends CI_Model {

    function __construct()
    {
        parent::__construct();

    }
//some inser update codes here

}


问:
Building an executable file for python code using py2exe. ImportError: No module named cell
I installed "py2exe" for "Python2.7" , made a "Hello World" program, used py2exe to build its exe and it worked perfectly.

Now when I tried building the exe of my actual code, the folders get created and exe is also created without any problem but when I launch the exe the console appears for less than a second and closes.

Following are import commands which I am using:

```<code>import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
__version__='2.4.8'
from openpyxl import __version__
from openpyxl import Workbook
from Tkinter import *
import tkFileDialog
</code>```

My setup file is like this:

```<code>from distutils.core import setup
import py2exe
__version__='2.3.5'
from openpyxl import __version__
from openpyxl.cell import Cell

setup(
    windows=[{"script":'try.py'}],
    options = {"py2exe":{"includes":["tweepy","openpyxl.reader.excel","openpyxl.cell","openpyxl.workbook","openpyxl.worksheet","jdcal","xlutils","json","xlrd","Tkconstants","Tkinter","tkFileDialog","xml.etree.ElementPath", "xml.etree.ElementTree","xml.etree.cElementTree"],
 "packages": ["xml.etree", "xml"]}}
    )
</code>```

The error which I am getting is :

```<code>Traceback (most recent call last):
  File "try.py", line 7, in <module>
  File "openpyxl\__init__.pyc", line 29, in <module>
  File "openpyxl\workbook\__init__.pyc", line 5, in <module>
  File "openpyxl\workbook\workbook.pyc", line 8, in <module>
  File "openpyxl\worksheet\__init__.pyc", line 4, in <module>
  File "openpyxl\worksheet\worksheet.pyc", line 23, in <module>
  File "openpyxl\utils\__init__.pyc", line 5, in <module>
ImportError: No module named cell
</code>```

My file name is try.py

答:
You problem is with openpyxl\utils\__init__.py that imports .cell, i.e. openpyxl\utils\cell.py which is not included in your application.

In your setup.py you listed some of the openpyxl subpackages in option include:

```<code>options = {"py2exe":{"includes":["tweepy","openpyxl.reader.excel","openpyxl.cell","openpyxl.workbook","openpyxl.worksheet",…
</code>```

And openpyxl has a lot of subpackages.

You have to list openpyxl in packages:

```<code>setup(
    …
    options = {"py2exe":{
        "packages": ["openpyxl", "xml.etree", "xml"]}}
    )
</code>```

No sure about listing all subpackages. If the packages above don't help try
listing them all:

```<code>setup(
    …
    options = {"py2exe":{
        "packages": ["openpyxl", "openpyxl.workbook", etc…, "xml.etree", "xml"]}}
    )
</code>```

Body:
I installed "py2exe" for "Python2.7" , made a "Hello World" program, used py2exe to build its exe and it worked perfectly.

Now when I tried building the exe of my actual code, the folders get created and exe is also created without any problem but when I launch the exe the console appears for less than a second and closes.

Following are import commands which I am using:

import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
__version__='2.4.8'
from openpyxl import __version__
from openpyxl import Workbook
from Tkinter import *
import tkFileDialog

My setup file is like this:

from distutils.core import setup
import py2exe
__version__='2.3.5'
from openpyxl import __version__
from openpyxl.cell import Cell

setup(
    windows=[{"script":'try.py'}],
    options = {"py2exe":{"includes":["tweepy","openpyxl.reader.excel","openpyxl.cell","openpyxl.workbook","openpyxl.worksheet","jdcal","xlutils","json","xlrd","Tkconstants","Tkinter","tkFileDialog","xml.etree.ElementPath", "xml.etree.ElementTree","xml.etree.cElementTree"],
 "packages": ["xml.etree", "xml"]}}
    )

The error which I am getting is :

Traceback (most recent call last):
  File "try.py", line 7, in <module>
  File "openpyxl\__init__.pyc", line 29, in <module>
  File "openpyxl\workbook\__init__.pyc", line 5, in <module>
  File "openpyxl\workbook\workbook.pyc", line 8, in <module>
  File "openpyxl\worksheet\__init__.pyc", line 4, in <module>
  File "openpyxl\worksheet\worksheet.pyc", line 23, in <module>
  File "openpyxl\utils\__init__.pyc", line 5, in <module>
ImportError: No module named cell

My file name is try.py

Body:
You problem is with openpyxl\utils\__init__.py that imports .cell, i.e. openpyxl\utils\cell.py which is not included in your application.

In your setup.py you listed some of the openpyxl subpackages in option include:

options = {"py2exe":{"includes":["tweepy","openpyxl.reader.excel","openpyxl.cell","openpyxl.workbook","openpyxl.worksheet",…

And openpyxl has a lot of subpackages.

You have to list openpyxl in packages:

setup(
    …
    options = {"py2exe":{
        "packages": ["openpyxl", "xml.etree", "xml"]}}
    )

No sure about listing all subpackages. If the packages above don't help try
listing them all:

setup(
    …
    options = {"py2exe":{
        "packages": ["openpyxl", "openpyxl.workbook", etc…, "xml.etree", "xml"]}}
    )


问:
What I should use font icons or sprite images?
What I should use font icons or sprite images for better performance? What will
be load faster and light weighted?</p>

答:
You use font icons or sprite images when you have a lot of small separate images, you basically bundle them into one image so one request is done to get all the images.

Typically those are used for small icons for buttons, or icons in the navbar, and similar stuff. For example StackOverflow's editor buttons on the top (the bold, italic, etc.) probably use font images for that:

Imagine the case where you have had to load something like 10 different images just for that bar of buttons, that would be very inefficient.

Another example is emojies. There are thousands of emojies out there, imagine if you have to load each one of them in a separate request.

Currently with the modern websites, usually font icons are used much more than sprite images.

This also reduces the server load as well. It's all for efficiency purposes, and because we use small images to represent buttons instead of text sometimes.


问:
Android Studio Adding Dependencies
I have crated an app with multiple modules, Then i have linked them as Library files.
Now in order for me to create an onClick button to take me to the next module, i believe i have to make a dependency between the two modules.
When i try to add the dependencies i get this error:

before adding dependencies

after adding dependencies

the error

i am trying to create a button that calls another activity called MainActivity in Formupload module.

答:
Your libraries-formupload has a build.gradle for an app (main) module.

On top of you libraries-formupload/build.gradle you have

apply plugin: 'com.android.application'

but it must be:

apply plugin: 'com.android.library'

Make sure all modules build.gradle files have correct import statements.

applicationId, buildTypes and productFlavors also belong to the app module. Move them there.

Title: Android Studio Adding Dependencies