问:
Way to access stack top element to recursively compare if both stack elements are the same
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?

I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
  Thank you

```<code>public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}
</code>```

```<code>public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }
            return t;
        }

        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class
</code>```

答:
Spongebob meme Many Hours Later...........Figured it out by myself at last!</p>

```<code>import java.util.NoSuchElementException;

public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
               System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }

        public E pop() {
             if (isEmpty()==true) {
                   System.out.println("Stack Empty!");
                }
             else{
            E e = (E) items[top];
            items[top] = null;
            top = top-1;
            return e;
             }
            return null;
        }

        public boolean isFull() {
             if (top == items.length-1) {
                 return true;
             }
             return false;
        }

        public boolean isEmpty(){
             if (top==-1) {
                 return true;
             }
             return false;
        }

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
             for(int i = 0; i < items.length ;i++) {
                 System.out.print(items[i]+" ");
        }
             System.out.print("}");
            return "";
    }

        public int peek() {
            if (this.isEmpty()) throw new NoSuchElementException("Stack underflow");
            //System.out.println("items[top]"+this.items[top]);
            //System.out.println("e"+e);
            return (int) this.items[top];
        }

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }

            if ((int) this.peek() == s2.peek()) {
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                this.push(t1);
                s2.push(t2);
            }
            else {
                t = false;
                return t;
            }
            return t;
        }

        public static void main(String[] args)
        {
            // Code reference for sameStack method
           StackArray<Integer> stack = new StackArray<Integer>();
           StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(122);
            stack.push(222);
            stack.push(3313);
            stack.push(46);
            stack2.push(122);
            stack2.push(222);
            stack2.push(3313);
            stack2.push(46);
            System.out.println(stack);
            System.out.println(stack2);

            stack.peek();
            if (stack.sameStack(stack2) == true) {
                System.out.println("They are equal");
            }
            else {
                System.out.println("They are NOT equal");
            }

            System.out.println(stack);
            System.out.println(stack2);

            //Calling comparison method
           // stack.sameStack(stack2);
        }
}
</code>```

Body:
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?

I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
  Thank you

public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}

public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }
            return t;
        }

        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class

Body:
Spongebob meme Many Hours Later...........Figured it out by myself at last!

import java.util.NoSuchElementException;

public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
               System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }

        public E pop() {
             if (isEmpty()==true) {
                   System.out.println("Stack Empty!");
                }
             else{
            E e = (E) items[top];
            items[top] = null;
            top = top-1;
            return e;
             }
            return null;
        }

        public boolean isFull() {
             if (top == items.length-1) {
                 return true;
             }
             return false;
        }

        public boolean isEmpty(){
             if (top==-1) {
                 return true;
             }
             return false;
        }

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
             for(int i = 0; i < items.length ;i++) {
                 System.out.print(items[i]+" ");
        }
             System.out.print("}");
            return "";
    }

        public int peek() {
            if (this.isEmpty()) throw new NoSuchElementException("Stack underflow");
            //System.out.println("items[top]"+this.items[top]);
            //System.out.println("e"+e);
            return (int) this.items[top];
        }

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }

            if ((int) this.peek() == s2.peek()) {
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                this.push(t1);
                s2.push(t2);
            }
            else {
                t = false;
                return t;
            }
            return t;
        }

        public static void main(String[] args)
        {
            // Code reference for sameStack method
           StackArray<Integer> stack = new StackArray<Integer>();
           StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(122);
            stack.push(222);
            stack.push(3313);
            stack.push(46);
            stack2.push(122);
            stack2.push(222);
            stack2.push(3313);
            stack2.push(46);
            System.out.println(stack);
            System.out.println(stack2);

            stack.peek();
            if (stack.sameStack(stack2) == true) {
                System.out.println("They are equal");
            }
            else {
                System.out.println("They are NOT equal");
            }

            System.out.println(stack);
            System.out.println(stack2);

            //Calling comparison method
           // stack.sameStack(stack2);
        }
}


来源: stackexchange

问:
Logic error with an encode/decode program (C)
I am a beginner in a C programming class, and our assignment for the third chapter of our textbook was to create an encode/decode program that takes in four digits from user input and rearranges them depending on whether or not the user wants them to be either encoded or decoded. I am also having trouble with getting the program to do both decoding and encoding in one file. However, when I fire up the program, whenever I select encode and type in my four digits, the program not only gives me a massive number that should only be four digits as the encoded result. It also gives me the "press any key to continue" prompt, signifying the end of the program, instead of starting over completely and going back to where it asks the user to either decode or encode.

The output is also attached.

I've tried looking around and changing some of the variables from int to double, as well as checking my math... I'm not 100% sure why the encryption and decryption aren't limited to anything besides four digits.

As for getting the program to start over, I've tried using a do-while loop, but it still didn't seem to work, so I deleted it.. I also tried using another if statement and then using break, but it was marked as an error.

The assignment says that, "each digit should be encrypted by adding 7 and taking the remainder after division by 10; after encrypting each digit, swap the first and third digits, and then swap the second and fourth digits. Decryption should reverse the process. Program must do encode and decode in one file.

Here is the example that my instructor posted for this, this is what the output should look like.

```<code>Enter a four digit number: 1234
Encoded Digits: 0189
Continue (1) Exit (0): 1
Encode (1) Decode (2): 2
Enter a four digit number: 0189
Decoded Digits: 1234
Continue (1) Exit (0): 0
</code>```

Here is my code:

```<code>///Compiler used: Microsoft Visual Studio
///Language: C
#include <string>
#pragma warning(disable: 4996)
#include <math.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{

    int Encodechoice = 1;
    int inputdigit1 = 0;
    int Decodechoice = 2;
    int UserChoice = 0;
    int ContinueChoice = 0;
    int UserDigit1 = 0;
    int UserDigit2 = 0;
    int UserDigit3 = 0;
    int UserDigit4 = 0;

    {
        printf("(1) Encode, (2) Decode\n");
        printf("Make your selection.\n");//Asks user to make selection
        scanf_s("%d", &UserChoice);

        if (UserChoice == 1)//begin encryption

        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Encode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int EncodedIntegers1 = (UserDigit1 + 7) % 10;
            int EncodedIntegers2 = (UserDigit2 + 7) % 10;
            int EncodedIntegers3 = (UserDigit3 + 7) % 10;
            int EncodedIntegers4 = (UserDigit4 + 7) % 10;
            printf("Encoded result:\n");
            printf("%d", "%d", "%d", "%d\n", EncodedIntegers3, &EncodedIntegers4, &EncodedIntegers1, &EncodedIntegers2); /// swap order of integers
        }///end if

        if (UserChoice == 2)///begin decryption
        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Decode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int DecodedIntegers1 = (UserDigit1 - 7) * 10;
            int DecodedIntegers2 = (UserDigit2 - 7) * 10;
            int DecodedIntegers3 = (UserDigit3 - 7) * 10;
            int DecodedIntegers4 = (UserDigit4 - 7) * 10;
            printf("Decoded result:\n");
            printf("%d", "%d", "%d", "%d\n", DecodedIntegers1, &DecodedIntegers2, &DecodedIntegers3, &DecodedIntegers4); /// keep order the same to decrypt
        }///end if
        system("pause");
        return 0;
    }
}
</code>```

Output:

```<code>Make your selection.
1
Encode: Enter FOUR integers.
1234
Encoded result:
11893608 Continue? (1) Yes, (0) No
Make your selection.
1
Press any key to continue . . .```

```

答:
You scanf is wrong. I would rather do this

```<code>char UserInputNumber[5];
printf("Encode: Enter FOUR integers.\n");
scanf("%s", UserInputNumber);
// optional error checking the input: length is 4? All char is a number?
UserDigit1 = (UserInputNumber[0] - '0');
UserDigit2 = (UserInputNumber[1] - '0');
UserDigit3 = (UserInputNumber[2] - '0');
UserDigit4 = (UserInputNumber[3] - '0');

