问:
Toggle button not toggling for the first time
My app is simple: one button with one state toggleButton. In constructor toggleButton is set to the default value false. When I press the button, the app will start record some sensors and console.log their data to the chrome debugger screen.

```<code>constructor(props) {
    super(props);
    this.state = {
      toggleButton: false
    };
}

recordSensors() {
    let toggleButton = !this.state.toggleButton;
    this.setState({ toggleButton });

    if (this.state.toggleButton) {
        // start & record some sensors data
    } else {
        // stop recording
    }
}

render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={styles.toggleButton}
          onPress={() => this.recordSensors()}
        >
          <Text style={styles.buttonText}>
            {this.state.toggleButton ? 'Stop' : 'Start'}
          </Text>
        </TouchableOpacity>
        <Text>
          {this.state.toggleButton ? 'Recording...' : null}
        </Text>
      </View>
    );
  }
</code>```

The weird thing is, the first time I press the button, its text changed to Stop and the Recording... text appeared but the app didn't record sensors data. When I press the button again (the second time), then it now records.

But if I change if (this.state.toggleButton) to if (toggleButton) then it works fine. I can't understand the logic of it anymore. Can you guys help?

答:
Your problem:

```<code>onPress={() => this.recordSensors()}
</code>```

Fix:

```<code>onPress={() => this.recordSensors}
</code>```

Here is your logic:

In your constructor:

```<code>toggleButton = false;
</code>```

In render:

```<code>onPress={() => this.recordSensors()}
</code>```

Which calls:

```<code>//currently this.state.toggleButton == false;
let toggleButton = !this.state.toggleButton; // let toggleButton=true;
this.setState({ toggleButton }); // now state.toggleButton = true;
</code>```

So now when you click your button, you care call recordSensors() for a second time:

```<code>//currently this.state.toggleButton == true;
let toggleButton = !this.state.toggleButton; // let toggleButton =false;
this.setState({ toggleButton }); // now state.toggleButton == false;
</code>```

Body:
My app is simple: one button with one state toggleButton. In constructor toggleButton is set to the default value false. When I press the button, the app will start record some sensors and console.log their data to the chrome debugger screen.

constructor(props) {
    super(props);
    this.state = {
      toggleButton: false
    };
}

recordSensors() {
    let toggleButton = !this.state.toggleButton;
    this.setState({ toggleButton });

    if (this.state.toggleButton) {
        // start & record some sensors data
    } else {
        // stop recording
    }
}

render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={styles.toggleButton}
          onPress={() => this.recordSensors()}
        >
          <Text style={styles.buttonText}>
            {this.state.toggleButton ? 'Stop' : 'Start'}
          </Text>
        </TouchableOpacity>
        <Text>
          {this.state.toggleButton ? 'Recording...' : null}
        </Text>
      </View>
    );
  }

The weird thing is, the first time I press the button, its text changed to Stop and the Recording... text appeared but the app didn't record sensors data. When I press the button again (the second time), then it now records.

But if I change if (this.state.toggleButton) to if (toggleButton) then it works fine. I can't understand the logic of it anymore. Can you guys help?

Body:
Your problem:

onPress={() => this.recordSensors()}

Fix:

onPress={() => this.recordSensors}

Here is your logic:

In your constructor:

toggleButton = false;

In render:

onPress={() => this.recordSensors()}

Which calls:

//currently this.state.toggleButton == false;
let toggleButton = !this.state.toggleButton; // let toggleButton=true;
this.setState({ toggleButton }); // now state.toggleButton = true;

So now when you click your button, you care call recordSensors() for a second time:

//currently this.state.toggleButton == true;
let toggleButton = !this.state.toggleButton; // let toggleButton =false;
this.setState({ toggleButton }); // now state.toggleButton == false;


来源: stackexchange

问:
Is there for the bash something like perls __DATA__?
Is there for the bash something like perls __DATA__?
I mean the feature, that the code after __DATA__ will not be executed.

答:
This is a useful technique if you want to provide usage info for your script, but do not want to clutter up the main line of code with the help text. It's also great if you want to reference the usage more than once. To wit, a snippet from a shell script of mine:</p>

```<code>...
declare OPTSARGS
OPTSARGS=$(getoptp -o wh --long nopager,help -n myScript-- "$@")
status=$?
if ((status != 0))
then
    printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
    exit $status
fi
eval set -- "$OPTSARGS"
while true
do
    case "$1" in
        -w) diffargs="$diffargs -w"; shift;;
        --nopager) pager=cat; shift;;
        --) shift; break ;; ## end of opts, remaining $*, if any, are args
        -h | --help)
            printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
            exit 0;;
        *)
            echo "Internal error!"
            printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
            exit 1;;
   esac
done

...

echo "Done"
exit 0

__USAGE__
myScript [-w] [--nopager] [file [file...] ]

Some description goes here.

       -w - Do not compare whitespace
--nopager - Do not pass the output through 'less'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is a useful technique if you want to provide usage info for your script, but do not want to clutter up the main line of code with the help text. It's also great if you want to reference the usage more than once. To wit, a snippet from a shell script of mine:

...
declare OPTSARGS
OPTSARGS=$(getoptp -o wh --long nopager,help -n myScript-- "$@")
status=$?
if ((status != 0))
then
    printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
    exit $status
fi
eval set -- "$OPTSARGS"
while true
do
    case "$1" in
        -w) diffargs="$diffargs -w"; shift;;
        --nopager) pager=cat; shift;;
        --) shift; break ;; ## end of opts, remaining $*, if any, are args
        -h | --help)
            printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
            exit 0;;
        *)
            echo "Internal error!"
            printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
            exit 1;;
   esac
done

...

echo "Done"
exit 0

__USAGE__
myScript [-w] [--nopager] [file [file...] ]

Some description goes here.

       -w - Do not compare whitespace
--nopager - Do not pass the output through 'less'

ContentLicense: CC BY-SA 3.0


问:
Keep Getting a Segmentation Fault On This?
I keep getting the segmentation fault (core dumped) on the code below.  Any ideas on why this is happening.  The code is designed to read numbers from a text document, convert them to integers, perform radix sort, and print out the array.

```<code>#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti)
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    int arr[10000];
    int i = 0;
    int result;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            getline(myfile, line);
            result = StrToInt(line);
            arr[i] = result;
            //cout<< arr[i] <<"\n";
            i++;
        }
    }

    int n = sizeof(arr)/sizeof(arr[0]);
    radixsort(arr, n);

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << "\n";
    }

    return 0;
}
</code>```

Contents of the text file I am using for input:
1244
3455
6565
55
765
8768
687
879

答:
Your program has undefined behavior, because it uses more entries of the array than you initialized with data. You pass the length of the entire array for n even though only a small portion of it, from 0 to i, has been initialized.

Change the code to use n in place of i in the reading loop, and pass that n unmodified to the sort function. This is going to fix the problem (demo).

```<code>int n = 0;
myfile.open("integers2.txt");
if(myfile.is_open()) {
    while (myfile >> arr[n]) {
        n++;
    }
}
radixsort(arr, n);
</code>```

Body:
I keep getting the segmentation fault (core dumped) on the code below.  Any ideas on why this is happening.  The code is designed to read numbers from a text document, convert them to integers, perform radix sort, and print out the array.

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti)
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    int arr[10000];
    int i = 0;
    int result;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            getline(myfile, line);
            result = StrToInt(line);
            arr[i] = result;
            //cout<< arr[i] <<"\n";
            i++;
        }
    }

    int n = sizeof(arr)/sizeof(arr[0]);
    radixsort(arr, n);

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << "\n";
    }

    return 0;
}

Contents of the text file I am using for input:
1244
3455
6565
55
765
8768
687
879

Body:
Your program has undefined behavior, because it uses more entries of the array than you initialized with data. You pass the length of the entire array for n even though only a small portion of it, from 0 to i, has been initialized.

Change the code to use n in place of i in the reading loop, and pass that n unmodified to the sort function. This is going to fix the problem (demo).

int n = 0;
myfile.open("integers2.txt");
if(myfile.is_open()) {
    while (myfile >> arr[n]) {
        n++;
    }
}
radixsort(arr, n);


问:
How to implement bulk insert feature in Sql Server 2005
I have a table in database called user which has following entries.

```<code>Userid FirstName LastName
1          fa      la
2          fb      lb
3          fc      lc
</code>```

and another table userform

```<code>Userformid Userid  Form   Code modifieddate  Isclosed   IsForm
1             1     ff     cc     somedate     0           0
2             1     gg     rr     somedate     0           0
3             1     bb     bb     somedate     0           0
4             2     ss     aa     somedate     0           0
5             2     qq     sa     somedate     0           0
6             3     ws     xc     somedate     0           0
</code>```

Now i have to insert new record for every userid in userform table and only Form and Code column should get copied in inserted row from userform table only by latest modifieddate ( something like:- order by modifieddate desc.)

```<code>Output should be in userform table :
    Userformid Userid  Form   Code modifieddate  Isclosed   IsForm
    1             1     ff     cc     somedate     0           0
    2             1     gg     rr     somedate     0           0
    3             1     bb     bb     somedate     0           0
    4             2     ss     aa     somedate     0           0
    5             2     qq     sa     somedate     0           0
    6             3     ws     xc     somedate     0           0
newly added row
    7             1     bb     bb     newdate     0           0
    8             2     qq     sa     newdate     0           0
    9             3     ws     xc     newdate     0           0
</code>```

There are 6000 record in user table and userform table.

How can we achieve this using bulk insert feature OR using any other technics in sql server 2005.I don't want to use CURSOR.

答:
Something like this, making use of ROW_NUMBER should do the trick. Try it first without the INSERT to check the results it returns. If that is then what you want, just uncomment the INSERT line and go ahead.</p>

```<code>DECLARE @NewDate DATETIME
SET @NewDate = GETDATE()

