问:
Starting Tomcat with local user causes JVM_Bind exception
I have a tomcat service that starts fine with the local system account but when I switch it over to log on as a local user I am getting a JVM_Bind exception. The service starts and then shuts down. </p>

<p>It looks like the shutdown port is already being used by another service. I can change the tomcat service to use a different shutdown port, but I want to understand why it starts fine with the system account and complains about the shutdown port with the user account. </p>

```<code>06-Jun-2017 15:46:13.801 SEVERE [main] org.apache.catalina.core.StandardServer.await StandardServer.await: create[localhost:10006]:
 java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at org.apache.catalina.core.StandardServer.await(StandardServer.java:420)
    at org.apache.catalina.startup.Catalina.await(Catalina.java:713)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:659)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
</code>```

答:
Found that one service was listening to the invalid address and the Tomcat Service was listening on the loopback address.

According to https://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx

If both application are in the same user context then both can bind to the same port if one of the application is using the invalid address. (0.0.0.0)

If both application are in different user context then we get the exception.

Body:
I have a tomcat service that starts fine with the local system account but when I switch it over to log on as a local user I am getting a JVM_Bind exception. The service starts and then shuts down.

It looks like the shutdown port is already being used by another service. I can change the tomcat service to use a different shutdown port, but I want to understand why it starts fine with the system account and complains about the shutdown port with the user account.

06-Jun-2017 15:46:13.801 SEVERE [main] org.apache.catalina.core.StandardServer.await StandardServer.await: create[localhost:10006]:
 java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at org.apache.catalina.core.StandardServer.await(StandardServer.java:420)
    at org.apache.catalina.startup.Catalina.await(Catalina.java:713)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:659)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)


来源: stackexchange

问:
DELETE & INSERT or UPDATE best practice in SQL PDO
I'm trying to find an answer which is the best practice for following parts of code:

Let's say I have a single action for add and edit products

DELETE & INSERT

```<code>$product_id = 1;
$this->db->query("DELETE FROM `product_description` WHERE `product_id` = :product_id");
$this->db->bind(array(":product_id" => $product_id));
$this->db->execute();

$updateset = array(
    ":product_id" => $product_id,
    ":name" => $_POST["name"]
);
$this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
$this->db->bind($updateset);
$this->db->execute();
</code>```

UPDATE or INSERT

```<code>$product_id = 1;
$updateset = array(
    ":name" => $_POST["name"]
    ":product_id" => $product_id
);
$this->db->query("UPDATE `product_description` SET `name` = :name WHERE `product_id` = :product_id");
$this->db->bind($params);
$this->db->execute();
if(!$this->db->row_count()) {
    $this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
    $this->db->bind($updateset);
    $this->db->execute();
}
</code>```

so which is better?

答:
Neither option is good.

Problem 1:

They both are susceptible to a race condition. Another concurrent session might insert a row in the brief time between your two SQL statements.

Problem 2:

In the second solution, if the row-count of the UPDATE is zero, there may still be a matching row, because it won't count rows when the update doesn't change the value in the row.

Problem 3:

If you use the first option, and you use foreign keys, it won't work if there are any child rows referencing the row you delete. Either the delete will be blocked because of the child rows, or else you use ON DELETE CASCADE which means you will accidentally delete the child rows.

Better solution:

Define a UNIQUE constraint for product_id. Your usage suggests that this column would be a candidate key (i.e. there can only be one row per product_id).

Then use INSERT...ON DUPLICATE KEY UPDATE.

```<code>$updateset = array(
    "product_id" => $product_id,
    "name" => $_POST["name"]
);
$this->db->query("INSERT INTO `product_description`
    SET `product_id` = :product_id, `name` = :name
    ON DUPLICATE KEY UPDATE `name` = VALUES(`name`)");
$this->db->bind($updateset);
$this->db->execute();
</code>```

Tip: Your array doesn't need to prefix the column names with :. That was required in early versions of PDO, but they changed it so this hasn't been a requirement for years.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find an answer which is the best practice for following parts of code:

Let's say I have a single action for add and edit products

DELETE & INSERT

$product_id = 1;
$this->db->query("DELETE FROM `product_description` WHERE `product_id` = :product_id");
$this->db->bind(array(":product_id" => $product_id));
$this->db->execute();

$updateset = array(
    ":product_id" => $product_id,
    ":name" => $_POST["name"]
);
$this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
$this->db->bind($updateset);
$this->db->execute();

UPDATE or INSERT

$product_id = 1;
$updateset = array(
    ":name" => $_POST["name"]
    ":product_id" => $product_id
);
$this->db->query("UPDATE `product_description` SET `name` = :name WHERE `product_id` = :product_id");
$this->db->bind($params);
$this->db->execute();
if(!$this->db->row_count()) {
    $this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
    $this->db->bind($updateset);
    $this->db->execute();
}

so which is better?

Body:
Neither option is good.

Problem 1:

They both are susceptible to a race condition. Another concurrent session might insert a row in the brief time between your two SQL statements.

Problem 2:

In the second solution, if the row-count of the UPDATE is zero, there may still be a matching row, because it won't count rows when the update doesn't change the value in the row.

Problem 3:

If you use the first option, and you use foreign keys, it won't work if there are any child rows referencing the row you delete. Either the delete will be blocked because of the child rows, or else you use ON DELETE CASCADE which means you will accidentally delete the child rows.

Better solution:

Define a UNIQUE constraint for product_id. Your usage suggests that this column would be a candidate key (i.e. there can only be one row per product_id).

Then use INSERT...ON DUPLICATE KEY UPDATE.

$updateset = array(
    "product_id" => $product_id,
    "name" => $_POST["name"]
);
$this->db->query("INSERT INTO `product_description`
    SET `product_id` = :product_id, `name` = :name
    ON DUPLICATE KEY UPDATE `name` = VALUES(`name`)");
$this->db->bind($updateset);
$this->db->execute();

Tip: Your array doesn't need to prefix the column names with :. That was required in early versions of PDO, but they changed it so this hasn't been a requirement for years.


问:
Remote database management from local development server
I am looking for a way to access and query my remote databases from my local server.
Something like PhpMyAdmin, but little more versatile.

So that I can feed it with databases I would like to see, store my queries (or better, if it has ways to access simple queries built in itself)

Can someone help me with such a PHP Script (or Class)?

Regards
Nikhil Gupta

答:
I think it would be better to use a MySQL client instead.

I have been using sqlyog's community edition for years. It has a quick startup, and allows you to connect to multiple servers at the same time.

http://code.google.com/p/sqlyog/downloads/list

One of my favorite features is the ability to copy databases from one server to another.

( Yes, you could do this via the CLI, but having a GUI is handy. )

ContentLicense: CC BY-SA 2.5


问:
Scraping HTML from Google Translate
I want to translate a string using Google Translator.

My sample string is "this is my string".

I want to use HTML Agility Pack to parse HTML documents.

I tried this:

```<code>using HtmlAgilityPack;

........

var webGet = new HtmlWeb();
var document = webGet.Load(
    "http://translate.google.com/#en/bn/this%20is%20my%20string");

var node = document.DocumentNode.SelectNodes(
    "//span[@class='short_text' and @id='result_box']");

if (node != null)
{
    foreach (var xx in node)
    {
        x = xx.InnerText;
        MessageBox.Show(x);
    }
}
</code>```

But I get no results.

My aim is to translate a complete string using Google Translate and to show the translated string in a label in Windows Forms.

How can I do this?

答:
Basic example using HTML Agility Pack

```<code>using System;
using HtmlAgilityPack;
class Traslator
    {
        private string url;
        private HtmlWeb web;
        private HtmlDocument htmlDoc;

        public Translator(string langPair) // LangPair = "SL|TL" ( Source Lang | Target Lang - Ex.: "en|pt"
        {
            this.url = "http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair=" + langPair;
            this.web = new HtmlWeb();
            this.htmlDoc = new HtmlDocument();
        }

        public string Translate(string input)
        {
            this.htmlDoc = web.Load(String.Format(this.url, Uri.EscapeUriString(input)));
            HtmlNode htmlNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id=\"result_box\"]");
            return htmlNode.InnerText;
        }
    }
</code>```

Whats wrong in your example:
Just url used...  try inspect the document.Text prop to get the html received from  webGet...  u will se that span.result_box will be empty.

Title: Scraping HTML from Google Translate

Body:
I want to translate a string using Google Translator.

My sample string is "this is my string".

I want to use HTML Agility Pack to parse HTML documents.

I tried this:

using HtmlAgilityPack;

........

var webGet = new HtmlWeb();
var document = webGet.Load(
    "http://translate.google.com/#en/bn/this%20is%20my%20string");

var node = document.DocumentNode.SelectNodes(
    "//span[@class='short_text' and @id='result_box']");

if (node != null)
{
    foreach (var xx in node)
    {
        x = xx.InnerText;
        MessageBox.Show(x);
    }
}

But I get no results.

My aim is to translate a complete string using Google Translate and to show the translated string in a label in Windows Forms.

How can I do this?

Body:
Basic example using HTML Agility Pack

using System;
using HtmlAgilityPack;
class Traslator
    {
        private string url;
        private HtmlWeb web;
        private HtmlDocument htmlDoc;

        public Translator(string langPair) // LangPair = "SL|TL" ( Source Lang | Target Lang - Ex.: "en|pt"
        {
            this.url = "http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair=" + langPair;
            this.web = new HtmlWeb();
            this.htmlDoc = new HtmlDocument();
        }

        public string Translate(string input)
        {
            this.htmlDoc = web.Load(String.Format(this.url, Uri.EscapeUriString(input)));
            HtmlNode htmlNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id=\"result_box\"]");
            return htmlNode.InnerText;
        }
    }

Whats wrong in your example:
Just url used...  try inspect the document.Text prop to get the html received from  webGet...  u will se that span.result_box will be empty.


问:
Seedstack 16.7 Documentation
I need to access Seedstack 16.7.2 documentation but it’s not available online. I tried to get but without luck.
Do you have any access url to that specific version documentation? </p>

答:
Checking other staffs I found the url to previous versions.

http://seedstack.org/project/old-versions

Title: Seedstack 16.7 Documentation