</code>```

Also your printf should look like this:

```<code>printf("%d%d%d%d\n", EncodedIntegers3, EncodedIntegers4, EncodedIntegers1, EncodedIntegers2);
</code>```

With the & you tried to print their memory address not their value, but also your format string was wrong too.

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner in a C programming class, and our assignment for the third chapter of our textbook was to create an encode/decode program that takes in four digits from user input and rearranges them depending on whether or not the user wants them to be either encoded or decoded. I am also having trouble with getting the program to do both decoding and encoding in one file. However, when I fire up the program, whenever I select encode and type in my four digits, the program not only gives me a massive number that should only be four digits as the encoded result. It also gives me the "press any key to continue" prompt, signifying the end of the program, instead of starting over completely and going back to where it asks the user to either decode or encode.

The output is also attached.

I've tried looking around and changing some of the variables from int to double, as well as checking my math... I'm not 100% sure why the encryption and decryption aren't limited to anything besides four digits.

As for getting the program to start over, I've tried using a do-while loop, but it still didn't seem to work, so I deleted it.. I also tried using another if statement and then using break, but it was marked as an error.

The assignment says that, "each digit should be encrypted by adding 7 and taking the remainder after division by 10; after encrypting each digit, swap the first and third digits, and then swap the second and fourth digits. Decryption should reverse the process. Program must do encode and decode in one file.

Here is the example that my instructor posted for this, this is what the output should look like.

Enter a four digit number: 1234
Encoded Digits: 0189
Continue (1) Exit (0): 1
Encode (1) Decode (2): 2
Enter a four digit number: 0189
Decoded Digits: 1234
Continue (1) Exit (0): 0

Here is my code:

///Compiler used: Microsoft Visual Studio
///Language: C
#include <string>
#pragma warning(disable: 4996)
#include <math.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{

    int Encodechoice = 1;
    int inputdigit1 = 0;
    int Decodechoice = 2;
    int UserChoice = 0;
    int ContinueChoice = 0;
    int UserDigit1 = 0;
    int UserDigit2 = 0;
    int UserDigit3 = 0;
    int UserDigit4 = 0;

    {
        printf("(1) Encode, (2) Decode\n");
        printf("Make your selection.\n");//Asks user to make selection
        scanf_s("%d", &UserChoice);

        if (UserChoice == 1)//begin encryption

        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Encode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int EncodedIntegers1 = (UserDigit1 + 7) % 10;
            int EncodedIntegers2 = (UserDigit2 + 7) % 10;
            int EncodedIntegers3 = (UserDigit3 + 7) % 10;
            int EncodedIntegers4 = (UserDigit4 + 7) % 10;
            printf("Encoded result:\n");
            printf("%d", "%d", "%d", "%d\n", EncodedIntegers3, &EncodedIntegers4, &EncodedIntegers1, &EncodedIntegers2); /// swap order of integers
        }///end if

        if (UserChoice == 2)///begin decryption
        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Decode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int DecodedIntegers1 = (UserDigit1 - 7) * 10;
            int DecodedIntegers2 = (UserDigit2 - 7) * 10;
            int DecodedIntegers3 = (UserDigit3 - 7) * 10;
            int DecodedIntegers4 = (UserDigit4 - 7) * 10;
            printf("Decoded result:\n");
            printf("%d", "%d", "%d", "%d\n", DecodedIntegers1, &DecodedIntegers2, &DecodedIntegers3, &DecodedIntegers4); /// keep order the same to decrypt
        }///end if
        system("pause");
        return 0;
    }
}

Output:

Make your selection.
1
Encode: Enter FOUR integers.
1234
Encoded result:
11893608 Continue? (1) Yes, (0) No
Make your selection.
1
Press any key to continue . . .```

Body:
You scanf is wrong. I would rather do this

char UserInputNumber[5];
printf("Encode: Enter FOUR integers.\n");
scanf("%s", UserInputNumber);
// optional error checking the input: length is 4? All char is a number?
UserDigit1 = (UserInputNumber[0] - '0');
UserDigit2 = (UserInputNumber[1] - '0');
UserDigit3 = (UserInputNumber[2] - '0');
UserDigit4 = (UserInputNumber[3] - '0');

Also your printf should look like this:

printf("%d%d%d%d\n", EncodedIntegers3, EncodedIntegers4, EncodedIntegers1, EncodedIntegers2);

With the & you tried to print their memory address not their value, but also your format string was wrong too.


问:
Is meteor worth to be used in 2019 ? is it still alive?
I start to develop a new web application using meteor, but i noticed that the last update of meteor platform is from 2017 !!
so i became confused of its reliability.
is it dead??
or what is happen to meteor developing team?</p>

答: It's absolutely not dead. Meteor has been going strong and progress is being made.You can read about the latest changes in the Roadmap. 1.9.1 has been released a couple of days ago. You can find lots of Meteor community members at this slack channel


问:
Ajax is not defined - Grails jQuery plugin
I'm using jQuery in my project by the jQuery and jQuery-ui plugins. I have a simple form which I want to submit in Ajax call to the controller. The thing is, when I put the <g:submitToRemote /> tag and then click it, firebug shows error that Ajax is not defined. What can I do to make it work?

答:
Add this line to the layout file that your form GSP is using

```<code><g:javascript library="jquery" plugin="jquery"/>
</code>```

and the following to your grails-app/conf/Config.groovy

```<code>grails.views.javascript.library="jquery"
</code>```

Grails 2.0.0

In Grails 2.0.0 the correct way to include JQuery is to use the new resources plugin by adding the following to the layout GSP

```<code><html>
    <head>
        <!-- These 2 lines include JQuery -->
        <g:javascript library="jquery"/>
        <r:layoutResources/>

        <g:layoutHead/>
    </head>
    <body>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Add this line to the layout file that your form GSP is using

<g:javascript library="jquery" plugin="jquery"/>

and the following to your grails-app/conf/Config.groovy

grails.views.javascript.library="jquery"

Grails 2.0.0

In Grails 2.0.0 the correct way to include JQuery is to use the new resources plugin by adding the following to the layout GSP

<html>
    <head>
        <!-- These 2 lines include JQuery -->
        <g:javascript library="jquery"/>
        <r:layoutResources/>

        <g:layoutHead/>
    </head>
    <body>
    </body>
</html>


问:
Jasmine test for simple Angular2 component not working
I have this simple component:

```<code>@Component({
    selector: 'messages',
    styleUrls: ['messages.component.scss'],
    templateUrl: 'messages.component.html',
})
export class MessagesComponent implements OnInit {

    constructor(private dataService: DataService) {}

    public getOne(): number{
        return 1;
    }
}
</code>```

I'm trying to run a test for it but I can't get it to work please help:

```<code>describe('Component: MessagesComponent', () => {
    let component: MessagesComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [MessagesComponent],
        }).compileComponents();

        const fixture = TestBed.createComponent(MessagesComponent);
        component = fixture.componentInstance;
    });

    it('should have a defined component', () => {
        expect(true).toBeTruthy();
    });

});
</code>```

(I'm using webpack if that is relevant)

This is the error I get:

```<code>    Error: This test module uses the component MessagesComponent
 which is using a "templateUrl", but they were never compiled.
 Please call "TestBed.compileComponents" before your test.
</code>```

答:
You get this test failure message when the runtime environment compiles the source code during the tests themselves.

To correct the problem, call compileComponents() as explained below.

```<code>beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ YourComponent ],
  })
  .compileComponents()
  .then(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
  });
}));
</code>```

here we must call compileComponents() with async function and then create a component instance in 'then block', this will solve the problem.

refer https://angular.io/guide/testing#compile-components for more information.

Body:
I have this simple component:

@Component({
    selector: 'messages',
    styleUrls: ['messages.component.scss'],
    templateUrl: 'messages.component.html',
})
export class MessagesComponent implements OnInit {

    constructor(private dataService: DataService) {}

    public getOne(): number{
        return 1;
    }
}

I'm trying to run a test for it but I can't get it to work please help:

describe('Component: MessagesComponent', () => {
    let component: MessagesComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [MessagesComponent],
        }).compileComponents();

        const fixture = TestBed.createComponent(MessagesComponent);
        component = fixture.componentInstance;
    });

    it('should have a defined component', () => {
        expect(true).toBeTruthy();
    });

});

(I'm using webpack if that is relevant)

This is the error I get:

    Error: This test module uses the component MessagesComponent
 which is using a "templateUrl", but they were never compiled.
 Please call "TestBed.compileComponents" before your test.

Body:
You get this test failure message when the runtime environment compiles the source code during the tests themselves.

To correct the problem, call compileComponents() as explained below.

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ YourComponent ],
  })
  .compileComponents()
  .then(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
  });
}));

here we must call compileComponents() with async function and then create a component instance in 'then block', this will solve the problem.

refer https://angular.io/guide/testing#compile-components for more information.


问:
ModuleNotFoundError: No module named 'pynput' Python3 and pip3
I want to use 'pynput', so I used pip to add it to my environment.
The installation proceeds without problem.
But I am unable to import it into my project.

I am using python 3.8.1 on my environment.
I used pip3 for installation.
I have already tried to install pynput, uninstall it and reinstall it multiple times.
My .py file doesn't have a confusing name like "pynput.py"
I am comfortable with my environment when I try to execute my file.
I am trying to run from my terminal or VSCodium, and neither of them works.
And I work on Debian 10.

pip freeze :

```<code>pynput==1.6.7
python-xlib==0.26
six==1.14.0
</code>```

Traceback :

```<code>Traceback (most recent call last):
  File "./play.py", line 6, in <module>
    from pynput import keyboard