--INSERT UserForm (UserId, Form, Code, modifieddate, IsClosed, IsForm)
SELECT UserId, Form, Code, @NewDate, IsClosed, IsForm
FROM
(
    SELECT ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY modifieddate DESC) AS RowNo,
        UserId, Form, Code, IsClosed, IsForm
    FROM UserForm
) x
WHERE RowNo = 1
</code>```

Body:
I have a table in database called user which has following entries.

Userid FirstName LastName
1          fa      la
2          fb      lb
3          fc      lc

and another table userform

Userformid Userid  Form   Code modifieddate  Isclosed   IsForm
1             1     ff     cc     somedate     0           0
2             1     gg     rr     somedate     0           0
3             1     bb     bb     somedate     0           0
4             2     ss     aa     somedate     0           0
5             2     qq     sa     somedate     0           0
6             3     ws     xc     somedate     0           0

Now i have to insert new record for every userid in userform table and only Form and Code column should get copied in inserted row from userform table only by latest modifieddate ( something like:- order by modifieddate desc.)

Output should be in userform table :
    Userformid Userid  Form   Code modifieddate  Isclosed   IsForm
    1             1     ff     cc     somedate     0           0
    2             1     gg     rr     somedate     0           0
    3             1     bb     bb     somedate     0           0
    4             2     ss     aa     somedate     0           0
    5             2     qq     sa     somedate     0           0
    6             3     ws     xc     somedate     0           0
newly added row
    7             1     bb     bb     newdate     0           0
    8             2     qq     sa     newdate     0           0
    9             3     ws     xc     newdate     0           0

There are 6000 record in user table and userform table.

How can we achieve this using bulk insert feature OR using any other technics in sql server 2005.I don't want to use CURSOR.

Body:
Something like this, making use of ROW_NUMBER should do the trick. Try it first without the INSERT to check the results it returns. If that is then what you want, just uncomment the INSERT line and go ahead.

DECLARE @NewDate DATETIME
SET @NewDate = GETDATE()

--INSERT UserForm (UserId, Form, Code, modifieddate, IsClosed, IsForm)
SELECT UserId, Form, Code, @NewDate, IsClosed, IsForm
FROM
(
    SELECT ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY modifieddate DESC) AS RowNo,
        UserId, Form, Code, IsClosed, IsForm
    FROM UserForm
) x
WHERE RowNo = 1


问:
How to change the onclick of a button to another function using JavaScript?
This is my first question I'm asking. Is it possible to change the onclick="change()" to another function like onclick="change1()"

My code is like this:

```<code><a href="#" onclick="changeSrc()" id="a1"><img src="images/transparent-arrow-hi.png" style="position:absolute; top:525px; left:1000px; height:50px; width:50px;" ></a>
<img src="images/keyboard.png" id="pic1">
<img src="images/mouse1.png" id="pic2">
<img src="images/PCstand.png" id="pic3">
<img src="images/monitor.png" id="pic4">
</code>```

My Javascript is as follows:

```<code><script>
function changeSrc() {
document.getElementById('pic1').src="images/robber1.jpg";
document.getElementById('pic2').src="images/guarding entrance 1.jpg";
document.getElementById('pic3').src="images/Lock.ico";
document.getElementById('pic4').src="images/Number pads.jpg";
}
</script>
</code>```

This works so far in changing the img src , But I want to click the same button many times to change the img src to others.

So its like this button that when onclick , can call the first function to change the img src and at the same time prepare the onclick to call the second funtion.

Is that even possible?

I can add more code if needed.

答:
You can use this code snippet to dynamically associate and change the onclick function of the element.

function changeSrc(_this){
 //associate function change1 inside changeSrc
 $(_this).attr('onclick','change1(this)');
}

function change1(_this){
//associate function change2 inside change1
  $(_this).attr('onclick','change2(this)');
  console.log('Iniside Change1()')
}

function change2(_this){
//associate function change3 inside change2
  $(_this).attr('onclick','change3(this)');
  console.log('Iniside Change2()')
}

function change3(_this){
  console.log('Iniside Change3()')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="images/transparent-arrow-hi.png" style="position:absolute; top:525px; left:1000px; height:50px; width:50px;" >click</code>```

Body:
This is my first question I'm asking. Is it possible to change the onclick="change()" to another function like onclick="change1()"

My code is like this:

My Javascript is as follows:

This works so far in changing the img src , But I want to click the same button many times to change the img src to others.

So its like this button that when onclick , can call the first function to change the img src and at the same time prepare the onclick to call the second funtion.

Is that even possible?

I can add more code if needed.

Body:
You can use this code snippet to dynamically associate and change the onclick function of the element.

function changeSrc(_this){
 //associate function change1 inside changeSrc
 $(_this).attr('onclick','change1(this)');
}

function change1(_this){
//associate function change2 inside change1
  $(_this).attr('onclick','change2(this)');
  console.log('Iniside Change1()')
}

function change2(_this){
//associate function change3 inside change2
  $(_this).attr('onclick','change3(this)');
  console.log('Iniside Change2()')
}

function change3(_this){
  console.log('Iniside Change3()')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="changeSrc(this)" id="a1"><img src="images/transparent-arrow-hi.png" style="position:absolute; top:525px; left:1000px; height:50px; width:50px;" >click</a>


问:
Electron BrowserWindow Facebook Login Failed to Set Cookies
I am using Facebook Authentication in my Electron desktop app. I am loading the FB auth view into an Electron BrowserWindow. When the BrowserWindow first loads, I get the error:

```<code>Uncaught DOMException: Failed to set the 'cookie' property on 'Document': Cookies are disabled inside 'data:' URLs.
</code>```

And when I try to login, I get the error:

```<code>Uncaught DOMException: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs.
</code>```

Here is how I am loading my the raw HTML for the Facebook view (data['_body']) into the BrowserWindow:

```<code>let windowProperties = {
            height: 900,
            width: 1200,
            webPreferences: {
                webSecurity: false,
                nodeIntegration: false
            }
          };
          let win = new electron.remote.BrowserWindow(windowProperties)
          win.loadURL('data:text/html,' + encodeURIComponent(data["_body"]));
</code>```

Any help would be much appreciated!

答: You might be looking for browserWindow.webContents.Session. If you are working with older versions of electron you might look at Electron-cookies.</p>

Body:
I am using Facebook Authentication in my Electron desktop app. I am loading the FB auth view into an Electron BrowserWindow. When the BrowserWindow first loads, I get the error:

Uncaught DOMException: Failed to set the 'cookie' property on 'Document': Cookies are disabled inside 'data:' URLs.

And when I try to login, I get the error:

Uncaught DOMException: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs.

Here is how I am loading my the raw HTML for the Facebook view (data['_body']) into the BrowserWindow:

let windowProperties = {
            height: 900,
            width: 1200,
            webPreferences: {
                webSecurity: false,
                nodeIntegration: false
            }
          };
          let win = new electron.remote.BrowserWindow(windowProperties)
          win.loadURL('data:text/html,' + encodeURIComponent(data["_body"]));

Any help would be much appreciated!


问:
Cannot implicitly convert type 'string' to 'System.DateTime'
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

```<code>DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);
</code>```

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

答:
```<code>string input = "21-12-2010"; // dd-MM-yyyy
DateTime d;
if (DateTime.TryParseExact(input, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d))
{
    // use d
}
</code>```

Body:
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.


问:
c++ socket - sendto - no data recieved
Visual Studio 2017 Community

c++ CLR project

It should be sending a UDP datagram to a multicast address.

I am sending without errors.

```<code>--------------
MULTICAST
-------------------
'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\mswsock.dll'. Symbols loaded.

MULTICAST ----
IP:224.0.0.2
PORT:7125
-------------

Sent: 13

Sent: 13

Sent: 13
</code>```

The receiver gets this input

```<code> {"socketId":0,"data":{},"remoteAddress":"192.168.0.80","remotePort":2535}
</code>```

Here is the sending part of the code

```<code>const char *msg = "1 2 3 4 5 6 7";

while (sending) {

    //swprintf(str, L"\nMSG: \n%c ", channels);
    //OutputDebugString(str);

    // Send a message to the multicasting address.
    int ret = sendto(Sock, msg, strlen(msg), 0, (struct sockaddr FAR *) &dest_sin, sizeof(dest_sin));

    swprintf(str, L"\nSent: %d \n\n", ret);
    OutputDebugString(str);

    if (ret == SOCKET_ERROR)
    {
        swprintf(str, L"\nsendto failed! Error: %d ", WSAGetLastError());
        OutputDebugString(str);

        closesocket(Sock);
        sending = false;
    }
    Sleep(66);
}
</code>```

Full socket code if it helps

```<code>// Sent message string
TCHAR szError[100];               // Error message string
SOCKET Sock = INVALID_SOCKET;     // Datagram window socket

SOCKADDR_IN source_sin,           // Source socket address
    dest_sin;             // Destination socket address

WSADATA WSAData;                  // Contains details of the
                                  // Winsock implementation

OutputDebugString(L"\n--------------\nMULTICAST\n-------------------\n");

// Initialize Winsock.
if (WSAStartup(MAKEWORD(1, 1), &WSAData) != 0)
{
    swprintf(str, TEXT("WSAStartup failed! Error: %d"), WSAGetLastError());
    OutputDebugString(str);
    return FALSE;
}

// Create a datagram window socket, Sock.
if ((Sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
    swprintf(str, TEXT("Allocating socket failed! Error: %d"), WSAGetLastError());
    OutputDebugString(str);
    return FALSE;
}

// Fill out source socket's address information.
source_sin.sin_family = AF_INET;
source_sin.sin_port = htons(SOURCE_PORT);
source_sin.sin_addr.s_addr = htonl(INADDR_ANY);

// Associate the source socket's address with the socket, Sock.
if (bind(Sock,
    (struct sockaddr FAR *) &source_sin,
    sizeof(source_sin)) == SOCKET_ERROR)
{
    swprintf(str, TEXT("Binding socket failed! Error: %d"), WSAGetLastError());
    OutputDebugString(str);
    closesocket(Sock);
    return FALSE;
}

// Set the Time-to-Live of the multicast.
int set_sock = setsockopt(Sock, SOL_SOCKET, SO_BROADCAST, (char FAR *)&iOptVal, sizeof(int));
if (set_sock == SOCKET_ERROR)
{
    swprintf(str, TEXT("\n`setsockopt` failed! Error: %d\n\n"), WSAGetLastError());
    OutputDebugString(str);
    closesocket(Sock);
    return FALSE;
}

// Fill out the desination socket's address information.
dest_sin.sin_family = AF_INET;
dest_sin.sin_port = ntohs(mcast_port);
dest_sin.sin_addr.s_addr = inet_addr(mcast_ip);

swprintf(str, L"\nMULTICAST ----\nIP:%s\nPORT:%d\n-------------\n", mcast_ip, mcast_port);
OutputDebugString(str);

const char *msg = "1 2 3 4 5 6 7";

while (sending) {

    //swprintf(str, L"\nMSG: \n%c ", channels);
    //OutputDebugString(str);

    // Send a message to the multicasting address.
    int ret = sendto(Sock, msg, strlen(msg), 0, (struct sockaddr FAR *) &dest_sin, sizeof(dest_sin));

    swprintf(str, L"\nSent: %d \n\n", ret);
    OutputDebugString(str);

    if (ret == SOCKET_ERROR)
    {
        swprintf(str, L"\nsendto failed! Error: %d ", WSAGetLastError());
        OutputDebugString(str);

        closesocket(Sock);
        sending = false;
    }
    Sleep(66);
}

OutputDebugString(L"\n---------------------\nMULTICAST DONE\n---------------------\n");

if (!sending) {
    // Disable sending on Sock before closing it.
    shutdown(Sock, 0x01);

    // Close Sock.
    closesocket(Sock);

    WSACleanup();
}
</code>```

From what I have read.

const char * msg

should be correct.?

Any advise is appreciated.

Edit:

As per Remy Lebeau

int set_sock = setsockopt(Sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&iOptVal, sizeof(int));

Error: 10042 -- An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.

IP_ADD_MEMBERSHIP = 5

答:
Turns out...

setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP) is not the answer, data is sent using setsockopt(SOL_SOCKET, SO_BROADCAST). Which I tested and EJP pointed out.