问:
Reading the InputStream bytes
I am trying to get the byte of the  inputStream of the clientSocket. The code is written in C++ which I am trying to write in Java.

I am getting the byte number of the ClientSocket::receive by calling the  getBytes() method in Java. Is this the same what it has been done in the ClientSocket::receive() method? Does Java contain a method like recv in C++?

C++ Code:

```<code>//! Main function containing an endless loop which accepts and handels connections.
int _tmain(int argc, _TCHAR* argv[])
{
    while (true) {
        try {
            ServerSocket serverSocket;
            ClientSocket clientSocket(serverSocket.acceptConnection());
            try {
                SmartCard smartCard;
                handleConnection(clientSocket, smartCard);
            } catch (SmartCardException &e) {
                printf("SC Error: %s\n", e.what());
                SC_TCPPACKET answerMessage;
                answerMessage.type = e.getErrorCode();
                answerMessage.dLen = 0;
                clientSocket.send((char*)&answerMessage, answerMessage.dLen + MESSAGE_HEADER_LENGTH);
                throw e;
            }
        } catch (std::runtime_error &e) {
            printf("Error occured, resetting active connection.\nError message: %s\n", e.what());
        }
    }
    return 0;
}

//! Reads incoming stream and forwards complete pakets to the message handler defined above.
void handleConnection(ClientSocket &clientSocket, SmartCard &smartCard)
{
    BYTE receiveBuffer[RECEIVE_BUFFER_LENGTH];
    SC_TCPPACKET receivedMessage;
    DWORD bufferOffset = 0; // Number of unprocessed bytes overall
    int receivedBytes;      // Number of received bytes in current iteration
    do {
        receivedBytes = clientSocket.receive(((char*)receiveBuffer)+bufferOffset, RECEIVE_BUFFER_LENGTH-bufferOffset);
        bufferOffset += receivedBytes;
        while (bufferOffset >= MESSAGE_HEADER_LENGTH) { // header information with length available
            memcpy(&receivedMessage, receiveBuffer, MESSAGE_HEADER_LENGTH);
            if (receivedMessage.dLen > MESSAGE_MAXIMUM_LENGTH)
                throw std::runtime_error("Possible overflow attack, closing socket!");
            if (receivedMessage.dLen <= bufferOffset - MESSAGE_HEADER_LENGTH) { // paket complete
                // copy out whole package data
                memcpy(&receivedMessage, receiveBuffer, MESSAGE_HEADER_LENGTH + receivedMessage.dLen);
                // setting offset for remaining data in buffer
                bufferOffset -= MESSAGE_HEADER_LENGTH + receivedMessage.dLen;
                // move remaining data of buffer to front
                memmove(receiveBuffer, receiveBuffer + MESSAGE_HEADER_LENGTH + receivedMessage.dLen, bufferOffset);
                handleMessage(receivedMessage, clientSocket, smartCard);
            } else {
                break; // no further pakets to process, back to reading more data
            }
        }
    } while (receivedBytes > 0);
}

int ClientSocket::receive(char * buffer, int len, int flags)
{
    int ret = recv(socket, buffer, len, flags);
    if (ret == SOCKET_ERROR)
        throw ClientSocketException();

    printf("CS RX(%3d): ", ret);
    for (int b = 0; b < ret; ++b)
        printf("%02x ", (BYTE) (buffer[b]));
    printf("\n");

    return ret;
}
</code>```

Java Code

```<code>import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String args[]) throws Exception {
        InputStream inputStream = null;
        ServerSocket serverSocket = new ServerSocket(27015);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            inputStream = clientSocket.getInputStream();
            int byteData = Test.getBytes(inputStream, 512);
            System.out.println("Test");

        }
    }

    public static int getBytes(InputStream is, int size) throws IOException {
        int len;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1) {
                bos.write(buf, 0, len);
            }
            buf = bos.toByteArray();
        }
        return buf.length;
    }

}
</code>```

答:
Does Java contain a method like recv in C++?

Yes, and you're already calling it.

It's the int read(byte[] b, int off, int len) method, which reads from stream/socket into given buffer of given length and returns the actual number of bytes read.

Exactly like ssize_t recv(int sockfd, void *buf, size_t len, int flags) does.

As for your getBytes() method.

What is the purpose of that method, which consumes the bytes from the stream, and discards them?

There is nothing in the C code that comes close to what that method is doing.

Get rid of it!!!

Title: Reading the InputStream bytes

Body:
I am trying to get the byte of the  inputStream of the clientSocket. The code is written in C++ which I am trying to write in Java.

I am getting the byte number of the ClientSocket::receive by calling the  getBytes() method in Java. Is this the same what it has been done in the ClientSocket::receive() method? Does Java contain a method like recv in C++?

C++ Code:

//! Main function containing an endless loop which accepts and handels connections.
int _tmain(int argc, _TCHAR* argv[])
{
    while (true) {
        try {
            ServerSocket serverSocket;
            ClientSocket clientSocket(serverSocket.acceptConnection());
            try {
                SmartCard smartCard;
                handleConnection(clientSocket, smartCard);
            } catch (SmartCardException &e) {
                printf("SC Error: %s\n", e.what());
                SC_TCPPACKET answerMessage;
                answerMessage.type = e.getErrorCode();
                answerMessage.dLen = 0;
                clientSocket.send((char*)&answerMessage, answerMessage.dLen + MESSAGE_HEADER_LENGTH);
                throw e;
            }
        } catch (std::runtime_error &e) {
            printf("Error occured, resetting active connection.\nError message: %s\n", e.what());
        }
    }
    return 0;
}

//! Reads incoming stream and forwards complete pakets to the message handler defined above.
void handleConnection(ClientSocket &clientSocket, SmartCard &smartCard)
{
    BYTE receiveBuffer[RECEIVE_BUFFER_LENGTH];
    SC_TCPPACKET receivedMessage;
    DWORD bufferOffset = 0; // Number of unprocessed bytes overall
    int receivedBytes;      // Number of received bytes in current iteration
    do {
        receivedBytes = clientSocket.receive(((char*)receiveBuffer)+bufferOffset, RECEIVE_BUFFER_LENGTH-bufferOffset);
        bufferOffset += receivedBytes;
        while (bufferOffset >= MESSAGE_HEADER_LENGTH) { // header information with length available
            memcpy(&receivedMessage, receiveBuffer, MESSAGE_HEADER_LENGTH);
            if (receivedMessage.dLen > MESSAGE_MAXIMUM_LENGTH)
                throw std::runtime_error("Possible overflow attack, closing socket!");
            if (receivedMessage.dLen <= bufferOffset - MESSAGE_HEADER_LENGTH) { // paket complete
                // copy out whole package data
                memcpy(&receivedMessage, receiveBuffer, MESSAGE_HEADER_LENGTH + receivedMessage.dLen);
                // setting offset for remaining data in buffer
                bufferOffset -= MESSAGE_HEADER_LENGTH + receivedMessage.dLen;
                // move remaining data of buffer to front
                memmove(receiveBuffer, receiveBuffer + MESSAGE_HEADER_LENGTH + receivedMessage.dLen, bufferOffset);
                handleMessage(receivedMessage, clientSocket, smartCard);
            } else {
                break; // no further pakets to process, back to reading more data
            }
        }
    } while (receivedBytes > 0);
}

int ClientSocket::receive(char * buffer, int len, int flags)
{
    int ret = recv(socket, buffer, len, flags);
    if (ret == SOCKET_ERROR)
        throw ClientSocketException();

    printf("CS RX(%3d): ", ret);
    for (int b = 0; b < ret; ++b)
        printf("%02x ", (BYTE) (buffer[b]));
    printf("\n");

    return ret;
}

Java Code

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String args[]) throws Exception {
        InputStream inputStream = null;
        ServerSocket serverSocket = new ServerSocket(27015);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            inputStream = clientSocket.getInputStream();
            int byteData = Test.getBytes(inputStream, 512);
            System.out.println("Test");

        }
    }

    public static int getBytes(InputStream is, int size) throws IOException {
        int len;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1) {
                bos.write(buf, 0, len);
            }
            buf = bos.toByteArray();
        }
        return buf.length;
    }

}


问:
Is it possible to augment dataframes with time-series data for analysis in Convolutional Neural Networks?
I am trying to identify patterns in time-series data by using a convolutional neural network. However, due to limited number of observations (1500 in total), is it possible to augment the dataframes, similar to image augmentation without losing the relationship between time-series data? Just wondering what the best way is to approach this problem?</p>

答:
One common way to augment data while keeping the relationship is to add random noise.

Additional methods that can work and lead to utilization in convolutional neural networks depending on the dataset is transformation of data into images followed by suitable augmentation techniques such as blurring or horizontal shifts.


问:
React JS Error: is not defined react/jsx-no-undef
I'm developing a map functionality using ReactJS, My app.js file is:

```<code>import React, { Component } from 'react';
import './Map';
class App extends Component {
   render() {
     return (
         <div className="App">
            <Map/>
         </div>
     );
   }
}
export default App;
</code>```

The error is:

```<code>./src/App.js
Line 8:  'Map' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
</code>```

How can I solve this problem?

答:
Try using

```<code>import Map from './Map';
</code>```

When you use import 'module' it will just run the module as a script. This is useful when you are trying to introduce side-effects into global namespace, e. g. polyfill newer features for older/unsupported browsers.

ES6 modules are allowed to define default exports and regular exports. When you use the syntax import defaultExport from 'module' it will import the default export of that module with alias defaultExport.

For further reading on ES6 import - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Body:
I'm developing a map functionality using ReactJS, My app.js file is:

import React, { Component } from 'react';
import './Map';
class App extends Component {
   render() {
     return (

            <Map/>

     );
   }
}
export default App;

The error is:

./src/App.js
Line 8:  'Map' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.

How can I solve this problem?

Body:
Try using

import Map from './Map';

When you use import 'module' it will just run the module as a script. This is useful when you are trying to introduce side-effects into global namespace, e. g. polyfill newer features for older/unsupported browsers.

ES6 modules are allowed to define default exports and regular exports. When you use the syntax import defaultExport from 'module' it will import the default export of that module with alias defaultExport.