ModuleNotFoundError: No module named 'pynput'
</code>```

So I don't understand why it doesn't work.

thank you in advance for your help :)

答:
It might be possible you have two versions. Rry installing with python3 -m pip install pynput or you should use some older version of Python. I am using 3.7.5 and its works perfect for me.

Try importing from the terminal.

Body:
I want to use 'pynput', so I used pip to add it to my environment.
The installation proceeds without problem.
But I am unable to import it into my project.

I am using python 3.8.1 on my environment.
I used pip3 for installation.
I have already tried to install pynput, uninstall it and reinstall it multiple times.
My .py file doesn't have a confusing name like "pynput.py"
I am comfortable with my environment when I try to execute my file.
I am trying to run from my terminal or VSCodium, and neither of them works.
And I work on Debian 10.

pip freeze :

pynput==1.6.7
python-xlib==0.26
six==1.14.0

Traceback :

Traceback (most recent call last):
  File "./play.py", line 6, in <module>
    from pynput import keyboard
ModuleNotFoundError: No module named 'pynput'

So I don't understand why it doesn't work.

thank you in advance for your help :)


问:
Two date range return
How to return the two date combine string like below.

```<code>Start Date : 11/2/2020
End Date : 26/2/2020
</code>```

Then Output should be like this : 11 to 26 feb 2020

```<code>Start Date : 26/2/2020
End Date : 5/3/2020
</code>```

Then Output should be like this : 26 feb to 5 march 2020

```<code>Start Date : 29/12/2020
End Date : 2/1/2021
</code>```

Then Output should be like this : 29 Dec 2020 to 2 Jan 2021

Please Help me to solve this issue.

答:
Welcome to stackoverflow :-)

PHP has a native DateTime class which allows you to perform date manipulations and date-formatting.

In your specific case you could start to convert your two dates into objects and then reformat it into your expected format.

Here is an example:

```<code>$date = DateTime::createFromFormat('d/m/Y', $startString);
</code>```

With this in mind we can now create a function which will check your requirements and return the string on your custom format.

```<code>function my_date_range(DateTime $start, DateTime $end)
{
    $sameYear = $start->format('Y') === $end->format('Y');
    $sameMonth = $sameYear && $start->format('m') === $end->format('m');
    $sameDay = $sameMonth && $start->format('d') === $end->format('d');

    if ($sameDay) {
        return $start->format('d M Y');
    }
    if ($sameMonth) {
        return sprintf('%s to %s', $start->format('d'), $end->format('d M Y'));
    }
    if ($sameYear) {
        return sprintf('%s to %s', $start->format('d M'), $end->format('d M Y'));
    }

    return sprintf("%s to %s", $start->format('d M Y'), $end->format('d M Y'));
}
</code>```

Below you'll find my example dates and usage:

```<code>var_dump(
    my_date_range(DateTime::createFromFormat('d/m/Y', '11/2/2020'), DateTime::createFromFormat('d/m/Y', '26/2/2020')),
    my_date_range(DateTime::createFromFormat('d/m/Y', '26/2/2020'), DateTime::createFromFormat('d/m/Y', '5/3/2020')),
    my_date_range(DateTime::createFromFormat('d/m/Y', '29/12/2020'), DateTime::createFromFormat('d/m/Y', '2/1/2021')),
    my_date_range(DateTime::createFromFormat('d/m/Y', '2/1/2021'), DateTime::createFromFormat('d/m/Y', '2/1/2021')),
)
</code>```

Result:

```<code>string(17) "11 to 26 Feb 2020"
string(21) "26 Feb to 05 Mar 2020"
string(26) "29 Dec 2020 to 02 Jan 2021"
string(11) "02 Jan 2021"
</code>```

Title: Two date range return

Body:
How to return the two date combine string like below.

Start Date : 11/2/2020
End Date : 26/2/2020

Then Output should be like this : 11 to 26 feb 2020

Start Date : 26/2/2020
End Date : 5/3/2020

Then Output should be like this : 26 feb to 5 march 2020

Start Date : 29/12/2020
End Date : 2/1/2021

Then Output should be like this : 29 Dec 2020 to 2 Jan 2021

Please Help me to solve this issue.

Body:
Welcome to stackoverflow :-)

PHP has a native DateTime class which allows you to perform date manipulations and date-formatting.

In your specific case you could start to convert your two dates into objects and then reformat it into your expected format.

Here is an example:

$date = DateTime::createFromFormat('d/m/Y', $startString);

With this in mind we can now create a function which will check your requirements and return the string on your custom format.

function my_date_range(DateTime $start, DateTime $end)
{
    $sameYear = $start->format('Y') === $end->format('Y');
    $sameMonth = $sameYear && $start->format('m') === $end->format('m');
    $sameDay = $sameMonth && $start->format('d') === $end->format('d');

    if ($sameDay) {
        return $start->format('d M Y');
    }
    if ($sameMonth) {
        return sprintf('%s to %s', $start->format('d'), $end->format('d M Y'));
    }
    if ($sameYear) {
        return sprintf('%s to %s', $start->format('d M'), $end->format('d M Y'));
    }

    return sprintf("%s to %s", $start->format('d M Y'), $end->format('d M Y'));
}

Below you'll find my example dates and usage:

var_dump(
    my_date_range(DateTime::createFromFormat('d/m/Y', '11/2/2020'), DateTime::createFromFormat('d/m/Y', '26/2/2020')),
    my_date_range(DateTime::createFromFormat('d/m/Y', '26/2/2020'), DateTime::createFromFormat('d/m/Y', '5/3/2020')),
    my_date_range(DateTime::createFromFormat('d/m/Y', '29/12/2020'), DateTime::createFromFormat('d/m/Y', '2/1/2021')),
    my_date_range(DateTime::createFromFormat('d/m/Y', '2/1/2021'), DateTime::createFromFormat('d/m/Y', '2/1/2021')),
)

Result:

string(17) "11 to 26 Feb 2020"
string(21) "26 Feb to 05 Mar 2020"
string(26) "29 Dec 2020 to 02 Jan 2021"
string(11) "02 Jan 2021"


问:
How can I show a loading-skeleton / shimmer effect in ReactJS for an Owl-carousel
Any NPM library, or utilizing CSS transition ideas are welcome.

I have already tried out the following NPM libraries:

react-loading-skeleton

react-skeleton-loader

But if you have a way to make it work, please do help!

I am not able to change the size of their respective loaders in order to look like an owl-carousels

These are the two owl-carousels, I wanna show loading-skeleton for.

答:
Why not pass in some fake data to the carousels?</p>

```<code>const apiData = fetch(...)

<Carousel data={apiData.length || [{title: "...", image: "some_dummy_image.jpg"}]}
</code>```

Body:
Why not pass in some fake data to the carousels?

const apiData = fetch(...)

<Carousel data={apiData.length || [{title: "...", image: "some_dummy_image.jpg"}]}


问:
I have a list of the following structure and need to return data from it
The list is like this-

```<code>[(a,{1:True,2:False}),(b,{1:False,2:True})........]
</code>```

Now I need to return the numbers which are true for one or more letter inputs.

Sample input-
a

Sample output-
1

Sample input-
a,b

Sample output-
1,2(since 1 is true for A and 2 is true for B I need to return both)

It is basically a list of tuples in which there are also dictionaries.

答:
you can use list comprehension:

```<code>my_list = [('a',{1:True,2:False}),('b',{1:False,2:True}), ('b',{1:False,2:False}), ('a',{1:True,2:False})]
my_input = {'a', 'b'}

