问:
Passing const to function with non-const parameter
I'am following accelerated C++ book but i'am confused with the source code they provide. My confusion  involves functions double grade(double midterm, double final, const vector<double>& hw) and double median(vector<double> vec).
It says in the comment that the grade function does not copy it's argument because the median function does. Why is that so?
From my understanding you can't pass const to non-const since what would require write-access.

Here's the code:

```<code>#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::domain_error;
using std::endl;
using std::istream;
using std::ostream;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;

// compute the median of a `vector<double>'
// note that calling this function copies the entire argument `vector'
double median(vector<double> vec)
{
#ifdef _MSC_VER
    typedef std::vector<double>::size_type vec_sz;
#else
    typedef vector<double>::size_type vec_sz;
#endif

    vec_sz size = vec.size();
    if (size == 0)
        throw domain_error("median of an empty vector");

    sort(vec.begin(), vec.end());

    vec_sz mid = size/2;

    return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}

// compute a student's overall grade from midterm and final exam grades and homework grade
double grade(double midterm, double final, double homework)
{
    return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}

// compute a student's overall grade from midterm and final exam grades
// and vector of homework grades.
// this function does not copy its argument, because `median' does so for us.
double grade(double midterm, double final, const vector<double>& hw)
{
    if (hw.size() == 0)
        throw domain_error("student has done no homework");
    return grade(midterm, final, median(hw));
}

// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
        // get rid of previous contents
        hw.clear();

        // read homework grades
        double x;
        while (in >> x)
            hw.push_back(x);

        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}

int main()
{
    // ask for and read the student's name
    cout << "Please enter your first name: ";
    string name;
    cin >> name;
    cout << "Hello, " << name << "!" << endl;

    // ask for and read the midterm and final grades
    cout << "Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    // ask for the homework grades
    cout << "Enter all your homework grades, "
            "followed by end-of-file: ";

    vector<double> homework;

    // read the homework grades
    read_hw(cin, homework);

    // compute and generate the final grade, if possible
    try {
        double final_grade = grade(midterm, final, homework);
        streamsize prec = cout.precision();
        cout << "Your final grade is " << setprecision(3)
             << final_grade << setprecision(prec) << endl;
    } catch (domain_error) {
        cout << endl << "You must enter your grades.  "
            "Please try again." << endl;
        return 1;
    }

    return 0;
}
</code>```

答:
Take a look at this line:

```<code>return grade(midterm, final, median(hw));
</code>```

hw here is a const reference to a vector, which is being passed to median. While it is true that you can't modify an object through a const reference, you can still make a copy of it through a const reference. So, since median requires to change the vector (by sorting it), it makes a copy for itself (the copy will be implicitly created under the hood) and sorts it instead.

Body:
I'am following accelerated C++ book but i'am confused with the source code they provide. My confusion  involves functions double grade(double midterm, double final, const vector<double>& hw) and double median(vector<double> vec).
It says in the comment that the grade function does not copy it's argument because the median function does. Why is that so?
From my understanding you can't pass const to non-const since what would require write-access.

Here's the code:

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::domain_error;
using std::endl;
using std::istream;
using std::ostream;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;

// compute the median of a `vector<double>'
// note that calling this function copies the entire argument `vector'
double median(vector<double> vec)
{
#ifdef _MSC_VER
    typedef std::vector<double>::size_type vec_sz;
#else
    typedef vector<double>::size_type vec_sz;
#endif

    vec_sz size = vec.size();
    if (size == 0)
        throw domain_error("median of an empty vector");

    sort(vec.begin(), vec.end());

    vec_sz mid = size/2;

    return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}

// compute a student's overall grade from midterm and final exam grades and homework grade
double grade(double midterm, double final, double homework)
{
    return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}

// compute a student's overall grade from midterm and final exam grades
// and vector of homework grades.
// this function does not copy its argument, because `median' does so for us.
double grade(double midterm, double final, const vector<double>& hw)
{
    if (hw.size() == 0)
        throw domain_error("student has done no homework");
    return grade(midterm, final, median(hw));
}

// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
        // get rid of previous contents
        hw.clear();

        // read homework grades
        double x;
        while (in >> x)
            hw.push_back(x);

        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}

int main()
{
    // ask for and read the student's name
    cout << "Please enter your first name: ";
    string name;
    cin >> name;
    cout << "Hello, " << name << "!" << endl;

    // ask for and read the midterm and final grades
    cout << "Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    // ask for the homework grades
    cout << "Enter all your homework grades, "
            "followed by end-of-file: ";

    vector<double> homework;

    // read the homework grades
    read_hw(cin, homework);

    // compute and generate the final grade, if possible
    try {
        double final_grade = grade(midterm, final, homework);
        streamsize prec = cout.precision();
        cout << "Your final grade is " << setprecision(3)
             << final_grade << setprecision(prec) << endl;
    } catch (domain_error) {
        cout << endl << "You must enter your grades.  "
            "Please try again." << endl;
        return 1;
    }

    return 0;
}

Body:
Take a look at this line:

return grade(midterm, final, median(hw));

hw here is a const reference to a vector, which is being passed to median. While it is true that you can't modify an object through a const reference, you can still make a copy of it through a const reference. So, since median requires to change the vector (by sorting it), it makes a copy for itself (the copy will be implicitly created under the hood) and sorts it instead.


来源: stackexchange

问:
Buddhabrot fractal with pthread
I am trying to generate pgm image with a Buddhabrot fractal, in parallel, using pthreads and the master-slave model. From tests, I can see that the program starts the model with the right parallel mode, but it seems to be inside an infinite loop. The problem is that I can't see which one is the problem. Can someone give me a light about it? Thank you.</p>

```<code>#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#define N_SLAVES 3

double next = -1;

int i = 0, nColumns = 2048, nLines = 2048, ite = 600;
double y, dt = 0.001;

int completedIterations;

pthread_mutex_t mutex;
pthread_cond_t condM;
pthread_cond_t condE;

typedef struct {
    int x;
    int y;
} int2;
typedef struct{
    double x;
    double y;
} double2;

int2 coordinatesConversion( double x,double y, int nColumns,int nLines){

    int2 ret;
    int2 retError;
    retError.x=-1;
    retError.y=-1;

    ret.x=round(((2.0+x)/3.5) *((double)(nColumns-1)));
    ret.y=round(((1.5+y)/3.5) *((double)(nLines-1)));

    if(ret.x<0 || ret.x>=nColumns) return retError;
    if(ret.y<0 || ret.y>=nLines) return retError;

    return ret;
}

int printMatrixToFilePGM(float **mat,int tamx, int nLines, char *srcFile){

    printf("First\n");

    FILE *arq=fopen(srcFile,"w");

    int cont, cont2;
    float min,max;
    min=mat[0][0];
    max=mat[0][0];
    for(cont=0;cont<nLines;cont++){
        for(cont2=0;cont2<tamx;cont2++){
            if(min>mat[cont][cont2]) min=mat[cont][cont2];
            if(max<mat[cont][cont2]) max=mat[cont][cont2];
        }
    }
    max=max*0.35;
    float delta=max-min;
    fprintf(arq,"P2 \n");
    fprintf(arq,"#something \n");
    fprintf(arq,"%d\n%d \n",tamx,nLines);
    fprintf(arq,"255\n");
    for(cont=0;cont<nLines;cont++){
        for(cont2=0;cont2<tamx;cont2++){
            int valpixel=((mat[cont][cont2]-min)/delta)*255.0f;
            if(valpixel>255) valpixel=255;
            fprintf(arq,"%d \n", valpixel);
        }
    }
    fclose(arq);
}

float** mallocFloatMatrix(int tamx, int nLines, float defaultValueOfTheElementsAtMatrix){

    float **errorCodeReturn=0x0;
    float **mat;
    int i,j;
    int condErrorMalloc=0;
    mat=malloc(sizeof(float *)*nLines);
    if(mat==0x0) return errorCodeReturn;
    for(i=0;i<tamx;i++)
        mat[i]=malloc(sizeof(float )*tamx);

    for(i=0;i<tamx;i++){
        if(mat[i]==0x0){
            condErrorMalloc=1;
            break;
        }
    }

    if(condErrorMalloc==0){
        return mat;
    }
    for(i=0;i<nLines;i++){
        for(j=0;j<tamx;j++)
            mat[i][j]=defaultValueOfTheElementsAtMatrix;
    }
    for(i=0;i<tamx;i++)
        if(mat[i]!=0x0) free(mat[i]);

    free(mat);

    return errorCodeReturn;
}

void freeFloatMatrix(float **mat,int tamx, int nLines){
    int i;
    for(i=0;i<nLines;i++){
        if(mat[i]!=0x0) free(mat[i]);
    }
    free(mat);
}

int iteration(double x,double y, int nColumns,int nLines, int ite,int2 *iterationPath){

    int cont;
    int condInvalidPointer=1;
    double2 z;
    z.x=0.0;
    z.y=0.0;
    double2 c;
    c.x=x;
    c.y=y;
    double2 zt;

    for(cont=0;cont<ite;cont++){
        zt.x=((z.x*z.x)-(z.y*z.y))+c.x;
        zt.y=(2.0*(z.x*z.y))+c.y;
        z=zt;
        if(((z.x*z.x)+(z.y*z.y))>4.0){
            if(cont>100)
                condInvalidPointer=0;
            break;
        }
        iterationPath[cont]=coordinatesConversion(z.x,z.y,nColumns,nLines);
    }
    if(condInvalidPointer)
        return 0;

    return cont;
}

void *master(void *param){
    printf("Second\n");
    int size = round(4.0/dt);
    int i;
    int progress = 0;
    for(i = 0; i < size; i++){
        next = -2.0+i*dt;
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&condE);
        pthread_cond_wait(&condM, &mutex);
        pthread_mutex_unlock(&mutex);

    //     progress++;
    //     if(progress%100 ==0)//print at screen information about progrees of the operation
    //         printf("2 - %lf \n", next);
     }
}

void *slave(void *param){
    int size = round(4.0/dt);
    printf("Third\n");
    int k;
    float **mat = mallocFloatMatrix(nColumns, nLines, 0.0f);

    if(mat == 0x0) return 0;

    while(1){

        pthread_mutex_lock(&mutex);
        if(i >= size){
            pthread_mutex_unlock(&mutex);
            pthread_exit(0);

        }
        i++;
        while(next == -1){
            pthread_cond_signal(&condM);
            pthread_cond_wait(&condE, &mutex);

        }

        double x = next;

        next = -1;

        pthread_cond_signal(&condM);
        pthread_mutex_unlock(&mutex);

        for(y=-2.0;y<2.0;y=y+dt){
            int2* iterationPath = (int2 *)malloc(sizeof(int2) * ite);
            if(iterationPath==0x0) return 0x0;

            completedIterations = iteration(x, y, nColumns, nLines, ite, iterationPath);

            for(k = 0; k < completedIterations; k++){
                if(iterationPath[k].x!=-1 && iterationPath[k].y!=-1)//test if a point z in the iteration k may be normalized to coordinates at matrix mat.
                    mat[iterationPath[k].x][iterationPath[k].y] = mat[iterationPath[k].x][iterationPath[k].y]+1.0f;//increments a point in matrix, this point is pointed by z with  z points normalized.

            }

            free(iterationPath);

        }

    }
    printMatrixToFilePGM(mat,nColumns,nLines,"saida3.pgm");
    freeFloatMatrix(mat,nColumns,nLines);
}

int main(void){

    printf("Main\n");

    int i, j, k;

    pthread_t master_t;
    pthread_t slave_t[N_SLAVES];

    pthread_create(&master_t, NULL, master, NULL);

    for(i = 0; i < N_SLAVES; i++)
        pthread_create(&slave_t[i], NULL, slave, NULL);

    pthread_exit(0);

    return 0;
}
</code>```

