问:
Matlab serial communication inconsistency
I want to control a Prior ProScan II controller and the fitting motorized stage with Matlab R2016b. Manual Tested with R2010b, got the same results.  The relevant commands of the stage are VS(page 46), P(p.43), PS(p.44). In a plain terminal, immediately after the stage halts I can issue the P or PS command, returning the current position of the X and Y axes. If done in Matlab prompt, it MIGHT need a second or two to return the proper value, before that it returns 'R' - Probably not the ACK of the previous command as it is returned after init, without any R-ACKed commands issued before. When used in a script in a separate .m file, it can only return 'R'. My code in main.m is as follows:

```<code>%Opening serial port
s = serial('COM9');
set(s,'BaudRate',9600,'Terminator','CR');  %Note that CR will be concatenated to all commands
fopen(s);
s       %print for debugging

t=1     %loop index

while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %Here is code to mess with a joystick that works fine, using VS command
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if button(joy, 3) == 1          %Button3 of joystick should trigger position reading
        fprintf(s,'vs,0,0');        %Halt joystick movement
        pause(1)                    %Debouncing
        fprintf(s,'p');             %Axe-pos reading command
        fgets(s)                    %Reading the answer
end

%This way to increment follows the skipped parts and is required for timing
if mod(t, 100)==0
        fprintf(s,'%s',Command);
        t=1;
    else
        t=t+1;
end
</code>```

If the segment in if..end is invoked from the Matlab prompt, it works fine in most cases.

```<code>>> s = openserial()
%properties as before, skipped to save space
>> fprintf(s,'ps');
>> fgets(s)

ans =

100000,100000
</code>```

or

```<code>>> fprintf(s,'p');
>> fgets(s)

ans =

100000,100000,0
</code>```

If I Ctrl+C out of the infinite loop but leave the serial open and issue

```<code>>> fprintf(s,'p');
>> fgets(s)

ans =

R
</code>```

returns. Using fscanf() instead of fgets() yields the same results.

Is there any known bug of fprintf() or the ones mentioned above that could cause this? What could I do to succesfully and consistently read within a script? Thank you for any answers.

答: Solution was to force flush the serial input buffer, flushinput(s) before the line pause(1). For some reason, even fscanf() instead of fgets() didn't flush it. I still don't know why it worked fine outside the script but not within. Additionally, it also worked in a separate script.</p>

Body:
I want to control a Prior ProScan II controller and the fitting motorized stage with Matlab R2016b. Manual Tested with R2010b, got the same results.  The relevant commands of the stage are VS(page 46), P(p.43), PS(p.44). In a plain terminal, immediately after the stage halts I can issue the P or PS command, returning the current position of the X and Y axes. If done in Matlab prompt, it MIGHT need a second or two to return the proper value, before that it returns 'R' - Probably not the ACK of the previous command as it is returned after init, without any R-ACKed commands issued before. When used in a script in a separate .m file, it can only return 'R'. My code in main.m is as follows:

%Opening serial port
s = serial('COM9');
set(s,'BaudRate',9600,'Terminator','CR');  %Note that CR will be concatenated to all commands
fopen(s);
s       %print for debugging

t=1     %loop index

while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %Here is code to mess with a joystick that works fine, using VS command
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if button(joy, 3) == 1          %Button3 of joystick should trigger position reading
        fprintf(s,'vs,0,0');        %Halt joystick movement
        pause(1)                    %Debouncing
        fprintf(s,'p');             %Axe-pos reading command
        fgets(s)                    %Reading the answer
end

%This way to increment follows the skipped parts and is required for timing
if mod(t, 100)==0
        fprintf(s,'%s',Command);
        t=1;
    else
        t=t+1;
end

If the segment in if..end is invoked from the Matlab prompt, it works fine in most cases.

>> s = openserial()
%properties as before, skipped to save space
>> fprintf(s,'ps');
>> fgets(s)

ans =

100000,100000

or

>> fprintf(s,'p');
>> fgets(s)

ans =

100000,100000,0

If I Ctrl+C out of the infinite loop but leave the serial open and issue

>> fprintf(s,'p');
>> fgets(s)

ans =

R

returns. Using fscanf() instead of fgets() yields the same results.

Is there any known bug of fprintf() or the ones mentioned above that could cause this? What could I do to succesfully and consistently read within a script? Thank you for any answers.


来源: stackexchange

问:
How to hide angular element on click event
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-click="hide()" ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

</body>
</html></code>```

答:
ng-hide is just css(display:none) way hide element. ng-if is add/remove DOM element. (we can see if u hide element, ng-if we can't see).

You try remove. Just see the example.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = [0,1,2,3,4,5,6];
  $scope.hide = function(index){
  // in api call success function
    $scope.data.splice(index, 1);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-click="hide($index)" ng-repeat="x in data">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

</body>
</html></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});

{{x}}

Body:
ng-hide is just css(display:none) way hide element. ng-if is add/remove DOM element. (we can see if u hide element, ng-if we can't see).

You try remove. Just see the example.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = [0,1,2,3,4,5,6];
  $scope.hide = function(index){
  // in api call success function
    $scope.data.splice(index, 1);
  }
});

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-click="hide($index)" ng-repeat="x in data">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

</body>
</html>


问:
Convert const float* to std::array<float, ...>
I have a const float* pointing to a huge array, and would like to be able to access the elements through a std::array.
What is the best way to do this? Without copying the elements if possible.

Thanks!

答:
There are at least two proposed additions to the standard library that do something like that.  One is std::experimental::to_array<T,N>(), which makes a deep copy of the entire data.  That’s wasteful in terms of both time and memory, but could be useful if you really do want to create a copy, especially a const copy which you cannot create and then modify.

If what you want is a container interface to a range of data represented by an arbitrary pointer and element count, the Guideline Support Library offers a span template.  I recommend that, if you pass both, you wrap them in a lightweight object similar to this.

Since you said you can change the interface to the constructor, I strongly suggest you do so.  If you want to keep around the version that takes a std::array, you can, and delegate it to the version that takes an arbitrary range of data, such as:

```<code>#include <algorithm>
#include <array>
#include <iterator>
#include "span"

MyClass::MyClass( const span<value_type>& s /*, more, params */ )
{
 /* In this example, m_storage is some private container and span has a
  * container interface.
  */
  auto it = std::back_inserter(m_storage);
  std::copy_n( s.begin(), s.size(), it );
  // ...
}

MyClass::MyClass( std::array<value_type, initializer_size>& a /*, more, params */ )
: MyClass( span<value_type>( a.data(), a.size() ) /*, more, params */ )
{}
</code>```

Body:
There are at least two proposed additions to the standard library that do something like that.  One is std::experimental::to_array<T,N>(), which makes a deep copy of the entire data.  That’s wasteful in terms of both time and memory, but could be useful if you really do want to create a copy, especially a const copy which you cannot create and then modify.

If what you want is a container interface to a range of data represented by an arbitrary pointer and element count, the Guideline Support Library offers a span template.  I recommend that, if you pass both, you wrap them in a lightweight object similar to this.

Since you said you can change the interface to the constructor, I strongly suggest you do so.  If you want to keep around the version that takes a std::array, you can, and delegate it to the version that takes an arbitrary range of data, such as:

#include <algorithm>
#include <array>
#include <iterator>
#include "span"

MyClass::MyClass( const span<value_type>& s /*, more, params */ )
{
 /* In this example, m_storage is some private container and span has a
  * container interface.
  */
  auto it = std::back_inserter(m_storage);
  std::copy_n( s.begin(), s.size(), it );
  // ...
}

MyClass::MyClass( std::array<value_type, initializer_size>& a /*, more, params */ )
: MyClass( span<value_type>( a.data(), a.size() ) /*, more, params */ )
{}


问:
How to add "X-Frame-Options" header in .htaccess file to protect against 'ClickJacking' attacks
I have a Coldfusion Web application. To protect my site from Cross-Frame Scripting attack I'm planning to add a HTTP Response Header "X-Frame-Options" with a value of "SAMEORIGIN" in my '.htaccess file'. This is the article I'm referring:

https://geekflare.com/secure-apache-from-clickjacking-with-x-frame-options/,
https://www.garron.me/en/bits/apache-htaccess-add-cache-control-header-file-type.html

Below code doesn't worked.

```<code><FilesMatch "\.(cfm)$">
<ifModule mod_headers.c> Header append X-FRAME-OPTIONS 'SAMEORIGIN'</ifModule>
</FilesMatch>
</code>```

I am new to this, can somebody please help how to do it correctly.

Thanks in advance.

答: I have fixed this issue by adding Header set X-Frame-Options DENY outside IfModule mod_headers.c in the .htaccess file and enabling the Header module in the mod_headers.so file in Apache.

Body:
I have a Coldfusion Web application. To protect my site from Cross-Frame Scripting attack I'm planning to add a HTTP Response Header "X-Frame-Options" with a value of "SAMEORIGIN" in my '.htaccess file'. This is the article I'm referring:

https://geekflare.com/secure-apache-from-clickjacking-with-x-frame-options/,
https://www.garron.me/en/bits/apache-htaccess-add-cache-control-header-file-type.html

Below code doesn't worked.

<FilesMatch "\.(cfm)$">
<ifModule mod_headers.c> Header append X-FRAME-OPTIONS 'SAMEORIGIN'</ifModule>
</FilesMatch>

I am new to this, can somebody please help how to do it correctly.

Thanks in advance.

ContentLicense: CC BY-SA 4.0


问:
Message queues. msgsnd: Invalid argument
The task is:
Find all prime numbers in the specified interval of numbers divided into several ranges.
Each range is processed in the generated process.
Well, I really tried to make it. But something is going wrong. Can't understand my mistake.
The code:

```<code>#include <stdio.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <stdbool.h>