For further reading on ES6 import - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

ContentLicense: CC BY-SA 4.0


问:
Why is a single function not called second time in a jquery handler?
I am trying to create two divs that respond on mouseclick while increasing or decreasing their saturations. Here is a short fiddle to my problem:
https://jsfiddle.net/ds6w5uwj/

```<code>$(document).ready(function() {
  var oldbgc;
  oldbgc = void 0;
  return $(document.body).on('click', '.prio-step', function() {
    var bg, newbgc;
    alert("color recalc started");
    bg = $(this).css('background-color');
    oldbgc = rgb2hex(bg); //This line is only executed in the very first run
    newbgc = applySaturationToHexColor(oldbgc, 30);
    return $(this).css({
      backgroundColor: newbgc
    });
  });
});
</code>```

When you click on one div the first time, rgb2hex(bg) is called and the right value is written to oldbgc. But when you try to click again no matter on which div you want the script skips that specific line leading to NaN error.
I found both functions, applySaturationToHexColor(...) and rgb2hex(...), as top answers to their corresponding questions here on stackoverflow.com.

答:
In your code I see scope issues.

You have something on these lines in your code.

```<code>rgb2hex= function(rgb_in) { <============= #1
    // removed for simplicity
};

applySaturationToHexColor= function(hex, saturationPercent) {
    // removed for simplicity
    rgb2hex = function(rgb) { <============= #2
      return '#' + floatToHex(rgb[0]) + floatToHex(rgb[1]) + floatToHex(rgb[2]);
    };
    newHex = rgb2hex(newRgbIntensityFloat); <============= #3
    return newHex;
};

$(document).ready(function() {
    // removed for simplicity
    $(document.body).on('click', '.prio-step', function() {
       oldbgc = rgb2hex(bg); <============= #4
    });
    // removed for simplicity
  });
});
</code>```

Carefully check the lines I have pointed as 1,2,3 and 4. You have defined rgb2hex twice, once at pointer #1 and second at pointer #2. So when inside your on-click event when you intend to call function defined at pointer #1 your code ends up calling function at pointer #2 instead.

Body:
I am trying to create two divs that respond on mouseclick while increasing or decreasing their saturations. Here is a short fiddle to my problem:
https://jsfiddle.net/ds6w5uwj/

$(document).ready(function() {
  var oldbgc;
  oldbgc = void 0;
  return $(document.body).on('click', '.prio-step', function() {
    var bg, newbgc;
    alert("color recalc started");
    bg = $(this).css('background-color');
    oldbgc = rgb2hex(bg); //This line is only executed in the very first run
    newbgc = applySaturationToHexColor(oldbgc, 30);
    return $(this).css({
      backgroundColor: newbgc
    });
  });
});

When you click on one div the first time, rgb2hex(bg) is called and the right value is written to oldbgc. But when you try to click again no matter on which div you want the script skips that specific line leading to NaN error.
I found both functions, applySaturationToHexColor(...) and rgb2hex(...), as top answers to their corresponding questions here on stackoverflow.com.

Body:
In your code I see scope issues.

You have something on these lines in your code.

rgb2hex= function(rgb_in) { <============= #1
    // removed for simplicity
};

applySaturationToHexColor= function(hex, saturationPercent) {
    // removed for simplicity
    rgb2hex = function(rgb) { <============= #2
      return '#' + floatToHex(rgb[0]) + floatToHex(rgb[1]) + floatToHex(rgb[2]);
    };
    newHex = rgb2hex(newRgbIntensityFloat); <============= #3
    return newHex;
};

$(document).ready(function() {
    // removed for simplicity
    $(document.body).on('click', '.prio-step', function() {
       oldbgc = rgb2hex(bg); <============= #4
    });
    // removed for simplicity
  });
});

Carefully check the lines I have pointed as 1,2,3 and 4. You have defined rgb2hex twice, once at pointer #1 and second at pointer #2. So when inside your on-click event when you intend to call function defined at pointer #1 your code ends up calling function at pointer #2 instead.


问:
subprocess pid different from ps output
Why is it that the subprocess pid (Popen.pid) has different value from that the ps command returns?

I've noticed this when ps called both from inside python (with subprocess.call()) and from another terminal.

Here's a simple python file to test:

```<code>#!/usr/bin/python3
'''
Test subprocess termination
'''

import subprocess

command = 'cat'

#keep pipes so that cat doesn't complain
proc = subprocess.Popen(command,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    shell=True)

print('pid = %d' % proc.pid)
subprocess.call("ps -A | grep -w %s" % command,
                    shell=True)

proc.terminate()
proc.wait()             # make sure its dead before exiting pytyhon
</code>```

Usually the pid reported by ps is 1 or 2 more than that reported by Popen.pid.

答: Because the command is run with shell=True, the pid returned by subprocess is that of the shell process used to run the command.

Title: subprocess pid different from ps output

Body:
Why is it that the subprocess pid (Popen.pid) has different value from that the ps command returns?

I've noticed this when ps called both from inside python (with subprocess.call()) and from another terminal.

Here's a simple python file to test:

#!/usr/bin/python3
'''
Test subprocess termination
'''

import subprocess

command = 'cat'

#keep pipes so that cat doesn't complain
proc = subprocess.Popen(command,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    shell=True)

print('pid = %d' % proc.pid)
subprocess.call("ps -A | grep -w %s" % command,
                    shell=True)

proc.terminate()
proc.wait()             # make sure its dead before exiting pytyhon

Usually the pid reported by ps is 1 or 2 more than that reported by Popen.pid.


问:
How to change edge thickness in D3.js?
Code example https://jsfiddle.net/greggyNapalm/xtg7t5ch/
I want to control edge thickness with weight attr.

答:
Try adding:</p>

```<code> .attr("style", function(d) { return ("stroke-width:" + d.weight + "px;");})
</code>```

Title: How to change edge thickness in D3.js?

Body:
Try adding:

 .attr("style", function(d) { return ("stroke-width:" + d.weight + "px;");})


问:
UnicodeEncodeError disparity between code run via django test suite vs django URL
Specifically I'm using the webob library where I posted a similar issue (https://github.com/Pylons/webob/issues/320), since I'm not sure if it's my usage, or a bug / documentation issue

Take the following code:

```<code>from webob.request import BaseRequest
req = BaseRequest.blank('http://example.com/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82')
print req.environ['PATH_INFO']
print req.path
</code>```

If I run this via a django shell, I get:

```<code>>>> req = BaseRequest.blank('http://example.com/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82')
>>> print req.environ['PATH_INFO']
/дэльэнйт
>>> print req.path
/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82
</code>```

Where as running it as part of a Django test case I get the following from the first print:

```<code>/Ð´ÑÐ»ÑÑÐ½Ð¹Ñ
</code>```

Followed by the exception:

```<code>File "/code/frontend/tests/test_views.py", line 55, in test_event
    print req.path
File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/request.py", line 485, in path
    bpath = bytes_(self.path_info, self.url_encoding)
File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/descriptors.py", line 68, in fget
    return req.encget(key, encattr=encattr)
File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/request.py", line 175, in encget
    return val.decode(encoding)
File "/virtualenv/frontend/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-16: ordinal not in range(128)
</code>```

I get that this is probably some weird configuration with my test suite, however both run via the same method in the same environment (Django's manage.py test vs manage.py shell) and so I'm struggling to identify what's different. We're also running a ton of other unicode related tests without issue.

Thanks for any light shed on this.

答:
You have 2 options:

use logging instead of print it's a best practice in all (not only Django) applications.

Or use req.path.decode('utf-8')

Body:
Specifically I'm using the webob library where I posted a similar issue (https://github.com/Pylons/webob/issues/320), since I'm not sure if it's my usage, or a bug / documentation issue

Take the following code:

from webob.request import BaseRequest
req = BaseRequest.blank('http://example.com/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82')
print req.environ['PATH_INFO']
print req.path

If I run this via a django shell, I get:

>>> req = BaseRequest.blank('http://example.com/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82')
>>> print req.environ['PATH_INFO']
/дэльэнйт
>>> print req.path
/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82

Where as running it as part of a Django test case I get the following from the first print:

/Ð´ÑÐ»ÑÑÐ½Ð¹Ñ

Followed by the exception:

File "/code/frontend/tests/test_views.py", line 55, in test_event
    print req.path
File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/request.py", line 485, in path
    bpath = bytes_(self.path_info, self.url_encoding)
File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/descriptors.py", line 68, in fget
    return req.encget(key, encattr=encattr)
File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/request.py", line 175, in encget
    return val.decode(encoding)
File "/virtualenv/frontend/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-16: ordinal not in range(128)

I get that this is probably some weird configuration with my test suite, however both run via the same method in the same environment (Django's manage.py test vs manage.py shell) and so I'm struggling to identify what's different. We're also running a ton of other unicode related tests without issue.

Thanks for any light shed on this.


问:
Android Mp3 File - open failed: ENOENT (No such file or directory)
I'm not understanding why I am getting this exception. The directory itself seems to be there. I can play the music locally, but when I try to do this: FileInputStream inputStream = new FileInputStream(audioFile); I get this error: /document/2710: open failed: ENOENT (No such file or directory)

Here is my full Code:

```<code> @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0 && resultCode == Activity.RESULT_OK){
        if ((data != null) && (data.getData() != null)) {

      Uri audioFileUri = data.getData();
      File file = new File(audioFileUri.getPath());
      //file.mkdirs();  <---- Making a directory does not work
      try {
             FileInputStream inputStream = new FileInputStream(audioFile); //This is where I get the error
           }
      catch{
             Log.i("TAG", e.getMessage());
            }

     }
   }
 }
</code>```

答:
```<code>File file = new File(audioFileUri.getPath());
</code>```

At best, that line might work if the scheme of the Uri is file. In your case, it is content.

Use getContentResolver().openInputStream() to open an InputStream on the content identified by the Uri. This works for both the file and the content scheme.

Body:
I'm not understanding why I am getting this exception. The directory itself seems to be there. I can play the music locally, but when I try to do this: FileInputStream inputStream = new FileInputStream(audioFile); I get this error: /document/2710: open failed: ENOENT (No such file or directory)

Here is my full Code:

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0 && resultCode == Activity.RESULT_OK){
        if ((data != null) && (data.getData() != null)) {

      Uri audioFileUri = data.getData();
      File file = new File(audioFileUri.getPath());
      //file.mkdirs();  <---- Making a directory does not work
      try {
             FileInputStream inputStream = new FileInputStream(audioFile); //This is where I get the error
           }
      catch{
             Log.i("TAG", e.getMessage());
            }

     }
   }
 }