答:
It seems like the problem is that you are assigning -1 as a magic number to next, meaning "not yet initialized by the master". However, it's a possible legitimate value, because you calculate next like this:

```<code>next = -2.0+i*dt;
</code>```

Because dt is 0.001, next will be equal to -1 when i is 1000, and since i loops to 4000 (4.0/dt), it will happen before the loop ends. Then you'll get stuck in an infinite loop because your slave thread is waiting for a value other than -1, so never sets condM, so pthread_cond_wait(&condM, &mutex); never returns in the master, so i never increments.

Change your magic number from -1 to something outside the range of possible values for next (e.g. -100), or else use another mechanism.

ContentLicense: CC BY-SA 3.0

Title: Buddhabrot fractal with pthread

Body:
I am trying to generate pgm image with a Buddhabrot fractal, in parallel, using pthreads and the master-slave model. From tests, I can see that the program starts the model with the right parallel mode, but it seems to be inside an infinite loop. The problem is that I can't see which one is the problem. Can someone give me a light about it? Thank you.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#define N_SLAVES 3

double next = -1;

int i = 0, nColumns = 2048, nLines = 2048, ite = 600;
double y, dt = 0.001;

int completedIterations;

pthread_mutex_t mutex;
pthread_cond_t condM;
pthread_cond_t condE;

typedef struct {
    int x;
    int y;
} int2;
typedef struct{
    double x;
    double y;
} double2;

int2 coordinatesConversion( double x,double y, int nColumns,int nLines){

    int2 ret;
    int2 retError;
    retError.x=-1;
    retError.y=-1;

    ret.x=round(((2.0+x)/3.5) *((double)(nColumns-1)));
    ret.y=round(((1.5+y)/3.5) *((double)(nLines-1)));

    if(ret.x<0 || ret.x>=nColumns) return retError;
    if(ret.y<0 || ret.y>=nLines) return retError;

    return ret;
}

int printMatrixToFilePGM(float **mat,int tamx, int nLines, char *srcFile){

    printf("First\n");

    FILE *arq=fopen(srcFile,"w");

    int cont, cont2;
    float min,max;
    min=mat[0][0];
    max=mat[0][0];
    for(cont=0;cont<nLines;cont++){
        for(cont2=0;cont2<tamx;cont2++){
            if(min>mat[cont][cont2]) min=mat[cont][cont2];
            if(max<mat[cont][cont2]) max=mat[cont][cont2];
        }
    }
    max=max*0.35;
    float delta=max-min;
    fprintf(arq,"P2 \n");
    fprintf(arq,"#something \n");
    fprintf(arq,"%d\n%d \n",tamx,nLines);
    fprintf(arq,"255\n");
    for(cont=0;cont<nLines;cont++){
        for(cont2=0;cont2<tamx;cont2++){
            int valpixel=((mat[cont][cont2]-min)/delta)*255.0f;
            if(valpixel>255) valpixel=255;
            fprintf(arq,"%d \n", valpixel);
        }
    }
    fclose(arq);
}

float** mallocFloatMatrix(int tamx, int nLines, float defaultValueOfTheElementsAtMatrix){

    float **errorCodeReturn=0x0;
    float **mat;
    int i,j;
    int condErrorMalloc=0;
    mat=malloc(sizeof(float *)*nLines);
    if(mat==0x0) return errorCodeReturn;
    for(i=0;i<tamx;i++)
        mat[i]=malloc(sizeof(float )*tamx);

    for(i=0;i<tamx;i++){
        if(mat[i]==0x0){
            condErrorMalloc=1;
            break;
        }
    }

    if(condErrorMalloc==0){
        return mat;
    }
    for(i=0;i<nLines;i++){
        for(j=0;j<tamx;j++)
            mat[i][j]=defaultValueOfTheElementsAtMatrix;
    }
    for(i=0;i<tamx;i++)
        if(mat[i]!=0x0) free(mat[i]);

    free(mat);

    return errorCodeReturn;
}

void freeFloatMatrix(float **mat,int tamx, int nLines){
    int i;
    for(i=0;i<nLines;i++){
        if(mat[i]!=0x0) free(mat[i]);
    }
    free(mat);
}

int iteration(double x,double y, int nColumns,int nLines, int ite,int2 *iterationPath){

    int cont;
    int condInvalidPointer=1;
    double2 z;
    z.x=0.0;
    z.y=0.0;
    double2 c;
    c.x=x;
    c.y=y;
    double2 zt;

    for(cont=0;cont<ite;cont++){
        zt.x=((z.x*z.x)-(z.y*z.y))+c.x;
        zt.y=(2.0*(z.x*z.y))+c.y;
        z=zt;
        if(((z.x*z.x)+(z.y*z.y))>4.0){
            if(cont>100)
                condInvalidPointer=0;
            break;
        }
        iterationPath[cont]=coordinatesConversion(z.x,z.y,nColumns,nLines);
    }
    if(condInvalidPointer)
        return 0;

    return cont;
}

void *master(void *param){
    printf("Second\n");
    int size = round(4.0/dt);
    int i;
    int progress = 0;
    for(i = 0; i < size; i++){
        next = -2.0+i*dt;
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&condE);
        pthread_cond_wait(&condM, &mutex);
        pthread_mutex_unlock(&mutex);

    //     progress++;
    //     if(progress%100 ==0)//print at screen information about progrees of the operation
    //         printf("2 - %lf \n", next);
     }
}

void *slave(void *param){
    int size = round(4.0/dt);
    printf("Third\n");
    int k;
    float **mat = mallocFloatMatrix(nColumns, nLines, 0.0f);

    if(mat == 0x0) return 0;

    while(1){

        pthread_mutex_lock(&mutex);
        if(i >= size){
            pthread_mutex_unlock(&mutex);
            pthread_exit(0);

        }
        i++;
        while(next == -1){
            pthread_cond_signal(&condM);
            pthread_cond_wait(&condE, &mutex);

        }

        double x = next;

        next = -1;

        pthread_cond_signal(&condM);
        pthread_mutex_unlock(&mutex);

        for(y=-2.0;y<2.0;y=y+dt){
            int2* iterationPath = (int2 *)malloc(sizeof(int2) * ite);
            if(iterationPath==0x0) return 0x0;

            completedIterations = iteration(x, y, nColumns, nLines, ite, iterationPath);

            for(k = 0; k < completedIterations; k++){
                if(iterationPath[k].x!=-1 && iterationPath[k].y!=-1)//test if a point z in the iteration k may be normalized to coordinates at matrix mat.
                    mat[iterationPath[k].x][iterationPath[k].y] = mat[iterationPath[k].x][iterationPath[k].y]+1.0f;//increments a point in matrix, this point is pointed by z with  z points normalized.

            }

            free(iterationPath);

        }

    }
    printMatrixToFilePGM(mat,nColumns,nLines,"saida3.pgm");
    freeFloatMatrix(mat,nColumns,nLines);
}