#define MAX_SEND_SIZE 50

#define PROCESS_NUMBER 5

struct mymsgbuf {
    long mtype;
    int marray[MAX_SEND_SIZE];
};
typedef struct mymsgbuf type_mymsgbuf;

int msgqid, rc;

void send_message(int qid, type_mymsgbuf* qbuf, long type, int* text, int numbers_per_process) {
    int i;
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    for (i = 0; i < numbers_per_process; i++) {
        qbuf->marray[i] = text[i];
    }
    if ((msgsnd(qid, (struct msgbuf*)qbuf, (size_t) length, 0)) == -1) {
        perror("msgsnd");
        exit(1);
    }
}

void read_message(int qid, type_mymsgbuf* qbuf, long type, int numbers_per_process) {
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    msgrcv(qid, (struct msgbuf*)qbuf, (size_t)length, type, 0);
    for (int i = 0; i < numbers_per_process && qbuf->marray[i] != 0; i++) {
        printf("%d\n", qbuf->marray[i]);
    }
}

bool isprime (int a) {
    if(a == 1) {
        return false;
    }
    for (int i = 2; i*i < a; ++i) {
        if ((a % i) == 0) {
            return false;
        }
    }
    return true;
}

int* find_primes_part (int a, int b) {
    int j = 0;
    int* primes = (int*)malloc(sizeof(int)*(b-a));
    for (int k = 0; k < (b-a); ++k) {
        primes[k] = 0;
    }
    for (int i = a; i < b; ++i) {
        if(isprime(i)) {
            primes[j] = i;
            printf("%d\n TEST", primes[j]);
            j++;
        }
    }
    return primes;
}

int find_primes(int a, int b) {
    int status, stat;
    pid_t pid[PROCESS_NUMBER];
    key_t key;
    int qtype = 1;
    type_mymsgbuf qbuf;

    int numbers_per_process = (b-a)/PROCESS_NUMBER;
    if ((key = ftok(".", 'm')) < 0) {
        perror("ftok");
        exit(1);
    }
    if((msgqid = msgget(key, IPC_CREAT|0660)) == -1) {
        perror("msgget");
        exit(1);
    }

    for (int i = 0; i < PROCESS_NUMBER; i++) {
        pid[i] = fork();

        if (-1 == pid[i]) {
            perror("fork");
            exit(1);
        }
        else if (0 == pid[i]) {
            int* part_primes = find_primes_part(a + numbers_per_process*i, a + numbers_per_process*(i+1));
            send_message(msgqid, (type_mymsgbuf*)&qbuf, qtype, part_primes, numbers_per_process);
        }
    }
    for (int j = 0; j < PROCESS_NUMBER; ++j) {
        status = waitpid(pid[j], &stat, 0);
        if (pid[j] == status) {
            if (WEXITSTATUS(stat) != 0) {
                perror("process failed: ");
                exit(1);
            }
        }
    }
    for (int i = 0; i < PROCESS_NUMBER; ++i) {
        read_message(msgqid, &qbuf, qtype, numbers_per_process);
    }

    if ((rc = msgctl(msgqid, IPC_RMID, NULL)) < 0) {
        perror("msgctl");
        return 1;
    }
    return 0;
}

int main() {
    find_primes(10, 200);
    return 0;
}
</code>```

Output is very wrong and its different every other time.
Its something like:

```<code>181
191
193
197
199
163
167
169msgsnd: Invalid argument

173
179
181
191
193
197
msgctl: Invalid argument
</code>```

The main question is this 2 errors

```<code>msgsnd: Invalid argument
msgctl: Invalid argument
</code>```

How to eliminate it?

答:
You should finish your child process accordingly as follows:</p>

```<code>else if (0 == pid[i]) {
    // I'm child
    int* part_primes = find_primes_part(a + numbers_per_process*i, a + numbers_per_process*(i+1));
    send_message(msgqid, (type_mymsgbuf*)&qbuf, qtype, part_primes, numbers_per_process);
    return 0; // --> exit from the child process
}

/* Both parent and child come here if you do not return from child*/
</code>```

Body:
The task is:
Find all prime numbers in the specified interval of numbers divided into several ranges.
Each range is processed in the generated process.
Well, I really tried to make it. But something is going wrong. Can't understand my mistake.
The code:

#include <stdio.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <stdbool.h>

#define MAX_SEND_SIZE 50

#define PROCESS_NUMBER 5

struct mymsgbuf {
    long mtype;
    int marray[MAX_SEND_SIZE];
};
typedef struct mymsgbuf type_mymsgbuf;

int msgqid, rc;

void send_message(int qid, type_mymsgbuf* qbuf, long type, int* text, int numbers_per_process) {
    int i;
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    for (i = 0; i < numbers_per_process; i++) {
        qbuf->marray[i] = text[i];
    }
    if ((msgsnd(qid, (struct msgbuf*)qbuf, (size_t) length, 0)) == -1) {
        perror("msgsnd");
        exit(1);
    }
}

void read_message(int qid, type_mymsgbuf* qbuf, long type, int numbers_per_process) {
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    msgrcv(qid, (struct msgbuf*)qbuf, (size_t)length, type, 0);
    for (int i = 0; i < numbers_per_process && qbuf->marray[i] != 0; i++) {
        printf("%d\n", qbuf->marray[i]);
    }
}

bool isprime (int a) {
    if(a == 1) {
        return false;
    }
    for (int i = 2; i*i < a; ++i) {
        if ((a % i) == 0) {
            return false;
        }
    }
    return true;
}

int* find_primes_part (int a, int b) {
    int j = 0;
    int* primes = (int*)malloc(sizeof(int)*(b-a));
    for (int k = 0; k < (b-a); ++k) {
        primes[k] = 0;
    }
    for (int i = a; i < b; ++i) {
        if(isprime(i)) {
            primes[j] = i;
            printf("%d\n TEST", primes[j]);
            j++;
        }
    }
    return primes;
}

int find_primes(int a, int b) {
    int status, stat;
    pid_t pid[PROCESS_NUMBER];
    key_t key;
    int qtype = 1;
    type_mymsgbuf qbuf;

    int numbers_per_process = (b-a)/PROCESS_NUMBER;
    if ((key = ftok(".", 'm')) < 0) {
        perror("ftok");
        exit(1);
    }
    if((msgqid = msgget(key, IPC_CREAT|0660)) == -1) {
        perror("msgget");
        exit(1);
    }

    for (int i = 0; i < PROCESS_NUMBER; i++) {
        pid[i] = fork();

        if (-1 == pid[i]) {
            perror("fork");
            exit(1);
        }
        else if (0 == pid[i]) {
            int* part_primes = find_primes_part(a + numbers_per_process*i, a + numbers_per_process*(i+1));
            send_message(msgqid, (type_mymsgbuf*)&qbuf, qtype, part_primes, numbers_per_process);
        }
    }
    for (int j = 0; j < PROCESS_NUMBER; ++j) {
        status = waitpid(pid[j], &stat, 0);
        if (pid[j] == status) {
            if (WEXITSTATUS(stat) != 0) {
                perror("process failed: ");
                exit(1);
            }
        }
    }
    for (int i = 0; i < PROCESS_NUMBER; ++i) {
        read_message(msgqid, &qbuf, qtype, numbers_per_process);
    }

    if ((rc = msgctl(msgqid, IPC_RMID, NULL)) < 0) {
        perror("msgctl");
        return 1;
    }
    return 0;
}

int main() {
    find_primes(10, 200);
    return 0;
}

Output is very wrong and its different every other time.
Its something like:

181
191
193
197
199
163
167
169msgsnd: Invalid argument

173
179
181
191
193
197
msgctl: Invalid argument

The main question is this 2 errors

msgsnd: Invalid argument
msgctl: Invalid argument

How to eliminate it?

Body:
You should finish your child process accordingly as follows:

else if (0 == pid[i]) {
    // I'm child
    int* part_primes = find_primes_part(a + numbers_per_process*i, a + numbers_per_process*(i+1));
    send_message(msgqid, (type_mymsgbuf*)&qbuf, qtype, part_primes, numbers_per_process);
    return 0; // --> exit from the child process
}

/* Both parent and child come here if you do not return from child*/


问:
How to select a specific class from set of classes which are implementing same interface class?
How to select a specific class from set of classes which are implementing same interface class ?</p>

答: You don't call a method directly from an interface, you call it on a reference that points to an instance of a class. Whichever class that is determines which method gets called.</p>


问:
fullpage.js how to create slide custom image navigation dots?
I am using fullPage.js fullpage slider in my project. but i need the customized image as navigation dots. I searched the fullPage documentation also. but i cant find out the solutions. Anybody know about this, Thanks in advance.</p>

答:
Use this code and it will solve your needs.

.fp-slidesNav ul li:hover a.active span{
    background-image:  url("../img/bullets.png");
    height: 22px;
    width: 22px;
    margin: -6px 0 0 -6px;
    border-radius: 100%;
}```