Body:
File file = new File(audioFileUri.getPath());

At best, that line might work if the scheme of the Uri is file. In your case, it is content.

Use getContentResolver().openInputStream() to open an InputStream on the content identified by the Uri. This works for both the file and the content scheme.


问:
Remove Wrap Text from Access Query
I'm currently changing an access function so that instead of .xls files, it exports .xlsx. After completing this, the only formatting issue was that a wrap text was applied on all the cells exported (not sure if this is something that comes with converting to .xlsx)

I'm wondering if there's a way to remove the wrap text while the file is still in excel, or if there's a command I can add to my export query to make the cells not wrap text.

The command I use to create the data in Access is:

```<code>DoCmd.OpenQuery "Device Summary", acViewNormal, acEdit
</code>```

Then I export it to an .xlsx file

```<code>DoCmd.OutputTo acOutputQuery, "Device Summary", acFormatXLSX, Forms![BuildSheet]![Text2] & "-Summary.xlsx", True
</code>```

Thanks in advance

答:
After the word True at the end, specify a blank template file you would like to use.

```<code>DoCmd.OutputTo acOutputQuery, "Device Summary", acFormatXLSX, Forms![BuildSheet]![Text2] & "-Summary.xlsx", True, "C:\Template.xlsx"
</code>```

And make sure that template file has wrap turned off for the entire sheet.

Title: Remove Wrap Text from Access Query

Body:
I'm currently changing an access function so that instead of .xls files, it exports .xlsx. After completing this, the only formatting issue was that a wrap text was applied on all the cells exported (not sure if this is something that comes with converting to .xlsx)

I'm wondering if there's a way to remove the wrap text while the file is still in excel, or if there's a command I can add to my export query to make the cells not wrap text.

The command I use to create the data in Access is:

DoCmd.OpenQuery "Device Summary", acViewNormal, acEdit

Then I export it to an .xlsx file

DoCmd.OutputTo acOutputQuery, "Device Summary", acFormatXLSX, Forms![BuildSheet]![Text2] & "-Summary.xlsx", True

Thanks in advance

Body:
After the word True at the end, specify a blank template file you would like to use.

DoCmd.OutputTo acOutputQuery, "Device Summary", acFormatXLSX, Forms![BuildSheet]![Text2] & "-Summary.xlsx", True, "C:\Template.xlsx"

And make sure that template file has wrap turned off for the entire sheet.


答: you should do import Map from './Map' React is just telling you it doesn't know where variable you are importing is.

Title: React JS Error: is not defined react/jsx-no-undef


问:
How to use awk counting the number of specificed digit in certain column
How can I count the matched value in the certain column?

I have a file:(wm.csv)

I executed the command to get the targeted value in certain column: tail -n +497 wm.csv | awk -F"," '$2=="2" {print $3" "$4}'

then I get the following output data I want:

hit 2
hit 2
hit 2
hit 2
miss
hit 2
hit 2
hit 2
hit 2
hit 2
hit 2
hit 2
incorrect 1
hit 2
hit 2
hit 2

I want to count the number of "2" in second column in order to do simple math like: total digits in column divided by total number of row. Specifically, in this case, it would looks like: 14 (fourteen "2" in second column) / 16(total number of row)

Following is the command I tried but this does not work :
tail -n +497 wm.csv | awk -F"," '$2=="2" {count=0;} { if ($4 == "2") count+=1 } {print $3,$4,$count }'

thanks

答:
```<code>awk  '($0 ~ "hit 2"){count += 1}  END{print count, FNR, count/FNR}' sample.csv
14 16 0.875
</code>```

I use ~ to compare the whole line($0) matches "hit 2", if it is increase counter by 1. FNR is the file number of records which is the total line number.

Body:
awk  '($0 ~ "hit 2"){count += 1}  END{print count, FNR, count/FNR}' sample.csv
14 16 0.875

I use ~ to compare the whole line($0) matches "hit 2", if it is increase counter by 1. FNR is the file number of records which is the total line number.


问:
how to find totally duplicate object in array?
Here is an example js array:

```<code>var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]
</code>```

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

答:
My solution using a map with the stringified element as the key

var arr = [
      {
        name: 'test1',
        price: 20,
        otherKey: 123,
        yetAnotherKey: 'val'
      },
      {
        name: 'test2',
        price: 10,
        otherKey: 11,
        yetAnotherKey: 'erewrwert'
      },
      {
        name: 'test1',
        price: 20,
        otherKey: 123,
        yetAnotherKey: 'val'
      }
    ]

function solution(arr) {
  let map = new Map();
  let res = [];
  arr.forEach(e => {
    let currKey = JSON.stringify(e);
    // if not seen by the map, put in the the map and push element to result array
    if (!map.get(currKey)) {
      map.set(currKey, true);
      res.push(e);
    }
  });
  return res;
}

console.log(solution(arr))```

Body:
Here is an example js array:

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.


答:
You can use MySQL's find_in_set() function to check if a value exists in a commase separated list of values:</p>

```<code>select * from your_table
where find_in_set(field_name,'757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450')=0
</code>```

Title: Check which IDs from a set do not exists in a table

Body:
I have a list of user IDs, like this:

757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450,743799,643918,
749903,571888,30207,705953,749120,749001,749192,749978,750840,544228,702121,746246,383667,
558790,585628,592771,745818,749375,241209,749235,746860,748318,748016,748951,747321,748684,
748225,565375,748673,747869,748522,748335,744775,672229,578056,713127,740234,632608,711135,
746528,362131,742223,746567,745224,332989,439837,745418,673582,269584,742606,745135,746950,
476134,740830,742949,276934

I have a MySQL table users with the id field.

How do I check - using a query - which IDs of the ones I have do not exists in the users table?

This sounds like a simple problem to me, yet I couldn't find any example on StackOverflow which would address a fixed set of ID values.

Body:
You can use MySQL's find_in_set() function to check if a value exists in a commase separated list of values:

select * from your_table
where find_in_set(field_name,'757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450')=0


问:
Swagger ui description of array parameters in .NET
I have controller that recieves object of SearchProfilesModel. It consists of array of SearchProfiles and several properties in base classes.
Method:

```<code>[HttpGet]
[ResponseType(typeof(List<UserSearchResult>))]
[Route("SearchWithParams")]
public async Task<HttpResponseMessage>
    SearchWithParams([FromUri] SearchProfilesModel model)
{
    // Some logic
    return Request.CreateResponse(HttpStatusCode.OK, result);
}
</code>```

Model class:

```<code>public class SearchProfilesModel : LoginRequiredModel
{
    [Required]
    [JsonProperty("search_profiles")]
    public List<SearchProfileViewModel> ProfilesList { get; set; }
}
</code>```

List item class:

```<code>public class SearchProfileViewModel
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("surname")]
    public string Surname { get; set; }
    [JsonProperty("facebook_id")]
    public string FacebookId { get; set; }
    [JsonProperty("email")]
    public string Email { get; set; }
}
</code>```

I`m using Swagger ui (swashbuckle lib) to test my controllers, but when it generates help page for this method it shows following:
Help page

