问:
Can't load correct information from file
the problem with this bit of code is that it is not reading the .txt file correctly, I have provided a image of the .txt file while also providing the current output it is giving me. Any help would be welcomed.

```<code>#include <fstream>
#include <iostream>

using namespace std;
const int MAX_CHARS = 10;
const int MAX_STUDENTS = 1;
class File
{
public:
void openFile()
{
    ifstream input_file("UserPass.txt", ios::binary);
    if (input_file.fail())
    {
        cout << "Could not open file" << endl;
    }
    else
    {
        if (!input_file.read((char*)&studLoaded, sizeof(studLoaded)))
        {
            cout << "Could not read file" << endl;
        }
        else
        {
            streamsize bytesRead = input_file.gcount();
            if (bytesRead != sizeof(studLoaded))
            {
                cout << "Could not read expected number of bytes" << endl;
            }
            else
            {
                input_file.read((char*)&studLoaded, sizeof(studLoaded));
                input_file.close();
            }

        }
    }
};

void displayFile()
{
    for (size_t i = 0; i < MAX_STUDENTS; i++)
    {
        cout << "Username: " << studLoaded[i].username << endl;
        cout << "Password: " << studLoaded[i].password << endl;
        cout << "Verf ID:" << studLoaded[i].verfID << endl;
    }
}

private:

typedef struct
{
    char username[MAX_CHARS];
    char password[MAX_CHARS];
    int verfID;

}student_t;

student_t studLoaded[MAX_STUDENTS];
};
</code>```

The main is just calling these functions

```<code>File f;
f.openFile();
f.displayFile();
</code>```

This is what is in the .txt file

This is the current output I have. i have tried numerous of things but I can't seem to get it to work. This is the current output I am getting.

答:
Continuing from my comment above, given the input file you show is a TEXT file, you don't want to read as ios::binary. Why? When reading binary input, all text formatting character have no special meaning. You are simply reading bytes of data, and '\n' (value: 0xa) is just another byte in the stream. When reading text, you want to use the formatting characters in the text file to tell you when you have read a line or a word.

Further, as commented by @sheff were you to read in binary, it is up to you to know beforehand how many bytes you will read into username or password and where the verfID int is located in the stream. The link he provided gives a good explanation of the process C++ FAQ: Serialization and Unserialization. For writing binary data, especially when the data is in a struct, unless you serialize, there is no guarantee of portability between compilers due to where padding bits may be inserted into the struct.

So, unless you have a requirement to read and write in binary, you are better served reading a text file as text.

You can make the reading and outputting of your student data much simpler by overloading the << and >> operators to read a students worth of data at a time from your input stream as text. For example to overload the << operator to read a student_t worh of data, you can simply add a member function to your class:

```<code>    /* overload >> to read username, password, verfID from input stream */
    friend std::istream& operator >> (std::istream& is, passfile& pf)
    {
        student_t s {};     /* temporary struct student */

        /* attempt read of all 3 values (username, password, verfID) */
        if (is >> s.username >> s.password >> s.verfID) {
            /* handle storage of s here */
        }

        return is;  /* return stream state */
    }
</code>```

The benefit of using the overloaded operators not only reduces the custom input functions to have to write, but will reduce your main() considerably. For example:

```<code>int main (int argc, char **argv) {

    if (argc < 2) { /* verify at least 1 argument for filename */
        std::cerr << "error: password filename required.\n";
        return 1;
    }

    passfile pf (argv[1]);      /* declare instance of class, with filename */
    std::cout << pf;            /* output all student data */
}
</code>```

To put the pieces of your class together, avoid using fundamental types such as char[CONST] and instead what the STL provides such as std::string, std::vector (for your collection of student_t instead of a plain-old array of struct), etc. For your class, you will one additional container to force a unique verfID. You can write a function yourself to scan over all the collected student_t each time before insertion of a new student, or you can use std::unordered_set to do it for you in a much more efficient way.

So using the STL containers, you would simply need a std::vector<student_t> for your student information storage (instead of an array) and you would use std::unordered_set<int> to hash your verfID and enforce uniqueness. Your class private: data members could be something like:

```<code>class passfile {

    struct student_t {
        std::string username {}, password {};   /* user std:string istead */
        int verfID;
    };

    std::unordered_set<int> verfID;         /* require unique verfID before add */
    std::vector<student_t> students {};     /* use vector of struct for storage */
    ...
</code>```

For your public: members, you can use a constructor that takes the filename to read from as an argument, and then you would need only one helper-function in addition to the overloaded << and >> operators. The helper-function just loops taking input with the overloaded >> operator until you reach the end of file.

Your constructors really don't need to be any more than:

```<code>  public:

    passfile() {}
    passfile (std::string fname) { readpwfile (fname); }
    ...
</code>```

Your helper-function to repeatedly use the >> operator can be:

```<code>    void readpwfile (std::string fname)     /* read all students from filename */
    {
        std::ifstream f (fname);
        do
            f >> *this;                     /* use overloaded >> for read */
        while (f);
    }
    ...
</code>```

The remaining details are handled by the overloaded << and >> operators. Starting with the overload of <<, you really don't need it to do any more than loop over all students and output the data in the format you like, e.g.

```<code>    /* overload << to output all student data */
    friend std::ostream& operator << (std::ostream& os, const passfile& pf)
    {
        for (auto s : pf.students)
            os  << "Username: " << s.username << '\n'
                << "Password: " << s.password << '\n'
                << "Verf ID : " << s.verfID << "\n\n";

        return os;
    }
</code>```

(note: the friend keyword in used in the declaration within the class, if you defined the function elsewhere, you would omit friend before the definition)

Your overload of >> is where most of the work takes place, though the logic is simple. You declare a temporary student_t to read values into from the stream. If that succeeds, you do a quick lookup in your unordered_set to see if the verfID is already present. If it isn't you add the verfID to your unordered_set, and add your temporary student_t to your vector and your are done. If the verfID is a duplicate, you can issue a warning or error, e.g.

```<code>     /* overload >> to read username, password, verfID from input stream */
    friend std::istream& operator >> (std::istream& is, passfile& pf)
    {
        student_t s {};     /* temporary struct student */

        /* attempt read of all 3 values (username, password, verfID) */
        if (is >> s.username >> s.password >> s.verfID) {
            /* if verfID not already in verfID unordered_set */
            if (pf.verfID.find (s.verfID) == pf.verfID.end()) {
                pf.verfID.insert (s.verfID);    /* add verfID to unordered_set */
                pf.students.push_back (s);      /* add temp student to vector */
            }
            else    /* warn on duplicate verfID */
                std::cerr << "error: duplicate verfID " << s.verfID << ".\n";
        }

        return is;  /* return stream state */
    }
</code>```

Putting it altogether in a short example (which basically just adds the headers and closes the class for the information above), you would have:

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <unordered_set>

class passfile {

    struct student_t {
        std::string username {}, password {};   /* user std:string istead */
        int verfID;
    };

    std::unordered_set<int> verfID;         /* require unique verfID before add */
    std::vector<student_t> students {};     /* use vector of struct for storage */

  public:

    passfile() {}
    passfile (std::string fname) { readpwfile (fname); }

    void readpwfile (std::string fname)     /* read all students from filename */
    {
        std::ifstream f (fname);
        do
            f >> *this;                     /* use overloaded >> for read */
        while (f);
    }