This css code enable bullet images on your slider.

Body:
Use this code and it will solve your needs.

.fp-slidesNav ul li:hover a.active span{
    background-image:  url("../img/bullets.png");
    height: 22px;
    width: 22px;
    margin: -6px 0 0 -6px;
    border-radius: 100%;
}

This css code enable bullet images on your slider.


问:
How to get the URL from QuerySet in Django?

# Need:
some_method(SomeModel.objects.filter(some_field='some_value'))
# returns '?some_field__exact=some_value' — as is on admin pages changelists
```

Is there such a function?

答:
No there is not. You're mixing 2 differents things, Models and HTTP requests. So my guess is your question is actually "can I build an API to get data from my datastore just like using Models".

The answer to this new question is yes, you can look at http://www.django-rest-framework.org which provides a clean way to build such API.

Body:
# Need:
some_method(SomeModel.objects.filter(some_field='some_value'))
# returns '?some_field__exact=some_value' — as is on admin pages changelists

Is there such a function?


问:
How could I encode a long number using uppercase letters and numbers to make it shorter to type?
Is there a way I could encode a long number (e.g. 12349874529768521) as lower-case letters AND numbers for the purposes of reducing its length?  The idea is that a user might have a long number on a piece of paper.

It seems to me that if there are more symbols available, that the resulting number could be made shorter. So I'm looking for something like hexadecimal but using the larger symbol space of A-Z instead of just A-F.

This would be in C# (if it matters)

答:
You can use a base 36 encoder.

Base36 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-36 representation. The choice of 36 is convenient in that the digits can be represented using the Arabic numerals 0–9 and the Latin letters A–Z1 (the ISO basic Latin alphabet).

Here's an example of one, but any should work: https://github.com/thewindev/csharpbase36

Example Usage

```<code>// Encoding
Base36.Encode(10);    // returns "A"
Base36.Encode(10000); // returns "7PS"

// Decoding
Base36.Decode("Z");   // returns 35L
Base36.Decode("10");  // returns 36L
Base36.Decode("7PS"); // returns 10000L
</code>```

By default uppercase letters are used. If you really wanted to lowercase then a simple string.ToLowerInvarient() can change that.

However, uppercase is usually easier to read, which is why it's used by default, so you might want to consider using uppercase rather than lowercase.

Body:
You can use a base 36 encoder.

Base36 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-36 representation. The choice of 36 is convenient in that the digits can be represented using the Arabic numerals 0–9 and the Latin letters A–Z1 (the ISO basic Latin alphabet).

Here's an example of one, but any should work: https://github.com/thewindev/csharpbase36

Example Usage

// Encoding
Base36.Encode(10);    // returns "A"
Base36.Encode(10000); // returns "7PS"

// Decoding
Base36.Decode("Z");   // returns 35L
Base36.Decode("10");  // returns 36L
Base36.Decode("7PS"); // returns 10000L

By default uppercase letters are used. If you really wanted to lowercase then a simple string.ToLowerInvarient() can change that.

However, uppercase is usually easier to read, which is why it's used by default, so you might want to consider using uppercase rather than lowercase.


问:
JavaScript: Break out of for loop, if a condition is true
I'm try to break out of a double for loop, if a condition is true, my code doesnt work correctly. Anyone know how to do this?</p>

```<code>for (var i = 0; i <eightPoints.length; i++)
       {
            for (var j = 0; j <eightPoints.length; j++)
            {
              ....
              ....
                if (bool == true)
                {

                  calculateAndDisplayRoute(0);
                  //break;   ??

                }

            }
          //break;   ??

       }
</code>```

答: Set i = eightPoints.length before break. I don't have any other idea to get out of two for-loops. Definitely break is not the solution as it can break out of only one loop.</p>

Body:
I'm try to break out of a double for loop, if a condition is true, my code doesnt work correctly. Anyone know how to do this?

for (var i = 0; i <eightPoints.length; i++)
       {
            for (var j = 0; j <eightPoints.length; j++)
            {
              ....
              ....
                if (bool == true)
                {

                  calculateAndDisplayRoute(0);
                  //break;   ??

                }

            }
          //break;   ??

       }


答:
I presume you mean you want to represent the number with fewer characters.
Base 36 will do this (0-9, a-z).</p>

Title: How could I encode a long number using uppercase letters and numbers to make it shorter to type?

Body:
Is there a way I could encode a long number (e.g. 12349874529768521) as lower-case letters AND numbers for the purposes of reducing its length?  The idea is that a user might have a long number on a piece of paper.

It seems to me that if there are more symbols available, that the resulting number could be made shorter. So I'm looking for something like hexadecimal but using the larger symbol space of A-Z instead of just A-F.

This would be in C# (if it matters)


问:
How can I get kermit script to accept arguments and connect to serial device
I wrote the following in a kermit script to connect to my serial device:

```<code>#!/usr/bin/env kermit
set port /dev/ttyUSB8
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on
</code>```

It does the job pretty well. Now, I want to make this a generic script and would like to take the input from the user which port he wants to connect. So, I thought taking input as a commandline argument is the best way to do. And I modified the above in the following way:

```<code>#!/usr/bin/env kermit
port_num="/dev/ttyUSB"+$1
set port port_num
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on
</code>```

But, I get the following error:

```<code>user4@user-pc-4:~/Scripts$ ./test.script 8
?Not a command or macro name: "port_num="/dev/ttyUSB$1""
File: /home/Scripts/test.script, Line: 2
port_num
?SET SPEED has no effect without prior SET LINE
"8" - invalid command-line option, type "kermit -h" for help
</code>```

I tried replacing

```<code>port_num="/dev/ttyUSB"+$1
</code>```

with

```<code>port_num="/dev/ttyUSB$1"
</code>```

as well.

There is an obvious flaw in my second script. How can I get the script to accept the user input and connect to the serial port using kermit?

答:
The kermit script language is completely different from bash. Arguments passed on the command line are expanded by dollar signs in bash (as in $1). In kermit, they are expanded with the backslash-percent notation, as in \%1

To pass subsequent command line arguments to the scripting engine, you must invoke kermit with a + argument.

To tell the operating system that your script has to be interpreted by kermit, you used the so-called env shebang #!/usr/bin/env, which is incompatible with the + argument. This means that you have to locate kermit on your system, issuing the command

```<code>$ type kermit
kermit is /usr/bin/kermit
</code>```

(another common location is /usr/local/bin/kermit). Now, place the correct location in the shebang, add the + argument, and you are done:

```<code>#!/usr/bin/kermit +
set port /dev/ttyUSB8\%1
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on
</code>```

If you want to define a macro (kermit name for user-defined variables) you can, and this is a way to define default values:

```<code>assign port_num \%1
if not defined port_num assign port_num 8
set port /dev/ttyUSB\m(port_num)
</code>```

Body:
I wrote the following in a kermit script to connect to my serial device:

#!/usr/bin/env kermit
set port /dev/ttyUSB8
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on

It does the job pretty well. Now, I want to make this a generic script and would like to take the input from the user which port he wants to connect. So, I thought taking input as a commandline argument is the best way to do. And I modified the above in the following way:

#!/usr/bin/env kermit
port_num="/dev/ttyUSB"+$1
set port port_num
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on

But, I get the following error:

user4@user-pc-4:~/Scripts$ ./test.script 8
?Not a command or macro name: "port_num="/dev/ttyUSB$1""
File: /home/Scripts/test.script, Line: 2
port_num
?SET SPEED has no effect without prior SET LINE
"8" - invalid command-line option, type "kermit -h" for help

I tried replacing

port_num="/dev/ttyUSB"+$1

with

port_num="/dev/ttyUSB$1"

as well.

There is an obvious flaw in my second script. How can I get the script to accept the user input and connect to the serial port using kermit?

Body:
The kermit script language is completely different from bash. Arguments passed on the command line are expanded by dollar signs in bash (as in $1). In kermit, they are expanded with the backslash-percent notation, as in \%1

To pass subsequent command line arguments to the scripting engine, you must invoke kermit with a + argument.

To tell the operating system that your script has to be interpreted by kermit, you used the so-called env shebang #!/usr/bin/env, which is incompatible with the + argument. This means that you have to locate kermit on your system, issuing the command

$ type kermit
kermit is /usr/bin/kermit

(another common location is /usr/local/bin/kermit). Now, place the correct location in the shebang, add the + argument, and you are done:

#!/usr/bin/kermit +
set port /dev/ttyUSB8\%1
set speed 115200
set carrier-watch off
set flow-control none
set prefixing all
set input echo on

If you want to define a macro (kermit name for user-defined variables) you can, and this is a way to define default values:

assign port_num \%1
if not defined port_num assign port_num 8
set port /dev/ttyUSB\m(port_num)


问:
How To validate php post variables?
Here I Am going to insert the user details and my insert_search.php contains form fields and insert_dummy.php contains insert code for entering userdetails. My problem is how to validate php post variables and where i need to insert validate code eigther insert_search.php or insert_dummy.php?
As i am new to php.Thank you in Advance.
insert_search.php

```<code><?php
include('header/page_header.php');
$user="root";
$server="localhost";
$password="";
$db="coedsproddb1";
$dbconn= mysql_connect($server,$user,$password);
mysql_select_db($db,$dbconn);