My question is - can i somehow show structure of list item (from SearchProfileViewModel) in parameters? And if i can - how?
P.S. - Sorry for my English, it`s not my native language.

答:
The structure of your object is in the generated doc, take a look at mine:
http://swashbuckletest.azurewebsites.net/swagger/docs/v1</p>

```<code>{
"swagger": "2.0",
"info": {...},
"host": "swashbuckletest.azurewebsites.net",
"schemes": [...],
"paths": {...},
"definitions": {
    "Data": {
        "type": "object",
        "properties": {
            "integ": {
                "format": "int32",
                "type": "integer",
                "example": 123
            },
            "doub": {
                "format": "double",
                "type": "number",
                "example": 9858.216
            },
            "boolea": {
                "type": "boolean"
            },
            "guid": {
                "format": "uuid",
                "type": "string",
                "example": "f5849915-43c8-434c-92a7-7383d1acb631"
            },
            "date": {
                "format": "date-time",
                "type": "string"
            }
        }
    },
...
</code>```

Body:
I have controller that recieves object of SearchProfilesModel. It consists of array of SearchProfiles and several properties in base classes.
Method:

[HttpGet]
[ResponseType(typeof(List<UserSearchResult>))]
[Route("SearchWithParams")]
public async Task<HttpResponseMessage>
    SearchWithParams([FromUri] SearchProfilesModel model)
{
    // Some logic
    return Request.CreateResponse(HttpStatusCode.OK, result);
}

Model class:

public class SearchProfilesModel : LoginRequiredModel
{
    [Required]
    [JsonProperty("search_profiles")]
    public List<SearchProfileViewModel> ProfilesList { get; set; }
}

List item class:

public class SearchProfileViewModel
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("surname")]
    public string Surname { get; set; }
    [JsonProperty("facebook_id")]
    public string FacebookId { get; set; }
    [JsonProperty("email")]
    public string Email { get; set; }
}

I`m using Swagger ui (swashbuckle lib) to test my controllers, but when it generates help page for this method it shows following:
Help page

My question is - can i somehow show structure of list item (from SearchProfileViewModel) in parameters? And if i can - how?
P.S. - Sorry for my English, it`s not my native language.

Body:
The structure of your object is in the generated doc, take a look at mine:
http://swashbuckletest.azurewebsites.net/swagger/docs/v1

{
"swagger": "2.0",
"info": {...},
"host": "swashbuckletest.azurewebsites.net",
"schemes": [...],
"paths": {...},
"definitions": {
    "Data": {
        "type": "object",
        "properties": {
            "integ": {
                "format": "int32",
                "type": "integer",
                "example": 123
            },
            "doub": {
                "format": "double",
                "type": "number",
                "example": 9858.216
            },
            "boolea": {
                "type": "boolean"
            },
            "guid": {
                "format": "uuid",
                "type": "string",
                "example": "f5849915-43c8-434c-92a7-7383d1acb631"
            },
            "date": {
                "format": "date-time",
                "type": "string"
            }
        }
    },
...


问:
How to read particular range to last line of file using PowerShell?
How to read particular range of line ie if my file have 100 lines and I want to read the lines from 80 to last line of file using PowerShell?here I'm not sure about how many lines are available in the file.</p>

答:
Just do it :</p>

```<code>Get-Content "C:\temp\test.txt" | select -skip 80
</code>```

Body:
Just do it :

Get-Content "C:\temp\test.txt" | select -skip 80


问:
Django apps using class-based views and ajax?
I'm learning Django and I found class-based views and I wonder how to implement Ajax on those views.

I searched github for a django project and I found some using class-based views but not ajax.

So... Anybody knows an open source project that use both things? It easier to learn that way.

Thank you :)

答:
If you want to support both AJAX and traditional views, you can add something like this to your CreateView:

```<code># at top of file
from django.http import JsonResponse

# inside CreateView class
def render_to_response(self, context, **response_kwargs):
    """ Allow AJAX requests to be handled more gracefully """
    if self.request.is_ajax():
        return JsonResponse('Success',safe=False, **response_kwargs)
    else:
        return super(CreateView,self).render_to_response(context, **response_kwargs)
</code>```

This handles regular views normally (with redirect etc.) but for AJAX, it return a JsonResponse instead.  Where it returns 'Success', you may want to add more sophisticated logic but this is the basic idea.

Body:
If you want to support both AJAX and traditional views, you can add something like this to your CreateView:

# at top of file
from django.http import JsonResponse

# inside CreateView class
def render_to_response(self, context, **response_kwargs):
    """ Allow AJAX requests to be handled more gracefully """
    if self.request.is_ajax():
        return JsonResponse('Success',safe=False, **response_kwargs)
    else:
        return super(CreateView,self).render_to_response(context, **response_kwargs)

This handles regular views normally (with redirect etc.) but for AJAX, it return a JsonResponse instead.  Where it returns 'Success', you may want to add more sophisticated logic but this is the basic idea.


问:
Calling an .exe without the extension, but with -i
I'm working on integrating the functions of a batch file into a larger PowerShell file (that does other things too) so I can eventually get rid of some smaller batch files.

I came across a line that looks like this:

```<code>if exist "C:\path\thing.exe"
("C:\path\thing" -i "C:\otherpath\something.dll")
</code>```

What is it referencing in the second line when it says the .exe name but with no file extension?

EDIT: I ran a /? on the .exe, I think this might be relevant:

```<code>/i <assembly_path> [ /r <...> ] [ /f ]
    Installs an assembly to the global assembly cache. <assembly_path> is the
    name of the file that contains the assembly manifest.
    Example: /i myDll.dll /r FILEPATH c:\projects\myapp.exe "My App"
</code>```

So I guess the -i is running the .exe using the .dll file as some kind of config file?

答:
When executing a command that does not contain an extension, cmd.exe uses the value(s) of the %PATHEXT% variable:

```<code>SET PATHEXT
</code>```

It will supplement each entry in the order listed as a replacement extension until successful or all have been tried.

As you will note it is unlikely that the first entry will show as .EXE and I would suggest therefore that your new method reverts to the full name with extension thing.exe.

Body:
I'm working on integrating the functions of a batch file into a larger PowerShell file (that does other things too) so I can eventually get rid of some smaller batch files.

I came across a line that looks like this:

if exist "C:\path\thing.exe"
("C:\path\thing" -i "C:\otherpath\something.dll")

What is it referencing in the second line when it says the .exe name but with no file extension?

EDIT: I ran a /? on the .exe, I think this might be relevant:

/i <assembly_path> [ /r <...> ] [ /f ]
    Installs an assembly to the global assembly cache. <assembly_path> is the
    name of the file that contains the assembly manifest.
    Example: /i myDll.dll /r FILEPATH c:\projects\myapp.exe "My App"

So I guess the -i is running the .exe using the .dll file as some kind of config file?

Body:
When executing a command that does not contain an extension, cmd.exe uses the value(s) of the %PATHEXT% variable:

SET PATHEXT

It will supplement each entry in the order listed as a replacement extension until successful or all have been tried.

As you will note it is unlikely that the first entry will show as .EXE and I would suggest therefore that your new method reverts to the full name with extension thing.exe.


问:
SQL: Get value at index in binary value
Is there a SQL command that could be used in a query, stored procedure, function, that would work against a Binary Type similar to the following C# code?

```<code>if (someBinaryArray[index] == 0) {
...
</code>```

I'm wanting to check if an index of a position in the binary is a certain value instead of pulling the entire array down and doing the comparison?

答:
You can use Substring(), according to the documentation it works with binary columns:

```<code>SELECT *
FROM Table
WHERE Substring(column, index, length) = 'blah'
</code>```

If you really wanted to check for a null (as in your example)... you could do this:

```<code>SELECT *
FROM table
WHERE SUBSTRING(column, 3, 1) = CHAR(0)
</code>```

OwnerDisplayName: HBoss

Title: SQL: Get value at index in binary value

Body:
Is there a SQL command that could be used in a query, stored procedure, function, that would work against a Binary Type similar to the following C# code?

if (someBinaryArray[index] == 0) {
...

I'm wanting to check if an index of a position in the binary is a certain value instead of pulling the entire array down and doing the comparison?

Body:
You can use Substring(), according to the documentation it works with binary columns:

SELECT *
FROM Table
WHERE Substring(column, index, length) = 'blah'

If you really wanted to check for a null (as in your example)... you could do this:

SELECT *
FROM table
WHERE SUBSTRING(column, 3, 1) = CHAR(0)

OwnerDisplayName: bobwienholt


问:
string.endswith("") does not work in IE(not sure how to use a Polyfill)
I am using string.endswith() to loop through JSON objects and find out if the any property of the object endswith a "Value" substring.

After finding out if the the object property ends with "Value", i am trying to round off the value of the property to 2 decimals which are by default 5 decimals.

Here is my code

```<code>var MyObj= [{"$id":"1","GeoName":"EAST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206},{"$id":"2","GeoName":"WEST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206}];
Obj = JSON.parse(JSON.stringify(MyObj)).map(function (e) {
            return Object.keys(e).reduce(function (p, n) {
                if (n.endsWith("Value"))
                    p[n] = Math.round(e[n] * 100) / 100;
                else
                    p[n] = e[n];
                return p;
            }, {})
        });
</code>```

The above code works absolutely fine in chrome and Firefox, While IE it throws endsWith is not a function exception.

I found out for such issues pollyfills are used, which i tried and i failed. I am not even sure if i used the pollyfill correctly.

so here is how i did it,

```<code>function polyFillEndswith(searchString, position) {
            if (!String.prototype.endsWith) {
                String.prototype.endsWith = function (searchString, position) {
                    var subjectString = this.toString();
                    if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
                        position = subjectString.length;
                    }
                    position -= searchString.length;
                    var lastIndex = subjectString.lastIndexOf(searchString, position);
                    return lastIndex !== -1 && lastIndex === position;
                }
            }
        }

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
                return Object.keys(e).reduce(function (p, n) {
                    if (n.polyFillEndswith("Value", "0"))
                        p[n] = Math.round(e[n] * 100) / 100;
                    else
                        p[n] = e[n];
                    return p;
                }, {})
            });
</code>```

is the above code even correct? if not how can i change it to  achieve my objective?

答:
The polyfill function you have is actually for attaching the endsWith function to the native String object, which JavaScript allows you to do. It will allow you to call endsWith like normal.

Instead of wrapping it in a function, let it run right away, then just use the normal endsWith:

```<code>if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.lastIndexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    }
}

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
    return Object.keys(e).reduce(function (p, n) {
        if (n.endsWith("Value"))
            p[n] = Math.round(e[n] * 100) / 100;
        else
            p[n] = e[n];
        return p;
    }, {})
});
</code>```

Body:
I am using string.endswith() to loop through JSON objects and find out if the any property of the object endswith a "Value" substring.

After finding out if the the object property ends with "Value", i am trying to round off the value of the property to 2 decimals which are by default 5 decimals.

Here is my code

var MyObj= [{"$id":"1","GeoName":"EAST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206},{"$id":"2","GeoName":"WEST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206}];
Obj = JSON.parse(JSON.stringify(MyObj)).map(function (e) {
            return Object.keys(e).reduce(function (p, n) {
                if (n.endsWith("Value"))
                    p[n] = Math.round(e[n] * 100) / 100;
                else
                    p[n] = e[n];
                return p;
            }, {})
        });

The above code works absolutely fine in chrome and Firefox, While IE it throws endsWith is not a function exception.

I found out for such issues pollyfills are used, which i tried and i failed. I am not even sure if i used the pollyfill correctly.

so here is how i did it,

function polyFillEndswith(searchString, position) {
            if (!String.prototype.endsWith) {
                String.prototype.endsWith = function (searchString, position) {
                    var subjectString = this.toString();
                    if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
                        position = subjectString.length;
                    }
                    position -= searchString.length;
                    var lastIndex = subjectString.lastIndexOf(searchString, position);
                    return lastIndex !== -1 && lastIndex === position;
                }
            }
        }

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
                return Object.keys(e).reduce(function (p, n) {
                    if (n.polyFillEndswith("Value", "0"))
                        p[n] = Math.round(e[n] * 100) / 100;
                    else
                        p[n] = e[n];
                    return p;
                }, {})
            });

is the above code even correct? if not how can i change it to  achieve my objective?

Body:
The polyfill function you have is actually for attaching the endsWith function to the native String object, which JavaScript allows you to do. It will allow you to call endsWith like normal.

Instead of wrapping it in a function, let it run right away, then just use the normal endsWith:

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.lastIndexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    }
}

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
    return Object.keys(e).reduce(function (p, n) {
        if (n.endsWith("Value"))
            p[n] = Math.round(e[n] * 100) / 100;
        else
            p[n] = e[n];
        return p;
    }, {})
});


问:
How to use methods to set a property in the default constructor in F#
I am trying to write a constructor that suppose to call method defined in the class and assign result to the member. In C# it would be something like:

```<code>public class Test
{
    public int Value { get; private set;}

    private static int SomeLogic(int a, int b)
    {
        return a + b;
    }

    public Test(int a, int b)
    {
        this.Value = SomeLogic(a,b);
    }
}
</code>```

But I have no idea how to do that it F#.

答:
Example of two different ways of achieving this in F#:

```<code>type Test_UsesVal =
  val value : int
  new (a, b) = { value = someLogic a b }
  member x.Value = x.value