[k for t in my_list if t[0]  in my_input for k, v in t[1].items() if v]
</code>```

output:

```<code>[1, 2, 1]
</code>```

Body:
The list is like this-

[(a,{1:True,2:False}),(b,{1:False,2:True})........]

Now I need to return the numbers which are true for one or more letter inputs.

Sample input-
a

Sample output-
1

Sample input-
a,b

Sample output-
1,2(since 1 is true for A and 2 is true for B I need to return both)

It is basically a list of tuples in which there are also dictionaries.

Body:
you can use list comprehension:

my_list = [('a',{1:True,2:False}),('b',{1:False,2:True}), ('b',{1:False,2:False}), ('a',{1:True,2:False})]
my_input = {'a', 'b'}

[k for t in my_list if t[0]  in my_input for k, v in t[1].items() if v]

output:

[1, 2, 1]


问:
Is it possible to create this animation using particles.js
I've been trying to make an animation similar to this but all I was able to achieve so far using particles.js is this.

Basically I was unable to make the shapes look like spheres and the interaction element itself is very lacking. So I'm just wondering If I can actually use particles.js for this, or if there's a much better or easier option.

JavaScript:

```<code> particlesJS("particles-js", {
  particles: {
    number: {
      value: 147,
      density: { enable: true, value_area: 946.9771699587272 }
    },
    color: { value: "#017185" },
    shape: {
      type: "circle",
      stroke: { width: 0, color: "#000000" },
      polygon: { nb_sides: 3 },
      image: { src: "img/github.svg", width: 100, height: 100 }
    },
    opacity: {
      value: 1,
      random: false,
      anim: { enable: false, speed: 1, opacity_min: 0.1, sync: false }
    },
    size: {
      value: 15,
      random: false,
      anim: { enable: false, speed: 40, size_min: 0.1, sync: false }
    },
    line_linked: {
      enable: false,
      distance: 150,
      color: "#ffffff",
      opacity: 0.4,
      width: 1
    },
    move: {
      enable: true,
      speed: 6,
      direction: "none",
      random: false,
      straight: false,
      out_mode: "out",
      bounce: false,
      attract: { enable: false, rotateX: 600, rotateY: 1200 }
    }
  },
  interactivity: {
    detect_on: "canvas",
    events: {
      onhover: { enable: true, mode: "repulse" },
      onclick: { enable: true, mode: "push" },
      resize: true
    },
    modes: {
      grab: { distance: 400, line_linked: { opacity: 1 } },
      bubble: { distance: 400, size: 40, duration: 2, opacity: 8, speed: 3 },
      repulse: { distance: 200, duration: 0.4 },
      push: { particles_nb: 4 },
      remove: { particles_nb: 2 }
    }
  },
  retina_detect: true
});
var count_particles, stats, update;
stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = "absolute";
stats.domElement.style.left = "0px";
stats.domElement.style.top = "0px";
document.body.appendChild(stats.domElement);
count_particles = document.querySelector(".js-count-particles");
update = function() {
  stats.begin();
  stats.end();
  if (window.pJSDom[0].pJS.particles && window.pJSDom[0].pJS.particles.array) {
    count_particles.innerText = window.pJSDom[0].pJS.particles.array.length;
  }
  requestAnimationFrame(update);
};
requestAnimationFrame(update);
</code>```

答:
As far as I know It's not possible with Particle.js
Check out Three js and its amazing features.
You can detect mouse event on particles such as bellow examples:

Waves

Points

Good luck

Body:
I've been trying to make an animation similar to this but all I was able to achieve so far using particles.js is this.

Basically I was unable to make the shapes look like spheres and the interaction element itself is very lacking. So I'm just wondering If I can actually use particles.js for this, or if there's a much better or easier option.

JavaScript:

 particlesJS("particles-js", {
  particles: {
    number: {
      value: 147,
      density: { enable: true, value_area: 946.9771699587272 }
    },
    color: { value: "#017185" },
    shape: {
      type: "circle",
      stroke: { width: 0, color: "#000000" },
      polygon: { nb_sides: 3 },
      image: { src: "img/github.svg", width: 100, height: 100 }
    },
    opacity: {
      value: 1,
      random: false,
      anim: { enable: false, speed: 1, opacity_min: 0.1, sync: false }
    },
    size: {
      value: 15,
      random: false,
      anim: { enable: false, speed: 40, size_min: 0.1, sync: false }
    },
    line_linked: {
      enable: false,
      distance: 150,
      color: "#ffffff",
      opacity: 0.4,
      width: 1
    },
    move: {
      enable: true,
      speed: 6,
      direction: "none",
      random: false,
      straight: false,
      out_mode: "out",
      bounce: false,
      attract: { enable: false, rotateX: 600, rotateY: 1200 }
    }
  },
  interactivity: {
    detect_on: "canvas",
    events: {
      onhover: { enable: true, mode: "repulse" },
      onclick: { enable: true, mode: "push" },
      resize: true
    },
    modes: {
      grab: { distance: 400, line_linked: { opacity: 1 } },
      bubble: { distance: 400, size: 40, duration: 2, opacity: 8, speed: 3 },
      repulse: { distance: 200, duration: 0.4 },
      push: { particles_nb: 4 },
      remove: { particles_nb: 2 }
    }
  },
  retina_detect: true
});
var count_particles, stats, update;
stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = "absolute";
stats.domElement.style.left = "0px";
stats.domElement.style.top = "0px";
document.body.appendChild(stats.domElement);
count_particles = document.querySelector(".js-count-particles");
update = function() {
  stats.begin();
  stats.end();
  if (window.pJSDom[0].pJS.particles && window.pJSDom[0].pJS.particles.array) {
    count_particles.innerText = window.pJSDom[0].pJS.particles.array.length;
  }
  requestAnimationFrame(update);
};
requestAnimationFrame(update);


问:
How running process does reload new lib file code dynamically in python?
I want to use  my project's new lib file. However, i don't hope to main progress stop running?
for example ,i have b.py:

```<code>import a
import time
def main():
    for i in range(1000):
        time.sleep(5)
        print i
        a.abc()
main()
</code>```

a.py is

```<code>def abc():
    print 'abc'
</code>```

I want to modify my abc function in a.py to

```<code>def abc():
    print '123'
</code>```

When i finish modified abc function in a.py, I hope it worked at once in main process in a.py .
i remove a.pyc file, but it still print abc, not 123. How to print 123 when don't stop main progress?

Can't change main process. Because it is always running.

答:
You might want to save your module hashsum and after every execution check if it changed and reload if so:

import hashlib
import time
import a

def main():
    with open('a.py', 'rb') as f:
        module_hashsum = hashlib.md5(f.read()).hexdigest()

    for i in range(1000):
        time.sleep(5)
        print i
        a.abc()

        with open('a.py', 'rb') as f:
            hashsum_temp = hashlib.md5(f.read()).hexdigest()

        if module_hashsum != hashsum_temp:
            module_hashsum = hashsum_temp
            reload(a)

main()
```

Or just reload it after every execution.

Might aswell do some fancy checks for file's mtime, like it's done in django. But it will trigger reload even if you didn't change anything in a file and only did :wq in Vim (just saved file) for e.g.
But I don't think it's necessary, as building hash is fast.

Body:
I want to use  my project's new lib file. However, i don't hope to main progress stop running?
for example ,i have b.py:

import a
import time
def main():
    for i in range(1000):
        time.sleep(5)
        print i
        a.abc()
main()

a.py is

def abc():
    print 'abc'

I want to modify my abc function in a.py to

def abc():
    print '123'

When i finish modified abc function in a.py, I hope it worked at once in main process in a.py .
i remove a.pyc file, but it still print abc, not 123. How to print 123 when don't stop main progress?

Can't change main process. Because it is always running.

Body:
You might want to save your module hashsum and after every execution check if it changed and reload if so:

import hashlib
import time
import a

def main():
    with open('a.py', 'rb') as f:
        module_hashsum = hashlib.md5(f.read()).hexdigest()

    for i in range(1000):
        time.sleep(5)
        print i
        a.abc()

        with open('a.py', 'rb') as f:
            hashsum_temp = hashlib.md5(f.read()).hexdigest()

        if module_hashsum != hashsum_temp:
            module_hashsum = hashsum_temp
            reload(a)

main()

Or just reload it after every execution.

Might aswell do some fancy checks for file's mtime, like it's done in django. But it will trigger reload even if you didn't change anything in a file and only did :wq in Vim (just saved file) for e.g.
But I don't think it's necessary, as building hash is fast.


问:
Invite Links with Devise
I want to build an invite system where each registered user has a unique invite link. And when their friends use that link to sign up they both get benefits. You should also be able to send the link through social media or email.

An example of what I mean is airbnb's invite system:

I have tried using devise invitable but it seems to work differently. It seems to register an user with an email first and then signs them up if they accept the invite. This does not allow for social media sharing.

So, how do I go about building such an invite system and how do I integrate it with devise.

答:
You could create specific route for this links, like eg /r/1234 (where 1234) is referrer code assigned to Referrer.

Once referee go through this link in assigned to this route controller you set the cookie referrer=1234 and redirect to signup page.