?>
<html>
<head><title>Insert</title>
<link rel="stylesheet" href="css/bookstyles.css">
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
  <script src="js/jquery-ui.js"></script>
</head>
<body>
<div class="container">

<style>
#display {
color:red;
font-size:12px;
text-align:center;
}
.logo {
padding:5px;
float:right;
}
header {
background-color:#074e7c;
height:60px;
width:100%;
text-align:center;
color:white;
font-size:40px;

}
#wrap {
text-align:center;
}
table ,tr,td {
border-collapse:collapse;
}
</style>
<?php
$end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["userName"])) {
        $userNameErr = "Missing";
    }
    else {
        $userName = $_POST["userName"];
    }

    if (empty($_POST["userEmail"])) {
        $userEmailErr = "Missing";
    }
    else {
        $userEmail = $_POST["userEmail"];
    }

    if (empty($_POST["userPassword"]))  {
        $userPasswordErr = "Missing";
    }
    else {
        $userPassword = $_POST["userPassword"];
    }

}
 ?>
<form name="useradd" id="useradd" action="insert_dummy.php" method="post">
<input type="hidden" name="end_date" >
<input type="hidden" name="userId" id="userId" value="<?php $userid;?>" >
<table align='center' border='1'>

    <tr>

           <td> <label for="userName">UserName</label></td>
            <td ><input id="userName" name="userName"  type="text" /></td>

        </tr>
        <tr>
        <td> <label for="userEmail">Email</label></td>
        <td ><input id="userEmail" name="userEmail" type="text"/></td>
        </tr>
        <tr>
        <td>
            <label for="userPassword">password</label></td>
            <td ><input id="userPassword" name="userPassword" type="password" /></td>

        </tr>
        <tr>
        <td>
            <label for="expiry_date">Application_expiry_date</label></td>
            <td ><input id="expiry_date" name="expiry_date" type="text" /></td>

        </tr>
        <br/>
        <br/>

    <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
</tr>

        </table>

<br>

<div id="wrap">
<input type="submit" name="add" value="add" id="add">

</form>
<div id="display">
</div>

</div>

                <script type="text/javascript">
$('document').ready(function() {

    $(".tooltip").click(function(e) {
     $('[data-toggle="tooltip"]').tooltip();
     e.preventDefault();
     });
     });
     </script>-->
     <script type="text/javascript" >
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });
</script>

</body>
</html>
</code>```

insert_dummy.php

```<code><html>
<head><title>Insertion</title>

</head>
<body>
<style>

#colour {
text-decoration:none;
}
</style>
<div id="display">
<?php
include('header/page_header.php');
include('db.php');

$userName=mysql_real_escape_string($_POST['userName']);
$userEmail=mysql_real_escape_string($_POST['userEmail']);
$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}
/*$string="select chapter_no from chapter_details ";
echo $string;
$query7=mysql_query($string);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date=mysql_real_escape_string($_POST['end_date']);

$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
}*/
else
{
$display= "Failed";
}
/*$str="select * from chapter_subscriptions where userId=$userid";
$query7=mysql_query($str);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th>ChapterLicense</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query7))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";
$display.="<td>".$result['chap_lic']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";*/

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="<table border='1' align='center'>";
$display.="<tr><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>ExpiryDate</th><th>RegistrationKey</th><th colspan='3'>Action</th></tr>";
while($result=mysql_fetch_array($query2))
{
$display.="<tr>";

$display.="<td>".$result['userName']."</td>";
$display.="<td>".$result['userEmail']."</td>";
$display.="<td>".$result['userPassword']."</td>";
$display.="<td>".$result['regDate']."</td>";
$display.="<td>".$result['expiry_date']."</td>";
$display.="<td>".$result['registration_key']."</td>";
$display.="<td><a id='colour' class='tooltip' title='Edit' href='user_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='user_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='insert' href='chapter_subscription_search.php?user_Id=".$result['userId']." '>i</a></td>";
$display.="</tr>";

$display.="</table>";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

<table align='center' border='1'>

    <tr>

           <td> <label for="userId">UserId</label></td>
            <td ><input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/></td>

        </tr>
        <tr>
        <td> <label for="userName">UserName</label></td>
        <td ><input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userEmail">UserEmail</label></td>
        <td ><input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userPassword">UserPassword</label></td>
        <td ><input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="expiry_date">ExpiryDate</label></td>
        <td ><input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
        </tr>

        </table>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query9))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";

echo $display;

?>
</div>
 <script type="text/javascript">
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });

</script>

</body>
</html>
</code>```

答:
After reading your example I think you just want to know if you're doing right... Right?

I'll show you something. Consider that you have the following variables being returned from your form: name, email, phone, subject and message (contact form). And you'll send them by POST. The best way you can check if it's your form calling your action file is checking all these names on POST.

```<code>$isMyForm = isset($_POST, $_POST['name'], $_POST['email'], $_POST['phone'], $_POST['subject'], $_POST['message']);
</code>```

This will result on TRUE if every test goes on or FALSE if something is missing. Don't be afraid, unless your inputs are checkboxes you'll receive them everytime.

But the data may come empty!

$isMyForm is just verifying if the expected indexes really exists in $ _POST, not validating. So you can do something like this:

```<code>if(!$isMyForm)
    exit("Ops! Something's missing.");