The problem egg on my face was I forgot that the data is always empty in the console until I parse the buffer, then data is present.

Thank you all.

Title: c++ socket - sendto - no data recieved

Body:
Visual Studio 2017 Community

c++ CLR project

It should be sending a UDP datagram to a multicast address.

I am sending without errors.

--------------
MULTICAST
-------------------
'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\mswsock.dll'. Symbols loaded.

MULTICAST ----
IP:224.0.0.2
PORT:7125
-------------

Sent: 13

Sent: 13

Sent: 13

The receiver gets this input

 {"socketId":0,"data":{},"remoteAddress":"192.168.0.80","remotePort":2535}

Here is the sending part of the code

const char *msg = "1 2 3 4 5 6 7";

while (sending) {

    //swprintf(str, L"\nMSG: \n%c ", channels);
    //OutputDebugString(str);

    // Send a message to the multicasting address.
    int ret = sendto(Sock, msg, strlen(msg), 0, (struct sockaddr FAR *) &dest_sin, sizeof(dest_sin));

    swprintf(str, L"\nSent: %d \n\n", ret);
    OutputDebugString(str);

    if (ret == SOCKET_ERROR)
    {
        swprintf(str, L"\nsendto failed! Error: %d ", WSAGetLastError());
        OutputDebugString(str);

        closesocket(Sock);
        sending = false;
    }
    Sleep(66);
}

Full socket code if it helps

// Sent message string
TCHAR szError[100];               // Error message string
SOCKET Sock = INVALID_SOCKET;     // Datagram window socket

SOCKADDR_IN source_sin,           // Source socket address
    dest_sin;             // Destination socket address

WSADATA WSAData;                  // Contains details of the
                                  // Winsock implementation

OutputDebugString(L"\n--------------\nMULTICAST\n-------------------\n");

// Initialize Winsock.
if (WSAStartup(MAKEWORD(1, 1), &WSAData) != 0)
{
    swprintf(str, TEXT("WSAStartup failed! Error: %d"), WSAGetLastError());
    OutputDebugString(str);
    return FALSE;
}

// Create a datagram window socket, Sock.
if ((Sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
    swprintf(str, TEXT("Allocating socket failed! Error: %d"), WSAGetLastError());
    OutputDebugString(str);
    return FALSE;
}

// Fill out source socket's address information.
source_sin.sin_family = AF_INET;
source_sin.sin_port = htons(SOURCE_PORT);
source_sin.sin_addr.s_addr = htonl(INADDR_ANY);

// Associate the source socket's address with the socket, Sock.
if (bind(Sock,
    (struct sockaddr FAR *) &source_sin,
    sizeof(source_sin)) == SOCKET_ERROR)
{
    swprintf(str, TEXT("Binding socket failed! Error: %d"), WSAGetLastError());
    OutputDebugString(str);
    closesocket(Sock);
    return FALSE;
}

// Set the Time-to-Live of the multicast.
int set_sock = setsockopt(Sock, SOL_SOCKET, SO_BROADCAST, (char FAR *)&iOptVal, sizeof(int));
if (set_sock == SOCKET_ERROR)
{
    swprintf(str, TEXT("\n`setsockopt` failed! Error: %d\n\n"), WSAGetLastError());
    OutputDebugString(str);
    closesocket(Sock);
    return FALSE;
}

// Fill out the desination socket's address information.
dest_sin.sin_family = AF_INET;
dest_sin.sin_port = ntohs(mcast_port);
dest_sin.sin_addr.s_addr = inet_addr(mcast_ip);

swprintf(str, L"\nMULTICAST ----\nIP:%s\nPORT:%d\n-------------\n", mcast_ip, mcast_port);
OutputDebugString(str);

const char *msg = "1 2 3 4 5 6 7";

while (sending) {

    //swprintf(str, L"\nMSG: \n%c ", channels);
    //OutputDebugString(str);

    // Send a message to the multicasting address.
    int ret = sendto(Sock, msg, strlen(msg), 0, (struct sockaddr FAR *) &dest_sin, sizeof(dest_sin));

    swprintf(str, L"\nSent: %d \n\n", ret);
    OutputDebugString(str);

    if (ret == SOCKET_ERROR)
    {
        swprintf(str, L"\nsendto failed! Error: %d ", WSAGetLastError());
        OutputDebugString(str);

        closesocket(Sock);
        sending = false;
    }
    Sleep(66);
}

OutputDebugString(L"\n---------------------\nMULTICAST DONE\n---------------------\n");

if (!sending) {
    // Disable sending on Sock before closing it.
    shutdown(Sock, 0x01);

    // Close Sock.
    closesocket(Sock);

    WSACleanup();
}

From what I have read.

const char * msg

should be correct.?

Any advise is appreciated.

Edit:

As per Remy Lebeau

int set_sock = setsockopt(Sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&iOptVal, sizeof(int));

Error: 10042 -- An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.

IP_ADD_MEMBERSHIP = 5


问:
iTunes Connect demo account in existing live database for app submittal?
I'm submitting my first app through iTunes Connect. It is a social networking community so I have to provide a demo account for the submission. My app already has a live database of users as there is currently an active web version.

I'm new to this and confused as to how I should handle this. Should I be creating a demo account that will not show up in any other live user's search results? Are the testers going to be attempting to interact with other live users? I am assuming I will need to show the various functions of the app, like messaging and events. In that case should I be creating a few "demo" users for the testers to interact with?

Alternatively, should I be linking them to the development version and development database? If that's the case, then the build that I send them would only be a development build then?

I am confused on how this is supposed to work and can't seem to find any information to help?

答:
In my experience, you'll need to give them the production version that will go into the store.  So not the development build.

When we submit an app for approval, it seems to get installed and activated on a couple of devices, but nothing much ever happens.  They barely use it, as far as we can tell.  We can tell that it's installed and run.  We have previously been rejected when the network connectivity wasn't working right, so we know that they do look at the app after it's installed.

I'd suggest you make them an account that looks relatively anonymous (or even "Test Account" which you real users are hardly likely to try to interact with).  You could create another account and say "If you want to send a message, send it to account xxxx".  We've never had them interact with our app enough to utilise the suggestions we've made.

If you have an active / inactive flag, you could think about making these accounts inactive once the app is approved, then re-activating it when you next want to submit your app.


问:
Building host on macOS Sierra
i have installed visual studio 2017 in my windows10 ..I want to build an ios app in windows10 using xamarin.IOS.For that I am running macOS Sierra on oracle virtual box and building host from this VM mac.I am unable to find in my Xamarin Mac Agent in windows10.Can anyone help with this problem??</p>

答:
You need to install the Remote iOS Simulator.

https://developer.xamarin.com/guides/cross-platform/windows/ios-simulator/

Title: Building host on macOS Sierra


问:
Yii2 cannot save model data in controller
I am trying to get value from title and I did but after pressing save button the title is not saving in database

```<code>$model = new Translation();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
    $getfromtitle = Yii::$app->request->post('Translation')['translation_title'];
    echo $getfromtitle;
    echo "<br />";
    $model->translation_drive_title = $getfromtitle;
    echo $model->translation_drive_title;
    echo "<br />";
    echo "here";
    die();
}
</code>```

after killing the code, yes everything is printing as I wanted but after pressing save/submit button (of course removing the die() function to let the code continue), the title which I got from first input is not saving to the second input $model->translation_drive_title in db

Thank you all

答:
You are saving model before assigning value to translation_drive_title

```<code>$model = new Translation();
if ($model->load(Yii::$app->request->post())) {
    $model->translation_drive_title = Yii::$app->request->post('Translation')['translation_title'];
    $model->save();
}
</code>```

Body:
I am trying to get value from title and I did but after pressing save button the title is not saving in database

$model = new Translation();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
    $getfromtitle = Yii::$app->request->post('Translation')['translation_title'];
    echo $getfromtitle;
    echo "
";
    $model->translation_drive_title = $getfromtitle;
    echo $model->translation_drive_title;
    echo "
";
    echo "here";
    die();
}