Let's add to User model :referrer_code_on_signup attribute:

```<code>class User < ApplicationRecord
  attr_accessor :referrer_code_on_signup
  after_commit :grand_rewards, on: create
  # ... other user stuff

  private

    def grand_rewards
      return unless referrer_code_on_signup.present?

      # some rewards logic
    end
end
</code>```

In case if referee will pass signup form and submit it you should tweak registrations controller:

```<code># app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    if cookies[:referrer].present?
      build_resource(referrer_code_on_signup: cookies[:referrer])
    else
      build_resource
    end
  end
end
</code>```

And then tell devise to use that controller instead of the default with:

```<code># app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
</code>```

For the special route:
You could create ReferrerController:

```<code># app/controllers/referrers_controller.rb
class ReferrersController < ApplicationController
  before_action :set_referrer

  # Endpoint for share referrer link like example.com/r/123456 - redirects to
  # sign in page and setup referrer cookies
  def show
    cookies[:referrer] = @referrer.referrer_code if @referrer.present?
    redirect_to user_sign_up_path
  end

  private

    def set_referrer
      @referrer = User.find_by(referrer_code: params[:id])
    end
end
</code>```

And update your routes with line:

```<code>resources :referrers, only: :show, path: :r
</code>```

We assume your User model has referrer_code stored at DB and assigns random, unique value on signup

Title: Invite Links with Devise

Body:
You could create specific route for this links, like eg /r/1234 (where 1234) is referrer code assigned to Referrer.

Once referee go through this link in assigned to this route controller you set the cookie referrer=1234 and redirect to signup page.

Let's add to User model :referrer_code_on_signup attribute:

class User < ApplicationRecord
  attr_accessor :referrer_code_on_signup
  after_commit :grand_rewards, on: create
  # ... other user stuff

  private

    def grand_rewards
      return unless referrer_code_on_signup.present?

      # some rewards logic
    end
end

In case if referee will pass signup form and submit it you should tweak registrations controller:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    if cookies[:referrer].present?
      build_resource(referrer_code_on_signup: cookies[:referrer])
    else
      build_resource
    end
  end
end

And then tell devise to use that controller instead of the default with:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

For the special route:
You could create ReferrerController:

# app/controllers/referrers_controller.rb
class ReferrersController < ApplicationController
  before_action :set_referrer

  # Endpoint for share referrer link like example.com/r/123456 - redirects to
  # sign in page and setup referrer cookies
  def show
    cookies[:referrer] = @referrer.referrer_code if @referrer.present?
    redirect_to user_sign_up_path
  end

  private

    def set_referrer
      @referrer = User.find_by(referrer_code: params[:id])
    end
end

And update your routes with line:

resources :referrers, only: :show, path: :r

We assume your User model has referrer_code stored at DB and assigns random, unique value on signup


问:
Not able to throw exception for @override method
```<code>@Override
protected void configure() throws IOException{

        Properties props = new Properties();
        props.load(new FileInputStream(System.getProperty("user.dir")+"/src/properties/android.properties"));
        Names.bindProperties(binder(), props);

}
</code>```

I am not able to throw any Exception for the above-overridden method. I'm getting error remove throw Exception. This is the implementation of a Guice module.

答:
You can't change the Module interface, but you can work around it in several ways with Guice.

You can wrap the exception:

```<code>try (InputStream in = new FileInputStream(System.getProperty("user.dir")+"/src/properties/android.properties")) {
   Properties props = new Properties();
    props.load(in);
    Names.bindProperties(binder(), props);
} catch (IOException e) {
  // Yes, it's hard to create Guice exceptions. It's just like that.
  Message message = new Message(List.of(this), "Unable to load properties file", e);
  throw new ConfigurationException(List.of(message));
}
</code>```

You can move the file loading out of the module:

```<code>class MyModule extends AbstractModule {
  private final Properties properties;
  MyModule(Properties properties) {
    this.properties = properties;
  }
  @Override protected void configure() {
    Names.bind(binder(), props);
  }
}
</code>```

And create your module like this. Normally you should be able to throw your exceptions outside the module implementations.

```<code>Properties properties = new Properties();
try (InputStream in = FileInputStream(System.getProperty("user.dir")+"/src/properties/android.properties")) {
  properties.load(in);
}
Module module = new MyModule(properties);
</code>```

Body:
@Override
protected void configure() throws IOException{

        Properties props = new Properties();
        props.load(new FileInputStream(System.getProperty("user.dir")+"/src/properties/android.properties"));
        Names.bindProperties(binder(), props);

}

I am not able to throw any Exception for the above-overridden method. I'm getting error remove throw Exception. This is the implementation of a Guice module.

Body:
You can't change the Module interface, but you can work around it in several ways with Guice.

You can wrap the exception:

try (InputStream in = new FileInputStream(System.getProperty("user.dir")+"/src/properties/android.properties")) {
   Properties props = new Properties();
    props.load(in);
    Names.bindProperties(binder(), props);
} catch (IOException e) {
  // Yes, it's hard to create Guice exceptions. It's just like that.
  Message message = new Message(List.of(this), "Unable to load properties file", e);
  throw new ConfigurationException(List.of(message));
}

You can move the file loading out of the module:

class MyModule extends AbstractModule {
  private final Properties properties;
  MyModule(Properties properties) {
    this.properties = properties;
  }
  @Override protected void configure() {
    Names.bind(binder(), props);
  }
}

And create your module like this. Normally you should be able to throw your exceptions outside the module implementations.

Properties properties = new Properties();
try (InputStream in = FileInputStream(System.getProperty("user.dir")+"/src/properties/android.properties")) {
  properties.load(in);
}
Module module = new MyModule(properties);


问:
How to pass everything possible to i, j and by in nested functions?
I'm working on a package which uses data.table inside. In this package, I have a function count_by which calculates the number of distinct ID's for a specific variable in a data.table by groups. With some help (R data.table: How to pass "everything possible" to by in a function?) I got this to work as expected:

library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2

# create example data
sample_dt <- data.table(
    id = sort(rep(LETTERS[1:3], 3)),
    year = rep(2018L:2020L),
    x = runif(9)
)
sample_dt[id == "B" & year < 2020, x := NA_real_]

# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
    id_var <- as.character(substitute(id_var))
    val_var <- as.character(substitute(val_var))

    eval(substitute(
        DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
    ))
}

# test inner function -> works as expected
(reference <- count_by(sample_dt, id_var = id, val_var = x, by = year))
#>    year distinct_ids
#> 1: 2018            2
#> 2: 2019            2
#> 3: 2020            3

identical(count_by(sample_dt, "id", x, year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", year)     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", "year")   , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, "year")       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, c("year"))    , reference)
#> [1] TRUE
```

<p><sup>Created on 2020-02-20 by the reprex package (v0.3.0)</sup></p>

<p>Now I would like to use the function <code>count_by()</code> within another function (minimal example below):</p>

<pre class="lang-r prettyprint-override"><code># define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
    data <- as.data.table(data)
    count_by(data, id_var, val_var, by)
}

# test wrapper function
wrapper(sample_dt, id_var = id, val_var = x, by = year)
#> Error in .(distinct_ids = uniqueN(get("id_var"))): could not find function "."
</code>```

Created on 2020-02-20 by the reprex package (v0.3.0)

Debugging count_by() lead to the observation that if count_by() is called from wrapper(), substitute(DT[...]) also substitutes DT to data:

Browse[2]> substitute(
+         DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
+     )
data[!is.na(get("val_var")), .(distinct_ids = uniqueN(get("id_var"))),
    by = by]
```

Since data is not available in the function environment of count_by() it gets evaluated to utils::data which then leads to the error. This makes the problem clear, but I cannot think of a solution.

I need to substitute the whole DT[...] expression in order for by to work properly (see R data.table: How to pass "everything possible" to by in a function? or pass variables and names to data.table function). But I can't substitute the whole expression in order for DT not beeing substituted.

What is the solution to this dilemma?

答:
@chinsoon12, thank you very much! You answer almost did it! I still need to convert id_var and val_var to character and then get() these in the call to data.table - otherwise, passing strings to id_var and val_var does not work.

But evaluating at the higher level is the necessary key idea. Here is the complete answer for future reference:

# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
    id_var <- as.character(substitute(id_var))
    val_var <- as.character(substitute(val_var))

    substitute(
        DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
    )
}

# define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
    data <- as.data.table(data)
    expr <- eval(substitute(count_by(data, id_var, val_var, by)))
    eval(expr)
}

# test wrapper function
(reference <- (wrapper(sample_dt, id_var = id, val_var = x, by = year)))
#>    year distinct_ids
#> 1: 2018            2
#> 2: 2019            2
#> 3: 2020            3

identical(wrapper(sample_dt, "id", x, year)       , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", "x", year)     , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", x, "year")     , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", x, c("year"))  , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", "x", "year")   , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, "x", year)       , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, "x", "year")     , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, "x", c("year"))  , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, x, "year")       , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, x, c("year"))    , reference)
#> [1] TRUE

# test expression in by
wrapper(sample_dt, "id", x, by = .(year_2019 = year > 2019L))
#>    year_2019 distinct_ids
#> 1:     FALSE            2
#> 2:      TRUE            3
```

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
I'm working on a package which uses data.table inside. In this package, I have a function count_by which calculates the number of distinct ID's for a specific variable in a data.table by groups. With some help (R data.table: How to pass "everything possible" to by in a function?) I got this to work as expected:

library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2

# create example data
sample_dt <- data.table(
    id = sort(rep(LETTERS[1:3], 3)),
    year = rep(2018L:2020L),
    x = runif(9)
)
sample_dt[id == "B" & year < 2020, x := NA_real_]

# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
    id_var <- as.character(substitute(id_var))
    val_var <- as.character(substitute(val_var))

    eval(substitute(
        DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
    ))
}

# test inner function -> works as expected
(reference <- count_by(sample_dt, id_var = id, val_var = x, by = year))
#>    year distinct_ids
#> 1: 2018            2
#> 2: 2019            2
#> 3: 2020            3

identical(count_by(sample_dt, "id", x, year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", year)     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", "year")   , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", year)       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", "year")     , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", c("year"))  , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, "year")       , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, c("year"))    , reference)
#> [1] TRUE

Created on 2020-02-20 by the reprex package (v0.3.0)

Now I would like to use the function count_by() within another function (minimal example below):

# define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
    data <- as.data.table(data)
    count_by(data, id_var, val_var, by)
}

# test wrapper function
wrapper(sample_dt, id_var = id, val_var = x, by = year)
#> Error in .(distinct_ids = uniqueN(get("id_var"))): could not find function "."

Created on 2020-02-20 by the reprex package (v0.3.0)

Debugging count_by() lead to the observation that if count_by() is called from wrapper(), substitute(DT[...]) also substitutes DT to data:

Browse[2]> substitute(
+         DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
+     )
data[!is.na(get("val_var")), .(distinct_ids = uniqueN(get("id_var"))),
    by = by]

Since data is not available in the function environment of count_by() it gets evaluated to utils::data which then leads to the error. This makes the problem clear, but I cannot think of a solution.

I need to substitute the whole DT[...] expression in order for by to work properly (see R data.table: How to pass "everything possible" to by in a function? or pass variables and names to data.table function). But I can't substitute the whole expression in order for DT not beeing substituted.

What is the solution to this dilemma?

Body:
@chinsoon12, thank you very much! You answer almost did it! I still need to convert id_var and val_var to character and then get() these in the call to data.table - otherwise, passing strings to id_var and val_var does not work.

But evaluating at the higher level is the necessary key idea. Here is the complete answer for future reference:

# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
    id_var <- as.character(substitute(id_var))
    val_var <- as.character(substitute(val_var))

    substitute(
        DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
    )
}

# define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
    data <- as.data.table(data)
    expr <- eval(substitute(count_by(data, id_var, val_var, by)))
    eval(expr)
}

# test wrapper function
(reference <- (wrapper(sample_dt, id_var = id, val_var = x, by = year)))
#>    year distinct_ids
#> 1: 2018            2
#> 2: 2019            2
#> 3: 2020            3

identical(wrapper(sample_dt, "id", x, year)       , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", "x", year)     , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", x, "year")     , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", x, c("year"))  , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", "x", "year")   , reference)
#> [1] TRUE
identical(wrapper(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, "x", year)       , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, "x", "year")     , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, "x", c("year"))  , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, x, "year")       , reference)
#> [1] TRUE
identical(wrapper(sample_dt, id, x, c("year"))    , reference)
#> [1] TRUE

# test expression in by
wrapper(sample_dt, "id", x, by = .(year_2019 = year > 2019L))
#>    year_2019 distinct_ids
#> 1:     FALSE            2
#> 2:      TRUE            3

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
Querying DynamoDB with Lambda does nothing
I have the following code for a Lambda function:

```<code>console.log('Loading function');
var aws = require('aws-sdk');
var ddb = new aws.DynamoDB();

function getUser(userid) {
    var q = ddb.getItem({
        TableName: "Users",
        Key: {
            userID: { S: userid } }
        }, function(err, data) {
            if (err) {
                console.log(err);
                return err;
            }
            else {
                console.log(data);
            }
    });
    console.log(q);
}

exports.handler = function(event, context) {
    console.log('Received event');
    getUser('user1');
    console.log("called DynamoDB");
    context.succeed();
};
</code>```

I have a [Users] table that is defined as such:

```<code>{
    "cognitoID": { "S": "token" },
    "email": { "S": "user1@domain.com" },
    "password": { "S": "somepassword" },
    "tos_aggreement": { "BOOL": true },
    "userID": { "S": "user1" }
}
</code>```

When I call the function (from the AWS Console or the CLI) I can see the messages in the logs but the callback for the getItem() is never called.

I tried with doing getItem(params) with no callback, then defined the callbacks for complete, success and failure but when I do the send(), even the complete callback isn't called either.

I know that the calls are asynchronous and I thought that maybe, the lambda function was finishing before the query was done and therefore the callback would not be called, but, I added a simple stupid loop at the end of the function and the call timed out after 3 seconds, without the callbacks being called at all.

I tried with different functions batchGetItem, getItem, listTables and scan. Result is the same, no error but the callback function is never called.

I'm betting that if I query dynamoDB without using Lambda it will get me the results so I'm really wondering why nothing is happening here.

I create a role for the function and I created a policy that would allow access to the functionalities in dynamoDB that I need but to no avail.