    /* overload >> to read username, password, verfID from input stream */
    friend std::istream& operator >> (std::istream& is, passfile& pf)
    {
        student_t s {};     /* temporary struct student */

        /* attempt read of all 3 values (username, password, verfID) */
        if (is >> s.username >> s.password >> s.verfID) {
            /* if verfID not already in verfID unordered_set */
            if (pf.verfID.find (s.verfID) == pf.verfID.end()) {
                pf.verfID.insert (s.verfID);    /* add verfID to unordered_set */
                pf.students.push_back (s);      /* add temp student to vector */
            }
            else    /* warn on duplicate verfID */
                std::cerr << "error: duplicate verfID " << s.verfID << ".\n";
        }

        return is;  /* return stream state */
    }

    /* overload << to output all student data */
    friend std::ostream& operator << (std::ostream& os, const passfile& pf)
    {
        for (auto s : pf.students)
            os  << "Username: " << s.username << '\n'
                << "Password: " << s.password << '\n'
                << "Verf ID : " << s.verfID << "\n\n";

        return os;
    }
};

int main (int argc, char **argv) {

    if (argc < 2) { /* verify at least 1 argument for filename */
        std::cerr << "error: password filename required.\n";
        return 1;
    }

    passfile pf (argv[1]);      /* declare instance of class, with filename */
    std::cout << pf;            /* output all student data */
}
</code>```

Example Input File

Using your input file above as a TEXT file:

```<code>$ cat dat/userpass.txt
Adam
Pass121
1
Jamie
abc1
2
</code>```

Example Use/Output

Running the program and providing your input file as the first argument would result in:

```<code>$ ./bin/passwdfile dat/userpass.txt
Username: Adam
Password: Pass121
Verf ID : 1

Username: Jamie
Password: abc1
Verf ID : 2
</code>```

If you needed to add more students by prompting the user for information, then all that would be needed is:

```<code>int main (int argc, char **argv) {

    if (argc < 2) { /* verify at least 1 argument for filename */
        std::cerr << "error: password filename required.\n";
        return 1;
    }

    passfile pf (argv[1]);      /* declare instance of class, with filename */
    std::cout << pf;            /* output all student data */
}
</code>```0

(try it, and try adding with a duplicate verfID...)

Look things over and let me know if you have further questions. Using the containers the STL provides is by far the better approach to take rather than trying to reinvent the wheel on your own (you eliminate a lot of errors that way...)

Body:
the problem with this bit of code is that it is not reading the .txt file correctly, I have provided a image of the .txt file while also providing the current output it is giving me. Any help would be welcomed.

#include <fstream>
#include <iostream>

using namespace std;
const int MAX_CHARS = 10;
const int MAX_STUDENTS = 1;
class File
{
public:
void openFile()
{
    ifstream input_file("UserPass.txt", ios::binary);
    if (input_file.fail())
    {
        cout << "Could not open file" << endl;
    }
    else
    {
        if (!input_file.read((char*)&studLoaded, sizeof(studLoaded)))
        {
            cout << "Could not read file" << endl;
        }
        else
        {
            streamsize bytesRead = input_file.gcount();
            if (bytesRead != sizeof(studLoaded))
            {
                cout << "Could not read expected number of bytes" << endl;
            }
            else
            {
                input_file.read((char*)&studLoaded, sizeof(studLoaded));
                input_file.close();
            }

        }
    }
};

void displayFile()
{
    for (size_t i = 0; i < MAX_STUDENTS; i++)
    {
        cout << "Username: " << studLoaded[i].username << endl;
        cout << "Password: " << studLoaded[i].password << endl;
        cout << "Verf ID:" << studLoaded[i].verfID << endl;
    }
}

private:

typedef struct
{
    char username[MAX_CHARS];
    char password[MAX_CHARS];
    int verfID;

}student_t;

student_t studLoaded[MAX_STUDENTS];
};

The main is just calling these functions

File f;
f.openFile();
f.displayFile();

This is what is in the .txt file

This is the current output I have. i have tried numerous of things but I can't seem to get it to work. This is the current output I am getting.

Body:
Continuing from my comment above, given the input file you show is a TEXT file, you don't want to read as ios::binary. Why? When reading binary input, all text formatting character have no special meaning. You are simply reading bytes of data, and '\n' (value: 0xa) is just another byte in the stream. When reading text, you want to use the formatting characters in the text file to tell you when you have read a line or a word.

Further, as commented by @sheff were you to read in binary, it is up to you to know beforehand how many bytes you will read into username or password and where the verfID int is located in the stream. The link he provided gives a good explanation of the process C++ FAQ: Serialization and Unserialization. For writing binary data, especially when the data is in a struct, unless you serialize, there is no guarantee of portability between compilers due to where padding bits may be inserted into the struct.

So, unless you have a requirement to read and write in binary, you are better served reading a text file as text.

You can make the reading and outputting of your student data much simpler by overloading the << and >> operators to read a students worth of data at a time from your input stream as text. For example to overload the << operator to read a student_t worh of data, you can simply add a member function to your class:

    /* overload >> to read username, password, verfID from input stream */
    friend std::istream& operator >> (std::istream& is, passfile& pf)
    {
        student_t s {};     /* temporary struct student */

        /* attempt read of all 3 values (username, password, verfID) */
        if (is >> s.username >> s.password >> s.verfID) {
            /* handle storage of s here */
        }

        return is;  /* return stream state */
    }

The benefit of using the overloaded operators not only reduces the custom input functions to have to write, but will reduce your main() considerably. For example:

int main (int argc, char **argv) {

    if (argc < 2) { /* verify at least 1 argument for filename */
        std::cerr << "error: password filename required.\n";
        return 1;
    }

    passfile pf (argv[1]);      /* declare instance of class, with filename */
    std::cout << pf;            /* output all student data */
}

To put the pieces of your class together, avoid using fundamental types such as char[CONST] and instead what the STL provides such as std::string, std::vector (for your collection of student_t instead of a plain-old array of struct), etc. For your class, you will one additional container to force a unique verfID. You can write a function yourself to scan over all the collected student_t each time before insertion of a new student, or you can use std::unordered_set to do it for you in a much more efficient way.

So using the STL containers, you would simply need a std::vector<student_t> for your student information storage (instead of an array) and you would use std::unordered_set<int> to hash your verfID and enforce uniqueness. Your class private: data members could be something like:

class passfile {

    struct student_t {
        std::string username {}, password {};   /* user std:string istead */
        int verfID;
    };

    std::unordered_set<int> verfID;         /* require unique verfID before add */
    std::vector<student_t> students {};     /* use vector of struct for storage */
    ...

For your public: members, you can use a constructor that takes the filename to read from as an argument, and then you would need only one helper-function in addition to the overloaded << and >> operators. The helper-function just loops taking input with the overloaded >> operator until you reach the end of file.

Your constructors really don't need to be any more than:

  public:

    passfile() {}
    passfile (std::string fname) { readpwfile (fname); }
    ...

Your helper-function to repeatedly use the >> operator can be:

    void readpwfile (std::string fname)     /* read all students from filename */
    {
        std::ifstream f (fname);
        do
            f >> *this;                     /* use overloaded >> for read */
        while (f);
    }
    ...

The remaining details are handled by the overloaded << and >> operators. Starting with the overload of <<, you really don't need it to do any more than loop over all students and output the data in the format you like, e.g.

    /* overload << to output all student data */
    friend std::ostream& operator << (std::ostream& os, const passfile& pf)
    {
        for (auto s : pf.students)
            os  << "Username: " << s.username << '\n'
                << "Password: " << s.password << '\n'
                << "Verf ID : " << s.verfID << "\n\n";

        return os;
    }

(note: the friend keyword in used in the declaration within the class, if you defined the function elsewhere, you would omit friend before the definition)

Your overload of >> is where most of the work takes place, though the logic is simple. You declare a temporary student_t to read values into from the stream. If that succeeds, you do a quick lookup in your unordered_set to see if the verfID is already present. If it isn't you add the verfID to your unordered_set, and add your temporary student_t to your vector and your are done. If the verfID is a duplicate, you can issue a warning or error, e.g.

     /* overload >> to read username, password, verfID from input stream */
    friend std::istream& operator >> (std::istream& is, passfile& pf)
    {
        student_t s {};     /* temporary struct student */

        /* attempt read of all 3 values (username, password, verfID) */
        if (is >> s.username >> s.password >> s.verfID) {
            /* if verfID not already in verfID unordered_set */
            if (pf.verfID.find (s.verfID) == pf.verfID.end()) {
                pf.verfID.insert (s.verfID);    /* add verfID to unordered_set */
                pf.students.push_back (s);      /* add temp student to vector */
            }
            else    /* warn on duplicate verfID */
                std::cerr << "error: duplicate verfID " << s.verfID << ".\n";
        }

        return is;  /* return stream state */
    }

Putting it altogether in a short example (which basically just adds the headers and closes the class for the information above), you would have:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <unordered_set>

class passfile {

    struct student_t {
        std::string username {}, password {};   /* user std:string istead */
        int verfID;
    };

    std::unordered_set<int> verfID;         /* require unique verfID before add */
    std::vector<student_t> students {};     /* use vector of struct for storage */

  public:

    passfile() {}
    passfile (std::string fname) { readpwfile (fname); }

    void readpwfile (std::string fname)     /* read all students from filename */
    {
        std::ifstream f (fname);
        do
            f >> *this;                     /* use overloaded >> for read */
        while (f);
    }

    /* overload >> to read username, password, verfID from input stream */
    friend std::istream& operator >> (std::istream& is, passfile& pf)
    {
        student_t s {};     /* temporary struct student */

        /* attempt read of all 3 values (username, password, verfID) */
        if (is >> s.username >> s.password >> s.verfID) {
            /* if verfID not already in verfID unordered_set */
            if (pf.verfID.find (s.verfID) == pf.verfID.end()) {
                pf.verfID.insert (s.verfID);    /* add verfID to unordered_set */
                pf.students.push_back (s);      /* add temp student to vector */
            }
            else    /* warn on duplicate verfID */
                std::cerr << "error: duplicate verfID " << s.verfID << ".\n";
        }

        return is;  /* return stream state */
    }

    /* overload << to output all student data */
    friend std::ostream& operator << (std::ostream& os, const passfile& pf)
    {
        for (auto s : pf.students)
            os  << "Username: " << s.username << '\n'
                << "Password: " << s.password << '\n'
                << "Verf ID : " << s.verfID << "\n\n";

        return os;
    }
};

int main (int argc, char **argv) {

    if (argc < 2) { /* verify at least 1 argument for filename */
        std::cerr << "error: password filename required.\n";
        return 1;
    }

    passfile pf (argv[1]);      /* declare instance of class, with filename */
    std::cout << pf;            /* output all student data */
}

Example Input File

Using your input file above as a TEXT file:

$ cat dat/userpass.txt
Adam
Pass121
1
Jamie
abc1
2

Example Use/Output

Running the program and providing your input file as the first argument would result in:

$ ./bin/passwdfile dat/userpass.txt
Username: Adam
Password: Pass121
Verf ID : 1

Username: Jamie
Password: abc1
Verf ID : 2

If you needed to add more students by prompting the user for information, then all that would be needed is:

    std::cout << "enter user pass verfID: ";
    std::cin >> pf;

(try it, and try adding with a duplicate verfID...)

Look things over and let me know if you have further questions. Using the containers the STL provides is by far the better approach to take rather than trying to reinvent the wheel on your own (you eliminate a lot of errors that way...)


来源: stackexchange

问:
How do I concatenate two strings in Java?
I am trying to concatenate strings in Java.  Why isn't this working?</p>

```<code>public class StackOverflowTest {
    public static void main(String args[]) {
        int theNumber = 42;
        System.out.println("Your number is " . theNumber . "!");
    }
}
</code>```

答:
Using "+" symbol u can concatenate strings.</p>

```<code>String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to concatenate strings in Java.  Why isn't this working?