</code>```

And then test each input without PHP errors! I'm sorry but the next steps you should try by yourself. If you want some tips like "how to validate email onn PHP?" you can try THIS. There's a lot of information here.

EDIT

Please, becareful with exit(); when $isMyForm is false. In your case that would be something like this:

```<code>$isMyForm = isset($_POST, $_POST['name'], $_POST['email'], $_POST['phone'], $_POST['subject'], $_POST['message']);
if($isMyForm) {
    // your action should run here
}
</code>```

Title: How To validate php post variables?

Body:
Here I Am going to insert the user details and my insert_search.php contains form fields and insert_dummy.php contains insert code for entering userdetails. My problem is how to validate php post variables and where i need to insert validate code eigther insert_search.php or insert_dummy.php?
As i am new to php.Thank you in Advance.
insert_search.php

<?php
include('header/page_header.php');
$user="root";
$server="localhost";
$password="";
$db="coedsproddb1";
$dbconn= mysql_connect($server,$user,$password);
mysql_select_db($db,$dbconn);

?>

<title>Insert</title>
<link rel="stylesheet" href="css/bookstyles.css">
<link rel="stylesheet" href="css/jquery-ui.css">

<?php
$end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["userName"])) {
        $userNameErr = "Missing";
    }
    else {
        $userName = $_POST["userName"];
    }

    if (empty($_POST["userEmail"])) {
        $userEmailErr = "Missing";
    }
    else {
        $userEmail = $_POST["userEmail"];
    }

    if (empty($_POST["userPassword"]))  {
        $userPasswordErr = "Missing";
    }
    else {
        $userPassword = $_POST["userPassword"];
    }

}
 ?>
<form name="useradd" id="useradd" action="insert_dummy.php" method="post">
<input type="hidden" name="end_date" >
<input type="hidden" name="userId" id="userId" value="<?php $userid;?>" >

            UserName
            <input id="userName" name="userName"  type="text" />

         Email
        <input id="userEmail" name="userEmail" type="text"/>

            password
            <input id="userPassword" name="userPassword" type="password" />

            Application_expiry_date
            <input id="expiry_date" name="expiry_date" type="text" />

     EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<input type="submit" name="add" value="add" id="add">

</form>

                -->

insert_dummy.php

<title>Insertion</title>

<?php
include('header/page_header.php');
include('db.php');

$userName=mysql_real_escape_string($_POST['userName']);
$userEmail=mysql_real_escape_string($_POST['userEmail']);
$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}
/*$string="select chapter_no from chapter_details ";
echo $string;
$query7=mysql_query($string);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date=mysql_real_escape_string($_POST['end_date']);

$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
}*/
else
{
$display= "Failed";
}
/*$str="select * from chapter_subscriptions where userId=$userid";
$query7=mysql_query($str);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	ChapterLicense	Action
";
while($result=mysql_fetch_array($query7))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";
$display.="".$result['chap_lic']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";*/

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="
";
$display.="
UserName	UserEmail	UserPassword	RegDate	ExpiryDate	RegistrationKey	Action
";
while($result=mysql_fetch_array($query2))
{
$display.="
";

$display.="".$result['userName']."	";
$display.="".$result['userEmail']."	";
$display.="".$result['userPassword']."	";
$display.="".$result['regDate']."	";
$display.="".$result['expiry_date']."	";
$display.="".$result['registration_key']."	";
$display.="	";
$display.="	";

$display.="i	";
$display.="
";

$display.="
";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

            UserId
            <input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/>

         UserName
        <input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/>

         UserEmail
        <input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/>

         UserPassword
        <input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/>

         ExpiryDate
        <input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/>

         EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	Action
";
while($result=mysql_fetch_array($query9))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";

echo $display;

?>

Body:
After reading your example I think you just want to know if you're doing right... Right?

I'll show you something. Consider that you have the following variables being returned from your form: name, email, phone, subject and message (contact form). And you'll send them by POST. The best way you can check if it's your form calling your action file is checking all these names on POST.

$isMyForm = isset($_POST, $_POST['name'], $_POST['email'], $_POST['phone'], $_POST['subject'], $_POST['message']);

This will result on TRUE if every test goes on or FALSE if something is missing. Don't be afraid, unless your inputs are checkboxes you'll receive them everytime.

But the data may come empty!

$isMyForm is just verifying if the expected indexes really exists in $ _POST, not validating. So you can do something like this:

if(!$isMyForm)
    exit("Ops! Something's missing.");

And then test each input without PHP errors! I'm sorry but the next steps you should try by yourself. If you want some tips like "how to validate email onn PHP?" you can try THIS. There's a lot of information here.

EDIT

Please, becareful with exit(); when $isMyForm is false. In your case that would be something like this:

$isMyForm = isset($_POST, $_POST['name'], $_POST['email'], $_POST['phone'], $_POST['subject'], $_POST['message']);
if($isMyForm) {
    // your action should run here
}


问:
How to get last access/modification date of a PostgreSQL database?
On development server I'd like to remove unused databases. To realize that I need to know if database is still used by someone or not.

Is there a way to get last access or modification date of given database, schema or table?

答:
PostgreSQL 9.5 let us to track last modified commit.

Check track commit is on or off using the following query

```<code>show track_commit_timestamp;
</code>```

If it return "ON" go to step 3 else modify postgresql.conf

```<code>cd /etc/postgresql/9.5/main/
vi postgresql.conf
</code>```

Change

```<code>track_commit_timestamp = off
</code>```

to

```<code>track_commit_timestamp = on
</code>```

Restart the postgres / system

Repeat step 1.

Use the following query to track last commit

```<code>SELECT pg_xact_commit_timestamp(xmin), * FROM  YOUR_TABLE_NAME;

SELECT pg_xact_commit_timestamp(xmin), * FROM YOUR_TABLE_NAME where COLUMN_NAME=VALUE;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
PostgreSQL 9.5 let us to track last modified commit.

Check track commit is on or off using the following query

show track_commit_timestamp;

If it return "ON" go to step 3 else modify postgresql.conf

cd /etc/postgresql/9.5/main/
vi postgresql.conf

Change

track_commit_timestamp = off

to

track_commit_timestamp = on

Restart the postgres / system

Repeat step 1.

Use the following query to track last commit

SELECT pg_xact_commit_timestamp(xmin), * FROM  YOUR_TABLE_NAME;

SELECT pg_xact_commit_timestamp(xmin), * FROM YOUR_TABLE_NAME where COLUMN_NAME=VALUE;


问:
Make WPF TextBox or other focusable controls transparent to certain key presses (i.e. pass-through, not swallow)
I have a ListBox with a custom data template which contains a CheckBox, a TextBlock and a TextBox.  Normally when you select an item in a ListBox, the underlying ListBoxItem is actually what has the focus and as such, it responds to the up and down keys.  Additionally, if the CheckBox has focus, since it doesn't do anything with the up and down keys itself, it just happily ignores them and they're handled by the underlying ListBoxItem as well.  All's good so far.

However, a TextBox has its own processing rules for the up and down keys, namingly moving the caret up or down a line in text, which doesn't apply here because in this case it's a single line (it's a number actually.)  As such, if the TextBox has focus, the up and down keys break the navigation of the ListBox's selection, nor do they really help with editing.

Now while I could handle the PreviewKeyDownEvent (which I do below, but for different reasons) and manually process the behaviors depending on the pressed keys, that's a very specific solution and requires the control to have knowledge of its container's behavior.

In a perfect world (and in pseudocode), I'd like to just say MyTextBox.KeysToIgnore(Up, Down) or something similar and have it do just that... ignore those keys as if it wasn't even there. (Again, not swallow, but ignore so they pass through.)

But until then, here's what I've come up with, which seems to work, but just looks so 'hacky' to me...

```<code>private void PreviewKeyDownHandler(object sender, KeyEventArgs e) {

    switch (e.Key){
        case Key.Up:
        case Key.Down:
        case Key.OtherKeyToIgnore
        case Key.AndAnother

            e.Handled = true;

            FrameworkElement target = VisualTreeHelper.GetParent(
                e.Source as DependencyObject) as FrameworkElement;

            target.RaiseEvent(
                new KeyEventArgs(
                    e.KeyboardDevice,
                    PresentationSource.FromVisual(target),
                    0,
                    e.Key
                ){
                    RoutedEvent=Keyboard.KeyDownEvent
                }
            );
            break;

    }

}
</code>```

This also has the added negative of not sending the PreviewKeyDown event to the target.  Now I could work around that and fake it by sending that event first, then looking at the e.Handled before sending the actual KeyDown message, which makes sense, but then I hit another wall with the PreviewKeyUp and KeyUp events since thanks to setting e.Handled above, I never get the real 'key up' events to know when to send the fake ones.  Plus I'm pretty sure I'd also be breaking the direction of the PreviewKeyxxx messages since they bubble the opposite direction from the regular non non-preview versions. (Maybe that's handled internally but I don't think so.)

Like I said... hacky, hacky, hacky!

But it does work so there's that.  And I can implement this via Attached Behaviors which is why I even went this route. (In the attached behaviors implementation, it's not a case statement but rather a check against a collection of keys that I specify in XAML.)  I just don't like the idea of losing all the other behaviors that I want.

Again, I just want to say 'Hey TextBox... when you see the Up or Down keys being pressed, STFU ya b*stard!!' and otherwise make it key-transparent.

Thoughts anyone?

答:
Yeh, TextBox key event handling sure can give you a headache.
The trouble is that it is impossible to determine call order of callbacks, registered via EventManager.RegisterClassEventHandler. I.e. your callback gets called on unhandled event, then event is handled, and thats it...
I found a way to "unhandle" key events by subclassing TextBox and by calling "AddEventHandler(KeyDownEvent, callback, true)" in constructor. Then set e.Handled = false by circumstances. Seems like callback gets called after event is processed by TextBox.
It is very not nice to have instance of delegate per instance of TextBox, rather than to have one delegate instance per class, but i can't see any other way to workaround.</p>