The policy looks like this:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": "arn:aws:lambda:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "dynamodb:GetItem",
                "dynamodb:BatchGetItem",
                "dynamodb:Scan",
                "dynamodb:PutItem",
                "dynamodb:Query",
                "dynamodb:GetRecords",
                "dynamodb:ListTables"
            ],
            "Resource": "arn:aws:dynamodb:*:*:*"
        },
        {
            "Action": [
                "logs:*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
</code>```

I ran the policy in the simulator and it worked as I thought it would.
Suggestions?

答:
My problem was that the function I was trying to call accepted a callback.

Node.js therefore just continued the execution of the Lambda function and once it reaches the end it tells Lambda to shut down because it's done.

Here's an example of how you can solve it using Promises:

```<code>'use strict';

exports.handler = async (event, context) => {

  // WRAP THE FUNCTION WHICH USES A CALLBACK IN A PROMISE AND RESOLVE IT, WHEN
  // THE CALLBACK FINISHES

  return await new Promise( (resolve, reject) => {

    // FUNCTION THAT USES A CALLBACK
    functionThatUsesACallback(params, (error, data) => {
      if(error) reject(error)
      if(data) resolve(data)
    });

  });

};
</code>```

Body:
I have the following code for a Lambda function:

console.log('Loading function');
var aws = require('aws-sdk');
var ddb = new aws.DynamoDB();

function getUser(userid) {
    var q = ddb.getItem({
        TableName: "Users",
        Key: {
            userID: { S: userid } }
        }, function(err, data) {
            if (err) {
                console.log(err);
                return err;
            }
            else {
                console.log(data);
            }
    });
    console.log(q);
}

exports.handler = function(event, context) {
    console.log('Received event');
    getUser('user1');
    console.log("called DynamoDB");
    context.succeed();
};

I have a [Users] table that is defined as such:

{
    "cognitoID": { "S": "token" },
    "email": { "S": "user1@domain.com" },
    "password": { "S": "somepassword" },
    "tos_aggreement": { "BOOL": true },
    "userID": { "S": "user1" }
}

When I call the function (from the AWS Console or the CLI) I can see the messages in the logs but the callback for the getItem() is never called.

I tried with doing getItem(params) with no callback, then defined the callbacks for complete, success and failure but when I do the send(), even the complete callback isn't called either.

I know that the calls are asynchronous and I thought that maybe, the lambda function was finishing before the query was done and therefore the callback would not be called, but, I added a simple stupid loop at the end of the function and the call timed out after 3 seconds, without the callbacks being called at all.

I tried with different functions batchGetItem, getItem, listTables and scan. Result is the same, no error but the callback function is never called.

I'm betting that if I query dynamoDB without using Lambda it will get me the results so I'm really wondering why nothing is happening here.

I create a role for the function and I created a policy that would allow access to the functionalities in dynamoDB that I need but to no avail.

The policy looks like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": "arn:aws:lambda:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "dynamodb:GetItem",
                "dynamodb:BatchGetItem",
                "dynamodb:Scan",
                "dynamodb:PutItem",
                "dynamodb:Query",
                "dynamodb:GetRecords",
                "dynamodb:ListTables"
            ],
            "Resource": "arn:aws:dynamodb:*:*:*"
        },
        {
            "Action": [
                "logs:*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

I ran the policy in the simulator and it worked as I thought it would.
Suggestions?

Body:
My problem was that the function I was trying to call accepted a callback.

Node.js therefore just continued the execution of the Lambda function and once it reaches the end it tells Lambda to shut down because it's done.

Here's an example of how you can solve it using Promises:

'use strict';

exports.handler = async (event, context) => {

  // WRAP THE FUNCTION WHICH USES A CALLBACK IN A PROMISE AND RESOLVE IT, WHEN
  // THE CALLBACK FINISHES

  return await new Promise( (resolve, reject) => {

    // FUNCTION THAT USES A CALLBACK
    functionThatUsesACallback(params, (error, data) => {
      if(error) reject(error)
      if(data) resolve(data)
    });

  });

};


问:
OAuth2 authentication code for already logged in user
With an OAuth2 implementation (either developed in-house, or a 3rd party like Google, Facebook, Login With Amazon, etc.), is it possible to generate an authentication code on behalf of a user logged into a mobile app or web app without requiring any action from the user?

The typical flow to obtain the authentication code requires the user to authenticate and authorize the requested scope. But in this case, the user is already authenticated into the app, so I want to avoid requiring the user to log in again.

The authentication code is required for invoking an external third-party API that will eventually exchange the authentication code for refresh/access tokens. The backend system (associated with the API) needs to get its own refresh/access token based on the authentication code shared with it. This is not for a one-time use of the token; the system needs to have its own tokens for that logged in user, independent of the mobile client.

答:
It is possible to get user token for another client. You do not need new authentication code, you just call token endpoind with some params. For example, in Keycloak this flow is called Token Exchange. You need to configure clients in the Keycloak and then you can call token endpoint with access token you have.

```<code>{
  client_id: your client id,
  client_secret: your client secret,
  subject_token: token you have
  audience: target client id,
  grant_type: urn:ietf:params:oauth:grant-type:token-exchange,
  requested token type: urn:ietf:params:oauth:token-type:refresh_token
}
</code>```

You can read about this flow here:
https://tools.ietf.org/id/draft-ietf-oauth-token-exchange-12.html

It is also called On-Behalf-Of flow like in Azure:
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow

Body:
It is possible to get user token for another client. You do not need new authentication code, you just call token endpoind with some params. For example, in Keycloak this flow is called Token Exchange. You need to configure clients in the Keycloak and then you can call token endpoint with access token you have.

{
  client_id: your client id,
  client_secret: your client secret,
  subject_token: token you have
  audience: target client id,
  grant_type: urn:ietf:params:oauth:grant-type:token-exchange,
  requested token type: urn:ietf:params:oauth:token-type:refresh_token
}

You can read about this flow here:
https://tools.ietf.org/id/draft-ietf-oauth-token-exchange-12.html

It is also called On-Behalf-Of flow like in Azure:
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow


问:
Django Many-To-One
I'm trying to create a simple to-do app in Django. I have some trouble to understand the idea of foreign keys. Each project suppose to get multiple apartments, and each apartment should get multiple tasks.

models:

```<code># Project model
class Project(models.Model):
    name = models.CharField(_("Name"), max_length=30)
    city = models.CharField(_("City"), max_length=30)
    street = models.CharField(_("Street"), max_length=30)
    number = models.IntegerField(_("Number"), max_length=4)
    ZIP = models.ImageField(_("ZIP"), max_length=10)
    manager = models.CharField(_("Manager"), choices=managers, default='ariel')

    # Apartments
    apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE)

    def __repr__(self):
        return "{}".format(self.name)

# Apartment model
class Apartment(models.Model):
    building = models.CharField(_("Building"), max_length=4)
    floor = models.CharField(_("Floor"), max_length=4)
    number = models.CharField(_("Number"), max_length=4)
    type = models.CharField(_("Type"), max_length=4)
    upgraded = models.BooleanField(_("Upgraded"), default=False)
    drawing = models.FileField(_("Drawing"), upload_to=None)
    notes = models.TextField(_("Notes"), max_length=500)
    status = models.BooleanField(_("Completed"), default=False)

    # Tasks
    airTunnels = models.ForeignKey(_("Air Tunnels"), Task, on_delete=models.CASCADE)
    gasPipelines = models.ForeignKey(_("Gas Pipelines"), Task, on_delete=models.CASCADE)

    def __repr__(self):
        return "{} - {}".format(self.number, self.status)

# Task model
class Task(models.Model):
    title = models.CharField(_("Task"), max_length=30)
    doneBy = models.CharField(_("Done By"), choices=workers, default='daniel')
    date = models.DateTimeField(_("Date"), default=timezone.now())

    def __repr__(self):
        return "{}".format(self.title)
</code>```

答:
If you use apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE), it means that each project has onyl one apartment. So you must define different project for each apartment. If your each apartment can has only one project, you must define foreignkey inside your apartment model like that:

```<code>class Apartment(models.Model):
    #...your other fields
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
</code>```

For apartment tasks, If I understood correctly, your apartment model can has multiple tasks.So, you can use ManyToMany field for this.With this definition, your each apartment can has multiple tasks. But your each task can belong to multiple apartment objects. If you don't want to each task can belongs to different apartment objects, you must set OneToMany relation.You can do that with adding foreignkeyfield to task model like that:

```<code>class Task(models.Model):
    #...your other fields
    apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE)