public class StackOverflowTest {
    public static void main(String args[]) {
        int theNumber = 42;
        System.out.println("Your number is " . theNumber . "!");
    }
}

Body:
Using "+" symbol u can concatenate strings.

String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

ContentLicense: CC BY-SA 4.0


问:
Program is not running
I am writing to find out whether the user is Teen ager or not? I am getting error while executing the program.

```<code>public class TeenNumberChecker
{
    public static void main (String[] args)
    {
        System.out.println(hasteen(22,28,32));
    }

public static boolean  hasteen(int age1,int age2,int age3) {
        if ((age1>=13&&age1<=19)||(age2>=13&&age2<=19)||(age2>=13&&age2<=19))
            return true;
}
else {
           return false;
}
}
</code>```

Error i am getting is "Exception in thread "main" java.lang.Error: Unresolved compilation problem: "

答:
I am not sure how my below solutions work:

```<code>public class TeenNumberChecker
{
    public static void main (String[] args)
    {
        System.out.println(hasteen(00,88,32));
    }

public static boolean hasteen(int age1, int age2, int age3)
{
    if (
            (age1 >= 13 && age1 <= 19) ||
            (age2 >= 13 && age2 <= 19) ||
            (age3 >= 13 && age3 <= 19)
    )
        return true;

    return false;
}
</code>```

Can someone explain it?

Title: Program is not running

Body:
I am writing to find out whether the user is Teen ager or not? I am getting error while executing the program.

public class TeenNumberChecker
{
    public static void main (String[] args)
    {
        System.out.println(hasteen(22,28,32));
    }

public static boolean  hasteen(int age1,int age2,int age3) {
        if ((age1>=13&&age1<=19)||(age2>=13&&age2<=19)||(age2>=13&&age2<=19))
            return true;
}
else {
           return false;
}
}

Error i am getting is "Exception in thread "main" java.lang.Error: Unresolved compilation problem: "

Body:
I am not sure how my below solutions work:

public class TeenNumberChecker
{
    public static void main (String[] args)
    {
        System.out.println(hasteen(00,88,32));
    }

public static boolean hasteen(int age1, int age2, int age3)
{
    if (
            (age1 >= 13 && age1 <= 19) ||
            (age2 >= 13 && age2 <= 19) ||
            (age3 >= 13 && age3 <= 19)
    )
        return true;

    return false;
}

Can someone explain it?


问:
Remove item from a list after I pick it
I want my code to pick a random number between 0 and 99, and then do it again 99 more times without picking a duplicate. I know how I'd do this in a very inefficient way (pick a random number and then check it against all numbers already picked, repicking if it is a duplicate).

I am sure that there is a better way, I just am not sure what to call the correct structure and thus I'm having a hard time getting the google results I need to figure this out.

What I think I need to do:

Build a "list" of 100 items, numbers 0 - 99.

Pick 1 item at random from that list, which will remove it from the list.

Pick from the entire list again, this time the list is 99 items in size.

Repeat until the list is empty

What is this called and what are the key concepts I need to understand?

答:
Answering my own question based on information I learned from the comments.

Here is how I did it using Collections:

```<code>Sub collections()
Randomize

Dim x As Byte
Dim coll As New Collection
Dim pick As Integer
Dim i As Byte: i = 1

For x = 0 To 99
    coll.Add x
Next

Do While coll.Count <> 0
    pick = Int((coll.Count - 1 + 1) * Rnd + 1)
    'Cells(i, 1).Value = coll.Item(pick)
    coll.Remove (pick)
    i = i + 1
Loop
end sub
</code>```

A little long winded, but I wanted to check to be sure it was working right (hence write to the activesheet and i as a counter).

Here is how I did it using a Dictionary:

```<code>Sub dictionary()
Randomize

Dim dict As New Scripting.dictionary
Dim x As Byte
Dim pick As Integer
Dim i As Byte: i = 1

For x = 0 To 99
    Do
        pick = Int((99 - 0 + 1) * Rnd + 0)
    Loop Until Not dict.Exists(pick)
    dict.Add pick, 0
    'Cells(i, 4).Value = pick
    i = i + 1
Next
End Sub
</code>```

And when I compared the two ways of doing it, the collections sub was always faster by ~ a factor of 10.

```<code>Dim StartTime As Double
Dim ElapsedTime As Double
Dim TotalTime As Double
Dim x As Byte

For x = 1 To 100
    StartTime = Timer
    Call collections
    ElapsedTime = Timer - StartTime
    TotalTime = TotalTime + ElapsedTime
Next
Debug.Print TotalTime & " Collections"

TotalTime = 0

For x = 1 To 100
    StartTime = Timer
    Call dictionary
    ElapsedTime = Timer - StartTime
    TotalTime = TotalTime + ElapsedTime
Next
Debug.Print TotalTime & " Dictionary"
</code>```

Title: Remove item from a list after I pick it

Body:
Answering my own question based on information I learned from the comments.

Here is how I did it using Collections:

Sub collections()
Randomize

Dim x As Byte
Dim coll As New Collection
Dim pick As Integer
Dim i As Byte: i = 1

For x = 0 To 99
    coll.Add x
Next

Do While coll.Count <> 0
    pick = Int((coll.Count - 1 + 1) * Rnd + 1)
    'Cells(i, 1).Value = coll.Item(pick)
    coll.Remove (pick)
    i = i + 1
Loop
end sub

A little long winded, but I wanted to check to be sure it was working right (hence write to the activesheet and i as a counter).

Here is how I did it using a Dictionary:

Sub dictionary()
Randomize

Dim dict As New Scripting.dictionary
Dim x As Byte
Dim pick As Integer
Dim i As Byte: i = 1

For x = 0 To 99
    Do
        pick = Int((99 - 0 + 1) * Rnd + 0)
    Loop Until Not dict.Exists(pick)
    dict.Add pick, 0
    'Cells(i, 4).Value = pick
    i = i + 1
Next
End Sub

And when I compared the two ways of doing it, the collections sub was always faster by ~ a factor of 10.

Dim StartTime As Double
Dim ElapsedTime As Double
Dim TotalTime As Double
Dim x As Byte

For x = 1 To 100
    StartTime = Timer
    Call collections
    ElapsedTime = Timer - StartTime
    TotalTime = TotalTime + ElapsedTime
Next
Debug.Print TotalTime & " Collections"

TotalTime = 0

For x = 1 To 100
    StartTime = Timer
    Call dictionary
    ElapsedTime = Timer - StartTime
    TotalTime = TotalTime + ElapsedTime
Next
Debug.Print TotalTime & " Dictionary"


问:
How to set up CIAbot for github repository
As in the title, I want to know how to set up the CIAbot for a github repository.</p>

答: CIA bot for gavin's bitcoin branch on github</p>


问:
Filtering results in MySQL in join result
I am beginner programmer. I have small problem with my MySQL Queries.
This is my MySQL data: https://pastebin.com/69PcBSVH

I have this tables:

```<code>CREATE TABLE `dishes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `dish_values` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `dishes_id` bigint(20) UNSIGNED NOT NULL,
  `food_ingredient_id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `quantity` decimal(9,2) NOT NULL DEFAULT '0.00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `food_ingredients` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `garbage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `energy_value` decimal(9,2) NOT NULL DEFAULT '0.00',
  `protein` decimal(9,2) NOT NULL DEFAULT '0.00',
  `fat` decimal(9,2) NOT NULL DEFAULT '0.00',
  `available_carbohydrates` decimal(9,2) NOT NULL DEFAULT '0.00',
  `roughage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `url_address` varchar(160) COLLATE utf8mb4_unicode_ci NOT NULL,
  `allergen` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen1` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen2` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen3` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `available_in_demo` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

My base is a base of dishes and ingredients needed to prepare a dish.

I need to display all dishes that are not allergens (food_ingredients.allergen = 0).

```<code>Table dishes = given dishes
Table dish_values = ingredients that are assigned to a given dish
Food_ingredients table = ingredients of the dish.
</code>```

Dishes that are allergens have a value of 1 in the allergen column and those that are not allergens 0.

I make query to show my dish (without allergens):

```<code>SELECT
  dishes.id, dishes.company_id, dishes.name, dishes.description, dishes.enable
FROM `dishes`  join dish_values on dish_values.dishes_id = dishes.id
      join food_ingredients on food_ingredients.id = dish_values.food_ingredient_id
WHERE food_ingredients.allergen = 0
GROUP BY dishes.id
</code>```

But it's not working correct.

As a result, I have both dishes that contain allergens and those that do not have them.

How can I repair it?

答:
Remove the WHERE clause and add the condition to the HAVING clause:

```<code>SELECT d.id, d.company_id, d.name, d.description, d.enable
FROM dishes d
INNER JOIN dish_values v ON v.dishes_id = d.id
INNER JOIN food_ingredients i ON i.id = v.food_ingredient_id
GROUP BY d.id, d.company_id, d.name, d.description, d.enable
HAVING SUM(i.allergen) = 0
</code>```

The condition SUM(i.allergen) = 0 makes sure that all matching rows from the table food_ingredients have i.allergen = 0.

Body:
I am beginner programmer. I have small problem with my MySQL Queries.
This is my MySQL data: https://pastebin.com/69PcBSVH

I have this tables:

CREATE TABLE `dishes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `dish_values` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `dishes_id` bigint(20) UNSIGNED NOT NULL,
  `food_ingredient_id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `quantity` decimal(9,2) NOT NULL DEFAULT '0.00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `food_ingredients` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `garbage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `energy_value` decimal(9,2) NOT NULL DEFAULT '0.00',
  `protein` decimal(9,2) NOT NULL DEFAULT '0.00',
  `fat` decimal(9,2) NOT NULL DEFAULT '0.00',
  `available_carbohydrates` decimal(9,2) NOT NULL DEFAULT '0.00',
  `roughage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `url_address` varchar(160) COLLATE utf8mb4_unicode_ci NOT NULL,
  `allergen` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen1` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen2` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen3` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `available_in_demo` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

My base is a base of dishes and ingredients needed to prepare a dish.

I need to display all dishes that are not allergens (food_ingredients.allergen = 0).

Table dishes = given dishes
Table dish_values = ingredients that are assigned to a given dish
Food_ingredients table = ingredients of the dish.

Dishes that are allergens have a value of 1 in the allergen column and those that are not allergens 0.

I make query to show my dish (without allergens):

SELECT
  dishes.id, dishes.company_id, dishes.name, dishes.description, dishes.enable
FROM `dishes`  join dish_values on dish_values.dishes_id = dishes.id
      join food_ingredients on food_ingredients.id = dish_values.food_ingredient_id
WHERE food_ingredients.allergen = 0
GROUP BY dishes.id

But it's not working correct.

As a result, I have both dishes that contain allergens and those that do not have them.

How can I repair it?

Body:
Remove the WHERE clause and add the condition to the HAVING clause:

SELECT d.id, d.company_id, d.name, d.description, d.enable
FROM dishes d
INNER JOIN dish_values v ON v.dishes_id = d.id
INNER JOIN food_ingredients i ON i.id = v.food_ingredient_id
GROUP BY d.id, d.company_id, d.name, d.description, d.enable
HAVING SUM(i.allergen) = 0

The condition SUM(i.allergen) = 0 makes sure that all matching rows from the table food_ingredients have i.allergen = 0.


问:
Spring boot - HttpSession is null between two different request
First, when I call the API "/fetch/event/1221", I am able to set the session attribute,
But I am getting httpSession as null when I call the "fetch/partcipant" API.
How can I fix this?

```<code>@RequestMapping(value = "/fetch/event/{eventId}", method = RequestMethod.GET)
        public SuccessResponse<Event> fetchEvent(@PathVariable("eventId") String eventId, HttpServletRequest httpServletRequest) throws ExecutionException, InterruptedException {
            Event event = eventService.getEventById(eventId);
            HttpSession httpSession = httpServletRequest.getSession(false);
            httpSession.setAttribute("event", event);
            return new SuccessResponse<Event>(event);
        }

 @RequestMapping(value = "/fetch/participant", method = RequestMethod.GET)
    public SuccessResponse<List<Participant>> getListOfActiveParticipants(HttpServletRequest httpServletRequest) throws ExecutionException, InterruptedException {
        HttpSession httpSession = httpServletRequest.getSession(false);
        Event event = (Event) httpSession.getAttribute("event");
        System.out.println((Event) httpSession.getAttribute("event"));
        return new SuccessResponse<>(participantService.getParticipants("ALL", event.getId()));
    }
</code>```

答:
First of all , you are using httpServletRequest.getSession(false) in /fetch/event/ , it will not create a session if there is no current session. Change it to true to force it create a new one if there are no current session:

 HttpSession httpSession = httpServletRequest.getSession(true);
```

<p>Once the session is created , it will return the session id through cookie in the response header : </p>

<pre class="lang-sh prettyprint-override"><code>< HTTP/1.1 200
< Set-Cookie: JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65; Path=/; HttpOnly
</code>```

To tell the server to use a particular session , the subsequent request should include this session id through cookie. In case of curl, you can do :

$ curl -v --cookie "JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65" http://127.0.0.1:8080/fetch/partcipant
```

<p>which will add the following HTTP request header :</p>

<pre class="lang-sh prettyprint-override"><code>> GET /fetch/participant HTTP/1.1
> Host: 127.0.0.1:8080
> Cookie: JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65
</code>```

Then in getListOfActiveParticipants() , you should get the session that is created in fetchEvent()

Body:
First, when I call the API "/fetch/event/1221", I am able to set the session attribute,
But I am getting httpSession as null when I call the "fetch/partcipant" API.
How can I fix this?

@RequestMapping(value = "/fetch/event/{eventId}", method = RequestMethod.GET)
        public SuccessResponse<Event> fetchEvent(@PathVariable("eventId") String eventId, HttpServletRequest httpServletRequest) throws ExecutionException, InterruptedException {
            Event event = eventService.getEventById(eventId);
            HttpSession httpSession = httpServletRequest.getSession(false);
            httpSession.setAttribute("event", event);
            return new SuccessResponse<Event>(event);
        }

 @RequestMapping(value = "/fetch/participant", method = RequestMethod.GET)
    public SuccessResponse<List<Participant>> getListOfActiveParticipants(HttpServletRequest httpServletRequest) throws ExecutionException, InterruptedException {
        HttpSession httpSession = httpServletRequest.getSession(false);
        Event event = (Event) httpSession.getAttribute("event");
        System.out.println((Event) httpSession.getAttribute("event"));
        return new SuccessResponse<>(participantService.getParticipants("ALL", event.getId()));
    }

Body:
First of all , you are using httpServletRequest.getSession(false) in /fetch/event/ , it will not create a session if there is no current session. Change it to true to force it create a new one if there are no current session:

 HttpSession httpSession = httpServletRequest.getSession(true);

Once the session is created , it will return the session id through cookie in the response header :

< HTTP/1.1 200
< Set-Cookie: JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65; Path=/; HttpOnly

To tell the server to use a particular session , the subsequent request should include this session id through cookie. In case of curl, you can do :

$ curl -v --cookie "JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65" http://127.0.0.1:8080/fetch/partcipant

which will add the following HTTP request header :

> GET /fetch/participant HTTP/1.1
> Host: 127.0.0.1:8080
> Cookie: JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65

Then in getListOfActiveParticipants() , you should get the session that is created in fetchEvent()


问:
How to Pass Iterator as Function Parameter in C++
I'm writing my own C++ vector class and I want to be able to pass an iterator as a function parameter to my reverse() function, so that I can do something like

```<code>vector<int> scores{5,8,89,32};
reverse(scores.begin(), scores.end());
</code>```

instead of

```<code>...
scores.reverse();
or
reverse(scores)
</code>```

I'm able to do the later with this code

```<code>template<typename T>
void reverse(vector<T> &orig) {
    //Reverse the elements of the array
    auto begin = orig.begin();
    auto end = --orig.end();    //Move the iterator 1 place back to keep within range

    while (begin < end) {

    std::swap(*begin, *end);

    begin++;
    end--;
    }
}

</code>```

But when I do this

```<code>template<typename T>
void reverse(vector<T>::iterator begin, vector<T>::iterator end) {

    while (begin < end) {

        std::swap(*begin, *end);

        begin++;
        end--;
    }
}
</code>```

I get this error

```<code>error: expected ')' before 'begin'
</code>```

What am I doing wrong, please?

Thank you.

答:
It should be:

template <typename T>
void reverse(typename std::vector<T>::iterator begin, typename std::vector<T>::iterator end)
{...}
```

Without typename compiler cannot determine whether iterator is a member or type. So compiler assumes it is a member.

Body:
I'm writing my own C++ vector class and I want to be able to pass an iterator as a function parameter to my reverse() function, so that I can do something like

vector<int> scores{5,8,89,32};
reverse(scores.begin(), scores.end());

instead of

...
scores.reverse();
or
reverse(scores)

I'm able to do the later with this code

template<typename T>
void reverse(vector<T> &orig) {
    //Reverse the elements of the array
    auto begin = orig.begin();
    auto end = --orig.end();    //Move the iterator 1 place back to keep within range

    while (begin < end) {

    std::swap(*begin, *end);

    begin++;
    end--;
    }
}

But when I do this

template<typename T>
void reverse(vector<T>::iterator begin, vector<T>::iterator end) {

    while (begin < end) {

        std::swap(*begin, *end);

        begin++;
        end--;
    }
}

I get this error

error: expected ')' before 'begin'

What am I doing wrong, please?

Thank you.

Body:
It should be:

template <typename T>
void reverse(typename std::vector<T>::iterator begin, typename std::vector<T>::iterator end)
{...}

Without typename compiler cannot determine whether iterator is a member or type. So compiler assumes it is a member.


问:
Implementing Runnable in Enum
I am just playing around with enum and I wanted to see how it behaves under some crazy scenarios. Well, few java nerds might know that we can actually implement a interface in Enums.
So I came up with below code and wanted to know if the thread is created and called. I am curious if anyone can explain why the sysout is not printed. The below code is valid i.e compiles fine and executes. It just prints nothing. Can anyone explain clearly?

Also why values() method is not declared either in Enum class or Object class. Why the values method is provided by java compiler. Why the Sun/Oracle din't think of implementing it in Enum class.

```<code> package com.test;