type Test_Preferred (a : int, b: int) =
  let value = someLogic a b
  member x.Value = value
</code>```

Two examples with drawbacks:

```<code>// This type is default constructible and when using default ctor someLogic is not used
type Test_DefaultConstructible () =
  let mutable value = 0
  new (a, b) as x = Test_DefaultConstructible () then x.Value <- someLogic a b
  member x.Value with get () = value and private set v = value <- v

// This type has 2 constructors and using single value ctor someLogic is not used
type Test_2Constructors (value : int) =
  new (a, b) = Test_2Constructors (someLogic a b)
  member x.Value with get () = value
</code>```

As self referential types were mentioned I would just like to point out that making a type self referential adds hidden overhead:

```<code>// Self referential types add hidden overhead
type Test_SelfReferential (a : int, b: int) as this =
  let computeValue () = someLogic this.A this.B

  member x.A      = a
  member x.B      = b
  member x.Value  = computeValue ()
</code>```

Decompiled the overhead shows:

```<code>[CompilationMapping(SourceConstructFlags.ObjectType)]
[Serializable]
public class Test_SelfReferential
{
  internal int b;

  internal int a;

  // An extra field added
  internal FSharpRef<Program.Test_SelfReferential> @this = new FSharpRef<Program.Test_SelfReferential>(null);

  // An extra field added
  internal int init@29-1;

  public int A
  {
    get
    {
      // An extra check added in each method
      if (this.init@29-1 < 1)
      {
        LanguagePrimitives.IntrinsicFunctions.FailInit();
      }
      return this.a;
    }
  }

  public int B
  {
    get
    {
      // An extra check added in each method
      if (this.init@29-1 < 1)
      {
        LanguagePrimitives.IntrinsicFunctions.FailInit();
      }
      return this.b;
    }
  }

  public int Value
  {
    get
    {
      // An extra check added in each method
      if (this.init@29-1 < 1)
      {
        LanguagePrimitives.IntrinsicFunctions.FailInit();
      }
      return this.computeValue();
    }
  }

  public Test_SelfReferential(int a, int b) : this()
  {
    this.a = a;
    this.b = b;
    // An extra init added in .ctor
    this.@this.contents = this;
    this.init@29-1 = 1;
  }

  [CompilerGenerated]
  internal int computeValue()
  {
    // Extra checks added
    return LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.Test_SelfReferential>(this.@this.contents).A + LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.Test_SelfReferential>(this.@this.contents).B;
  }
}
</code>```

The hidden overhead from self referential types in F# once caused me a performance regression (in some use-cases performance dropped by 50%).

Body:
I am trying to write a constructor that suppose to call method defined in the class and assign result to the member. In C# it would be something like:

public class Test
{
    public int Value { get; private set;}

    private static int SomeLogic(int a, int b)
    {
        return a + b;
    }

    public Test(int a, int b)
    {
        this.Value = SomeLogic(a,b);
    }
}

But I have no idea how to do that it F#.

Body:
Example of two different ways of achieving this in F#:

type Test_UsesVal =
  val value : int
  new (a, b) = { value = someLogic a b }
  member x.Value = x.value

type Test_Preferred (a : int, b: int) =
  let value = someLogic a b
  member x.Value = value

Two examples with drawbacks:

// This type is default constructible and when using default ctor someLogic is not used
type Test_DefaultConstructible () =
  let mutable value = 0
  new (a, b) as x = Test_DefaultConstructible () then x.Value <- someLogic a b
  member x.Value with get () = value and private set v = value <- v

// This type has 2 constructors and using single value ctor someLogic is not used
type Test_2Constructors (value : int) =
  new (a, b) = Test_2Constructors (someLogic a b)
  member x.Value with get () = value

As self referential types were mentioned I would just like to point out that making a type self referential adds hidden overhead:

// Self referential types add hidden overhead
type Test_SelfReferential (a : int, b: int) as this =
  let computeValue () = someLogic this.A this.B

  member x.A      = a
  member x.B      = b
  member x.Value  = computeValue ()

Decompiled the overhead shows:

[CompilationMapping(SourceConstructFlags.ObjectType)]
[Serializable]
public class Test_SelfReferential
{
  internal int b;

  internal int a;

  // An extra field added
  internal FSharpRef<Program.Test_SelfReferential> @this = new FSharpRef<Program.Test_SelfReferential>(null);

  // An extra field added
  internal int init@29-1;

  public int A
  {
    get
    {
      // An extra check added in each method
      if (this.init@29-1 < 1)
      {
        LanguagePrimitives.IntrinsicFunctions.FailInit();
      }
      return this.a;
    }
  }

  public int B
  {
    get
    {
      // An extra check added in each method
      if (this.init@29-1 < 1)
      {
        LanguagePrimitives.IntrinsicFunctions.FailInit();
      }
      return this.b;
    }
  }

  public int Value
  {
    get
    {
      // An extra check added in each method
      if (this.init@29-1 < 1)
      {
        LanguagePrimitives.IntrinsicFunctions.FailInit();
      }
      return this.computeValue();
    }
  }

  public Test_SelfReferential(int a, int b) : this()
  {
    this.a = a;
    this.b = b;
    // An extra init added in .ctor
    this.@this.contents = this;
    this.init@29-1 = 1;
  }

  [CompilerGenerated]
  internal int computeValue()
  {
    // Extra checks added
    return LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.Test_SelfReferential>(this.@this.contents).A + LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.Test_SelfReferential>(this.@this.contents).B;
  }
}

The hidden overhead from self referential types in F# once caused me a performance regression (in some use-cases performance dropped by 50%).


问:
How do I use regex to take all numbers followed by the first digit of the identifier of a string using javascript?
I have the following string that needs to be converted to the following:</p>

```<code>3 Apples 5 Bananas 7 Oranges ===> 3A 5B 7O

3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries ===> 3A 5B 7O 19C
</code>```

答:
In .NET(C#) you can use System.Text.RegularExpressions.Regex class:</p>

```<code>        Regex re = new Regex(@"([\d]*)\sApples?\s([\d]*)\sBananas?\s([\d]*)\sOranges?");
        Match m = re.Match("3 Apple 5 Banana 7 Orange");
        string res = string.Format("{0}A {1}B {2}O", m.Groups[1], m.Groups[2], m.Groups[3]);
</code>```

Body:
I have the following string that needs to be converted to the following:

3 Apples 5 Bananas 7 Oranges ===> 3A 5B 7O

3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries ===> 3A 5B 7O 19C

Body:
In .NET(C#) you can use System.Text.RegularExpressions.Regex class:

        Regex re = new Regex(@"([\d]*)\sApples?\s([\d]*)\sBananas?\s([\d]*)\sOranges?");
        Match m = re.Match("3 Apple 5 Banana 7 Orange");
        string res = string.Format("{0}A {1}B {2}O", m.Groups[1], m.Groups[2], m.Groups[3]);


问:
What is a "_e" or "_vs" Google Tag Manager event?
I see these in my console output in Xcode but they don't correspond to any events I am explicitly sending.  They are just littering up the debug output and I'd like to get rid of them.

https://i.stack.imgur.com/OpYfR.png

https://i.stack.imgur.com/YIALz.png

答: "_e" is user_engagement event and "_vs" is screen_view event. Both are internal automatic events. Active users and user engagement reports are based on user_engagement event. Screen reporting is based on screen_view events.</p>


问:
How to remove CRLF in Vi editor
I am copying  "E)H@McQfTjWnZr4t7w!z%C*F-JaNdRgU"  to a file using vi editor. The file size should be 32 bytes but its 33bytes. I opened the same file using notepad++ and found that CRLF is being added at the end of the text.

How can i remove CRLF in vi editor.

答:
Also, without using vi:</p>

```<code>~$ echo -n 'E)H@McQfTjWnZr4t7w!z%C*F-JaNdRgU' > t
~$ ls -l t
-rw-r--r-- 1 niglesias niglesias 32 Jun  8 14:07 t
</code>```

Title: How to remove CRLF in Vi editor

Body:
Also, without using vi:

~$ echo -n 'E)H@McQfTjWnZr4t7w!z%C*F-JaNdRgU' > t
~$ ls -l t
-rw-r--r-- 1 niglesias niglesias 32 Jun  8 14:07 t


问:
How to choose parameters for svm in sklearn
I'm trying to use SVM from sklearn for a classification problem. I got a highly sparse dataset with more than 50K rows and binary outputs.

The problem is I don't know quite well how to efficiently choose the parameters, mainly the kernel, gamma anc C.

For the kernels for example, am I supposed to try all kernels and just keep the one that gives me the most satisfying results or is there something related to our data that we can see in the first place before choosing the kernel ?

Same goes for C and gamma.

Thanks !

答:
Yes, this is mostly a matter of experimentation -- especially as you've told us very little about your data set: separability, linearity, density, connectivity, ... all the characteristics that affect classification algorithms.

Try the linear and Gaussian kernels for starters.  If linear doesn't work well and Gaussian does, then try the other kernels.

Once you've found the best 1 or 2 kernels, then play with the cost and gamma parameters.  Gamma is a "slack" parameter: it gives the kernel permission to make a certain proportion of raw classification errors as a trade-off for other benefits: width of the gap, simplicity of the partition function, etc.

I haven't yet had an application that got more than trivial benefit from altering the cost.


问:
grant access to user on amazon RDS server
i need to grant all privileges for user master to the database 'mysql'(i mean the database not the server) on amazon RDS
i am trying to use

```<code>GRANT ALL PRIVILEGES ON mysql.* To 'master'@'aurora-wqeqwe-rdscluster-1jjch50tq2n3s.qrwerw-2.rds.amazon
aws.com' IDENTIFIED BY 'm3vyrtywrsY026y';
</code>```

答:
You can't grant SUPER privilege on RDS, so you can't use the ALL PRIVILEGES shortcut.

Sorry, you must name the privileges you want to grant explicitly, even if it means listing every privilege except SUPER.

You also can't grant privileges you don't have. I'm not sure your user has privileges to the mysql database. You can find out what privileges you have with SHOW GRANTS.

Body:
i need to grant all privileges for user master to the database 'mysql'(i mean the database not the server) on amazon RDS
i am trying to use

GRANT ALL PRIVILEGES ON mysql.* To 'master'@'aurora-wqeqwe-rdscluster-1jjch50tq2n3s.qrwerw-2.rds.amazon
aws.com' IDENTIFIED BY 'm3vyrtywrsY026y';


问:
mysql select on two different tables depending on field-value
I have the following problem and my brain burns out :)

I have two tables with personal data (one for customer 'table_a' and one for interesting peoples 'table_b').
In a third table 'table_inv' there are entries with invited_persons from both tables (a nd b).

The table_inv has a field 'invited_id' in which the id from table a or table b is stored. Another field 'type' has the value 'cust' or 'interest' to separate from which table (a or b) the entry comes.

Now i have to get the full data from table_a / table_b depending on the value from field 'type'...

I tried it whith case and if but with no result.

I'm searching for something like this:

```<code>SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
CASE a.type
    WHEN 'CUST' THEN
        LEFT JOIN accounts b ON a.inviteid = b.id;
    ELSE
        LEFT JOIN ext_contacts b ON a.inviteid = b.id;