int main(void){

    printf("Main\n");

    int i, j, k;

    pthread_t master_t;
    pthread_t slave_t[N_SLAVES];

    pthread_create(&master_t, NULL, master, NULL);

    for(i = 0; i < N_SLAVES; i++)
        pthread_create(&slave_t[i], NULL, slave, NULL);

    pthread_exit(0);

    return 0;
}

Body:
It seems like the problem is that you are assigning -1 as a magic number to next, meaning "not yet initialized by the master". However, it's a possible legitimate value, because you calculate next like this:

next = -2.0+i*dt;

Because dt is 0.001, next will be equal to -1 when i is 1000, and since i loops to 4000 (4.0/dt), it will happen before the loop ends. Then you'll get stuck in an infinite loop because your slave thread is waiting for a value other than -1, so never sets condM, so pthread_cond_wait(&condM, &mutex); never returns in the master, so i never increments.

Change your magic number from -1 to something outside the range of possible values for next (e.g. -100), or else use another mechanism.


问:
match columns in 2 tab-delimited text files
I have two tab-delimited .txt files

file1 has 20 million lines and the following structure

```<code>col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
6       x       y       E       x
7       x       z       F       x
</code>```

file2 has 3000 lines and the following structure

```<code>col1
A
B
C
D
</code>```

Now I want to extract from file1 the lines where there is a match between col1 from file2 and col4 of file1

So the new file3 should look like this

```<code>col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
</code>```

How can I do this with perl or bash?

答:
try this - </p>

```<code>awk -F'[ ]+' 'NR==FNR {a[$1]++;next} $4 in a{print $0}' f2 f1
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
</code>```

Body:
I have two tab-delimited .txt files

file1 has 20 million lines and the following structure

col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
6       x       y       E       x
7       x       z       F       x

file2 has 3000 lines and the following structure

col1
A
B
C
D

Now I want to extract from file1 the lines where there is a match between col1 from file2 and col4 of file1

So the new file3 should look like this

col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x

How can I do this with perl or bash?

Body:
try this -

awk -F'[ ]+' 'NR==FNR {a[$1]++;next} $4 in a{print $0}' f2 f1
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x


问:
Access blob with one more security in azure android
i am storing my data to azure blobs. if the container name known, then we can access all the blobs in that container. but i need to make some authentication for accessing the blobs.

Example : set some password to access the blob while creating it.

send the password to get the blob's content.

is this possible?

code retrieve the blob without any authnetication:

```<code>       for (ListBlobItem blobItem : container.listBlobs()) {
            // If the item is a blob, not a virtual directory
            if (blobItem instanceof CloudBlockBlob) {
                // Download the text
                CloudBlockBlob retrievedBlob = (CloudBlockBlob) blobItem;
                act.outputText(view, retrievedBlob.downloadText());
            }
        }
</code>```

答:
Blob storage supports 3 access levels - Public which enables anonymous read and listing of all the blobs in a container, Blob read - where an anonymous request can read blobs but not list the contents of the container to find others or No public access.  These permissions are detailed here:

https://learn.microsoft.com/en-us/azure/storage/storage-manage-access-to-resources

For your needs I think Shared Access Signatures (SAS) would be a good bet - the article below has an example which I think should help:
https://learn.microsoft.com/en-us/azure/storage/storage-dotnet-shared-access-signature-part-2

The SAS documentation is available here:
https://learn.microsoft.com/en-us/azure/storage/storage-dotnet-shared-access-signature-part-1

Finally the article listed below has a good summary of the topic:
https://www.simple-talk.com/cloud/platform-as-a-service/azure-blob-storage-part-9-shared-access-signatures/

HTH

Body:
i am storing my data to azure blobs. if the container name known, then we can access all the blobs in that container. but i need to make some authentication for accessing the blobs.

Example : set some password to access the blob while creating it.

send the password to get the blob's content.

is this possible?

code retrieve the blob without any authnetication:

       for (ListBlobItem blobItem : container.listBlobs()) {
            // If the item is a blob, not a virtual directory
            if (blobItem instanceof CloudBlockBlob) {
                // Download the text
                CloudBlockBlob retrievedBlob = (CloudBlockBlob) blobItem;
                act.outputText(view, retrievedBlob.downloadText());
            }
        }


问:
Windows Azure automatic deployment. Problem with powershell script
I am using Azure Management Cmdlets version 1.0.

I run the following PowerShell script

New-Deployment -subscriptionId bef7722c-1a13-4c9f-b7f6-fafc0a958b35 -certificate D:\pcg\T.cer -serviceName 1ClickDeploymentTest -slot Production -package D:\pcg

\CloudTodorTest.cspkg -configuration D:\pcg\ServiceConfiguration.cscfg -label lbl1 -StorageServiceName TodorTestStorage

where the D:\pcg\T.cert is the certificate which is already uploaded to Azure too.
The package and the configuration are the local copies of the application that is already running on Azure.
I've tried to deploy them manually and they are working.

After executing this script I receive the following error message:

PS C:\Windows\SysWOW64\WindowsPowerShell\v1.0> D:\PSScripts\dt2.ps1
New-Deployment : The remote server returned an unexpected response: (400) Bad Request.
At D:\PSScripts\dt2.ps1:1 char:15
+ New-Deployment <<<<  -subscriptionId bef7722c-1a13-4c9f-b7f6-fafc0a958b35 -certificate D:\pcg\T.cer -serviceName 1Cli
ckDeploymentTest -slot Staging -package D:\pcg\CloudTodorTest.cspkg -configuration D:\pcg\ServiceConfiguration.cscfg -l
abel lbl1 -StorageServiceName TodorTestStorage | Get-OperationStatus -WaitToComplete
    + CategoryInfo          : CloseError: (:) [New-Deployment], ProtocolException
    + FullyQualifiedErrorId : Microsoft.Samples.AzureManagementTools.PowerShell.HostedServices.NewDeploymentCommand

I can execute other cmdlets. For example to check the current deployments.

答: Storage accounts have to be lowercase.  I'm not sure that's your issue (maybe the cmdlets auto-lowercase it), but it's something to try.</p>

ContentLicense: CC BY-SA 2.5


问:
Inline CKEditor save to MySQL using AJAX/PHP
I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.

For some reason, nothing happens when I click the save button.. not even in the console.

It's just using jQuery at the moment, will I have to use AJAX for this?

If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.

Here is my code:

index.php

```<code>          <div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
           <?php
            $query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
            $show = mysql_query($query3, $con);
            while ($row = mysql_fetch_array($show))
            {
              echo $row['file'];
            }
            ?>
        </div>
        <button type="button" id="save"><span>Save</span></button>
            <script>
               $(document).ready(function (e) {

                  $("#save").click(function (e) {
                      var data = CKEDITOR.instances.caption1.getData();
                      var options = {
                           url: "save.php",
                          type: "post",
                          data: { "editor" : encodeUriComponent(data) },
                         success: function (e) {
                           echo "Succesfully updated!";
                         }
                       };
                  }
               });
            </script>
      </div>
</code>```

save.php

```<code>     <?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
</code>```

答:
You need to send the data to the server like this;

```<code>$.ajax({
   url: "save.php",
   data: {
      "editor" : encodeUriComponent(data)
   },
   error: function() {
      //Error
   },
   success: function(data) {
      //Success
   },
   type: 'POST'
});
</code>```

Currently you are just creating an object called 'options'

Your code should look like this;

```<code>$("#save").click(function (e) {
  var data = CKEDITOR.instances.caption1.getData();
  $.ajax({
   url: "save.php",
   data: {
       "editor" : encodeUriComponent(data)
   },
   error: function() {
      //Error
   },
   success: function(data) {
      alert('Success');
   },
   type: 'POST'
});
</code>```

}

Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'

Body:
I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.

For some reason, nothing happens when I click the save button.. not even in the console.

It's just using jQuery at the moment, will I have to use AJAX for this?

If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.

Here is my code:

index.php

           <?php
            $query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
            $show = mysql_query($query3, $con);
            while ($row = mysql_fetch_array($show))
            {
              echo $row['file'];
            }
            ?>

        <button type="button" id="save">Save</button>

save.php

     <?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>

Body:
You need to send the data to the server like this;

$.ajax({
   url: "save.php",
   data: {
      "editor" : encodeUriComponent(data)
   },
   error: function() {
      //Error
   },
   success: function(data) {
      //Success
   },
   type: 'POST'
});

Currently you are just creating an object called 'options'

Your code should look like this;