  enum MyEnum implements Runnable{

      ENUM1,ENUM2,ENUM3;
      public void run() {

          System.out.println("Inside MyEnum"+Thread.currentThread().getName());
      }
}

public class EnumTesting {

    MyEnum en;

      public static void main(String[] args) {

    EnumTesting test = new EnumTesting();

          Thread t = new Thread(test.en);
        t.start();

    }
}
</code>```

答:
1)  Because test.en is null, you never initialize it.

2) Implementing values() must be done by the compiler because the array type is the type of the concrete Enum, here MyEnum[]. If it would be declared in Enum class, it would need to have a return type of Enum[].

Title: Implementing Runnable in Enum

Body:
I am just playing around with enum and I wanted to see how it behaves under some crazy scenarios. Well, few java nerds might know that we can actually implement a interface in Enums.
So I came up with below code and wanted to know if the thread is created and called. I am curious if anyone can explain why the sysout is not printed. The below code is valid i.e compiles fine and executes. It just prints nothing. Can anyone explain clearly?

Also why values() method is not declared either in Enum class or Object class. Why the values method is provided by java compiler. Why the Sun/Oracle din't think of implementing it in Enum class.

 package com.test;

  enum MyEnum implements Runnable{

      ENUM1,ENUM2,ENUM3;
      public void run() {

          System.out.println("Inside MyEnum"+Thread.currentThread().getName());
      }
}

public class EnumTesting {

    MyEnum en;

      public static void main(String[] args) {

    EnumTesting test = new EnumTesting();

          Thread t = new Thread(test.en);
        t.start();

    }
}


问:
How do I improve the time it takes to load and parse files
So I 'm trying to load some data that my website can use in order to display some items.
Each item is in a json format and this is what I'm doing.

When the user sends a request to load the page, it then tries to load 400 items (there are in total 26000, i'm just using 400 to test)
and obviously 400 is going to take a lot of time, and it does that when the user clicks next as well since it's using pagination.

And my idea was that maybe I could load like 50 at a time, which would make it way more efficient!
But I'm not sure what I could do in order to implement that thought.
I tried using foreach skip and take but I couldnt really come up with a decent algorithm.
Each file is between 1 and 2KB.

Would it improve the speed a lot if I just made it one file? Seeing how it would try to load it each time I click next or another page number.

```<code>public ActionResult Items(int? page)
        {
            var items = new List<ItemModel>();
            var path = @"C:\Users\MyUser\Desktop\items-json";
            var itemFiles = Directory.GetFiles(path);

            for (int i = 0; i < 400; i++)
            {
                try
                {
                    var json = System.IO.File.ReadAllText(itemFiles[i]);

                    var itemObject = JsonConvert.DeserializeObject<ItemModel>(json);
                    items.Add(itemObject);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            var pageNumber = page ?? 1;
            var onePageOfItems = items.ToPagedList(pageNumber, 10);
            //ViewBag.OnePageProducts = onePageOfProducts;
            return View(onePageOfItems);
        }
</code>```

答:
Parallel programming can help reduce the time a lot, below is a simplified sample:

Parallel.ForEach(itemFiles, file =>
{
    var json = System.IO.File.ReadAllText(file);
    var itemObject = JsonConvert.DeserializeObject<ItemModel>(json);
    items.Add(itemObject);
}
```

Additionally, this article compares the performance of file reading methods:

C# .Net: Fastest Way to Read Text Files

Body:
So I 'm trying to load some data that my website can use in order to display some items.
Each item is in a json format and this is what I'm doing.

When the user sends a request to load the page, it then tries to load 400 items (there are in total 26000, i'm just using 400 to test)
and obviously 400 is going to take a lot of time, and it does that when the user clicks next as well since it's using pagination.

And my idea was that maybe I could load like 50 at a time, which would make it way more efficient!
But I'm not sure what I could do in order to implement that thought.
I tried using foreach skip and take but I couldnt really come up with a decent algorithm.
Each file is between 1 and 2KB.

Would it improve the speed a lot if I just made it one file? Seeing how it would try to load it each time I click next or another page number.

public ActionResult Items(int? page)
        {
            var items = new List<ItemModel>();
            var path = @"C:\Users\MyUser\Desktop\items-json";
            var itemFiles = Directory.GetFiles(path);

            for (int i = 0; i < 400; i++)
            {
                try
                {
                    var json = System.IO.File.ReadAllText(itemFiles[i]);

                    var itemObject = JsonConvert.DeserializeObject<ItemModel>(json);
                    items.Add(itemObject);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            var pageNumber = page ?? 1;
            var onePageOfItems = items.ToPagedList(pageNumber, 10);
            //ViewBag.OnePageProducts = onePageOfProducts;
            return View(onePageOfItems);
        }

Body:
Parallel programming can help reduce the time a lot, below is a simplified sample:

Parallel.ForEach(itemFiles, file =>
{
    var json = System.IO.File.ReadAllText(file);
    var itemObject = JsonConvert.DeserializeObject<ItemModel>(json);
    items.Add(itemObject);
}

Additionally, this article compares the performance of file reading methods:

C# .Net: Fastest Way to Read Text Files


问:
X509Certificate Decrypt Exceprion
I got a digital certificate from a certified body, with it I got a usb sticker with a private key.
In VisualStudio I make Console application, i want to test the encryption and decryption with that certificate. For this I used already well known code:

```<code>private static string EncryptRSA(string input)
        {
            string outputMessage = String.Empty;
            X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PublicKey.Key)
            {
                byte[] byteData = Encoding.UTF8.GetBytes(input);
                byte[] byteEncrypted = csp.Encrypt(byteData, false);
                outputMessage = Convert.ToBase64String(byteEncrypted);
            }

            return izlaznaPoruka;
        }

        public static string DecryptRsa(string enkriptovan)
        {
            string text = string.Empty;
            X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");

            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PrivateKey)
            {
                byte[] byteEncrypted = Convert.FromBase64String(enkriptovan);
                byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
                text = Encoding.UTF8.GetString(byteDecrypted);
            }

            return text;
        }
</code>```

Everything goes as it should until this moment, in the method DecryptRsa:

```<code>byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
</code>```

At this point, my authentication client requires a password - I enter the correct password, and the following exception pops up for me:
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll An internal error occurred.

Can any one help me?

I've researched a lot of solutions, but most private keys are exported to a .pfx file and use a three-parameter X509Certificate2 constructor when like this

```<code>X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
    X509KeyStorageFlags.MachineKeySet);
</code>```

Then change the permission of the folder ProgramData\Microsoft\Crypto\RSA\MachineKeys
I manually changed the folder rights..

答:
If the error in stack trace is 'keyset does not exist.', then you may need permission in private key from 'Manage Private Keys'

Create a Microsoft Management Console (MMC) with the Certificates snap-in that targets the Local Machine certificate store.

Expand the MMC and select Manage Private Keys

On the Security tab, Add the pool identity or the IIS user account with Read access.

Please check this

Title: X509Certificate Decrypt Exceprion

Body:
I got a digital certificate from a certified body, with it I got a usb sticker with a private key.
In VisualStudio I make Console application, i want to test the encryption and decryption with that certificate. For this I used already well known code:

private static string EncryptRSA(string input)
        {
            string outputMessage = String.Empty;
            X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PublicKey.Key)
            {
                byte[] byteData = Encoding.UTF8.GetBytes(input);
                byte[] byteEncrypted = csp.Encrypt(byteData, false);
                outputMessage = Convert.ToBase64String(byteEncrypted);
            }

            return izlaznaPoruka;
        }

        public static string DecryptRsa(string enkriptovan)
        {
            string text = string.Empty;
            X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");

            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PrivateKey)
            {
                byte[] byteEncrypted = Convert.FromBase64String(enkriptovan);
                byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
                text = Encoding.UTF8.GetString(byteDecrypted);
            }

            return text;
        }

Everything goes as it should until this moment, in the method DecryptRsa:

byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);

At this point, my authentication client requires a password - I enter the correct password, and the following exception pops up for me:
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll An internal error occurred.

Can any one help me?

I've researched a lot of solutions, but most private keys are exported to a .pfx file and use a three-parameter X509Certificate2 constructor when like this

X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
    X509KeyStorageFlags.MachineKeySet);

Then change the permission of the folder ProgramData\Microsoft\Crypto\RSA\MachineKeys
I manually changed the folder rights..


问:
get file path from stdin in C
I am trying to pass a file to my program however it always gives error, cannot open file.

My command is: (I am on desktop path, I am using ubuntu)

```<code>./out < /usr/share/dict/words > out.txt 2> out2.txt
</code>```

Output files are created but file input seems empty. I am getting file path as:

```<code>char *infile;
scanf("%s", infile);
printf("file: %s\n", infile);
</code>```

I also tried:

```<code>fscanf(stdin, "%s", infile);
</code>```

Nothing changed. Also, I have to take input as shown above, I know < means stdin but I cannot read its content somehow.

This is file opening part and error message:

```<code> file = fopen(infile, "r");
 if (file == 0) {
     fprintf(stderr, "File failed\n");
     return 1;
 }
</code>```

答: char *infile is just a pointer and does not allocate space for the string, so the input will not be saved. Try something like char infile[50]. Increase the size if needed for your input.

Title: get file path from stdin in C

Body:
I am trying to pass a file to my program however it always gives error, cannot open file.

My command is: (I am on desktop path, I am using ubuntu)

./out < /usr/share/dict/words > out.txt 2> out2.txt

Output files are created but file input seems empty. I am getting file path as:

char *infile;
scanf("%s", infile);
printf("file: %s\n", infile);

I also tried:

fscanf(stdin, "%s", infile);

Nothing changed. Also, I have to take input as shown above, I know < means stdin but I cannot read its content somehow.

This is file opening part and error message:

 file = fopen(infile, "r");
 if (file == 0) {
     fprintf(stderr, "File failed\n");
     return 1;
 }


问:
Get average data based on date, week, month
I have a dataset that includes three years data of a factory workers' output. Now I would like to get average output based on date, week, month for example. The problem is the date format is like %d.%m.%Y (day-month-year). My question is how could I keep the date format unchanged while get the expected output.

My dataset is like this (There are many values daily.)

```<code>date         output
1.1.2017     261
2.1.2017     152 (Jan.02,2017)
17.1.2017    256
17.1.2017    261
18.1.2017    193
18.1.2017    462
1.2.2017     212 (Feb.1,2017)
3.2.2017     266 (Feb.3,2017)

....

1.3.2018    360
</code>```

The error message I got like this: time data '2017-01-01' does not match format '%d.%m.%Y' (match). FYI, my code is like this when I read the dataset

```<code>df['date'] = pd.to_datetime(df['date'],format='%d.%m.%Y').dt.date
df.groupby(['date'],as_index=False).mean()
</code>```

I have tried solve it by googling different solutions. But I can not get the expect result. The output got totally confused between date and month.e.g. 1.2.2017 (Jan.2,2017) was treated as (Feb.1,2017).How can I solve it? Thank you!

答: Your code seems fine and in fact works well at least for the first four data records. The problem here is that the date format is not consistent from the error you reported. Like others pointed out, letting the pandas find out format for you would solve the problem, i.e. df["date"]=pd.to_datetime(df["date"]). But I just feel that this is a little bit tricky or dangerous. I would like to recommend you unify the date format using string operations in Python before any analysis on them. Hope this helps.

Body:
I have a dataset that includes three years data of a factory workers' output. Now I would like to get average output based on date, week, month for example. The problem is the date format is like %d.%m.%Y (day-month-year). My question is how could I keep the date format unchanged while get the expected output.

My dataset is like this (There are many values daily.)

date         output
1.1.2017     261
2.1.2017     152 (Jan.02,2017)
17.1.2017    256
17.1.2017    261
18.1.2017    193
18.1.2017    462
1.2.2017     212 (Feb.1,2017)
3.2.2017     266 (Feb.3,2017)

....

1.3.2018    360

The error message I got like this: time data '2017-01-01' does not match format '%d.%m.%Y' (match). FYI, my code is like this when I read the dataset

df['date'] = pd.to_datetime(df['date'],format='%d.%m.%Y').dt.date
df.groupby(['date'],as_index=False).mean()

I have tried solve it by googling different solutions. But I can not get the expect result. The output got totally confused between date and month.e.g. 1.2.2017 (Jan.2,2017) was treated as (Feb.1,2017).How can I solve it? Thank you!


问:
RecyclerView doesn't load items on first start of activity
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708

The Item i am spawning in:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>
</code>```

My conversation layout:

```<code><?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >

        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">

        </android.support.v7.widget.RecyclerView>

        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />

    </RelativeLayout>
</code>```

My Adapter:

```<code>public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

    @Override
    public int getItemCount() {
        return mUsers.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;

        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}
</code>```

My main class

```<code>public class ConnectionsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }

    }
</code>```

So if the recyclerView Activity is the first activity I visit then it will not create the items.

答: You can use Boolean button to check if it is true adapter is made</p>

Body:
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708

The Item i am spawning in:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

My conversation layout:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >

        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">

        </android.support.v7.widget.RecyclerView>

        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />

    </RelativeLayout>

My Adapter:

public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

    @Override
    public int getItemCount() {
        return mUsers.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;

        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}

My main class

public class ConnectionsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }

    }

So if the recyclerView Activity is the first activity I visit then it will not create the items.


问:
Prestashop 1.7.2 + Nginx 1.10 + SSL - Rewrite Rules
I keep getting 404 error when trying to navigate to the frontend shop of a Prestashop 1.7.2 site products page.I am having some problems with images not shown. However it is fine when going to the admin backend.

Any suggestions would be helpful.

This is my /etc/nginx/site-available/default conf file:

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
        access_log  /var/log/nginx/h2o.prod.access.log;
        error_log   /var/log/nginx/h2o.prod.error.log;

        root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name 165.227.162.248;
        #Specify a charset
        charset utf-8;
        # Gzip Settings, convert all types.
            gzip on;
            gzip_vary on;
            gzip_proxied any;

            # Can be enhance to 5, but it can slow you server
            # gzip_comp_level    5;
            # gzip_min_length    256;

            gzip_types
                application/atom+xml
                application/javascript
                application/json
                application/ld+json
                application/manifest+json
                application/rss+xml
                application/vnd.geo+json
                application/vnd.ms-fontobject
                application/x-font-ttf
                application/x-web-app-manifest+json
                application/xhtml+xml
                application/xml
                font/opentype
                image/bmp
                image/svg+xml
                image/x-icon
                text/cache-manifest
                text/css
                text/plain
                text/vcard
                text/vnd.rim.location.xloc
                text/vtt
                text/x-component
                text/x-cross-domain-policy;
                # Supposed to be the case but we never know
                # text/html;

        gzip_disable "MSIE [1-6]\.(?!.*SV1)";

        location ~* \.(eot|gif|ico|jpg|jpeg|otf|pdf|png|svg|swf|ttf|woff)$ {
    rewrite ^/([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$1$2$3.jpg break;
    rewrite ^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$1$2$3$4.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$1$2$3$4$5.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg break;
    rewrite ^/c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2$3.jpg break;
    rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg break;
    rewrite ^/images_ie/?([^/]+)\.(jpe?g|png|gif)$ /js/jquery/plugins/fancybox/images/$1.$2 break;
    # next line is PSCSX-2790 bug workaround, fixed in 1.6.0.10
    rewrite ^/[a-zA-Z]+/img/cms/(.*)$ /img/cms/$1 break;
    expires 1M;
    add_header Cache-Control public;
    allow all;
        }

        # Block everything else in these directories
        location ~ ^/img/cms/ {
                deny all;
        }

        # 1 week expiry on CSS and JavaScript
        location ~ \.(css|js)$ {
                expires 1w;
                add_header Cache-Control public;
                allow all;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ ^/medicalstrechers17/admin1900/index.php/(.*) {
        try_files $uri $uri/ /medicalstrechers17/admin1900/index.php$is_args$args;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        #include snippets/fastcgi-php.conf;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                include fastcgi.conf;
                fastcgi_intercept_errors on;

    }
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                    expires max;
                    log_not_found off;
        }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}
</code>```

Thanks in advance.

答:
First of all, if you post NGINX configuration, I advise to hide the admin directory URL. Then, I can think of two things. Are you using multilanguage? If so, add the following lines to your config. For example, english and spanish:

```<code>rewrite ^/es$ /es/ redirect;
rewrite ^/es/(.*) /$1;
rewrite ^/en$ /en/ redirect;
rewrite ^/en/(.*) /$1;
</code>```

Then, if that does not work, add this (single language):

```<code>try_files $uri $uri/ /index.php?$args;
</code>```

Or this (multiple languages, in this case spanish and english):

```<code>location ~ (/es|/en)/index\.php$ {
    try_files $uri $uri/ /index.php?$args;
}
</code>```

Let's see if it helps!

Body:
I keep getting 404 error when trying to navigate to the frontend shop of a Prestashop 1.7.2 site products page.I am having some problems with images not shown. However it is fine when going to the admin backend.

Any suggestions would be helpful.

This is my /etc/nginx/site-available/default conf file:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
        access_log  /var/log/nginx/h2o.prod.access.log;
        error_log   /var/log/nginx/h2o.prod.error.log;