Body:
I have a ListBox with a custom data template which contains a CheckBox, a TextBlock and a TextBox.  Normally when you select an item in a ListBox, the underlying ListBoxItem is actually what has the focus and as such, it responds to the up and down keys.  Additionally, if the CheckBox has focus, since it doesn't do anything with the up and down keys itself, it just happily ignores them and they're handled by the underlying ListBoxItem as well.  All's good so far.

However, a TextBox has its own processing rules for the up and down keys, namingly moving the caret up or down a line in text, which doesn't apply here because in this case it's a single line (it's a number actually.)  As such, if the TextBox has focus, the up and down keys break the navigation of the ListBox's selection, nor do they really help with editing.

Now while I could handle the PreviewKeyDownEvent (which I do below, but for different reasons) and manually process the behaviors depending on the pressed keys, that's a very specific solution and requires the control to have knowledge of its container's behavior.

In a perfect world (and in pseudocode), I'd like to just say MyTextBox.KeysToIgnore(Up, Down) or something similar and have it do just that... ignore those keys as if it wasn't even there. (Again, not swallow, but ignore so they pass through.)

But until then, here's what I've come up with, which seems to work, but just looks so 'hacky' to me...

private void PreviewKeyDownHandler(object sender, KeyEventArgs e) {

    switch (e.Key){
        case Key.Up:
        case Key.Down:
        case Key.OtherKeyToIgnore
        case Key.AndAnother

            e.Handled = true;

            FrameworkElement target = VisualTreeHelper.GetParent(
                e.Source as DependencyObject) as FrameworkElement;

            target.RaiseEvent(
                new KeyEventArgs(
                    e.KeyboardDevice,
                    PresentationSource.FromVisual(target),
                    0,
                    e.Key
                ){
                    RoutedEvent=Keyboard.KeyDownEvent
                }
            );
            break;

    }

}

This also has the added negative of not sending the PreviewKeyDown event to the target.  Now I could work around that and fake it by sending that event first, then looking at the e.Handled before sending the actual KeyDown message, which makes sense, but then I hit another wall with the PreviewKeyUp and KeyUp events since thanks to setting e.Handled above, I never get the real 'key up' events to know when to send the fake ones.  Plus I'm pretty sure I'd also be breaking the direction of the PreviewKeyxxx messages since they bubble the opposite direction from the regular non non-preview versions. (Maybe that's handled internally but I don't think so.)

Like I said... hacky, hacky, hacky!

But it does work so there's that.  And I can implement this via Attached Behaviors which is why I even went this route. (In the attached behaviors implementation, it's not a case statement but rather a check against a collection of keys that I specify in XAML.)  I just don't like the idea of losing all the other behaviors that I want.

Again, I just want to say 'Hey TextBox... when you see the Up or Down keys being pressed, STFU ya b*stard!!' and otherwise make it key-transparent.

Thoughts anyone?


答: You could look to Base64 encoding. It uses 0-9, A-Z, a-z, + and / characters. Or Base36, if you're interested only in 0-9 and A-Z.


问:
Replacing words in text file using a dictionary
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line
</code>```

答:
```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for field in fields:
        if field in line:
            line = line.replace(field, fields[field])

    print line
</code>```

Body:
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line


问:
Alexa skill 2 intents and open slot
Is it possible that Alexa reacts right when I have in a sample utterances something like this, opened slots?

```<code>MyNameIsIntent {firstname}
ProjektIntent {projekt}
</code>```

Right now she always goes back to  MyNameIsIntent even if she ask a question for a ProjektIntent

The bad conversation:

```<code>Alexa: Welcome, what is your name?
Me: Frank
Alexa Hi Frank, Tell me what project is interesting for you?
Me: Teleshoping
Alexa: Hi Teleshoping, Tell me what project is interesting for you?
</code>```

Im totally new to Alexa, could you give me please a tip if it is possible that Alexa answers the right question? I tried to do it with a session atributes but it doesn't work

答:
And just to add a little further clarification to Tom's answer, Alexa can't tell if the word "teleshoping" is your first name or project.
If you use longer utterances as Tom mentions, such as "my name is {firstname}" and "I want to {projekt}" then Alexa will have no trouble discerning.
You can also help Alexa tell the difference by filling in the slot values, but this assumes that you know what the possible projekt values will be.
firstname can use the builtin AMAZON.US_FIRST_NAME slottype.</p>

Title: Alexa skill 2 intents and open slot

Body:
Is it possible that Alexa reacts right when I have in a sample utterances something like this, opened slots?

MyNameIsIntent {firstname}
ProjektIntent {projekt}

Right now she always goes back to  MyNameIsIntent even if she ask a question for a ProjektIntent

The bad conversation:

Alexa: Welcome, what is your name?
Me: Frank
Alexa Hi Frank, Tell me what project is interesting for you?
Me: Teleshoping
Alexa: Hi Teleshoping, Tell me what project is interesting for you?

Im totally new to Alexa, could you give me please a tip if it is possible that Alexa answers the right question? I tried to do it with a session atributes but it doesn't work


问:
A strange codes in c
There's a strange code here:

```<code>const double a[] = {0,1,2,3,4};
int main()
{
    double *p = a;
    printf("%f\n",p[2]); //2.000000
    printf("%f\n",p);    //2.000000
}
</code>```

It return 2.000000 ,why?

答:
The code

```<code>printf("%f\n",p);
</code>```

causes undefined behavior. To print an address (a pointer) which is the type an array name decays to when passed as function argument, you need to

use %p conversion specifier.

cast the argument to (void *).

Title: A strange codes in c

Body:
There's a strange code here:

const double a[] = {0,1,2,3,4};
int main()
{
    double *p = a;
    printf("%f\n",p[2]); //2.000000
    printf("%f\n",p);    //2.000000
}

It return 2.000000 ,why?

Body:
The code

printf("%f\n",p);

causes undefined behavior. To print an address (a pointer) which is the type an array name decays to when passed as function argument, you need to

use %p conversion specifier.

cast the argument to (void *).


问:
Table that dynamically changes when pivot table changes
I have the following problem that I have trouble solving (couldn't find a case online that quiet fits what I have in mind).

I currently update a normal Excel table manually with data from a Pivot table, which is updated once a week (it's basically the exact same table as the Pivot, only as a normal table with values). I want the data displayed in a normal Excel table as values for calculation purposes.

As the manual updates of the normal tables are currently pretty time-consuming, I was wondering if there was a way to automatically refresh the table as soon as the Pivot table is refreshed with new data?

Normally, I would simply link the data from the Pivot to the according cells in the normal table, but the size of the Pivot table changes weekly depending on the Input data.

Is there a way to adjust the normal table in a way that it also changes ist size and exactly mirrors the Pivot?

I hope I made myself clear.

答:
See my answer at  this other stackoverflow thread that does this.

It resizes a Table to match the dimension of a PivotTable. You can then reference the PivotTable cells you want from that Table using calculated columns.

Also check out my guest post here that creates dynamic named ranges for PivotTables, which is another way to reference any part of a PivotTable.


问:
Structuring a multi-dimensional object with varying data
I have three functions which create three objects, firstPayment, interimPayment and finalPayment

firstPayment will always have data. But interimPayment shouldn't always be used, same finalPayment.

The signifier that interimPayment or finalPayment isn't needed is based on another variable numberOfPayments.

If numberOfPayments === 1 then only firstPayment will have data. If numberOfPayments === 2 then both firstPayment and finalPayment are needed. And finally if numberOfPayments > 2 then all three payment objects are needed.

I'm trying to work out how to add all these objects to another object paymentSchedule based on the numberOfPayments variable.

Here's my start on the code but I'm a bit lost!

```<code>  getPaymentSchedule(id) {
    const firstPayment = this.getFirstPayment(id);
    const numberOfPayments = this.getNumberOfPayments(id);

    if (numberOfPayments === 2) {
      const finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
      const interimPayments = this.getInterimPayments(id);
    }
  }