$("#save").click(function (e) {
  var data = CKEDITOR.instances.caption1.getData();
  $.ajax({
   url: "save.php",
   data: {
       "editor" : encodeUriComponent(data)
   },
   error: function() {
      //Error
   },
   success: function(data) {
      alert('Success');
   },
   type: 'POST'
});

}

Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'


问:
ABORT: Aborting on channel error line :2076 in Selenium 3.0.0 beta 2
I have been using Selenium 3.0.0 beta2 with the Firefox 48.0.2 and geckodriverv10.0 for win 64.

The problem is that the browser crashes without closing.

```<code>>  [Child 10232] ###!!! ABORT: Aborting on channel error.: file c:/builds/moz2_slave/m-rel-w32-00000000000000000000/build/src/ipc/glue/MessageChannel.cpp,
> line 2046
</code>```

And it passes the test case.

I tried with FF 46.0.9 as well still gives the same error.

答:
I got it to work by using these versions:

Firefox Setup 48.0.2 (32bit)

geckodriver-v0.15.0-win32

JavaSetup8u121 (32bit)

selenium-server-standalone-3.3.1

Body:
I have been using Selenium 3.0.0 beta2 with the Firefox 48.0.2 and geckodriverv10.0 for win 64.

The problem is that the browser crashes without closing.

>  [Child 10232] ###!!! ABORT: Aborting on channel error.: file c:/builds/moz2_slave/m-rel-w32-00000000000000000000/build/src/ipc/glue/MessageChannel.cpp,
> line 2046

And it passes the test case.

I tried with FF 46.0.9 as well still gives the same error.


问:
Resize PictureBox with its related controls
I have a PictureBox where I put some other controls (smaller PictureBoxes, labels..).

```<code>PictureBox pictureBox = new PictureBox();
pictureBox.Size = new Size(Width, Height);
pictureBox.Location = new Point(0, 0);
pictureBox.BackColor = Color.Transparent;
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

// add child controls

PictureBox iconPictureBox = new PictureBox();
iconPictureBox.Location = new Point(icon.x, icon.y);
iconPictureBox.Size = new Size(icon.width, icon.height);
iconPictureBox.BackColor = Color.Transparent;
iconPictureBox.Image = Image.FromFile(resourcesPath);
iconPictureBox.Click += IconPictureBox_Click;
pictureBox.Controls.Add(iconPictureBox);
</code>```

When I tried to attach the main picture box "pictureBox" to the MainForm window using Controls.Add, after setting the new size and position of the picture box, it is drawn in the correct place with correct size but the contents are not stretched i.e. their positions are not changed.

Is there a method to make the related controls stretched within the main pictureBox?

答: The scale method of the forms container (PictureBox or Panel) can be used to resize it, all child forms should have the SizeMode to stretch so that they will follow the scaling.</p>

Body:
I have a PictureBox where I put some other controls (smaller PictureBoxes, labels..).

PictureBox pictureBox = new PictureBox();
pictureBox.Size = new Size(Width, Height);
pictureBox.Location = new Point(0, 0);
pictureBox.BackColor = Color.Transparent;
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

// add child controls

PictureBox iconPictureBox = new PictureBox();
iconPictureBox.Location = new Point(icon.x, icon.y);
iconPictureBox.Size = new Size(icon.width, icon.height);
iconPictureBox.BackColor = Color.Transparent;
iconPictureBox.Image = Image.FromFile(resourcesPath);
iconPictureBox.Click += IconPictureBox_Click;
pictureBox.Controls.Add(iconPictureBox);

When I tried to attach the main picture box "pictureBox" to the MainForm window using Controls.Add, after setting the new size and position of the picture box, it is drawn in the correct place with correct size but the contents are not stretched i.e. their positions are not changed.

Is there a method to make the related controls stretched within the main pictureBox?


问:
Best way to encode text data for XML
I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one.  So, before I go too much further, could I just be missing the built-in function?

Assuming for a moment that it really doesn't exist, I'm putting together my own generic EncodeForXml(string data) method, and I'm thinking about the best way to do this.

The data I'm using that prompted this whole thing could contain bad characters like &, <, ", etc.  It could also contains on occasion the properly escaped entities: &, <, and ", which means just using a CDATA section may not be the best idea.  That seems kinda klunky anyay; I'd much rather end up with a nice string value that can be used directly in the xml.

I've used a regular expression in the past to just catch bad ampersands, and I'm thinking of using it to catch them in this case as well as the first step, and then doing a simple replace for other characters.

So, could this be optimized further without making it too complex, and is there anything I'm missing? :

Function EncodeForXml(ByVal data As String) As String
    Static badAmpersand As new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)")

    data = badAmpersand.Replace(data, "&")

    return data.Replace("<", "<").Replace("""", """).Replace(">", "gt;")
End Function
```

Sorry for all you C# -only folks-- I don't really care which language I use, but I wanted to make the Regex static and you can't do that in C# without declaring it outside the method, so this will be VB.Net

Finally, we're still on .Net 2.0 where I work, but if someone could take the final product and turn it into an extension method for the string class, that'd be pretty cool too.

Update The first few responses indicate that .Net does indeed have built-in ways of doing this.  But now that I've started, I kind of want to finish my EncodeForXml() method just for the fun of it, so I'm still looking for ideas for improvement.  Notably: a more complete list of characters that should be encoded as entities (perhaps stored in a list/map), and something that gets better performance than doing a .Replace() on immutable strings in serial.

答:
Here is a single line solution using the XElements. I use it in a very small tool. I don't need it a second time so I keep it this way. (Its dirdy doug)

```<code>StrVal = (<x a=<%= StrVal %>>END</x>).ToString().Replace("<x a=""", "").Replace(">END</x>", "")
</code>```

Oh and it only works in VB not in C#

OwnerDisplayName: Joel Coehoorn

Title: Best way to encode text data for XML

Body:
I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one.  So, before I go too much further, could I just be missing the built-in function?

Assuming for a moment that it really doesn't exist, I'm putting together my own generic EncodeForXml(string data) method, and I'm thinking about the best way to do this.

The data I'm using that prompted this whole thing could contain bad characters like &, <, ", etc.  It could also contains on occasion the properly escaped entities: &, <, and ", which means just using a CDATA section may not be the best idea.  That seems kinda klunky anyay; I'd much rather end up with a nice string value that can be used directly in the xml.

I've used a regular expression in the past to just catch bad ampersands, and I'm thinking of using it to catch them in this case as well as the first step, and then doing a simple replace for other characters.

So, could this be optimized further without making it too complex, and is there anything I'm missing? :

Function EncodeForXml(ByVal data As String) As String
    Static badAmpersand As new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)")

    data = badAmpersand.Replace(data, "&")

    return data.Replace("<", "<").Replace("""", """).Replace(">", "gt;")
End Function

Sorry for all you C# -only folks-- I don't really care which language I use, but I wanted to make the Regex static and you can't do that in C# without declaring it outside the method, so this will be VB.Net

Finally, we're still on .Net 2.0 where I work, but if someone could take the final product and turn it into an extension method for the string class, that'd be pretty cool too.

Update The first few responses indicate that .Net does indeed have built-in ways of doing this.  But now that I've started, I kind of want to finish my EncodeForXml() method just for the fun of it, so I'm still looking for ideas for improvement.  Notably: a more complete list of characters that should be encoded as entities (perhaps stored in a list/map), and something that gets better performance than doing a .Replace() on immutable strings in serial.

LastEditorDisplayName: Joel Coehoorn

Body:
Here is a single line solution using the XElements. I use it in a very small tool. I don't need it a second time so I keep it this way. (Its dirdy doug)

StrVal = (<x a=<%= StrVal %>>END</x>).ToString().Replace("<x a=""", "").Replace(">END</x>", "")

Oh and it only works in VB not in C#


问:
Slideshow - css jquery
I need like this slide any help please

This is my slideshow looks like

答:
You can use bootstrap carousel or you can find an slideshow example on w3school, then you can style it on your own.

https://www.w3schools.com/bootstrap/bootstrap_carousel.asp

https://v4-alpha.getbootstrap.com/components/carousel/

https://getbootstrap.com/examples/carousel/

If you want to make it quick, you can download WOWSlider software and choose the style of slideshow as you want : http://wowslider.com/

Try to do it first, then if you have any problem while making it, you can post your issue here for help.

Title: Slideshow - css jquery


问:
Page Scroll and JQuery
Using Codeigniter / PHP and this Bootstrap template. This template includes a page scroll feature on the home page.

I have a header.php template that will be used to display the main navigation on each page.

This main navigation code;

```<code><div class="collapse navbar-collapse">
    <ul class="nav navbar-nav navbar-right">
        <li>
            <a class="page-scroll" href="#home">Home</a>
        </li>
        <li>
            <a class="page-scroll" href="#items">Items</a>
        </li>
        <li>
            <a class="page-scroll" href="#features">Features</a>
        </li>
        <li>
            <a class="page-scroll" href="#contact">Contact</a>
        </li>
    </ul>
</div>
</code>```

The Jquery code;

```<code>(function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $(document).on('click', 'a.page-scroll', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 100
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 50
        }
    })

})(jQuery); // End of use strict
</code>```

Everything works as expected, but only on the home page (home.php).

I need to create some additional pages (e.g. items.php) this is where the header navigation doesn't work.

When I visit items.php and hover over the Contact menu link, the URL is /items#contact. It's looking for the #contact anchor on the items page. Instead I want to go to the #contact anchor on the home page.

So, in order to get this working I added <?php echo base_url();?> to my menu links - making them #items">Items. My home page URL is http://localhost/ci

This works, and when on the items page successfully takes me to the correct anchor on the home page.

However it seems like after adding <?php echo base_url();?>, the home page scroll doesn't work. Clickiong the links takes me to the correct anchor, but instead of scrolling it 'jumps'.

Probably something very simple! Any ideas?

答:
You can use this function. It uses javascript pathname to find if the current page is homepage. If the current page is homepage it will scroll to the desired position or else it will navigate to the homepage. (Use your homepage pathname instead of "/")

 (function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $(document).on('click', 'a.page-scroll', function(event) {
  /*******USE YOUR HOMEPAGE PATHNAME HERE*****/
  if(window.location.pathname == '/') {
   var url = $(this).attr("href");
   var hash = url.split('#')[1];
   $('html, body').stop().animate({
     scrollTop: ($('#' + hash).offset().top - 50)
    }, 1250, 'easeInOutExpo');
    event.preventDefault();
   }

    });

})(jQuery); // End of use strict```