        root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name 165.227.162.248;
        #Specify a charset
        charset utf-8;
        # Gzip Settings, convert all types.
            gzip on;
            gzip_vary on;
            gzip_proxied any;

            # Can be enhance to 5, but it can slow you server
            # gzip_comp_level    5;
            # gzip_min_length    256;

            gzip_types
                application/atom+xml
                application/javascript
                application/json
                application/ld+json
                application/manifest+json
                application/rss+xml
                application/vnd.geo+json
                application/vnd.ms-fontobject
                application/x-font-ttf
                application/x-web-app-manifest+json
                application/xhtml+xml
                application/xml
                font/opentype
                image/bmp
                image/svg+xml
                image/x-icon
                text/cache-manifest
                text/css
                text/plain
                text/vcard
                text/vnd.rim.location.xloc
                text/vtt
                text/x-component
                text/x-cross-domain-policy;
                # Supposed to be the case but we never know
                # text/html;

        gzip_disable "MSIE [1-6]\.(?!.*SV1)";

        location ~* \.(eot|gif|ico|jpg|jpeg|otf|pdf|png|svg|swf|ttf|woff)$ {
    rewrite ^/([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$1$2$3.jpg break;
    rewrite ^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$1$2$3$4.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$1$2$3$4$5.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg break;
    rewrite ^/c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2$3.jpg break;
    rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg break;
    rewrite ^/images_ie/?([^/]+)\.(jpe?g|png|gif)$ /js/jquery/plugins/fancybox/images/$1.$2 break;
    # next line is PSCSX-2790 bug workaround, fixed in 1.6.0.10
    rewrite ^/[a-zA-Z]+/img/cms/(.*)$ /img/cms/$1 break;
    expires 1M;
    add_header Cache-Control public;
    allow all;
        }

        # Block everything else in these directories
        location ~ ^/img/cms/ {
                deny all;
        }

        # 1 week expiry on CSS and JavaScript
        location ~ \.(css|js)$ {
                expires 1w;
                add_header Cache-Control public;
                allow all;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ ^/medicalstrechers17/admin1900/index.php/(.*) {
        try_files $uri $uri/ /medicalstrechers17/admin1900/index.php$is_args$args;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        #include snippets/fastcgi-php.conf;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                include fastcgi.conf;
                fastcgi_intercept_errors on;

    }
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                    expires max;
                    log_not_found off;
        }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

Thanks in advance.

Body:
First of all, if you post NGINX configuration, I advise to hide the admin directory URL. Then, I can think of two things. Are you using multilanguage? If so, add the following lines to your config. For example, english and spanish:

rewrite ^/es$ /es/ redirect;
rewrite ^/es/(.*) /$1;
rewrite ^/en$ /en/ redirect;
rewrite ^/en/(.*) /$1;

Then, if that does not work, add this (single language):

try_files $uri $uri/ /index.php?$args;

Or this (multiple languages, in this case spanish and english):

location ~ (/es|/en)/index\.php$ {
    try_files $uri $uri/ /index.php?$args;
}

Let's see if it helps!


问:
In microsoft dynamics crm 4.0 dlg_error.aspx page with customer number as error pops up on clicking on the save button on CASE form for service
I am trying to customize the 'CASE'  form  for service. Someone else was working on it before me he added a lookup 'contact'  field . we have one live crm system and one test system . Everything is working fine on live system but not on test system. On test system when i click on  'Save' button a pop up coms up with a big red cross sign and displays customer number as error. The address bar of the popup shows that it is the dlg_error.aspx page. i compared it with the live sytem's entity but i cannot find anything wrong.which files/events i need to check . i alredy checked the page onload, onsave events and onchange events of fields.

Can anyone please help me with this problem. so that i can solve this and proceed with my new stuff.

答: What I would try first is to export the Case entity from the test org (just as a backup), export the Case entity from prod, import prod's version into test, then publish. Does the error still occur?</p>