after killing the code, yes everything is printing as I wanted but after pressing save/submit button (of course removing the die() function to let the code continue), the title which I got from first input is not saving to the second input $model->translation_drive_title in db

Thank you all

Body:
You are saving model before assigning value to translation_drive_title

$model = new Translation();
if ($model->load(Yii::$app->request->post())) {
    $model->translation_drive_title = Yii::$app->request->post('Translation')['translation_title'];
    $model->save();
}


问:
How to order a list of paragraphs
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

```<code>newList = (from a in list orderby a.Name ascending select a).ToList();
</code>```

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

答:
01 is different from 1. Lexicographically 13 comes before 3. Presuming that all "paragraphs" are prepended with a non-zero-prefixed integer, you will need to parse each integer and order your list by that.

The previous answers will throw FormatException if a list item is not prefixed by an integer.

Title: How to order a list of paragraphs

Body:
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

newList = (from a in list orderby a.Name ascending select a).ToList();

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?


问:
Concatenate multiple instances of complex data structure in python
To give some background: often in experimental science we have a set of probes at different locations that record some variables (temperature and velocity here) in time. These probes may be interrupted at certain times and so what we are left with are chunks of restart data that just continue where the previous data set ended. I have created an example data set to show this, and now the only thing is to find an elegant way of concatenating the "chunks" of data collected:

```<code>import pandas as pd
import numpy as np

dimS = 1  # dimension of a scalar variable
dimV = 3  # dimension of a vector variable
Np = 3    # number of measurement locations
Nt = 10   # time samples

def create_single_probe(Nt):
    """
    Create fictitious data for a probe
    """
    probe = {}
    probe["temp"] = np.random.rand(dimS*Nt).reshape(dimS,Nt)
    probe["velo"] = np.random.rand(dimV*Nt).reshape(dimV,Nt)
    probe["loc"] = np.random.rand(3)
    return probe

def create_multiple_probes(Np,Nt):
    """
    Gather mutliple probes into dict
    """
    probes = []

    for i in range(Np):
        probes.append(create_single_probe(Nt))

    data = {}
    data["time"] = range(Nt)
    data["probes"] = probes

    return data

# Create data that we want to concatenate
restarts = [create_multiple_probes(Np,Nt) for i in range(3)]

# Now we want to concatenate the entries of restarts

def concat_complex_dict(restarts):

   # Solution here...

   return concat_data
</code>```

in this example the location of the probe for each restart location will change with the new restart data, but this is not the case in reality.

After concatenation I expect the following:

concat_data["time"] to be a list or array of length 30

concat_data["probes"] to be a list of length 3 (since there are three probe locations) where each entry is a dictionary such that the ith entry we have

concat_data["probes"][i]["temp"] is an array length 30 and
concat_data["probes"][i]["velo"] is an array length 3x30

I can make a very laborious solution whereby I go through all the elements of my dictionary that I want concatenate with a bunch of lists but I am wondering if there is a more elegant way maybe using pandas...

I hope it makes sense what I want to do and any suggestions would be helpful.

答:
Assuming I followed the explanation correctly and made the correct assumptions (veloctiy is in X,Y,Z format), here is my suggestion for a more readable format. If I'm close I can change it to be more reliable, if I'm off I will remove.</p>

```<code>dimS = 1  # dimension of a scalar variable
dimV = 3  # dimension of a vector variable
Np = 3    # number of measurement locations
Nt = 10   # time samples

def create_single_probe(Nt):
    """
    Create fictitious data for a probe
    """
    probe = {}
    probe["temp"] = np.random.rand(dimS*Nt).reshape(dimS,Nt)
    probe["velo"] = np.random.rand(dimV*Nt).reshape(dimV,Nt)

    '''Create dataframe'''
    mat = np.concatenate([probe['temp'].reshape(Nt,dimS),probe['velo'].reshape(Nt,dimV)],axis=1)
    frame = pd.DataFrame(mat,columns=['temp','VelocityX','VelocityY','VelocityZ'])
    probe["loc"] = np.random.rand(3)

    '''Add location of probe as comma separated string'''
    frame['loc'] = ",".join(map(str,probe['loc']))
    return frame

def create_multiple_probes(Np,Nt):
    """
    Gather mutliple probes into dict
    """
    probes = []

    for i in range(Np):
        df = create_single_probe(Nt)
        '''Set time as a row value for each probe'''
        df['time'] = range(Nt)
        probes.append(df)

    '''Concat into one dataframe'''
    data = pd.concat(probes)

    return data

print create_multiple_probes(Np,Nt)
</code>```

Body:
To give some background: often in experimental science we have a set of probes at different locations that record some variables (temperature and velocity here) in time. These probes may be interrupted at certain times and so what we are left with are chunks of restart data that just continue where the previous data set ended. I have created an example data set to show this, and now the only thing is to find an elegant way of concatenating the "chunks" of data collected:

import pandas as pd
import numpy as np

dimS = 1  # dimension of a scalar variable
dimV = 3  # dimension of a vector variable
Np = 3    # number of measurement locations
Nt = 10   # time samples

def create_single_probe(Nt):
    """
    Create fictitious data for a probe
    """
    probe = {}
    probe["temp"] = np.random.rand(dimS*Nt).reshape(dimS,Nt)
    probe["velo"] = np.random.rand(dimV*Nt).reshape(dimV,Nt)
    probe["loc"] = np.random.rand(3)
    return probe

def create_multiple_probes(Np,Nt):
    """
    Gather mutliple probes into dict
    """
    probes = []

    for i in range(Np):
        probes.append(create_single_probe(Nt))

    data = {}
    data["time"] = range(Nt)
    data["probes"] = probes

    return data

# Create data that we want to concatenate
restarts = [create_multiple_probes(Np,Nt) for i in range(3)]

# Now we want to concatenate the entries of restarts

def concat_complex_dict(restarts):

   # Solution here...

   return concat_data

in this example the location of the probe for each restart location will change with the new restart data, but this is not the case in reality.

After concatenation I expect the following:

concat_data["time"] to be a list or array of length 30

concat_data["probes"] to be a list of length 3 (since there are three probe locations) where each entry is a dictionary such that the ith entry we have

concat_data["probes"][i]["temp"] is an array length 30 and
concat_data["probes"][i]["velo"] is an array length 3x30

I can make a very laborious solution whereby I go through all the elements of my dictionary that I want concatenate with a bunch of lists but I am wondering if there is a more elegant way maybe using pandas...

I hope it makes sense what I want to do and any suggestions would be helpful.

Body:
Assuming I followed the explanation correctly and made the correct assumptions (veloctiy is in X,Y,Z format), here is my suggestion for a more readable format. If I'm close I can change it to be more reliable, if I'm off I will remove.

dimS = 1  # dimension of a scalar variable
dimV = 3  # dimension of a vector variable
Np = 3    # number of measurement locations
Nt = 10   # time samples

def create_single_probe(Nt):
    """
    Create fictitious data for a probe
    """
    probe = {}
    probe["temp"] = np.random.rand(dimS*Nt).reshape(dimS,Nt)
    probe["velo"] = np.random.rand(dimV*Nt).reshape(dimV,Nt)

    '''Create dataframe'''
    mat = np.concatenate([probe['temp'].reshape(Nt,dimS),probe['velo'].reshape(Nt,dimV)],axis=1)
    frame = pd.DataFrame(mat,columns=['temp','VelocityX','VelocityY','VelocityZ'])
    probe["loc"] = np.random.rand(3)

    '''Add location of probe as comma separated string'''
    frame['loc'] = ",".join(map(str,probe['loc']))
    return frame

def create_multiple_probes(Np,Nt):
    """
    Gather mutliple probes into dict
    """
    probes = []

    for i in range(Np):
        df = create_single_probe(Nt)
        '''Set time as a row value for each probe'''
        df['time'] = range(Nt)
        probes.append(df)

    '''Concat into one dataframe'''
    data = pd.concat(probes)

    return data

print create_multiple_probes(Np,Nt)


问:
UNIQUE constraint failed - Django
I am unable to solve this problem. I have seen the similar queries posted but none of the answers helped.

my Models:

```<code>class MyUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    contact_number = models.IntegerField(_('contact number'), validators=RegexValidator(r'^\+?1?\d{9,10}$'), unique=True, null=True, blank=True)
    ....
</code>```

On migration the error that appears:

```<code>django.db.utils.IntegrityError: UNIQUE constraint failed: user_profile_myuser.contact_number
</code>```

Update:

My Traceback:

Traceback (most recent call last):