Title: Page Scroll and JQuery

Body:
Using Codeigniter / PHP and this Bootstrap template. This template includes a page scroll feature on the home page.

I have a header.php template that will be used to display the main navigation on each page.

This main navigation code;

            Home

            Items

            Features

            Contact

The Jquery code;

(function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $(document).on('click', 'a.page-scroll', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 100
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 50
        }
    })

})(jQuery); // End of use strict

Everything works as expected, but only on the home page (home.php).

I need to create some additional pages (e.g. items.php) this is where the header navigation doesn't work.

When I visit items.php and hover over the Contact menu link, the URL is /items#contact. It's looking for the #contact anchor on the items page. Instead I want to go to the #contact anchor on the home page.

So, in order to get this working I added <?php echo base_url();?> to my menu links - making them <a class="page-scroll" href="<?php echo base_url();?>#items">Items. My home page URL is http://localhost/ci

This works, and when on the items page successfully takes me to the correct anchor on the home page.

However it seems like after adding <?php echo base_url();?>, the home page scroll doesn't work. Clickiong the links takes me to the correct anchor, but instead of scrolling it 'jumps'.

Probably something very simple! Any ideas?


问:
jquery unable to log input value
HTML:

```<code><div id="Background">
    <input id="search-Bar" type="text">
    <button id="SearchButton">Search</button>
</div>

var name = $("#search-Bar").val();
$("#SearchButton").on("click", function() {
    console.log(name);
});
</code>```

i am trying to get the value of the input using .val() but when i console log it turns out blank every time, can someone please tell me how to fix this?