</code>```

Title: Django Many-To-One

Body:
I'm trying to create a simple to-do app in Django. I have some trouble to understand the idea of foreign keys. Each project suppose to get multiple apartments, and each apartment should get multiple tasks.

models:

# Project model
class Project(models.Model):
    name = models.CharField(_("Name"), max_length=30)
    city = models.CharField(_("City"), max_length=30)
    street = models.CharField(_("Street"), max_length=30)
    number = models.IntegerField(_("Number"), max_length=4)
    ZIP = models.ImageField(_("ZIP"), max_length=10)
    manager = models.CharField(_("Manager"), choices=managers, default='ariel')

    # Apartments
    apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE)

    def __repr__(self):
        return "{}".format(self.name)

# Apartment model
class Apartment(models.Model):
    building = models.CharField(_("Building"), max_length=4)
    floor = models.CharField(_("Floor"), max_length=4)
    number = models.CharField(_("Number"), max_length=4)
    type = models.CharField(_("Type"), max_length=4)
    upgraded = models.BooleanField(_("Upgraded"), default=False)
    drawing = models.FileField(_("Drawing"), upload_to=None)
    notes = models.TextField(_("Notes"), max_length=500)
    status = models.BooleanField(_("Completed"), default=False)

    # Tasks
    airTunnels = models.ForeignKey(_("Air Tunnels"), Task, on_delete=models.CASCADE)
    gasPipelines = models.ForeignKey(_("Gas Pipelines"), Task, on_delete=models.CASCADE)

    def __repr__(self):
        return "{} - {}".format(self.number, self.status)

# Task model
class Task(models.Model):
    title = models.CharField(_("Task"), max_length=30)
    doneBy = models.CharField(_("Done By"), choices=workers, default='daniel')
    date = models.DateTimeField(_("Date"), default=timezone.now())

    def __repr__(self):
        return "{}".format(self.title)

Body:
If you use apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE), it means that each project has onyl one apartment. So you must define different project for each apartment. If your each apartment can has only one project, you must define foreignkey inside your apartment model like that:

class Apartment(models.Model):
    #...your other fields
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

For apartment tasks, If I understood correctly, your apartment model can has multiple tasks.So, you can use ManyToMany field for this.With this definition, your each apartment can has multiple tasks. But your each task can belong to multiple apartment objects. If you don't want to each task can belongs to different apartment objects, you must set OneToMany relation.You can do that with adding foreignkeyfield to task model like that:

class Task(models.Model):
    #...your other fields
    apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE)


问:
Disable pasting text into HTML form
Is there a way using JavaScript to disable the ability to paste text into a text field on an HTML form?

E.g.
I have a simple registration form where the user is required to input their email twice. The second email entry is to verify there are no typos in the first email entry. However if the user copy/pastes their email then that defeats the purpose and I've been experiencing users having problems because they've input the wrong email and copy/pasted it.

Maybe I wasn't clear on my question but I am not trying to prevent people from copying (or drag selecting) text on their browser. I just want to stop them from pasting input into a text field to minimize user error.

Perhaps instead of using this "hack" you can suggest another solution to the core problem of what I'm trying to solve here? I've done less than half a dozen user tests and this has already happened twice. My audience does not have a high level of computer proficiency.

答:
You can disable the copy paste option with jQuery by the below script:

```<code>jQuery("input").attr("onpaste","return false;");
</code>```

of by using the bellow oppaste attribute into the input fields.

```<code>onpaste="return false;"
</code>```

Title: Disable pasting text into HTML form

Body:
You can disable the copy paste option with jQuery by the below script:

jQuery("input").attr("onpaste","return false;");

of by using the bellow oppaste attribute into the input fields.

onpaste="return false;"


问:
manual object constructor call
Can you please tell me if it is possible to call object constructor manually? I know it's wrong and I would never do something like that in my own code and I know I can fix this problem by creating and calling initialization function, however the problem is that I stumbled at a case where there are thousands of lines of code in object's and its parents' constructors...

```<code>class MyClass()
{
    MyClass() { }
    virtual ~MyClass();

    void reset()
    {
         this->~MyClass();
         this->MyClass::MyClass(); //error: Invalid use of MyClass
    }
};
</code>```

答:
You can still move construction/destruction into separate functions and call those directly. i.e.</p>

```<code>class MyClass {
public:
    MyClass() { construct(); }
    ~MyClass() { destruct(); }

    void reset() {
        destruct();
        construct();
    }

private:
    void construct() {
        // lots of code
    }

    void destruct() {
        // lots of code
    }
};
</code>```

Title: manual object constructor call

Body:
Can you please tell me if it is possible to call object constructor manually? I know it's wrong and I would never do something like that in my own code and I know I can fix this problem by creating and calling initialization function, however the problem is that I stumbled at a case where there are thousands of lines of code in object's and its parents' constructors...

class MyClass()
{
    MyClass() { }
    virtual ~MyClass();

    void reset()
    {
         this->~MyClass();
         this->MyClass::MyClass(); //error: Invalid use of MyClass
    }
};

Body:
You can still move construction/destruction into separate functions and call those directly. i.e.

class MyClass {
public:
    MyClass() { construct(); }
    ~MyClass() { destruct(); }

    void reset() {
        destruct();
        construct();
    }

private:
    void construct() {
        // lots of code
    }

    void destruct() {
        // lots of code
    }
};


问:
Typescript and fixed array length (array.slice)
I am trying to fix my arguments array to a length of 2 so that it can be spread into a function that requires 2 arguments. However, the array comes from a slice of another array that returns the type number[].

```<code>const twoArgs: [number, number] = [2,3,4].slice(0, 2));
//Type 'number[]' is missing the following properties from type '[number, number]': 0, 1

functionThatRequiresTwoArgs(...twoArgs);
//Expected 2 arguments, but got 0 or more.
</code>```

I have found a solution but I wasn't able to clearly do it in a neat fashion. Perhaps a typescript user can enlighten me with a better way of doing this?

```<code>const myWorkaround = (t: number[]) => {
  let result: [number, number] = [0, 0];
  t.forEach((value, index) => (result[index] = value));
  return result;
};

const twoArgs: [number, number] = myWorkaround([2,3,4].slice(0, 2));

functionThatRequiresTwoArgs(...twoArgs);
</code>```

答:
This should do the trick

```<code>const twoArgs = [2,3,4].slice(0, 2) as [number, number];

functionThatRequiresTwoArgs(...twoArgs);
</code>```

The slice function returns an array of undefined length (event if you know it will become a certain length), so you can't define twoArgs to be of a defined length. However, you can typecast it with the as keyword.

Body:
I am trying to fix my arguments array to a length of 2 so that it can be spread into a function that requires 2 arguments. However, the array comes from a slice of another array that returns the type number[].

const twoArgs: [number, number] = [2,3,4].slice(0, 2));
//Type 'number[]' is missing the following properties from type '[number, number]': 0, 1

functionThatRequiresTwoArgs(...twoArgs);
//Expected 2 arguments, but got 0 or more.

I have found a solution but I wasn't able to clearly do it in a neat fashion. Perhaps a typescript user can enlighten me with a better way of doing this?

const myWorkaround = (t: number[]) => {
  let result: [number, number] = [0, 0];
  t.forEach((value, index) => (result[index] = value));
  return result;
};

const twoArgs: [number, number] = myWorkaround([2,3,4].slice(0, 2));

functionThatRequiresTwoArgs(...twoArgs);

Body:
This should do the trick

const twoArgs = [2,3,4].slice(0, 2) as [number, number];

functionThatRequiresTwoArgs(...twoArgs);

The slice function returns an array of undefined length (event if you know it will become a certain length), so you can't define twoArgs to be of a defined length. However, you can typecast it with the as keyword.


问:
How to make the if statement without repetition of code?
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.</p>

```<code>    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }
</code>```

答:
1)You can put out of the 'if' the sentences that are repeated:

```<code>arrow.setAttribute("class","arrow2");
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);
if(allTasks[t].status === "Completed"){

    tag.setAttribute("class","completed");

}else if(allTasks[t].status === "Past Due"){

    tag.setAttribute("class","pastdue");

}else if(allTasks[t].status === "Duetoday"){

    tag.setAttribute("class","duetoday");

}else if(allTasks[t].status === "Onhold"){

    tag.setAttribute("class","onhold");

}else if(allTasks[t].status === "Canceled"){

    tag.setAttribute("class","canceled");

}
</code>```

2) (much more specific to your code) if you notice, inside setAttribute you're entering the lowered case of your status

```<code>tag.setAttribute("class",allTasks[y].status.toLowerCase().replace(/\s/g, ''));
arrow.setAttribute("class","arrow2");
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);
</code>```

Body:
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.

    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }

Body:
1)You can put out of the 'if' the sentences that are repeated:

arrow.setAttribute("class","arrow2");
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);
if(allTasks[t].status === "Completed"){

    tag.setAttribute("class","completed");

}else if(allTasks[t].status === "Past Due"){

    tag.setAttribute("class","pastdue");

}else if(allTasks[t].status === "Duetoday"){

    tag.setAttribute("class","duetoday");

}else if(allTasks[t].status === "Onhold"){

    tag.setAttribute("class","onhold");

}else if(allTasks[t].status === "Canceled"){

    tag.setAttribute("class","canceled");

}

2) (much more specific to your code) if you notice, inside setAttribute you're entering the lowered case of your status

tag.setAttribute("class",allTasks[y].status.toLowerCase().replace(/\s/g, ''));
arrow.setAttribute("class","arrow2");
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);


问:
BottomNavigationBar without Text
Yes, my question is this. How can I do like this?

I did a BottomNavigationBar but it looks like this.

My codes are like this:

```<code>bottomNavigationBar: BottomNavigationBar(
    items: <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Icon(Icons.home),
        title: Text("Home"),
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.markunread),
        title: Text("Chat"),
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.location_on),
        title: Text("Your Country"),
      ),
    ],
    fixedColor: Colors.blue,
    onTap: clickedBottomBtn,
  ),
</code>```

答:
Set showSelectedLabels and showUnselectedLabels to `false:

```<code>      bottomNavigationBar: BottomNavigationBar(
        currentIndex: 0,
        type: BottomNavigationBarType.fixed,
        items: // ...
        showSelectedLabels: false,
        showUnselectedLabels: false,
      ),
</code>```

Title: BottomNavigationBar without Text

Body:
Yes, my question is this. How can I do like this?

I did a BottomNavigationBar but it looks like this.

My codes are like this:

bottomNavigationBar: BottomNavigationBar(
    items: <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Icon(Icons.home),
        title: Text("Home"),
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.markunread),
        title: Text("Chat"),
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.location_on),
        title: Text("Your Country"),
      ),
    ],
    fixedColor: Colors.blue,
    onTap: clickedBottomBtn,
  ),

Body:
Set showSelectedLabels and showUnselectedLabels to `false:

      bottomNavigationBar: BottomNavigationBar(
        currentIndex: 0,
        type: BottomNavigationBarType.fixed,
        items: // ...
        showSelectedLabels: false,
        showUnselectedLabels: false,
      ),