END CASE
WHERE a.eventid = :eventid AND a.userid = '4711'
ORDER BY b.name_last ASC, b.name_first ASC
</code>```

Can somebody help me?

答:
You could simply join to both tables and then conditionally select the data from the relevant one. Another option is given below. I've assumed the alternative to 'CUST' is 'CONT' (for 'Contact'), so you'll need to tweak that if it's something else ...

```<code>SELECT
    a.id, a.created, a.userid, a.type, a.inviteid,
    b.name_first, b.name_last, b.zip, b.city
FROM
    ext_event_invites i
    LEFT JOIN
    (
    SELECT
       'CUST' as type,
       a.name_first,
       a.name_last,
       a.zip,
       a.city
    FROM accounts a

    UNION ALL

    SELECT
       'CONT' as type,
       c.name_first,
       c.name_last,
       c.zip,
       c.city
    FROM ext_contacts c
    ) as b ON
       i.inviteid = b.id AND
       i.type = b.type
WHERE
    a.eventid = :eventid AND a.userid = '4711'
ORDER BY
    b.name_last ASC,
    b.name_first ASC
</code>```

Body:
I have the following problem and my brain burns out :)

I have two tables with personal data (one for customer 'table_a' and one for interesting peoples 'table_b').
In a third table 'table_inv' there are entries with invited_persons from both tables (a nd b).

The table_inv has a field 'invited_id' in which the id from table a or table b is stored. Another field 'type' has the value 'cust' or 'interest' to separate from which table (a or b) the entry comes.

Now i have to get the full data from table_a / table_b depending on the value from field 'type'...

I tried it whith case and if but with no result.

I'm searching for something like this:

SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
CASE a.type
    WHEN 'CUST' THEN
        LEFT JOIN accounts b ON a.inviteid = b.id;
    ELSE
        LEFT JOIN ext_contacts b ON a.inviteid = b.id;
END CASE
WHERE a.eventid = :eventid AND a.userid = '4711'
ORDER BY b.name_last ASC, b.name_first ASC

Can somebody help me?

Body:
You could simply join to both tables and then conditionally select the data from the relevant one. Another option is given below. I've assumed the alternative to 'CUST' is 'CONT' (for 'Contact'), so you'll need to tweak that if it's something else ...

SELECT
    a.id, a.created, a.userid, a.type, a.inviteid,
    b.name_first, b.name_last, b.zip, b.city
FROM
    ext_event_invites i
    LEFT JOIN
    (
    SELECT
       'CUST' as type,
       a.name_first,
       a.name_last,
       a.zip,
       a.city
    FROM accounts a

    UNION ALL

    SELECT
       'CONT' as type,
       c.name_first,
       c.name_last,
       c.zip,
       c.city
    FROM ext_contacts c
    ) as b ON
       i.inviteid = b.id AND
       i.type = b.type
WHERE
    a.eventid = :eventid AND a.userid = '4711'
ORDER BY
    b.name_last ASC,
    b.name_first ASC


问:
Displaying user input html with newlines
I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is

```<code>Hello, this is the code: <a href='foo'>foo</a>

Bye
</code>```

I want it to be displayed just as above. The same with anything else, including iframe tags.

The closest I got is:

```<code>= simple_format(comment.body)
</code>```

but it sanitizes html code and it's not displayed. Example: foo biz bar is displayed as:

```<code>foo biz bar
</code>```

What should I do to achieve what I want?

答:
Just use it without any method, it will be rendered as plain text:

```<code>= comment.body
</code>```

Using your second example, the output will be:

```<code>foo <iframe>biz</iframe> bar
</code>```

To make \n behave as
, you can use CSS:

```<code>.add-line {
  white-space: pre-wrap;
}
</code>```

And use it in your view:

```<code>.add-line = comment.body
</code>```

Using your first example:

```<code>comment.body = "Hello, this is the code: <a href='foo'>foo</a>\n\nBye"
</code>```

The output will be:

```<code>Hello, this is the code: <a href='foo'>foo</a>

Bye
</code>```

Body:
I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is

Hello, this is the code: foo

Bye

I want it to be displayed just as above. The same with anything else, including iframe tags.

The closest I got is:

= simple_format(comment.body)

but it sanitizes html code and it's not displayed. Example: foo biz bar is displayed as:

foo biz bar

What should I do to achieve what I want?

Body:
Just use it without any method, it will be rendered as plain text:

= comment.body

Using your second example, the output will be:

foo <iframe>biz</iframe> bar

To make \n behave as <br>, you can use CSS:

.add-line {
  white-space: pre-wrap;
}

And use it in your view:

.add-line = comment.body

Using your first example:

comment.body = "Hello, this is the code: <a href='foo'>foo</a>\n\nBye"

The output will be:

Hello, this is the code: <a href='foo'>foo</a>

Bye


问:
hover link info
how can i get the effect that when u point over a link an information is shown in a box which tells u what that link does.

its like when you hover over a link a box explains its action.

Can some1 help me out with a neat sample.

do i need to use the ajax - hovermenuextender for this??

Thanks

答: Since you are using ASP.NET you could use ASPNET ToolTip; hover over the bulleted items in the link to see examples.</p>

Title: hover link info


问:
call multiple functions nodejs
I just started with nodejs and I basically have two functions I want to execute and based on the success of each of those functions, or error of those functions, I want the wrapper function to generate an overall status code.  I looked at the async package and I got it working in the happy path where everything succeeds and my last callback gets a success.  But what if one fails?  I see that the error gets sent to the last callback of async.waterfall, but the second function never gets run since there was an error and I do want to know the results of both functions.  I've tried, series, parallel, and waterfall, and from what I can tell, they all call the final callback once an error is hit.  Is there an idiomatic way to do this in Node? </p>

答:
Try this:</p>

```<code>const doTwoThings = callback => {
  let done = 0;
  const results = [];
  const check = n => (err, result) => {
    done++;
    if (!err) results[n] = result;
    if (done === 2) callback(results);
  }
  doFirstThing(args, check(0));
  doSecondThing(args, check(1));
}
</code>```

Title: call multiple functions nodejs

Body:
Try this:

const doTwoThings = callback => {
  let done = 0;
  const results = [];
  const check = n => (err, result) => {
    done++;
    if (!err) results[n] = result;
    if (done === 2) callback(results);
  }
  doFirstThing(args, check(0));
  doSecondThing(args, check(1));
}


问:
Track arrays elements order
I think my code is self explaining.

```<code>public Town[] GetShortestDistanceBetweenTowns() {
    Town[] allTowns = getTowns();
    Town[] bestPath = allTowns;
    int bestDistance = CalculateDistance(bestPath);
    int newDistance = bestDistance;

    //shuffle allTowns array and look for best distance
    for(int i=0; i<100; i++) {
        MixArray(allTowns);
        newDistance = CalculateDistance(allTowns);

        if (newDistance < bestDistance) {
            bestPath = allTowns;
            bestDistance = newDistance;
        }
    }

    return bestPath;
}
</code>```

The problem is when I use MixArray(allTowns) it is also changing order of my bestPath array. I want to keep only best order in this array. What can I do with that?

答:
Town is a reference type, so Town[] bestPath = allTowns; means that bestPath will always match allTowns.  To copy, you can implement IClonable for your Town class, or simply add a copy function that creates a new Town with duplicated values.

Here's a great article on reference vs value types:
http://www.albahari.com/valuevsreftypes.aspx

Title: Track arrays elements order

Body:
I think my code is self explaining.

public Town[] GetShortestDistanceBetweenTowns() {
    Town[] allTowns = getTowns();
    Town[] bestPath = allTowns;
    int bestDistance = CalculateDistance(bestPath);
    int newDistance = bestDistance;

    //shuffle allTowns array and look for best distance
    for(int i=0; i<100; i++) {
        MixArray(allTowns);
        newDistance = CalculateDistance(allTowns);

        if (newDistance < bestDistance) {
            bestPath = allTowns;
            bestDistance = newDistance;
        }
    }

    return bestPath;
}

The problem is when I use MixArray(allTowns) it is also changing order of my bestPath array. I want to keep only best order in this array. What can I do with that?


答:
You implemented the polyfill incorrectly.

You just need to include somewhere before using your endsWith function.

```<code>if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.lastIndexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}
</code>```

Line 1 checks whether you need a polyfill. On line 2, the function is assigned to String.prototype.endsWith, which means it can be called with String.endsWith(searchString, position)

Title: string.endswith("") does not work in IE(not sure how to use a Polyfill)

Body:
You implemented the polyfill incorrectly.

You just need to include somewhere before using your endsWith function.

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.lastIndexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}

Line 1 checks whether you need a polyfill. On line 2, the function is assigned to String.prototype.endsWith, which means it can be called with String.endsWith(searchString, position)


问:
mysql not ordering using Order by using DESC
Using mysql on ubuntu

the following command is not ordering in descending order

```<code>mysql> select spo_id, count(spo_id) as "maxCount" from order_details GROUP BY spo_id ORDER BY "maxCount" DESC;
+--------+----------+
| spo_id | maxCount |
+--------+----------+
|      1 |        1 |
|      2 |        3 |
|      3 |        1 |
+--------+----------+
3 rows in set (0.00 sec)
</code>```

答:
MySQL allows string literals with double quotes. So when you order by "maxCount", you're in fact ordering by a string literal, which is just meaningless. Remove the quotes and it should work just fine:</p>

```<code>MariaDB [db]> select spo_id, count(spo_id) as maxCount from order_details GROUP BY spo_id ORDER BY maxCount DESC;
+--------+----------+
| spo_id | maxCount |
+--------+----------+
|      2 |        3 |
|      3 |        1 |
|      1 |        1 |
+--------+----------+
3 rows in set (0.00 sec)
</code>```

Body:
Using mysql on ubuntu

the following command is not ordering in descending order

mysql> select spo_id, count(spo_id) as "maxCount" from order_details GROUP BY spo_id ORDER BY "maxCount" DESC;
+--------+----------+
| spo_id | maxCount |
+--------+----------+
|      1 |        1 |
|      2 |        3 |
|      3 |        1 |
+--------+----------+
3 rows in set (0.00 sec)

Body:
MySQL allows string literals with double quotes. So when you order by "maxCount", you're in fact ordering by a string literal, which is just meaningless. Remove the quotes and it should work just fine:

MariaDB [db]> select spo_id, count(spo_id) as maxCount from order_details GROUP BY spo_id ORDER BY maxCount DESC;
+--------+----------+
| spo_id | maxCount |
+--------+----------+
|      2 |        3 |
|      3 |        1 |
|      1 |        1 |
+--------+----------+
3 rows in set (0.00 sec)


问:
Automatically copy images to assets folder
I am running Angular 4 using Angular CLI and I am looking for a way to copy files from a component directory to the assets folder at run time.

So given the following folder structure:

```<code>/component
    my.component.*
    /images
        image1.png
        image2.png