```<code>File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/home/surajit/website/PubNet/user_profile/manager.py", line 31, in create_superuser
    **extra_fields)
  File "/home/surajit/website/PubNet/user_profile/manager.py", line 22, in _create_user
    user.save(using=self._db)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/base_user.py", line 80, in save
    super(AbstractBaseUser, self).save(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 806, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 836, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 922, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 961, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 1060, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/compiler.py", line 1099, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: user_profile_myuser.contact_number
</code>```

Please help.

答:
from django.core.validators import RegexValidator</p>

```<code>class MyUser(AbstractBaseUser, PermissionsMixin):
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,10}$', message="Phone number must be entered in the format: '+999999999'")
    phone_number = models.CharField(validators=[phone_regex], blank=True unique=True, null=True, blank=True)
</code>```

Title: UNIQUE constraint failed - Django

Body:
I am unable to solve this problem. I have seen the similar queries posted but none of the answers helped.

my Models:

class MyUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    contact_number = models.IntegerField(_('contact number'), validators=RegexValidator(r'^\+?1?\d{9,10}$'), unique=True, null=True, blank=True)
    ....

On migration the error that appears:

django.db.utils.IntegrityError: UNIQUE constraint failed: user_profile_myuser.contact_number

Update:

My Traceback:

Traceback (most recent call last):

File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/home/surajit/website/PubNet/user_profile/manager.py", line 31, in create_superuser
    **extra_fields)
  File "/home/surajit/website/PubNet/user_profile/manager.py", line 22, in _create_user
    user.save(using=self._db)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/base_user.py", line 80, in save
    super(AbstractBaseUser, self).save(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 806, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 836, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 922, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 961, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 1060, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/compiler.py", line 1099, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: user_profile_myuser.contact_number

Please help.

Body:
from django.core.validators import RegexValidator

class MyUser(AbstractBaseUser, PermissionsMixin):
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,10}$', message="Phone number must be entered in the format: '+999999999'")
    phone_number = models.CharField(validators=[phone_regex], blank=True unique=True, null=True, blank=True)


问:
Webbased MySQL interface better that phpMyAdmin
Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

答: Among non-web clients, I use Navicat for MySQL. The free version can do everything phpMyAdmin can</p>

OwnerDisplayName: Siamak

OwnerDisplayName: Imran


问:
C#, variable value as a part of an object name?
For example i have a player object with a list of suits of cards it has.

```<code>player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...
</code>```

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

```<code>if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
</code>```

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

```<code>for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}
</code>```

答: I don't think that you can use a value as a part of the control name. But, one can use an aray of controls. You will have to change many declarations and initializations of your picture boxes and put them into an array, but you will be able to write more descriptive and readable code.</p>

Body:
For example i have a player object with a list of suits of cards it has.

player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}


问:
Template instantiation failure: compiler choosing improper overload function
I'm not new to templates but I ran into a rather curious problem where I need to separate a template type into it's components for the data serializer I'm working on.  It's hard to explain so I've demonstrated it.

Here's my simplified example problem, example.cpp.

```<code>template<typename T> void foo(T& arg) { }
template<typename T, typename V> void foo(T<V>& arg) { }

int main(int argc, char *argv[])
{
  foo(argc);
  return 0;
}
</code>```

I get an error and then a warning which seems to indicate it's trying to instantiate both functions when only one of them is suitable.

```<code>$ g++ -Wall -W example.cpp
example.cpp:2:43: error: ‘T’ is not a template
 template<typename T, typename V> void foo(T<V>& arg) { }
                                           ^
example.cpp: In instantiation of ‘void foo(T&) [with T = int]’:
example.cpp:6:11:   required from here
example.cpp:1:34: warning: unused parameter ‘arg’ [-Wunused-parameter]
 template<typename T> void foo(T& arg) { }
                                  ^~~
</code>```

Any suggestions on how to resolve my problem and/or prevent this confusion?

答:
Template template-parameters (parameters that are themselves deducible templates) require a different syntax that what you're using. As you've written it, the compiler does not expect T to be a template, so the syntax T<V> make no sense.

```<code>template< template<class> class T, class V> void foo(T<V>& arg>)
</code>```

would be a correct example.

Example

```<code>#include <iostream>

template<typename T> void foo(T& arg)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

template<template<class> class T, class V> void foo(T<V>& arg)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

template<class T>
struct Bar
{

};

int main(int argc, char *argv[])
{
    foo(argc);

    Bar<int> bar;
    foo(bar);

    return 0;
}
</code>```

Output

```<code>void foo(T &) [T = int]
void foo(T<V> &) [T = Bar, V = int]
</code>```

Body:
I'm not new to templates but I ran into a rather curious problem where I need to separate a template type into it's components for the data serializer I'm working on.  It's hard to explain so I've demonstrated it.

Here's my simplified example problem, example.cpp.

template<typename T> void foo(T& arg) { }
template<typename T, typename V> void foo(T<V>& arg) { }

int main(int argc, char *argv[])
{
  foo(argc);
  return 0;
}

I get an error and then a warning which seems to indicate it's trying to instantiate both functions when only one of them is suitable.

$ g++ -Wall -W example.cpp
example.cpp:2:43: error: ‘T’ is not a template
 template<typename T, typename V> void foo(T<V>& arg) { }
                                           ^
example.cpp: In instantiation of ‘void foo(T&) [with T = int]’:
example.cpp:6:11:   required from here
example.cpp:1:34: warning: unused parameter ‘arg’ [-Wunused-parameter]
 template<typename T> void foo(T& arg) { }
                                  ^~~

Any suggestions on how to resolve my problem and/or prevent this confusion?

Body:
Template template-parameters (parameters that are themselves deducible templates) require a different syntax that what you're using. As you've written it, the compiler does not expect T to be a template, so the syntax T<V> make no sense.

template< template<class> class T, class V> void foo(T<V>& arg>)

would be a correct example.

Example

#include <iostream>

template<typename T> void foo(T& arg)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

template<template<class> class T, class V> void foo(T<V>& arg)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

template<class T>
struct Bar
{

};

int main(int argc, char *argv[])
{
    foo(argc);

    Bar<int> bar;
    foo(bar);

    return 0;
}

Output

void foo(T &) [T = int]
void foo(T<V> &) [T = Bar, V = int]


问:
spread operator to replace value?
Why does the spread operator replace the value of 'Stratford' with 'HB woodlawn' here? How does this work?</p>

```<code>const editName = (oldName, name, arr) =>
  arr.map(item => {
    if (item.name === oldName) {
      return {
        ...item,
        name
      }
    } else {
      return item
    }
  })

let schools = [
  { name: "Yorktown"},
  { name: "Stratford" },
  { name: "Washington & Lee"},
  { name: "Wakefield"}
]
let updatedSchools = editName("Stratford", "HB Woodlawn", schools)
console.log( updatedSchools[1] ) // { name: "HB Woodlawn" }
console.log( schools[1] ) // { name: "Stratford" },
</code>```

答:
What it comes down to is this:

```<code>const oldObject = { name: 'Stratford' };
const newObject = { ...oldObject, name: 'HB Woodlawn' };
</code>```

which you can think of as expanding oldObject’s properties into the new object literal:

```<code>const newObject = { name: 'Stratford', name: 'HB Woodlawn' };
</code>```

Properties with the same key in a literal get the value of the last one.

Title: spread operator to replace value?

Body:
Why does the spread operator replace the value of 'Stratford' with 'HB woodlawn' here? How does this work?

const editName = (oldName, name, arr) =>
  arr.map(item => {
    if (item.name === oldName) {
      return {
        ...item,
        name
      }
    } else {
      return item
    }
  })

let schools = [
  { name: "Yorktown"},
  { name: "Stratford" },
  { name: "Washington & Lee"},
  { name: "Wakefield"}
]
let updatedSchools = editName("Stratford", "HB Woodlawn", schools)
console.log( updatedSchools[1] ) // { name: "HB Woodlawn" }
console.log( schools[1] ) // { name: "Stratford" },

Body:
What it comes down to is this:

const oldObject = { name: 'Stratford' };
const newObject = { ...oldObject, name: 'HB Woodlawn' };

which you can think of as expanding oldObject’s properties into the new object literal:

const newObject = { name: 'Stratford', name: 'HB Woodlawn' };

Properties with the same key in a literal get the value of the last one.


问:
AutoIT Close all windows except shutdown
I'm building a program that shuts down all open windows after 60 seconds of no mouse movement using AutoIT and a code I found here:
https://www.autoitscript.com/forum/topic/97638-closing-all-open-windows/

I edited it a little such that it looks like this:

```<code>#include <MsgBoxConstants.au3>
Opt("WinTitleMatchMode", 3) ;3 = exact title match
Opt("TrayIconDebug", 1)

$S_running = "check-4-app2" ;name the script
If WinExists($S_running) Then Exit

AutoItWinSetTitle($S_running)

$count = 0
$mousePos = MouseGetPos()
while 1
   $count += 1
   $mousePosNow = mouseGetPos()

   If $mousePosNow[0] <> $mousePos[0] Or $mousePosNow[1] <> $mousePos[1] Then $count = 0

   $mousePos = MouseGetPos()

   ;ToolTip("count = " & $count, 0, 0)

   If $count > 60 Then
      $count = 0
      $var = WinList ()
      $length = UBound($var) - 2
      For $i = 1 to $length
         If BitAnd (WinGetState ($var[$i][1]), 2) And $var[$i][0] <> "" AND $var[$i][0] <> "Program Manager" Then WinClose ($var[$i][1], "")
         Next
   EndIf
   Sleep(1000)
WEnd
</code>```

It does actually close all open windows after 60 seconds but it opens the windows shutdown window as well (like when you press the alt+f4 combination) in windows 7.