</code>```

This is where I'm a bit stuck. I need to add the three objects firstPayment, getInterimPayments and finalPayment in that order, but obviously only if they have been set. I feel like I could do this some quicker way than lots and lots of if statements.

Example of paymentSchedule I am trying to achieve:

```<code>{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    interimPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

or

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}
</code>```

答:
Maybe I'm missing something but is this what you're looking for?</p>

```<code>getPaymentSchedule(id) {
    const numberOfPayments = this.getNumberOfPayments(id);
    const schedule = {};
    schedule.firstPayment = this.getFirstPayment(id);

    if (numberOfPayments === 2) {
        schedule.finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
        schedule.interimPayments = this.getInterimPayments(id);
    }
    return schedule;
}
</code>```

Body:
I have three functions which create three objects, firstPayment, interimPayment and finalPayment

firstPayment will always have data. But interimPayment shouldn't always be used, same finalPayment.

The signifier that interimPayment or finalPayment isn't needed is based on another variable numberOfPayments.

If numberOfPayments === 1 then only firstPayment will have data. If numberOfPayments === 2 then both firstPayment and finalPayment are needed. And finally if numberOfPayments > 2 then all three payment objects are needed.

I'm trying to work out how to add all these objects to another object paymentSchedule based on the numberOfPayments variable.

Here's my start on the code but I'm a bit lost!

  getPaymentSchedule(id) {
    const firstPayment = this.getFirstPayment(id);
    const numberOfPayments = this.getNumberOfPayments(id);

    if (numberOfPayments === 2) {
      const finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
      const interimPayments = this.getInterimPayments(id);
    }
  }

This is where I'm a bit stuck. I need to add the three objects firstPayment, getInterimPayments and finalPayment in that order, but obviously only if they have been set. I feel like I could do this some quicker way than lots and lots of if statements.

Example of paymentSchedule I am trying to achieve:

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    interimPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

or

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

Body:
Maybe I'm missing something but is this what you're looking for?

getPaymentSchedule(id) {
    const numberOfPayments = this.getNumberOfPayments(id);
    const schedule = {};
    schedule.firstPayment = this.getFirstPayment(id);

    if (numberOfPayments === 2) {
        schedule.finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
        schedule.interimPayments = this.getInterimPayments(id);
    }
    return schedule;
}


问:
Date arithmetic between two date variables
I want to enter two dates into two fields where first date is current date and other has firstdate+3months. I wish to get this in a variable first and directly input it to those fields using sendkeys. How can this be achieved. I am using Java for Selenium.

```<code>import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateTimeDisplay {

 public static void main(String[] args) {

 DateFormat dateFormat1 = new SimpleDateFormat("MM/dd/yyyy");
 Date date = new Date();
 String date1= dateFormat1.format(date);
 System.out.println(date1);
 }

}
</code>```

Here say I want another string date2 which stores date1+3months. How do I achieve it.?

答:
Try below code:

```<code>import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;

public class datetest {

public static void main(String[] args){

    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date date = new Date();
    String date1 = dateFormat.format(date);
    Date newDate = DateUtils.addMonths(date, 3);
    String date2 = dateFormat.format(newDate);
    System.out.println("Current date: "+date1);
    System.out.println("Date after 3 months: "+date2);
}

}
</code>```

Let me know if you have any queries.

Body:
I want to enter two dates into two fields where first date is current date and other has firstdate+3months. I wish to get this in a variable first and directly input it to those fields using sendkeys. How can this be achieved. I am using Java for Selenium.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateTimeDisplay {

 public static void main(String[] args) {

 DateFormat dateFormat1 = new SimpleDateFormat("MM/dd/yyyy");
 Date date = new Date();
 String date1= dateFormat1.format(date);
 System.out.println(date1);
 }

}

Here say I want another string date2 which stores date1+3months. How do I achieve it.?

Body:
Try below code:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;

public class datetest {

public static void main(String[] args){

    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date date = new Date();
    String date1 = dateFormat.format(date);
    Date newDate = DateUtils.addMonths(date, 3);
    String date2 = dateFormat.format(newDate);
    System.out.println("Current date: "+date1);
    System.out.println("Date after 3 months: "+date2);
}

}

Let me know if you have any queries.


问:
FileNotFoundError with selenium
So I'm trying to emulate the code in this page: Javascript in Python

```<code>#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

url = "http://www.python.org"
# use firefox to get page with javascript generated content
with Firefox() as browser:
     browser.get(url)
</code>```

but I am getting this error:

```<code>FileNotFoundError                         Traceback (most recent call last)
c:\programdata\miniconda3\lib\site-packages\selenium\webdriver\common\service.py in start(self)
     73                                             close_fds=platform.system() != 'Windows',
---> 74                                             stdout=self.log_file, stderr=self.log_file)
     75         except TypeError:
</code>```

any suggestions, please?

I am using python 3.6 in a Jupyter notebook

答:
Solved! As mhawke mentioned above, I needed to install the geckodriver.  But where to install it?

Since I was using Miniconda3, I simply downloaded the geckodriver.exe and placed it into the C:\ProgramData\Miniconda3 folder.

Thanks, mhawke.

Title: FileNotFoundError with selenium

Body:
So I'm trying to emulate the code in this page: Javascript in Python

#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

url = "http://www.python.org"
# use firefox to get page with javascript generated content
with Firefox() as browser:
     browser.get(url)

but I am getting this error:

FileNotFoundError                         Traceback (most recent call last)
c:\programdata\miniconda3\lib\site-packages\selenium\webdriver\common\service.py in start(self)
     73                                             close_fds=platform.system() != 'Windows',
---> 74                                             stdout=self.log_file, stderr=self.log_file)
     75         except TypeError:

any suggestions, please?

I am using python 3.6 in a Jupyter notebook


问:
504 Gateway timeout when sending Ajax Post to PHP file
I am having an issue where i get a timeout if i run a certain php script with parameters sent from a Jquery Ajax reequest. However if i simply run this script with no parameters I.E just run it on its own its fine.

The php file the Ajax request is in is noteContent.php
noteContent.php:

```<code><script type="text/javascript">

    // Submit generalNote to the database

function submitNoteText()
{
    var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
    var notetext = $("#ta1").val();

    var dataString = 'noteid1=' + noteid + '&notetext1=' + notetext;

    if(noteid == ''||notetext == '')
    {
        alert("NoteID or Text is blank");
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "submitNoteText.php",
            dataType: 'json',
            data: dataString,
            cache: false,
            success: function(result){
                alert("Success");
            }
        });
    }
    return false;
};

</script>
</code>```

The script its trying to run
submitNoteText.php:

```<code><?php include 'connectionDetails.php'; ?>
<?php
if (isset($_POST['noteid1'], $_POST['notetext1']))
{
    var_dump($_POST['notetext1']);
    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];
    $stmt = "UPDATE Notes SET Note = '?' WHERE NoteID = ?";
    $params = array($noteid2, $notetext2);
    $stmt = sqlsrv_query($conn, $stmt, $params);
    if ($stmt === false)
    {
        die( print_r(sqlsrv_errors(), true));
    }
}
else
{
    echo "No Data";
}
?>
</code>```

they are all connected with an include to
connectionDetails.php(which has never returned an error before):

```<code><?php
$myServer = "Test";
$connectionInfo = array('Database' => 'Test', 'UID' => 'Test', 'PWD' => 'test');

//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
  or die("Couldn't connect to SQL Server on $myServer");

//Test connection to server
// if ($conn)
// {
//     echo "connection successful";    # code...
// }

?>

<?php

//Defining my queries
$getNotes = "SELECT NoteID, NoteName, Note FROM Notes ORDER BY NoteName ASC";
$getTemplateNotes = "SELECT TemplateNoteID, TemplateNoteName, TemplateNote FROM TemplateNotes ORDER BY TemplateNoteName ASC";
$getReplaceVariables = "SELECT ReplaceVariableID, ReplaceVariableName, ReplaceVariableNote FROM ReplaceVariables ORDER BY ReplaceVariableName ASC";

$resultNotes = sqlsrv_query($conn, $getNotes);
$resultTemplate = sqlsrv_query($conn, $getTemplateNotes);
$resultVariables = sqlsrv_query($conn, $getReplaceVariables);

if( $resultNotes === false)
{
    die( print_r( sqlsrv_errors(), true) );
}
if( $resultTemplate === false)
{
    die( print_r( sqlsrv_errors(), true) );
}

if( $resultVariables === false)
{
    die( print_r( sqlsrv_errors(), true) );
}