答:
$("#SearchButton").on("click", function() {
  var name = $("#search-Bar").val(); //this should be here

  console.log(name);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Background">
  <input id="search-Bar" type="text">
  <button id="SearchButton"> Search </button></code>```

Title: jquery unable to log input value

Body:
HTML:

    <input id="search-Bar" type="text">
    <button id="SearchButton">Search</button>

var name = $("#search-Bar").val();
$("#SearchButton").on("click", function() {
    console.log(name);
});

i am trying to get the value of the input using .val() but when i console log it turns out blank every time, can someone please tell me how to fix this?

Body:
$("#SearchButton").on("click", function() {
  var name = $("#search-Bar").val(); //this should be here

  console.log(name);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Background">
  <input id="search-Bar" type="text">
  <button id="SearchButton"> Search </button>


问:
How do I convert the date from one format to another date object in another format without using any deprecated classes?
I'd like to convert a date in date1 format to a date object in date2 format.</p>

```<code>    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
    Calendar cal = Calendar.getInstance();
    cal.set(2012, 8, 21);
    Date date = cal.getTime();
    Date date1 = simpleDateFormat.parse(date);
    Date date2 = simpleDateFormat.parse(date1);
    println date1
    println date2
</code>```

答:
Hope this will help someone.</p>

```<code> public static String getDate(
        String date, String currentFormat, String expectedFormat)
throws ParseException {
    // Validating if the supplied parameters is null
    if (date == null || currentFormat == null || expectedFormat == null ) {
        return null;
    }
    // Create SimpleDateFormat object with source string date format
    SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
    // Parse the string into Date object
    Date dateObj = sourceDateFormat.parse(date);
    // Create SimpleDateFormat object with desired date format
    SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
    // Parse the date into another format
    return desiredDateFormat.format(dateObj).toString();
}
</code>```

Body:
I'd like to convert a date in date1 format to a date object in date2 format.

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
    Calendar cal = Calendar.getInstance();
    cal.set(2012, 8, 21);
    Date date = cal.getTime();
    Date date1 = simpleDateFormat.parse(date);
    Date date2 = simpleDateFormat.parse(date1);
    println date1
    println date2

Body:
Hope this will help someone.

 public static String getDate(
        String date, String currentFormat, String expectedFormat)
throws ParseException {
    // Validating if the supplied parameters is null
    if (date == null || currentFormat == null || expectedFormat == null ) {
        return null;
    }
    // Create SimpleDateFormat object with source string date format
    SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
    // Parse the string into Date object
    Date dateObj = sourceDateFormat.parse(date);
    // Create SimpleDateFormat object with desired date format
    SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
    // Parse the date into another format
    return desiredDateFormat.format(dateObj).toString();
}


答:
The name variable is being set only once on script load, when it's actually empty and stays at this state.

Declare it inside the functions body to get a new, actual value with every function call.

$("#SearchButton").on("click", function() {
  var name = $("#search-Bar").val();
  console.log(name);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Background"></div>
<input id="search-Bar" type="text">
<button id="SearchButton"> Search </button></code>```

Title: jquery unable to log input value

Body:
The name variable is being set only once on script load, when it's actually empty and stays at this state.

Declare it inside the functions body to get a new, actual value with every function call.

$("#SearchButton").on("click", function() {
  var name = $("#search-Bar").val();
  console.log(name);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Background"></div>
<input id="search-Bar" type="text">
<button id="SearchButton"> Search </button>


问:
Asynchronous Stored Procedure call in C#
I am new to C#. I'm trying to make an Asynchronous Stored Procedure call in my MVC ASP.net application.

This is what my code looks like:

```<code>public void RevalidateRule(int ruleKey)
    {
        var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
    }
</code>```

It has to be triggered whenever I press the save button in my view. However, it doesn't seem to be doing anything.

Does anyone have an idea?

答:
please write try catch in code.
where exactly you will get exception if anything going wrong in Store procedure</p>

```<code>try
{
  var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
}
catch(exception ex)
{

}
</code>```

Body:
I am new to C#. I'm trying to make an Asynchronous Stored Procedure call in my MVC ASP.net application.

This is what my code looks like:

public void RevalidateRule(int ruleKey)
    {
        var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
    }

It has to be triggered whenever I press the save button in my view. However, it doesn't seem to be doing anything.

Does anyone have an idea?

Body:
please write try catch in code.
where exactly you will get exception if anything going wrong in Store procedure

try
{
  var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
}
catch(exception ex)
{

}


问:
Should you lock resources when reading values?
When doing thread synchronization in C# should I also lock an object when I read a value or just changing it?

for example I have Queue<T> object. Should I just lock it when doing the Enqueue and Dequeue or should I also lock it when checking values like Count?

答:
Depends on what you want to do with lock. Usually this kind of locking needs a reader/writer locking mechanism.

Readers/writers locking means that readers share a lock, so you can have multiple readers reading the collection simultaneously, but to write, you should acquire an exclusive lock.

OwnerDisplayName: Superdumbell

OwnerDisplayName: Mehrdad Afshari


答:
Why is that so? From my understanding you can't pass const to
  non-const since what would require write-access.

Yes and no, it is correct that you can't write to a const variable but that's not what's happening here.

```<code>return grade(midterm, final, median(hw));
</code>```

The call here to median does the work for us. median expects a std::vector and the compiler passes it one under the hood. It copies over the vector referenced by the const & and passes that copy to median. Remember, the compiler only needs read access to copy, not write, which is exactly what hw gives us.

Title: Passing const to function with non-const parameter

Body:
I'am following accelerated C++ book but i'am confused with the source code they provide. My confusion  involves functions double grade(double midterm, double final, const vector<double>& hw) and double median(vector<double> vec).
It says in the comment that the grade function does not copy it's argument because the median function does. Why is that so?
From my understanding you can't pass const to non-const since what would require write-access.

Here's the code:

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::domain_error;
using std::endl;
using std::istream;
using std::ostream;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;

// compute the median of a `vector<double>'
// note that calling this function copies the entire argument `vector'
double median(vector<double> vec)
{
#ifdef _MSC_VER
    typedef std::vector<double>::size_type vec_sz;
#else
    typedef vector<double>::size_type vec_sz;
#endif

    vec_sz size = vec.size();
    if (size == 0)
        throw domain_error("median of an empty vector");

    sort(vec.begin(), vec.end());

    vec_sz mid = size/2;

    return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}

// compute a student's overall grade from midterm and final exam grades and homework grade
double grade(double midterm, double final, double homework)
{
    return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}

// compute a student's overall grade from midterm and final exam grades
// and vector of homework grades.
// this function does not copy its argument, because `median' does so for us.
double grade(double midterm, double final, const vector<double>& hw)
{
    if (hw.size() == 0)
        throw domain_error("student has done no homework");
    return grade(midterm, final, median(hw));
}

// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
        // get rid of previous contents
        hw.clear();

        // read homework grades
        double x;
        while (in >> x)
            hw.push_back(x);

        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}

int main()
{
    // ask for and read the student's name
    cout << "Please enter your first name: ";
    string name;
    cin >> name;
    cout << "Hello, " << name << "!" << endl;

    // ask for and read the midterm and final grades
    cout << "Please enter your midterm and final exam grades: ";
    double midterm, final;
    cin >> midterm >> final;

    // ask for the homework grades
    cout << "Enter all your homework grades, "
            "followed by end-of-file: ";

    vector<double> homework;

    // read the homework grades
    read_hw(cin, homework);

    // compute and generate the final grade, if possible
    try {
        double final_grade = grade(midterm, final, homework);
        streamsize prec = cout.precision();
        cout << "Your final grade is " << setprecision(3)
             << final_grade << setprecision(prec) << endl;
    } catch (domain_error) {
        cout << endl << "You must enter your grades.  "
            "Please try again." << endl;
        return 1;
    }

    return 0;
}

Body:
Why is that so? From my understanding you can't pass const to
  non-const since what would require write-access.

Yes and no, it is correct that you can't write to a const variable but that's not what's happening here.

return grade(midterm, final, median(hw));

The call here to median does the work for us. median expects a std::vector and the compiler passes it one under the hood. It copies over the vector referenced by the const & and passes that copy to median. Remember, the compiler only needs read access to copy, not write, which is exactly what hw gives us.


问:
Trying to change the content of a page without reloading after passing a value to a variable on submit
Retrieving data from an API using Php. This my code:

```<code><?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>
</code>```

Html code:

```<code> <div id="get_text" >
<div><em>CHECK YOUR POINTS</em></div>
<div ><em>Enter mobile number</em></div>
<form action='' method='POST' id='search-form'>
<div>
<input type='search' name='search' id="sub1" />
</div>
<div>
<button type="submit"  id="sub" >Submit</button>
</div>
</form>
</div>

<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
</code>```

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

```<code> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
    $("#show_text").hide();
    $("#sub").on("click", function (e) {
        e.preventDefault();
        $.ajax({
            url: 'aristocracy-test.php',
            method: 'POST',
            data : $("#get_text").serialize(), //pass your form elements as key-value pairs
            success: function (response) {
                $("#show_text").show();
                $("#get_text").hide();
            }
        });
    });
});
 </script>
</code>```

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.

答:
Just add $("#show_text").html(response); in your ajax success method.

Or perhaps you should try this $('input[name=points]').val(response);

Body:
Retrieving data from an API using Php. This my code:

<?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>

Html code:

CHECK YOUR POINTS

Enter mobile number

<form action='' method='POST' id='search-form'>

<input type='search' name='search' id="sub1" />

<button type="submit"  id="sub" >Submit</button>

</form>

YOUR CURRENT POINTS ARE

<form action='' method='GET' id='result'>

<input type='text' name='points' value="<?php echo $inner; ?>"/>

</form>

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.


问:
Go Golang to serve a specific html file
```<code>http.Handle("/", http.FileServer(http.Dir("static")))
</code>```

Serves the html file in static directory.

Is there any way in Go that we can specify the html file to serve?

Something like render_template in Flask

I want to do something like:

```<code>http.Handle("/hello", http.FileServer(http.Dir("static/hello.html")))
</code>```

答:
You could use http.StripPrefix

Like this:

```<code>http.Handle("/hello/", http.StripPrefix("/hello/",http.FileServer(http.Dir("static"))))
</code>```

Title: Go Golang to serve a specific html file

Body:
http.Handle("/", http.FileServer(http.Dir("static")))

Serves the html file in static directory.

Is there any way in Go that we can specify the html file to serve?

Something like render_template in Flask

I want to do something like:

http.Handle("/hello", http.FileServer(http.Dir("static/hello.html")))

Body:
You could use http.StripPrefix

Like this:

http.Handle("/hello/", http.StripPrefix("/hello/",http.FileServer(http.Dir("static"))))


问:
Comparing Strings in String array
This code works perfectly for numbers but not for characters. Can someone tell me why an give me suggestions?</p>

```<code>package optimum.output;
import java.util.Scanner;
public class OptimumOutput {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    // First of all we have to get what the runs planned for next month. To get that there should be separate method

    plannedruns();

}
//plannedruns method is ment to get next month planned runs
 static String[] plannedruns(){

    String[] runs=new String[50];
    //Writes instructions in console
    System.out.println("Instructions"+"\n"+"Please enter Job ID's that planned for this month (Mazimum 50 jobs)"+"\n"+"At the end of the list, enter 0");
    // Scanner to take inputs
    Scanner scanner = new Scanner(System.in);
    int i=0;
    //takes job ID inputs
    for(int position=0;position<50;position++){
        System.out.print("Enter Job ID for Job " + ++i +" : ");
        runs[position]=null;
        runs[position] = scanner.nextLine();
        try{
                if (Integer.parseInt(runs[position])==0){
                break;
            }
            for(int j=0;position>j;j++){
                System.out.print(runs[j].equalsIgnoreCase(runs[position]));
                if(runs[j].equals(runs[position])){
                    System.out.println("One job repeated. Please enter the run correctly");
                    --i;
                    --position;
                }
            }

        }
        catch(Exception e){
        }
    }
    //Print before printing job details
    System.out.println("These are the entered jobs for this month");
    i=0;
    for(int position=0;position<50;){
        try{
            if (Integer.parseInt(runs[position])==0){
                break;
            }
        }
        catch(Exception e){
        }
        System.out.println("Job No."+ ++i +" is "
                + ""+runs[position++]);

    }
    System.out.println("end");
    return runs;
  }
}
</code>```

答:
I don't know why earlier it wasn't working. But few non related changes it is completely working.</p>

```<code>static String[] plannedruns(){
         //job ID is taken as String
        String[] runs=new String[50];
        //Writes instructions in console
        System.out.println("Instructions"+"\n"+"Please enter Job ID's that planned for this month (Mazimum 50 jobs)"+"\n"+"At the end of the list, enter 0");
        // Scanner to take inputs
        Scanner scanner = new Scanner(System.in);
        int i=0;
        //takes job ID inputs
        for(int position=0;position<50;position++){
            System.out.print("Enter Job ID for Job " + ++i +" : ");
            runs[position]=null;
            runs[position] = scanner.nextLine();
            try{
                    if (runs[position].equalsIgnoreCase("end")){
                        runs[position]=null;
                    break;
                }
                for(int j=0;position>j;j++){
                    //1
                    System.out.print(runs[j].equals(runs[position]));
                    if(runs[j].equals(runs[position])){
                        System.out.println("One job repeated. Please enter the run correctly");
                        --i;
                        --position;
                    }
                }

            }
            catch(Exception e){
            }
        }
        //Print before printing job details
        System.out.println("These are the entered jobs for this month");
        i=0;
        for(int position=0;position<50;){
            try{
                if (runs[position]==null){
                    break;
                }
            }
            catch(Exception e){
            }
            System.out.println("Job No."+ ++i +" is "
                    + ""+runs[position++]);

        }
        System.out.println("end");
        return runs;
    }
</code>```

Title: Comparing Strings in String array

Body:
This code works perfectly for numbers but not for characters. Can someone tell me why an give me suggestions?

package optimum.output;
import java.util.Scanner;
public class OptimumOutput {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    // First of all we have to get what the runs planned for next month. To get that there should be separate method

    plannedruns();

}
//plannedruns method is ment to get next month planned runs
 static String[] plannedruns(){

    String[] runs=new String[50];
    //Writes instructions in console
    System.out.println("Instructions"+"\n"+"Please enter Job ID's that planned for this month (Mazimum 50 jobs)"+"\n"+"At the end of the list, enter 0");
    // Scanner to take inputs
    Scanner scanner = new Scanner(System.in);
    int i=0;
    //takes job ID inputs
    for(int position=0;position<50;position++){
        System.out.print("Enter Job ID for Job " + ++i +" : ");
        runs[position]=null;
        runs[position] = scanner.nextLine();
        try{
                if (Integer.parseInt(runs[position])==0){
                break;
            }
            for(int j=0;position>j;j++){
                System.out.print(runs[j].equalsIgnoreCase(runs[position]));
                if(runs[j].equals(runs[position])){
                    System.out.println("One job repeated. Please enter the run correctly");
                    --i;
                    --position;
                }
            }

        }
        catch(Exception e){
        }
    }
    //Print before printing job details
    System.out.println("These are the entered jobs for this month");
    i=0;
    for(int position=0;position<50;){
        try{
            if (Integer.parseInt(runs[position])==0){
                break;
            }
        }
        catch(Exception e){
        }
        System.out.println("Job No."+ ++i +" is "
                + ""+runs[position++]);

    }
    System.out.println("end");
    return runs;
  }
}

Body:
I don't know why earlier it wasn't working. But few non related changes it is completely working.

static String[] plannedruns(){
         //job ID is taken as String
        String[] runs=new String[50];
        //Writes instructions in console
        System.out.println("Instructions"+"\n"+"Please enter Job ID's that planned for this month (Mazimum 50 jobs)"+"\n"+"At the end of the list, enter 0");
        // Scanner to take inputs
        Scanner scanner = new Scanner(System.in);
        int i=0;
        //takes job ID inputs
        for(int position=0;position<50;position++){
            System.out.print("Enter Job ID for Job " + ++i +" : ");
            runs[position]=null;
            runs[position] = scanner.nextLine();
            try{
                    if (runs[position].equalsIgnoreCase("end")){
                        runs[position]=null;
                    break;
                }
                for(int j=0;position>j;j++){
                    //1
                    System.out.print(runs[j].equals(runs[position]));
                    if(runs[j].equals(runs[position])){
                        System.out.println("One job repeated. Please enter the run correctly");
                        --i;
                        --position;
                    }
                }

            }
            catch(Exception e){
            }
        }
        //Print before printing job details
        System.out.println("These are the entered jobs for this month");
        i=0;
        for(int position=0;position<50;){
            try{
                if (runs[position]==null){
                    break;
                }
            }
            catch(Exception e){
            }
            System.out.println("Job No."+ ++i +" is "
                    + ""+runs[position++]);

        }
        System.out.println("end");
        return runs;
    }


问:
PjSIP Callling it from unknown/external thread
I'm trying to build pjsip and make a basic phone call by building a cordova plugin in Android. The following function is in a cordova plugin named

public class PJSIP extends CordovaPlugin{ .... }

```<code>  private void makeCall(String number,String hostip ) {

String buddy_uri = "sip:"+number+"@"+hostip;
MyAccount account = null;

AccountConfig accCfg = null;
accCfg = new AccountConfig();
accCfg.setIdUri("sip:localhost");
accCfg.getNatConfig().setIceEnabled(true);
accCfg.getVideoConfig().setAutoTransmitOutgoing(true);
accCfg.getVideoConfig().setAutoShowIncoming(true);

MyAccount acc = new MyAccount(accCfg);
account = acc;

MyCall call = new MyCall(account, -1);
CallOpParam prm = new CallOpParam(true);

try {
  call.makeCall(buddy_uri, prm);

} catch (Exception e) {
  call.delete();
  return;
}

currentCall = call;
</code>```

}

What I receive as an error is the following:

A/libc: ../src/pj/os_core_unix.c:692: pj_thread_this: assertion
  "!"Calling pjlib from unknown/external thread. You must " "register
  external threads with pj_thread_register() " "before calling any pjlib
  functions."" failed

I was checking around and it seems that there is an issue with the garbage collector but I'm not sure how to fix it.

Thanks

答:
In pjsip, every call must come from a thread known to pjsip.

On your EndPoint object there is a method that helps you with that.
Basically, I just created a static method checkThread which helps me registering the currentThread.

I call this method at the beginning of every method that accesses pjsip objects.
You need to synchronize this method.

```<code>public static synchronized void checkThread() {
    try {

        if (mEndpoint != null && !mEndpoint.libIsThreadRegistered())
            mEndpoint.libRegisterThread(Thread.currentThread().getName());

    } catch (Exception e) {
        Log.w("SIP", "Threading: libRegisterThread failed: " + e.getMessage());
    }
}
</code>```

And now each of your methods that access sip objects has to look like:

```<code>public void makeCall(String number) {
    checkThread();
    //...do your stuff...
}
</code>```

Hope this helps, Cheers.

Body:
I'm trying to build pjsip and make a basic phone call by building a cordova plugin in Android. The following function is in a cordova plugin named

public class PJSIP extends CordovaPlugin{ .... }

  private void makeCall(String number,String hostip ) {

String buddy_uri = "sip:"+number+"@"+hostip;
MyAccount account = null;

AccountConfig accCfg = null;
accCfg = new AccountConfig();
accCfg.setIdUri("sip:localhost");
accCfg.getNatConfig().setIceEnabled(true);
accCfg.getVideoConfig().setAutoTransmitOutgoing(true);
accCfg.getVideoConfig().setAutoShowIncoming(true);

MyAccount acc = new MyAccount(accCfg);
account = acc;

MyCall call = new MyCall(account, -1);
CallOpParam prm = new CallOpParam(true);

try {
  call.makeCall(buddy_uri, prm);

} catch (Exception e) {
  call.delete();
  return;
}

currentCall = call;

}

What I receive as an error is the following:

A/libc: ../src/pj/os_core_unix.c:692: pj_thread_this: assertion
  "!"Calling pjlib from unknown/external thread. You must " "register
  external threads with pj_thread_register() " "before calling any pjlib
  functions."" failed

I was checking around and it seems that there is an issue with the garbage collector but I'm not sure how to fix it.

Thanks

Body:
In pjsip, every call must come from a thread known to pjsip.

On your EndPoint object there is a method that helps you with that.
Basically, I just created a static method checkThread which helps me registering the currentThread.

I call this method at the beginning of every method that accesses pjsip objects.
You need to synchronize this method.

public static synchronized void checkThread() {
    try {

        if (mEndpoint != null && !mEndpoint.libIsThreadRegistered())
            mEndpoint.libRegisterThread(Thread.currentThread().getName());

    } catch (Exception e) {
        Log.w("SIP", "Threading: libRegisterThread failed: " + e.getMessage());
    }
}

And now each of your methods that access sip objects has to look like:

public void makeCall(String number) {
    checkThread();
    //...do your stuff...
}

Hope this helps, Cheers.


答:
You need to get the value using : $('#search-Bar').val()

var name = $("#search-Bar").val();
$("#SearchButton").on("click", function(){
    console.log($('#search-Bar').val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Background">
<input id="search-Bar" type="text">
<button id="SearchButton"> Search </button></code>```

Title: jquery unable to log input value

Body:
You need to get the value using : $('#search-Bar').val()

var name = $("#search-Bar").val();
$("#SearchButton").on("click", function(){
    console.log($('#search-Bar').val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Background">
<input id="search-Bar" type="text">
<button id="SearchButton"> Search </button>


问:
Getting another table's string via it's id
I have two tables, but since I can't format them here, you can check the table on this imgur img

The wildcard roles includes strings like department.* or blogger.department.*

I'm trying to create a role/permission inheritance system but i'm stuck on creating a many-to-many relationship

I've tried to use eloquent but since "wildcards" can't be/aren't a model , I can't use eloquent. So I tried to use the DB Facade but I'm not very good with SQL/DB so I've honestly got no clue on how to do this.

Here's what I need

Get the role ID (eg: admin = 1)

Get all wildcard_roles from the table role_wildcards by the Role ID

Return a collection of all the wildcard strings

Notes

It doesn't have to use eloquent, it can use the DB facade

答:
It was actually quite simple after playing around

```<code>DB::table('role_wildcards')->where('parent_role_id', $this->id)->get();
</code>```

Thought it'd be much more complicated

Body:
It was actually quite simple after playing around

DB::table('role_wildcards')->where('parent_role_id', $this->id)->get();

Thought it'd be much more complicated


问:
Access variables returned from function in django view with name of variable
I have a view in django that has a filter that uses two dates. I want to calculate the dates in a separate function to tidy it up a bit and return them to the view.

```<code>def index(request):
    function = month()
    objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh!
    context = {
        "objectcount": objectcount,
    }
    return render(request, 'entry/index.html', context)

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)

    return first_of_month, last_of_month
</code>```

This works fine, but I have to access the variables using function[0] and function[1].

How can I pass these variables so they are accessed from the index view using names - like first_of_month and last_of_month?

答:
Pass them as tuples

return (first_of_month, last_of_month)

and access it via index.

pass them as a dictionary like

var ={"a":a,"b":b}
return var

Body:
I have a view in django that has a filter that uses two dates. I want to calculate the dates in a separate function to tidy it up a bit and return them to the view.

def index(request):
    function = month()
    objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh!
    context = {
        "objectcount": objectcount,
    }
    return render(request, 'entry/index.html', context)

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)

    return first_of_month, last_of_month

This works fine, but I have to access the variables using function[0] and function[1].

How can I pass these variables so they are accessed from the index view using names - like first_of_month and last_of_month?


问:
Connect Unity to C++ WinSocket WITHOUT System.Net.Sockets
Windows 10, Unity 5.5.2 - note that this implicitly restricts .Net to version 3.5.

I have a C++ application that I'm trying to connect to a Unity application over the air.  I wish to continually send byte arrays from C++ to Unity.  The catch is that, for the device (Hololens, in my case) that I wish to deploy to, System.Net.Sockets is not available.

In C++ I instantiate a socket using the Winsock2.h header.  I can use UDP or TCP, it doesn't matter to me for my application.

In Unity, I wish to use either Unity.Networking or UWP to establish the connection.

To use UWP, I've only seen examples that use the async keyword, which is a headache to use in Unity (and I'm honestly not sure if it's possible).

Meanwhile, Unity.Networking seems to use its own protocol, and I'm not sure how to interface it with my C++ application.

Can anyone provide a very simple, concise way of accomplishing this task in Unity?

EDIT: Using Threads is difficult on the Hololens as well, async tasks seem to be a difficult proposition as well.

答:
We have build a C++ to Unity UDP client using Threads and https://github.com/nickgravelyn/UnityToolbag/tree/master/Dispatcher to make it 'Thread safe'.

According to https://forums.hololens.com/discussion/578/hololens-udp-server you could use Windows.Networking.Sockets


问:
Install4j: SQL Script and statement delimiter
I try to run several SQL-Statements in an SQL Script action for an Oracle dbms inside an installer and as part of a JDBC container action.
The script is encoded as UTF-8, and contains several statements, delimited by ";" and a new line between each statement, like this

```<code>statement 1;
statement 2;
...
</code>```

The statements contain installer variables that are replaced before execution. I used the semicolon as a statement separator in the SQL script action.
The first statement throws an error
Error executing script line "CREATE user testconuser identified by xxx TEMPORARY TABLESPACE temp;",

error message: "ORA-00911: invalid character"

The statement itselfs works fine within SQLPLUS, but the problems seems to be the semicolon, that is still part of the statement executed by install4j.
In a JDBC sql statement, semicolons are not valid.
I also tried to remove the semicolons from the statements and used "\n" as statement delimiter, but then the sql script actions fires all sql statements within the script at once, so it looks like the "\n" is not recognized.
I am using install4j 6.1.5 build 6349. The platform is windows and the sql script is build on windows.
Any idea what I should change?
Any help would be highly appreciated, thanks a lot in advance,
Alex

答:
I used the semicolon as a statement separator in the SQL script action. The first statement throws an error Error executing script line

and

I also tried to remove the semicolons from the statements and used "\n" as statement delimiter

Both are bugs in 6.1.5 and will be fixed in 6.1.6. Please contact support@ej-technologies.com to get a build where you can verify that this will work for you.

Body:
I try to run several SQL-Statements in an SQL Script action for an Oracle dbms inside an installer and as part of a JDBC container action.
The script is encoded as UTF-8, and contains several statements, delimited by ";" and a new line between each statement, like this

statement 1;
statement 2;
...

The statements contain installer variables that are replaced before execution. I used the semicolon as a statement separator in the SQL script action.
The first statement throws an error
Error executing script line "CREATE user testconuser identified by xxx TEMPORARY TABLESPACE temp;",

error message: "ORA-00911: invalid character"

The statement itselfs works fine within SQLPLUS, but the problems seems to be the semicolon, that is still part of the statement executed by install4j.
In a JDBC sql statement, semicolons are not valid.
I also tried to remove the semicolons from the statements and used "\n" as statement delimiter, but then the sql script actions fires all sql statements within the script at once, so it looks like the "\n" is not recognized.
I am using install4j 6.1.5 build 6349. The platform is windows and the sql script is build on windows.
Any idea what I should change?
Any help would be highly appreciated, thanks a lot in advance,
Alex


问:
TypeScript type casting issue - example
I am faced with a "type casting interface"-issue in TypeScript. I dont understand why my interface is not interfering! Please see my example below:</p>

```<code>interface IProduct {
    age  : number;
    price : number;
}

class Product{
    public age: number = 22;
}

let products : Array<Product> = [new Product(), new Product()];
let products_stringify = JSON.stringify(products);
let products_parsed = JSON.parse(products_stringify);

**// Now my problem starts here....**

// Why interface IProduct does not interfere ?
let firstProduct1: IProduct = products_parsed[0];
console.dir(typeof products_parsed[0]);// -> object

// When i do a typecasting with <object> the interface interferes, and throws an error!
let firstProduct2 : IProduct = <object>products_parsed[0];
console.dir(typeof products_parsed[0]);// -> object
</code>```

答:
Stringifying the products array and parsing it again makes it lose any type information you had before. That's why it is not read back as you'd expect.

The return type of JSON.parse is any.

Also an object of type object can't be assign can't be assigned to IProduct since it's missing the 2 properties defined on that interface. object is an empty objecct {}.

Title: TypeScript type casting issue - example

Body:
I am faced with a "type casting interface"-issue in TypeScript. I dont understand why my interface is not interfering! Please see my example below:

interface IProduct {
    age  : number;
    price : number;
}

class Product{
    public age: number = 22;
}

let products : Array<Product> = [new Product(), new Product()];
let products_stringify = JSON.stringify(products);
let products_parsed = JSON.parse(products_stringify);

**// Now my problem starts here....**

// Why interface IProduct does not interfere ?
let firstProduct1: IProduct = products_parsed[0];
console.dir(typeof products_parsed[0]);// -> object

// When i do a typecasting with <object> the interface interferes, and throws an error!
let firstProduct2 : IProduct = <object>products_parsed[0];
console.dir(typeof products_parsed[0]);// -> object


问:
SetWaitableTimer and daylight saving adjustments
For the purpose of a mini-scheduler inside my app I need to be able to schedule an event at some absolute local time.

For instance, I may want to schedule it for 7 AM on November 5, 2017. As anyone living in US probably knows, that is the night when the daylight saving ends at 2 AM.

So I use the following method:

```<code>//ERROR CHECKS ARE OMITTED FOR BREVITY
HANDLE hTimer = ::CreateWaitableTimer(NULL, FALSE, NULL);

//Nov 5, 2017 at 7:00 AM
SYSTEMTIME stLocal = {2017, 11, 0, 5, 7, 0, 0, 0};
SYSTEMTIME stUTC = {0};
::TzSpecificLocalTimeToSystemTime(NULL, &stLocal, &stUTC);

FILETIME ftUTC = {0};
::SystemTimeToFileTime(&stUTC, &ftUTC);

//Set timer
::SetWaitableTimer(hTimer, (LARGE_INTEGER*)&ftUTC, 0, NULL, NULL, FALSE);

//Wait for it
::WaitForSingleObject(hTimer, INFINITE);

::CloseHandle(hTimer);
</code>```

Since the SetWaitableTimer API takes time in UTC form, the method above will be off by 1 hour because of the local-to-UTC conversion done before DST commences on Nov. 5th.

So assuming any arbitrary absolute time for the timer, how do you factor in the daylight saving adjustment?

答:
You do not have to change your code to factor in the daylight saving adjustment, the TzSpecificLocalTimeToSystemTime API will already do that for you.

Please note that for future timestamps, the data Windows has for the DST->STD (and vice versa) transitions may be inaccurate. The government may choose to use a different moment for that in the future. Also, sometimes a government may choose to use a whole different time zone, that has happened! For timestamps in the past you probably will get good results, but you will never know how complete Windows' database is.

So, you don't have to change your code, but be aware of the fact that you still may get inaccurate results.

Body:
For the purpose of a mini-scheduler inside my app I need to be able to schedule an event at some absolute local time.

For instance, I may want to schedule it for 7 AM on November 5, 2017. As anyone living in US probably knows, that is the night when the daylight saving ends at 2 AM.

So I use the following method:

//ERROR CHECKS ARE OMITTED FOR BREVITY
HANDLE hTimer = ::CreateWaitableTimer(NULL, FALSE, NULL);

//Nov 5, 2017 at 7:00 AM
SYSTEMTIME stLocal = {2017, 11, 0, 5, 7, 0, 0, 0};
SYSTEMTIME stUTC = {0};
::TzSpecificLocalTimeToSystemTime(NULL, &stLocal, &stUTC);

FILETIME ftUTC = {0};
::SystemTimeToFileTime(&stUTC, &ftUTC);

//Set timer
::SetWaitableTimer(hTimer, (LARGE_INTEGER*)&ftUTC, 0, NULL, NULL, FALSE);

//Wait for it
::WaitForSingleObject(hTimer, INFINITE);

::CloseHandle(hTimer);

Since the SetWaitableTimer API takes time in UTC form, the method above will be off by 1 hour because of the local-to-UTC conversion done before DST commences on Nov. 5th.

So assuming any arbitrary absolute time for the timer, how do you factor in the daylight saving adjustment?


问:
Angular 2 : Directives and providers in @component decorator
Hi i am new to Angular 2, i referred many other similar post but nothing helped me.

Below are my Queries

When to use Directives and providers parameters in @component decorator? Do i need to pass component inside any of this parameters while i import component

I made a http subscribe call inside oninit() but it never's gets called when page loads I get undefined value in console. how do i call it when a page loads.

ngOnInit() {
    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
      });
      console.log(this.loginData);
  }```

how do i communicate between 2 components while routing?

What is  the difference between Directive and Component

答:
-- When to use Directives and providers parameters in @component decorator?

Directives , when you want to use directives , you can load those inside that , but that was in older version.

Providers ,  when you want to load services in your components or modules

-- First of all change your code to this :

```<code>ngOnInit() {
    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
        console.log(this.loginData);
      });

  }
</code>```

This is async call , so you will not get data in sequence , your console log will not called after http call finishes , it will be called as soon as the api called, so you have to log that inside subscribe method.

-- how do i communicate between 2 components while routing?

By using CommonService and provide it at route level or as per the project structure and your requirements.

Body:
Hi i am new to Angular 2, i referred many other similar post but nothing helped me.

Below are my Queries

When to use Directives and providers parameters in @component decorator? Do i need to pass component inside any of this parameters while i import component

I made a http subscribe call inside oninit() but it never's gets called when page loads I get undefined value in console. how do i call it when a page loads.

ngOnInit() {
    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
      });
      console.log(this.loginData);
  }

how do i communicate between 2 components while routing?

What is  the difference between Directive and Component

Body:
-- When to use Directives and providers parameters in @component decorator?

Directives , when you want to use directives , you can load those inside that , but that was in older version.

Providers ,  when you want to load services in your components or modules

-- First of all change your code to this :

ngOnInit() {
    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
        console.log(this.loginData);
      });

  }

This is async call , so you will not get data in sequence , your console log will not called after http call finishes , it will be called as soon as the api called, so you have to log that inside subscribe method.

-- how do i communicate between 2 components while routing?

By using CommonService and provide it at route level or as per the project structure and your requirements.