How to stop this window from popping up? I just like all windows to close and have a clean desktop view.

答:
First you should do some debug for all values in $var=WinList() to see if some window in your OS is special ,that means, if such window is shutdown, it will trigger windows shutdown, if problem still exists, I found a walkround way , I tried in my computer to do following code

```<code>WinClose("Close Windows")
; or maybe WinClose("Shutdown Windows")
</code>```

to close what you said "windows shutdown window",maybe you can put this line at the bottom of your code

attention: in my computer, its OS language is not english, so maybe you should first trigger "windows shutdown window" and use AutoIt window info tool to see its window title precisely

Body:
I'm building a program that shuts down all open windows after 60 seconds of no mouse movement using AutoIT and a code I found here:
https://www.autoitscript.com/forum/topic/97638-closing-all-open-windows/

I edited it a little such that it looks like this:

#include <MsgBoxConstants.au3>
Opt("WinTitleMatchMode", 3) ;3 = exact title match
Opt("TrayIconDebug", 1)

$S_running = "check-4-app2" ;name the script
If WinExists($S_running) Then Exit

AutoItWinSetTitle($S_running)

$count = 0
$mousePos = MouseGetPos()
while 1
   $count += 1
   $mousePosNow = mouseGetPos()

   If $mousePosNow[0] <> $mousePos[0] Or $mousePosNow[1] <> $mousePos[1] Then $count = 0

   $mousePos = MouseGetPos()

   ;ToolTip("count = " & $count, 0, 0)

   If $count > 60 Then
      $count = 0
      $var = WinList ()
      $length = UBound($var) - 2
      For $i = 1 to $length
         If BitAnd (WinGetState ($var[$i][1]), 2) And $var[$i][0] <> "" AND $var[$i][0] <> "Program Manager" Then WinClose ($var[$i][1], "")
         Next
   EndIf
   Sleep(1000)
WEnd

It does actually close all open windows after 60 seconds but it opens the windows shutdown window as well (like when you press the alt+f4 combination) in windows 7.

How to stop this window from popping up? I just like all windows to close and have a clean desktop view.

Body:
First you should do some debug for all values in $var=WinList() to see if some window in your OS is special ,that means, if such window is shutdown, it will trigger windows shutdown, if problem still exists, I found a walkround way , I tried in my computer to do following code

WinClose("Close Windows")
; or maybe WinClose("Shutdown Windows")

to close what you said "windows shutdown window",maybe you can put this line at the bottom of your code

attention: in my computer, its OS language is not english, so maybe you should first trigger "windows shutdown window" and use AutoIt window info tool to see its window title precisely


问:
How to alter my regex so that preg_match returns the desired string
I have the string:

```<code><mml:mi>P</mml:mi><mml:mn>2</mml:mn>
</code>```

and wish to retrieve the 2

My pattern is:

```<code>/(?:<mml:)(mn|mi|mo)>(.+)(?:<\/mml:\1>)$/
</code>```

the return is the 2 as it should be,

but if the string is:

```<code><mml:mi>P</mml:mi><mml:mi>s</mml:mi>
</code>```

the pattern should then return the s, from inside the second set of tags, but returns the P from inside the first set

```<code>P</mml:mi><mml:mi>s
</code>```

when changing the pattern as in the suggestion below to:

```<code>/<mml:(mn|mi|mo)>(.*?)<\/mml:\1>/sU
</code>```

the return is the same. The line of php is:

```<code>preg_match('/<mml:(mn|mi|mo)>(.*?)<\/mml:\1>/sU', '<mml:mi>P</mml:mi><mml:mi>s</mml:mi>', $ret, PREG_OFFSET_CAPTURE);
</code>```

and $ret contains:

```<code>Array
(
    [0] => Array
        (
            [0] => <mml:mi>P</mml:mi><mml:mi>s</mml:mi>
            [1] => 0
        )

    [1] => Array
        (
            [0] => mi
            [1] => 5
        )

    [2] => Array
        (
            [0] => P</mml:mi><mml:mi>s
            [1] => 8
        )

)
</code>```

and when changed to the edited suggestion, with the ? removed

```<code>/<mml:(mn|mi|mo)>(.*)<\/mml:\1>/sU
</code>```

the return is P, from the first occurrence, rather than the s from the second.

答:
Typing from my phone, so will be brief.

Instead of matching any character (.+), match any character that is not the beginning of the next tag ([^<]+)

This way you don't have to worry about using back references, nor will you grab everything between two identical tags.

(Double check where I put the caret, this is off the top of my head. )

To get the last occurrence, wrap the whole regex in ()+

```<code>/(<mml:(mn|mi|mo)>([^<]+)<\/mml:\2>)+/
</code>```

Body:
I have the string:

<mml:mi>P</mml:mi><mml:mn>2</mml:mn>

and wish to retrieve the 2

My pattern is:

/(?:<mml:)(mn|mi|mo)>(.+)(?:<\/mml:\1>)$/

the return is the 2 as it should be,

but if the string is:

<mml:mi>P</mml:mi><mml:mi>s</mml:mi>

the pattern should then return the s, from inside the second set of tags, but returns the P from inside the first set

P</mml:mi><mml:mi>s

when changing the pattern as in the suggestion below to:

/<mml:(mn|mi|mo)>(.*?)<\/mml:\1>/sU

the return is the same. The line of php is:

preg_match('/<mml:(mn|mi|mo)>(.*?)<\/mml:\1>/sU', '<mml:mi>P</mml:mi><mml:mi>s</mml:mi>', $ret, PREG_OFFSET_CAPTURE);

and $ret contains:

Array
(
    [0] => Array
        (
            [0] => <mml:mi>P</mml:mi><mml:mi>s</mml:mi>
            [1] => 0
        )

    [1] => Array
        (
            [0] => mi
            [1] => 5
        )

    [2] => Array
        (
            [0] => P</mml:mi><mml:mi>s
            [1] => 8
        )

)

and when changed to the edited suggestion, with the ? removed

/<mml:(mn|mi|mo)>(.*)<\/mml:\1>/sU

the return is P, from the first occurrence, rather than the s from the second.

Body:
Typing from my phone, so will be brief.

Instead of matching any character (.+), match any character that is not the beginning of the next tag ([^<]+)

This way you don't have to worry about using back references, nor will you grab everything between two identical tags.

(Double check where I put the caret, this is off the top of my head. )

To get the last occurrence, wrap the whole regex in ()+

/(<mml:(mn|mi|mo)>([^<]+)<\/mml:\2>)+/


问:
git pull and push specific files without the repository saved locally
I have a couple questions but I'll put them together given they look quite similar.

Let's say I have a repository called Repo, and it contains two folders, A and B.

Via terminal (and given I don't have the project in my machine), how can I...

(1) ...clone only folder A from Repo to my machine?

(2) ...send a file/folder C to Repo?

答:
If that repo is on GitHub (since there is a github tag), you can:

get just one file with the raw api (see "Download single files from GitHub")

```<code>https://raw.github.com/<username>/<repo>/<branch>/some_directory/file.rb
</code>```

That works well for files, and you can repeat that for each file in order to download a folder.

But if said folder content is large, you are best to use the zip link associated to each repo: that won't download the all history, only the current repo state, which is smaller. From that archive, you can extract your folder. See "Download a single folder or directory from a GitHub repo" (maybe you can avoid that with an SVN syntax)

For uploading anything to GitHub, you need to be the owner of the destination repo: you might have to fork the target repo in order to get your own: See GitHub  fork repo.

From there you can directly edit a file. This would be cumbersome for a all folder though.

Body:
If that repo is on GitHub (since there is a github tag), you can:

get just one file with the raw api (see "Download single files from GitHub")

https://raw.github.com/<username>/<repo>/<branch>/some_directory/file.rb

That works well for files, and you can repeat that for each file in order to download a folder.

But if said folder content is large, you are best to use the zip link associated to each repo: that won't download the all history, only the current repo state, which is smaller. From that archive, you can extract your folder. See "Download a single folder or directory from a GitHub repo" (maybe you can avoid that with an SVN syntax)

For uploading anything to GitHub, you need to be the owner of the destination repo: you might have to fork the target repo in order to get your own: See GitHub  fork repo.

From there you can directly edit a file. This would be cumbersome for a all folder though.


问:
Chrome extension: Add content (enable/disable icon)
I am writing an extension for Google Chrome and I am trying to add content in my current page when the user clicks on the add-on icon.

I would like to add the possibility to enable/disable the extension and to show/hide my injected content for every page.

manifest.json

```<code>"content_scripts": [
  {
    "matches": [
      "http://*/*",
      "https://*/*"
    ],
    "css": ["css/style.css"],
    "js": [
      "js/content.js"
    ]
  }
]
</code>```

I do not see how to add content only for the page where the icon has clicked because with that, every page has the script.

I also tried something with the background script without success.

Do you have any ideas?

Thanks!

答:
I had built the same feature for my chrome extension.
This will create an on/off switch / toggle (so many names when searching google to solve this :) )
I use the massaging between app and content script in the following method:

manifest

inserting my content script on all page (hover.js) and running my extension script (background.js)

```<code>....
"browser_action": {
    "default_icon": {
      "19": "icons/icon-active.png"
    }
  },
"content_scripts": [
{
  "matches": ["<all_urls>"],
  "css": ["css/hover.css"],
  "js": ["js/hover.js"]
}
],
"background" : { "scripts": ["js/background.js"] },
....
</code>```

background.js

Here we are preparing the background script (which run on all chrome windows) to send and receive extension status