?>
</code>```

When i click the button to run the request i get this:

All the text to be submitted is in the params:

答:
Ajax data parameter should be an array :</p>

```<code>$.ajax({
    type: 'POST',
    url: "your urls",
    data: {
     id: youridval,
     anothervar: anothervalvalue
    },
    beforeSend: function() {

    },
    complete: function() {

    },
    success: function(_result) {

    }
});
</code>```

Body:
I am having an issue where i get a timeout if i run a certain php script with parameters sent from a Jquery Ajax reequest. However if i simply run this script with no parameters I.E just run it on its own its fine.

The php file the Ajax request is in is noteContent.php
noteContent.php:

The script its trying to run
submitNoteText.php:

<?php include 'connectionDetails.php'; ?>
<?php
if (isset($_POST['noteid1'], $_POST['notetext1']))
{
    var_dump($_POST['notetext1']);
    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];
    $stmt = "UPDATE Notes SET Note = '?' WHERE NoteID = ?";
    $params = array($noteid2, $notetext2);
    $stmt = sqlsrv_query($conn, $stmt, $params);
    if ($stmt === false)
    {
        die( print_r(sqlsrv_errors(), true));
    }
}
else
{
    echo "No Data";
}
?>

they are all connected with an include to
connectionDetails.php(which has never returned an error before):

<?php
$myServer = "Test";
$connectionInfo = array('Database' => 'Test', 'UID' => 'Test', 'PWD' => 'test');

//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
  or die("Couldn't connect to SQL Server on $myServer");

//Test connection to server
// if ($conn)
// {
//     echo "connection successful";    # code...
// }

?>

<?php

//Defining my queries
$getNotes = "SELECT NoteID, NoteName, Note FROM Notes ORDER BY NoteName ASC";
$getTemplateNotes = "SELECT TemplateNoteID, TemplateNoteName, TemplateNote FROM TemplateNotes ORDER BY TemplateNoteName ASC";
$getReplaceVariables = "SELECT ReplaceVariableID, ReplaceVariableName, ReplaceVariableNote FROM ReplaceVariables ORDER BY ReplaceVariableName ASC";

$resultNotes = sqlsrv_query($conn, $getNotes);
$resultTemplate = sqlsrv_query($conn, $getTemplateNotes);
$resultVariables = sqlsrv_query($conn, $getReplaceVariables);

if( $resultNotes === false)
{
    die( print_r( sqlsrv_errors(), true) );
}
if( $resultTemplate === false)
{
    die( print_r( sqlsrv_errors(), true) );
}

if( $resultVariables === false)
{
    die( print_r( sqlsrv_errors(), true) );
}

?>

When i click the button to run the request i get this:

All the text to be submitted is in the params:

Body:
Ajax data parameter should be an array :

$.ajax({
    type: 'POST',
    url: "your urls",
    data: {
     id: youridval,
     anothervar: anothervalvalue
    },
    beforeSend: function() {

    },
    complete: function() {

    },
    success: function(_result) {

    }
});


问:
Error in data binding in Xaml
```<code>I have tried data binding in WPF.
But it is showing few errors.Please help me.
</code>```

I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.

```<code>Xaml code
<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Window.DataContext>
        <l:DataBinding />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

**Code behind**

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            Setupviewmodel();
        }
        private void Setupviewmodel
        {
            TextString="this worked";
        }
        public string TextString{get;set;}
    }
}
</code>```

答:
You are not specifying the DataContext correctly as you are trying to set it up on XAML by using a namespace that has not been declared. For more info on XAML namespaces, check the following link.

In your example it would be on the xaml side:

```<code><Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>
</code>```

And in your code behind:

```<code>namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            this.DataContext = this;  // Pay attention to this line!
            Setupviewmodel();
        }

        private void Setupviewmodel()
        {
            TextString="this worked";
        }

        public string TextString{get;set;}
    }
}
</code>```

The difference with the original version is that I'm not specifying the DataContext on XAML but on the code behind itself.

The DataContext can be considered as the place where the view will retrieve the information from. When in doubt, please refer to this MSDN article or you could learn about the MVVM pattern which is the pillar of working with XAML.

Title: Error in data binding in Xaml

Body:
I have tried data binding in WPF.
But it is showing few errors.Please help me.

I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.

Xaml code
<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Window.DataContext>
        <l:DataBinding />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

**Code behind**

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            Setupviewmodel();
        }
        private void Setupviewmodel
        {
            TextString="this worked";
        }
        public string TextString{get;set;}
    }
}

Body:
You are not specifying the DataContext correctly as you are trying to set it up on XAML by using a namespace that has not been declared. For more info on XAML namespaces, check the following link.

In your example it would be on the xaml side:

<Window x:Class="Shweta.DataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBinding" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="54*" />
            <ColumnDefinition Width="224*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="59*" />
            <RowDefinition Height="202*" />
        </Grid.RowDefinitions>
        <Grid Grid.Column="1" Grid.Row="1">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
        </Grid>
    </Grid>
</Window>

And in your code behind:

namespace Shweta
{
    public partial class DataBinding : Window
    {
        public DataBinding()
        {
            InitializeComponent();
            this.DataContext = this;  // Pay attention to this line!
            Setupviewmodel();
        }

        private void Setupviewmodel()
        {
            TextString="this worked";
        }

        public string TextString{get;set;}
    }
}

The difference with the original version is that I'm not specifying the DataContext on XAML but on the code behind itself.

The DataContext can be considered as the place where the view will retrieve the information from. When in doubt, please refer to this MSDN article or you could learn about the MVVM pattern which is the pillar of working with XAML.


问:
Reinitialise DataTables with HTML (DOM) sourced data without loosing the data in the dom
we have a rather complex structure and combination of technologies for generating a table at the end.

We have a custom binding ,in that custom binding I initialize the datatables with $('.DataTables').DataTable(); in the init(Knockout), this works fine if the data is already present.

But for the case, where the data will be loaded later ,because of an AJAX-Request, this does not work.

I need something to reinitialize the DataTable, with data which is present in the HTML(the data is already present in the html, but clicking on any column for sorting will make the data disappear).

What can I do ?

Now

答:
Process to re initialize data table:

```<code>$('#theID').DataTable().ajax.reload();
</code>```

This will reinitialize datatable loading new data if any.

Body:
Process to re initialize data table:

$('#theID').DataTable().ajax.reload();

This will reinitialize datatable loading new data if any.


问:
Removing range using EF Core
I´m getting an error when using RemoveRange to bulk delete data, in my unit tests, using InMemoryDatabase.

Here is the code:

```<code>public void DeletePatient(Paciente patient)
{
    var schedules = dbContext.Schedules.AsNoTracking().Where(x => x.PatientId == patient.Id).ToList();
    dbContext.Schedules.RemoveRange(schedules);

    dbContext.Patients.Remove(patient);
}
</code>```

This throws this error:

InvalidOperationException: The instance of entity type 'Schedule' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

But, if I perform a foreach and reload each entity, it works:

```<code>foreach(var item in schedules)
{
    var h = dbContext.Schedules.Find(item.Id);
    dbContext.Remove(h);
}
</code>```

The same foreach, using the item directly gives same error:

```<code>foreach(var item in schedules)
{
    dbContext.Remove(item);
}
</code>```

答: Try removing the AsNoTracking clause.  I haven't tested it but my guess is this is causing EF to re-read the entities from the database and not finding the ones already in the context.  Without the clause it should find the actual entities in the context to be removed.</p>

Title: Removing range using EF Core

Body:
I´m getting an error when using RemoveRange to bulk delete data, in my unit tests, using InMemoryDatabase.

Here is the code:

public void DeletePatient(Paciente patient)
{
    var schedules = dbContext.Schedules.AsNoTracking().Where(x => x.PatientId == patient.Id).ToList();
    dbContext.Schedules.RemoveRange(schedules);

    dbContext.Patients.Remove(patient);
}

This throws this error:

InvalidOperationException: The instance of entity type 'Schedule' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

But, if I perform a foreach and reload each entity, it works:

foreach(var item in schedules)
{
    var h = dbContext.Schedules.Find(item.Id);
    dbContext.Remove(h);
}

The same foreach, using the item directly gives same error:

foreach(var item in schedules)
{
    dbContext.Remove(item);
}


问:
iframe tag opens doubleClick link in iPhone's native Safari browser
When my web-checkout page loads in my iOS app (swift), user are automatically re-directed to a doubleClick link in phones native safari browser. Any idea how to prevent this? </p>

答: I was able to resolve this issue. Just look for the URL in debug console and blacklist the URL. That's how i resolved the issue</p>


问:
Dynamically register the route data in angular 2
In my case routing data are available in Database. So i need to take the value from Database and create routing dynamically at run time. I didn't find any option to load a route data before route init or pause the application until route data load.

Please suggest me a idea

答:
If your routes are not complex:

You can define routes with 'variables':

```<code>RouterModule.forRoot([
  { path: 'news/:id', component: MyComponent },
])
</code>```

The official documentation about the Router is available here

Body:
If your routes are not complex:

You can define routes with 'variables':

RouterModule.forRoot([
  { path: 'news/:id', component: MyComponent },
])

The official documentation about the Router is available here