</code>```

When I run ng serve or ng build I would like to have these files copied to the assets folder to be served up and available in the browser.

Is there a way to accomplish this? I've been searching for quite a while and am yet to find a solution.

答:
I guess you want to put those images in that folder for some personal preference? If they ultimately need to be in the assets folder at run time why not just put them there to start with? In your assets folder you could break them up into groups with folders that match your component structure.

It just doesn't seem like what you are trying to do is necessary.

To accomplish this I believe you would have to eject your project and then alter the entire build process to get this functionality. I don't believe the default angular CLI provides any mechanism to do this.

Body:
I am running Angular 4 using Angular CLI and I am looking for a way to copy files from a component directory to the assets folder at run time.

So given the following folder structure:

/component
    my.component.*
    /images
        image1.png
        image2.png

When I run ng serve or ng build I would like to have these files copied to the assets folder to be served up and available in the browser.

Is there a way to accomplish this? I've been searching for quite a while and am yet to find a solution.


问:
How to create a wrapping table in GTK#
I'm trying to make a table of square buttons in GTK# with the following properties:

Buttons will be added and removed one at a time.

Buttons should be laid out like text on a page - left to right until no more can fit on a row, then wrapping onto the next row.

If there are more buttons than will fit in the window, there should be a vertical scroll-bar.

The table should be resizable. Resizing should reflow the buttons as necessary.

Buttons should be of fixed size.

I started off trying to use a Table with Homogenous==true. I added a handler for SizeAllocated and in it I check if the width of the table has changed enough to add or remove a column. If it has, I removed all the buttons, updated NColumns and re-attached the buttons in the correct places. This seemed to work, but the buttons were not fixed size - they would expand to fill the horizontal space.

Next I tried turning off Homogenous and setting preferred dimensions for the buttons. A minor problem is that ideally I want to put a known-size bitmap on each button, and I would like to get the layout correct regardless of how many pixels the button adds around the bitmap, but I'm not sure how to find out the total size of the buttons to do my calculations. A more serious problem is that my application now redraws inconsistently - sometimes the button labels are off-centre or not drawn at all. I am wondering if this is because I am changing the layout in response to the wrong signal.

How should I do this instead? Is Table the right container for the job? Is there something that will do what I want out of the box? (Perhaps something more akin to "icon" or "thumbnail" view in a file browser?)  What is the correct way to manipulate the layout of the window in response to changes in size?

答: You might use GtkToolPalette which is available in GTK 2.20 and later.

Title: How to create a wrapping table in GTK#


问:
Why does not shuffling my train set and validation set result in huge performance gain?

I am using the ImageDataGenerator class of Keras, to load my samples in a Neural Network for a Binary classification problem.

No. +ve train images =5000, -ve train images = 5000. Similarly, +ve validation images=5000 and -ve validation image=5000. My batch size is 64.

My problem is, when I use the below code for loading the data and training, my accuracy hovers around 65-67 %. However, if I set shuffle = False, it hovers around 98-100 %, after 2-3 epochs.

Why is there such a big performance gain, how is shuffling playing a part in it?

Also, I noticed that, each batch, generated from flow_from_directory, has images entirely from any one class only. Would putting both positive and negative samples in a batch help give more realistic measure of accuracy ?

# data augmentation configuration we will use for training
train_datagen = ImageDataGenerator(preprocessing_function=HPF)

# data augmentation configuration we will use for testing
test_datagen = ImageDataGenerator(preprocessing_function=HPF)

# generator, for train data
train_generator = train_datagen.flow_from_directory(
        './data/train',  # this is the target directory
        target_size=(512, 512),  # all images will be resized to 512x512
        batch_size=batch_size,
        color_mode='grayscale',
        shuffle=True,
        class_mode='binary')  # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
        './data/validation',
        target_size=(512, 512),
        color_mode='grayscale',
        batch_size=batch_size,
        shuffle=True,
        class_mode='binary')
```

<p>What does the Shuffle = True actually does? Since the images in each batch are still either all positive or all negative.</p>

<p>The batches can be printed using the below code:</p>

<pre class="lang-py prettyprint-override"><code>for i in train_generator:
    idx = (train_generator.batch_index - 1) * train_generator.batch_size
    print(train_generator.filenames[idx : idx + train_generator.batch_size])
</code>```

答:
I think the most probable cause is that you have some correlation between train and validation batches. For example, when the training batches are all positives then validation also are. This could be aggravated by the fact that your training and validation sets have the same length : correlation could survive through epochs.

In any case I would rather trust the performance obtained with random shuffling. Any significant departure from those figures without shuffling is an indication of correlation in your data and a reminder why using random shuffling is needed and so commonly used.

EDIT

Here is a possible correlation in the data as you described it. Your training and validation sets have 10000 images. The first 5000 of both sets are/could be all positives. So during training, your net learns to label samples as positive no matter what. Validation samples are also positives, so this fits. Then, we train on all negative images. You net then adapts and labels samples as negative no matter what. This also correlates with your validation samples that happen to be also negative, and you end up with good validation scores.

One way to convince yourself that the real performance of unshuffled training is bad is to validate on the entire validation set, not on a single validation batch -- as I am assuming you are doing.

Body:
I am using the ImageDataGenerator class of Keras, to load my samples in a Neural Network for a Binary classification problem.

No. +ve train images =5000, -ve train images = 5000. Similarly, +ve validation images=5000 and -ve validation image=5000. My batch size is 64.

My problem is, when I use the below code for loading the data and training, my accuracy hovers around 65-67 %. However, if I set shuffle = False, it hovers around 98-100 %, after 2-3 epochs.

Why is there such a big performance gain, how is shuffling playing a part in it?

Also, I noticed that, each batch, generated from flow_from_directory, has images entirely from any one class only. Would putting both positive and negative samples in a batch help give more realistic measure of accuracy ?

# data augmentation configuration we will use for training
train_datagen = ImageDataGenerator(preprocessing_function=HPF)

# data augmentation configuration we will use for testing
test_datagen = ImageDataGenerator(preprocessing_function=HPF)

# generator, for train data
train_generator = train_datagen.flow_from_directory(
        './data/train',  # this is the target directory
        target_size=(512, 512),  # all images will be resized to 512x512
        batch_size=batch_size,
        color_mode='grayscale',
        shuffle=True,
        class_mode='binary')  # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
        './data/validation',
        target_size=(512, 512),
        color_mode='grayscale',
        batch_size=batch_size,
        shuffle=True,
        class_mode='binary')

What does the Shuffle = True actually does? Since the images in each batch are still either all positive or all negative.

The batches can be printed using the below code:

for i in train_generator:
    idx = (train_generator.batch_index - 1) * train_generator.batch_size
    print(train_generator.filenames[idx : idx + train_generator.batch_size])


问:
Vim problem with gf command
I am using Vim and I have set the path (set path+= c:/work/etc/etc) to my project directory (for C#), but still using command 'gf' give me error:

E:447 Can't find file.

Is there anything I am doing wrong over here?

答:
I also found out that

```<code>:set path+=./foo/bar
</code>```

adds a search location relative to the directory of the current file, just like '.' does.

My vim didn't want to search for such include

```<code>#include <common/util/string.h>
</code>```

So what I needed to do was

```<code>:set path+=foo/bar
</code>```

instead of

```<code>:set path+=./foo/bar
</code>```

The former adds a search path relative to current working directory. Hopefully it helps someone.

Title: Vim problem with gf command

Body:
I also found out that

:set path+=./foo/bar

adds a search location relative to the directory of the current file, just like '.' does.

My vim didn't want to search for such include

#include <common/util/string.h>

So what I needed to do was

:set path+=foo/bar

instead of

:set path+=./foo/bar

The former adds a search path relative to current working directory. Hopefully it helps someone.