```<code>    // start extension as active
var status = true;

// set toggle of extension on browser action click and notify content script
chrome.browserAction.onClicked.addListener(function(tabs) {
  if (status == 'true'){
    status = false;
    chrome.browserAction.setIcon({path: "icons/16x16.png"});
  }
  else{
    status = true;
    chrome.browserAction.setIcon({path: "icons/icon-active.png"});
  }
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {status: status});
  });
});

// check status on tab update and notify content script
chrome.tabs.onActivated.addListener(function() {
  if (status == 'true'){
    chrome.browserAction.setIcon({path: "icons/icon-active.png"});
  }
  else{
    chrome.browserAction.setIcon({path: "icons/16x16.png"});
  }
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {status: status});
  });
});

//send extension status on request
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status == "getStatus")
      sendResponse({status: status});
});
</code>```

As you can see there are 3 functions:

change the status on browser action button click.

check status when you move to a different tab and notify content script (each tab has it's own "instance" of content script so disabling in one tab might still be active in another tab).

send response of the status on request from content script.

content script

```<code>// check extension status
chrome.runtime.sendMessage({status: "getStatus"}, function(response) {
    if (response.status == 'true'){
        // check elements mouse is hover
        document.addEventListener("mouseover", setLink, true);
    }
    else{
        document.removeEventListener("mouseover", setLink, true);
    }
});

// wait for massage from background script
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status == 'true'){
        // check elements mouse is hover
        document.addEventListener("mouseover", setLink, true);
    }
    else{
        document.removeEventListener("mouseover", setLink, true);
    }
});
</code>```

Each content script should first check the status of the extension by sending massage to the background script and recieve a status update.

Also, if we turn the extension off in one tab, when we change tabs we will notify the content script of the change.

I'm sure that this can be done even better in terms of scripting but i hope it will help...

Body:
I am writing an extension for Google Chrome and I am trying to add content in my current page when the user clicks on the add-on icon.

I would like to add the possibility to enable/disable the extension and to show/hide my injected content for every page.

manifest.json

"content_scripts": [
  {
    "matches": [
      "http://*/*",
      "https://*/*"
    ],
    "css": ["css/style.css"],
    "js": [
      "js/content.js"
    ]
  }
]

I do not see how to add content only for the page where the icon has clicked because with that, every page has the script.

I also tried something with the background script without success.

Do you have any ideas?

Thanks!

Body:
I had built the same feature for my chrome extension.
This will create an on/off switch / toggle (so many names when searching google to solve this :) )
I use the massaging between app and content script in the following method:

manifest

inserting my content script on all page (hover.js) and running my extension script (background.js)

....
"browser_action": {
    "default_icon": {
      "19": "icons/icon-active.png"
    }
  },
"content_scripts": [
{
  "matches": ["<all_urls>"],
  "css": ["css/hover.css"],
  "js": ["js/hover.js"]
}
],
"background" : { "scripts": ["js/background.js"] },
....

background.js

Here we are preparing the background script (which run on all chrome windows) to send and receive extension status

    // start extension as active
var status = true;

// set toggle of extension on browser action click and notify content script
chrome.browserAction.onClicked.addListener(function(tabs) {
  if (status == 'true'){
    status = false;
    chrome.browserAction.setIcon({path: "icons/16x16.png"});
  }
  else{
    status = true;
    chrome.browserAction.setIcon({path: "icons/icon-active.png"});
  }
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {status: status});
  });
});

// check status on tab update and notify content script
chrome.tabs.onActivated.addListener(function() {
  if (status == 'true'){
    chrome.browserAction.setIcon({path: "icons/icon-active.png"});
  }
  else{
    chrome.browserAction.setIcon({path: "icons/16x16.png"});
  }
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {status: status});
  });
});

//send extension status on request
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status == "getStatus")
      sendResponse({status: status});
});

As you can see there are 3 functions:

change the status on browser action button click.

check status when you move to a different tab and notify content script (each tab has it's own "instance" of content script so disabling in one tab might still be active in another tab).

send response of the status on request from content script.

content script

// check extension status
chrome.runtime.sendMessage({status: "getStatus"}, function(response) {
    if (response.status == 'true'){
        // check elements mouse is hover
        document.addEventListener("mouseover", setLink, true);
    }
    else{
        document.removeEventListener("mouseover", setLink, true);
    }
});

// wait for massage from background script
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status == 'true'){
        // check elements mouse is hover
        document.addEventListener("mouseover", setLink, true);
    }
    else{
        document.removeEventListener("mouseover", setLink, true);
    }
});

Each content script should first check the status of the extension by sending massage to the background script and recieve a status update.

Also, if we turn the extension off in one tab, when we change tabs we will notify the content script of the change.

I'm sure that this can be done even better in terms of scripting but i hope it will help...

ContentLicense: CC BY-SA 4.0


问:
Angular JS data binding not working for HTML5 reset button
I my angular application, I'm using a reset button to clear the data in a text box. But the binding is not working properly with the reset button.

```<code><form>
  <input type="text" name="email" ng-model="ch.email"><br>
  <input type="reset" value="Reset">
</form>

<div>{{ch.email}}</div>
</code>```

When some text is typed in the text box, it appears in the div, But after resetting, The text in the div doesn't disappears.

Please see the fiddle

答:
HTML5 Reset button will only clears the input control values but not the angular ng-model values that doesn't mean it is refreshing the page but it resets html form fields to their initial values. Here is working example

```<code>Html:
    <form>
        <input type="text" data-ng-model="name" />
        <span data-ng-bind="name"></span>
        <input type="reset" value="Reset" />
    </form>

Script:
      var myApp=angular.module('myApp',[])
                       .controller('myCtrl',function($scope){
                         $scope.name="Angular JS";
                       })
</code>```

When you click on reset button it will clear textbox but not span tag value.After this you try to access name property value of scope using angular.element($0).scope() by doing inspect element on browser and it is still "Angular JS" only.

Body:
I my angular application, I'm using a reset button to clear the data in a text box. But the binding is not working properly with the reset button.

<form>
  <input type="text" name="email" ng-model="ch.email">

  <input type="reset" value="Reset">
</form>

{{ch.email}}

When some text is typed in the text box, it appears in the div, But after resetting, The text in the div doesn't disappears.

Please see the fiddle

Body:
HTML5 Reset button will only clears the input control values but not the angular ng-model values that doesn't mean it is refreshing the page but it resets html form fields to their initial values. Here is working example

Html:
    <form>
        <input type="text" data-ng-model="name" />
        <span data-ng-bind="name"></span>
        <input type="reset" value="Reset" />
    </form>

Script:
      var myApp=angular.module('myApp',[])
                       .controller('myCtrl',function($scope){
                         $scope.name="Angular JS";
                       })

When you click on reset button it will clear textbox but not span tag value.After this you try to access name property value of scope using angular.element($0).scope() by doing inspect element on browser and it is still "Angular JS" only.


问:
Element removing while collection iterating
I'm wondering what is really going on behind the scene when I'm executing the following peace of code:

```<code>    List<Object> list = new ArrayList<Object>();
    fillTheList(); // Filling a list with 10 objects
    int count = 0;
    for (Object o : list) {
        count++;
        if (count == 5) {
            list.remove(count);
        }
        o.toString();
     }
</code>```

Once element is removed I'm getting ConcurrentModificationException exception.

I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.

答:
get an Iterator instead of using the iterator in a for loop:

```<code>int count = 0;

for(final Iterator iterator = list.iterator(); iterator.hasNext();) {
    final Object o = iterator.next();

    if (++count == 5) {
        iterator.remove();
    }

    o.toString();
}
</code>```

edit: the reason why you get ConcurrentModificationException is because the for loop is using a different Iterator which was created before your modification will being made with list.remove() and that Iterator has a state inside.

Body:
I'm wondering what is really going on behind the scene when I'm executing the following peace of code:

    List<Object> list = new ArrayList<Object>();
    fillTheList(); // Filling a list with 10 objects
    int count = 0;
    for (Object o : list) {
        count++;
        if (count == 5) {
            list.remove(count);
        }
        o.toString();
     }

Once element is removed I'm getting ConcurrentModificationException exception.

I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.

Body:
get an Iterator instead of using the iterator in a for loop:

int count = 0;

for(final Iterator iterator = list.iterator(); iterator.hasNext();) {
    final Object o = iterator.next();

    if (++count == 5) {
        iterator.remove();
    }

    o.toString();
}

edit: the reason why you get ConcurrentModificationException is because the for loop is using a different Iterator which was created before your modification will being made with list.remove() and that Iterator has a state inside.


问:
Trying to send authenticated email using Net::SMTP::SSL
I'm attempting to send an authenticated email with the Net::SMTP::SSL module to a comcast email server. I'm using the following code.

```<code>#!/usr/bin/perl

use Net::SMTP::SSL;
use MIME::Base64;

$smtp = Net::SMTP::SSL->new
    (
    "smtp.comcast.net",
    Hello => "host.comcast.net",
    Port => 465,
    Timeout => 30,
    Debug => 1,
    );
$smtp->datasend("AUTH LOGIN\n");
$smtp->response();

# Mailbox info
$smtp->datasend(encode_base64('username')); # username
$smtp->response();
$smtp->datasend(encode_base64('password')); # password
$smtp->response();

# Email from
$smtp->mail('user\@comcast.net');

# Email to
$smtp->to('user\@host.com');

$smtp->data();

$smtp->datasend("To: user\@host.com\n");
$smtp->datasend("From: user\@comcast.net\n");
$smtp->datasend("Subject: Test");

# Line break to separate headers from body
$smtp->datasend("\n");

$smtp->datasend("Blah\n");
$smtp->dataend();

$smtp->quit();
exit;
</code>```

I'm basically following the code from here for comcast.

I've ran telnet and can connect to the smtp server on the port and I can issue the AUTH LOGIN and successfully login, but issuing the

```<code>$smtp->datasend("AUTH LOGIN\n");
</code>```

always results in:

```<code>Can't call method "datasend" on an undefined value
</code>```

I've also tried executing the auth method to login and that fails as well.

What am I missing here?  I know it's something simple I'm overlooking.

答:
For email services that use STARTTLS, it's best to use the newer NET::SMTPS module. Try the following code:

```<code>my $msg = MIME::Lite ->new (
From => 'from@bellsouth.net',
To => 'to@bellsouth.net',
Subject => 'Test Message',
Data => 'This is a test',
Type => 'text/html'
);

my $USERNAME = 'from@bellsouth.net';
my $PASSWORD = 'abc123';

my $smtps = Net::SMTPS->new("smtp.mail.att.net", Port => 587,  doSSL => 'starttls', SSL_version=>'TLSv1');

$smtps->auth ( $USERNAME, $PASSWORD ) or die("Could not authenticate with bellsouth.\n");

$smtps ->mail('from@bellsouth.net');
$smtps->to('to@bellsouth.net');
$smtps->data();
$smtps->datasend( $msg->as_string() );
$smtps->dataend();
$smtps->quit;
</code>```

Originally from http://www.skipser.com/p/2/p/send-email-using-perl-via-live.com.html

Body:
I'm attempting to send an authenticated email with the Net::SMTP::SSL module to a comcast email server. I'm using the following code.

#!/usr/bin/perl

use Net::SMTP::SSL;
use MIME::Base64;

$smtp = Net::SMTP::SSL->new
    (
    "smtp.comcast.net",
    Hello => "host.comcast.net",
    Port => 465,
    Timeout => 30,
    Debug => 1,
    );
$smtp->datasend("AUTH LOGIN\n");
$smtp->response();

# Mailbox info
$smtp->datasend(encode_base64('username')); # username
$smtp->response();
$smtp->datasend(encode_base64('password')); # password
$smtp->response();

# Email from
$smtp->mail('user\@comcast.net');

# Email to
$smtp->to('user\@host.com');

$smtp->data();

$smtp->datasend("To: user\@host.com\n");
$smtp->datasend("From: user\@comcast.net\n");
$smtp->datasend("Subject: Test");

# Line break to separate headers from body
$smtp->datasend("\n");

$smtp->datasend("Blah\n");
$smtp->dataend();

$smtp->quit();
exit;

I'm basically following the code from here for comcast.

I've ran telnet and can connect to the smtp server on the port and I can issue the AUTH LOGIN and successfully login, but issuing the

$smtp->datasend("AUTH LOGIN\n");

always results in:

Can't call method "datasend" on an undefined value

I've also tried executing the auth method to login and that fails as well.

What am I missing here?  I know it's something simple I'm overlooking.

Body:
For email services that use STARTTLS, it's best to use the newer NET::SMTPS module. Try the following code:

my $msg = MIME::Lite ->new (
From => 'from@bellsouth.net',
To => 'to@bellsouth.net',
Subject => 'Test Message',
Data => 'This is a test',
Type => 'text/html'
);

my $USERNAME = 'from@bellsouth.net';
my $PASSWORD = 'abc123';

my $smtps = Net::SMTPS->new("smtp.mail.att.net", Port => 587,  doSSL => 'starttls', SSL_version=>'TLSv1');

$smtps->auth ( $USERNAME, $PASSWORD ) or die("Could not authenticate with bellsouth.\n");

$smtps ->mail('from@bellsouth.net');
$smtps->to('to@bellsouth.net');
$smtps->data();
$smtps->datasend( $msg->as_string() );
$smtps->dataend();
$smtps->quit;

Originally from http://www.skipser.com/p/2/p/send-email-using-perl-via-live.com.html


问:
placeholder of textfield is not working extjs 6.0.2
i'm using textfield in a window, And there with that textfield placeholder is not working .
Will you please tell me what's the reason.

here is my code.

```<code>   Ext.create('Ext.window.Window', {
        title: 'edit box',
        closable: false,

        draggable:true,
        height: '80%',
        width: 1000,
        scrollable :true,
        liveDrag:true,
        layout: 'fit',
        items: [
        {
            xtype: 'form',
            scrollable:true,
            defaults: {
                msgTarget: 'side'
            },
            items: [{
                xtype: 'container',
                cls: 'instruction-text-static',
                overCls: 'over-instruction-text-static',
                layout: {
                    type: 'table',
                    columns: 2
                },
                items: [{
                    xtype: 'label',
                    html:'label',{
                    xtype:'container',
                    items:[{
                        xtype: 'button',
                        ui:'link-btn',
                        text: 'cancel',
                        style:{
                            float:'right'
                        },
                        handler: function (cmp) {
                           this.up('window').hide();
                        }
                    },{
                        xtype: 'button',
                        ui: 'green-btn',
                        text: 'save',
                        style:{
                            float:'right'
                        },
                        handler: function (cmp) {
                          //my logic
                        }
                    }]
                },{
                    xtype: 'textfield',
                   placeholder: "add title",
                    value:record.data.title,
                    width: 430,
                    itemId: "instructionTitleEdit",
                    name: 'instructionTitle1',
                    colspan: 2,
                    style:{
                        'margin-left':'10px'
                    },

                },{
                    xtype: 'label',
                    html:'a label'
                },{
                    xtype:'htmleditor',
                    value:record.data.description,

                },{
                    xtype: 'label',
                    html:'one lable'
                },{
                    xtype: 'label',
                    html:'my label'
                },{
                    xtype:'htmleditor',
                    scrollable:true,
                    value:record.data.examples,
                    height: 400,
                    width: 475,
                    name: 'instructionExample',

                },{
                    xtype:'htmleditor',
                    scrollable:true,
                    height: 400,
                    width: 475,
                    name: 'instructionRad',
                    value:record.data.hint,

                }]
            }]
        }]

    }).show();
</code>```

But that pakceholder thing is not working
Please help me out
Thanks in advance

答: There is no placeholder property for textfields. You should use emptyText instead.

Body:
i'm using textfield in a window, And there with that textfield placeholder is not working .
Will you please tell me what's the reason.

here is my code.

   Ext.create('Ext.window.Window', {
        title: 'edit box',
        closable: false,

        draggable:true,
        height: '80%',
        width: 1000,
        scrollable :true,
        liveDrag:true,
        layout: 'fit',
        items: [
        {
            xtype: 'form',
            scrollable:true,
            defaults: {
                msgTarget: 'side'
            },
            items: [{
                xtype: 'container',
                cls: 'instruction-text-static',
                overCls: 'over-instruction-text-static',
                layout: {
                    type: 'table',
                    columns: 2
                },
                items: [{
                    xtype: 'label',
                    html:'label',{
                    xtype:'container',
                    items:[{
                        xtype: 'button',
                        ui:'link-btn',
                        text: 'cancel',
                        style:{
                            float:'right'
                        },
                        handler: function (cmp) {
                           this.up('window').hide();
                        }
                    },{
                        xtype: 'button',
                        ui: 'green-btn',
                        text: 'save',
                        style:{
                            float:'right'
                        },
                        handler: function (cmp) {
                          //my logic
                        }
                    }]
                },{
                    xtype: 'textfield',
                   placeholder: "add title",
                    value:record.data.title,
                    width: 430,
                    itemId: "instructionTitleEdit",
                    name: 'instructionTitle1',
                    colspan: 2,
                    style:{
                        'margin-left':'10px'
                    },

                },{
                    xtype: 'label',
                    html:'a label'
                },{
                    xtype:'htmleditor',
                    value:record.data.description,

                },{
                    xtype: 'label',
                    html:'one lable'
                },{
                    xtype: 'label',
                    html:'my label'
                },{
                    xtype:'htmleditor',
                    scrollable:true,
                    value:record.data.examples,
                    height: 400,
                    width: 475,
                    name: 'instructionExample',

                },{
                    xtype:'htmleditor',
                    scrollable:true,
                    height: 400,
                    width: 475,
                    name: 'instructionRad',
                    value:record.data.hint,

                }]
            }]
        }]

    }).show();

But that pakceholder thing is not working
Please help me out
Thanks in advance


问:
diplaying mathematical equtaions in android app
I am creating a mathematics app and have to display mathematical equations in my app. There are many answers related to this but I am not able to conclude how to do this?

答:
As mentioned in the comments above you can use that library MathView or other possibilities are ,

You can go with using the spannable string and can make superscripts
and subscripts easily.

You can also use the HTML.fromHTML(String html) which will give you
the spanned text and that you can set it to the TextView.

Or else show a webview and load the html page that contains the
formulas and solutions. (This will be like creating a dynamic html
files with in the app and showing it in the Webiew)


问:
SSIS Data Conversion - Update Multiple Rows
First SSIS experience so I'm willing to accept I'm doing things completely wrong here:

Using SSIS:

I'm importing from an Excel sheet

exporting to a client's SQL (SQL Server) database

The data has >250 columns

The Client's database rows are all various nvarchar lengths like 3,5,8, etc

I can assume that the excel data will fit into the database properly, so if I truncate I won't lose any data

What I think I have to do here is truncate the data using a "Data Conversion" transform. The problem I have is it's going to take me hours to do this in the "Data Conversion" editor window because I'm dealing with so many columns, when it would only take me a few minutes in a text editor.

Is there any way to bulk update the Data Conversion settings? Am I doing this the wrong way?

答:
The solution I ended up with was:
- change the package to not fail on truncation.
- Once I did this I could get rid of the transform.
- in the database I created a staging table with the excel column names to import to so that I didn't have to manually match everything up in SSIS</p>