问:
switch in another switch case
i have some big problem witch switch case in switch. what is a problem.
if i do oprions 1-5(first switch) ever think working. If i use 6.(first) and 10.(second) also working. But If i do: take 1/2/3/4 times 1-5(options) and after 12.(from second menu) and than second time oprion 1-5(from first) program sometimes stop, and sometimes working but puts on screen/file somethink like "-12391239~21312312=3123121"
My code:

```<code>#include <stdio.h>
#include <stdlib.h>

struct d
{
    int a;
    int b;
    int wynik;
    char znak;
};
int ok;
void wypisz(struct d* tabs)
{
    if(ok==0)
    {
        printf("historia pusta!");
    }
    else
    {

        for (int i = 0; i < ok; i++) {
            printf("%d", tabs[i].a);
            printf("%c", tabs[i].znak);
            printf("%d", tabs[i].b);
            printf("=");
            printf("%d", tabs[i].wynik);
            printf("\n");
        }
    }
}
void usunzpliku()
{
    FILE *plik=fopen("siema.txt", "w");
    if(plik)
    {
        fputc('\0', plik);
        printf("WYCZYSZCZONO HISTORIE Z PLIKU\n");
        fclose(plik);
    }
    else
    {
        printf("Nie udalo sie wczytac pliku.");
    }

}
/*void usun(struct d* tabs)
{
    if(ok==0)
    {
        printf("historia pusta!");
    }
    else
    {
        ok=0;
        tabs = realloc(tabs, ok*sizeof(struct d));
    }
}*/
void zapiszdo(struct d* tabs)
{
    FILE *plik=fopen("siema.txt", "w");

    if(ok==0)
    {
        printf("historia pusta!");
    }
    else
    {
        if(plik)
        {
            printf("\n%d\n",ok);
            for (int i = 0; i < ok; i++) {
                fprintf(plik,"%d", tabs[i].a);
                fprintf(plik,"%c", tabs[i].znak);
                fprintf(plik,"%d", tabs[i].b);
                fprintf(plik, "=");
                fprintf(plik,"%d", tabs[i].wynik);
                fprintf(plik,"\n");
            }
            fclose(plik);
        }
        else
        {
            printf("Nie udalo sie wczytac pliku.");
        }
    }
}
void wyswietlz()
{
    FILE *plik=fopen("siema.txt", "r");
    if(plik)
    {
        int c;
        c=getc(plik);
        printf("####    HISTORIA   ####\n");
        while(c!=EOF)
        {
            printf("%c", c);
            c=getc(plik);
        }
        printf("####    KONIEC    ####");
    }
    else
    {
        printf("Nie udalo sie wczytac pliku.");
    }
    fclose(plik);
}
void dodawanie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x+y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '+';
    printf("\nWYKONUJE SIE\n");
}
void odejmowanie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x-y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '-';
}
void mnozenie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x*y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '*';
}
void dzielenie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x/y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '/';
}
void potegowanie(int x, struct d* dzialania)
{
    ok++;
    int w = x*x;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = 2;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '^';
}
int main()
{
    int A, B;
    int dz;
    struct d *dzi = malloc (ok* sizeof(struct d));
    for(;;)
    {
        printf(" KALKULATOR ");
        printf("[%d]\n", ok);
        printf(" 1. dodwanie \n");
        printf(" 2. odejmowanie \n");
        printf(" 3. mnozenie \n");
        printf(" 4. dzielenie \n");
        printf(" 5. potegowanie \n");
        printf(" 6. historia \n");
        printf(" co chcesz policzyc: ");
        scanf("%d", &dz);
        switch (dz) {
            case 1:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                while (getchar() != '\n')
                    continue;
                printf(" Podaj B: ");
                scanf("%d", &B);
                while (getchar() != '\n')
                    continue;
                dodawanie(A, B, dzi);

            }break;
            case 2:
            {
                printf("Podaj A: ");
                scanf(" %d", &A);
                printf(" Podaj B: ");
                scanf(" %d", &B);
                odejmowanie(A, B, dzi);
            }break;
            case 3:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                printf(" Podaj B: ");
                scanf("%d", &B);
                mnozenie(A, B, dzi);
            }break;
            case 4:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                printf(" Podaj B: ");
                scanf("%d", &B);
                dzielenie(A, B, dzi);
            }break;
            case 5:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                potegowanie(A, dzi);
            }break;
            case 6:
            {
                int h;
                printf(" HISTORIA \n");
                printf(" 10. wypisz. \n");
                printf(" 11. usun. \n");
                printf(" 12. zapisz do pliku \n");
                printf(" 13. wyswietl z pliku \n");
                printf(" 14. usun z pliku \n");
                printf(" co chcesz zrobic z historia: ");
                scanf("%d", &h);
                switch (h)
                {
                    case 10: {
                        wypisz(dzi);
                    }break;
                    case 11: {
                        // usun(dzi);
                    }break;
                    case 12: {
                        zapiszdo(dzi);
                    }break;
                    case 13: {
                        wyswietlz();
                    }break;
                    case 14: {
                        usunzpliku();
                    }break;
                    default: {
                        printf(" nie prawidlowe dzialanie ");
                    }break;
                }
            }break;
            default:
            {
                printf(" Brak dzialania ");
            }break;
        }
    }
}
</code>```

rezult:

```<code> KALKULATOR [0]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:1
 Podaj A:2
  Podaj B:2

WYKONUJE SIE
 KALKULATOR [1]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 2+2=4
 KALKULATOR [1]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:2
 Podaj A:2
  Podaj B:2
  KALKULATOR [2]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 2+2=4
2-2=0
 KALKULATOR [2]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:5
 Podaj A:2
  KALKULATOR [3]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 2+2=4
2-2=0
2^2=4
 KALKULATOR [3]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:12

3
 KALKULATOR [3]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:1
 Podaj A:2
  Podaj B:2

WYKONUJE SIE
 KALKULATOR [4]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 1309873488▀479=1309868368
2-2=0
2^2=4
1309891696?479=1102239351
 KALKULATOR [4]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:
</code>```

答:
your problem is the you are not updating your array pointer (dzi in main)

example

```<code>void dodawanie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x+y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '+';
    printf("\nWYKONUJE SIE\n");
}
</code>```

You have passed dzi by value, any changes you make in this function are private to it. The value of dzi in main is unchanged. SO the next time you call realloc you are pointing to an area that was already realloced.

You need to pass dzi by reference. I have fixed one, you need to fix all.

```<code>void dodawanie(int x, int y, struct d** dzialania)
{
    ok++;
    int w = x + y;
    *dzialania = realloc(*dzialania, ok * sizeof(struct d));
    struct d* dz = *dzialania;
    dz[ok - 1].a = x;
    dz[ok - 1].b = y;
    dz[ok - 1].wynik = w;
    dz[ok - 1].znak = '+';
    printf("\nWYKONUJE SIE\n");
}

...
...

    dodawanie(A, B, &dzi);
</code>```

Title: switch in another switch case

Body:
i have some big problem witch switch case in switch. what is a problem.
if i do oprions 1-5(first switch) ever think working. If i use 6.(first) and 10.(second) also working. But If i do: take 1/2/3/4 times 1-5(options) and after 12.(from second menu) and than second time oprion 1-5(from first) program sometimes stop, and sometimes working but puts on screen/file somethink like "-12391239~21312312=3123121"
My code:

#include <stdio.h>
#include <stdlib.h>

struct d
{
    int a;
    int b;
    int wynik;
    char znak;
};
int ok;
void wypisz(struct d* tabs)
{
    if(ok==0)
    {
        printf("historia pusta!");
    }
    else
    {

        for (int i = 0; i < ok; i++) {
            printf("%d", tabs[i].a);
            printf("%c", tabs[i].znak);
            printf("%d", tabs[i].b);
            printf("=");
            printf("%d", tabs[i].wynik);
            printf("\n");
        }
    }
}
void usunzpliku()
{
    FILE *plik=fopen("siema.txt", "w");
    if(plik)
    {
        fputc('\0', plik);
        printf("WYCZYSZCZONO HISTORIE Z PLIKU\n");
        fclose(plik);
    }
    else
    {
        printf("Nie udalo sie wczytac pliku.");
    }

}
/*void usun(struct d* tabs)
{
    if(ok==0)
    {
        printf("historia pusta!");
    }
    else
    {
        ok=0;
        tabs = realloc(tabs, ok*sizeof(struct d));
    }
}*/
void zapiszdo(struct d* tabs)
{
    FILE *plik=fopen("siema.txt", "w");

    if(ok==0)
    {
        printf("historia pusta!");
    }
    else
    {
        if(plik)
        {
            printf("\n%d\n",ok);
            for (int i = 0; i < ok; i++) {
                fprintf(plik,"%d", tabs[i].a);
                fprintf(plik,"%c", tabs[i].znak);
                fprintf(plik,"%d", tabs[i].b);
                fprintf(plik, "=");
                fprintf(plik,"%d", tabs[i].wynik);
                fprintf(plik,"\n");
            }
            fclose(plik);
        }
        else
        {
            printf("Nie udalo sie wczytac pliku.");
        }
    }
}
void wyswietlz()
{
    FILE *plik=fopen("siema.txt", "r");
    if(plik)
    {
        int c;
        c=getc(plik);
        printf("####    HISTORIA   ####\n");
        while(c!=EOF)
        {
            printf("%c", c);
            c=getc(plik);
        }
        printf("####    KONIEC    ####");
    }
    else
    {
        printf("Nie udalo sie wczytac pliku.");
    }
    fclose(plik);
}
void dodawanie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x+y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '+';
    printf("\nWYKONUJE SIE\n");
}
void odejmowanie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x-y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '-';
}
void mnozenie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x*y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '*';
}
void dzielenie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x/y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '/';
}
void potegowanie(int x, struct d* dzialania)
{
    ok++;
    int w = x*x;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = 2;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '^';
}
int main()
{
    int A, B;
    int dz;
    struct d *dzi = malloc (ok* sizeof(struct d));
    for(;;)
    {
        printf(" KALKULATOR ");
        printf("[%d]\n", ok);
        printf(" 1. dodwanie \n");
        printf(" 2. odejmowanie \n");
        printf(" 3. mnozenie \n");
        printf(" 4. dzielenie \n");
        printf(" 5. potegowanie \n");
        printf(" 6. historia \n");
        printf(" co chcesz policzyc: ");
        scanf("%d", &dz);
        switch (dz) {
            case 1:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                while (getchar() != '\n')
                    continue;
                printf(" Podaj B: ");
                scanf("%d", &B);
                while (getchar() != '\n')
                    continue;
                dodawanie(A, B, dzi);

            }break;
            case 2:
            {
                printf("Podaj A: ");
                scanf(" %d", &A);
                printf(" Podaj B: ");
                scanf(" %d", &B);
                odejmowanie(A, B, dzi);
            }break;
            case 3:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                printf(" Podaj B: ");
                scanf("%d", &B);
                mnozenie(A, B, dzi);
            }break;
            case 4:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                printf(" Podaj B: ");
                scanf("%d", &B);
                dzielenie(A, B, dzi);
            }break;
            case 5:
            {
                printf("Podaj A: ");
                scanf("%d", &A);
                potegowanie(A, dzi);
            }break;
            case 6:
            {
                int h;
                printf(" HISTORIA \n");
                printf(" 10. wypisz. \n");
                printf(" 11. usun. \n");
                printf(" 12. zapisz do pliku \n");
                printf(" 13. wyswietl z pliku \n");
                printf(" 14. usun z pliku \n");
                printf(" co chcesz zrobic z historia: ");
                scanf("%d", &h);
                switch (h)
                {
                    case 10: {
                        wypisz(dzi);
                    }break;
                    case 11: {
                        // usun(dzi);
                    }break;
                    case 12: {
                        zapiszdo(dzi);
                    }break;
                    case 13: {
                        wyswietlz();
                    }break;
                    case 14: {
                        usunzpliku();
                    }break;
                    default: {
                        printf(" nie prawidlowe dzialanie ");
                    }break;
                }
            }break;
            default:
            {
                printf(" Brak dzialania ");
            }break;
        }
    }
}

rezult:

 KALKULATOR [0]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:1
 Podaj A:2
  Podaj B:2

WYKONUJE SIE
 KALKULATOR [1]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 2+2=4
 KALKULATOR [1]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:2
 Podaj A:2
  Podaj B:2
  KALKULATOR [2]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 2+2=4
2-2=0
 KALKULATOR [2]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:5
 Podaj A:2
  KALKULATOR [3]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 2+2=4
2-2=0
2^2=4
 KALKULATOR [3]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:12

3
 KALKULATOR [3]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:1
 Podaj A:2
  Podaj B:2

WYKONUJE SIE
 KALKULATOR [4]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:6
  HISTORIA
 10. wypisz.
 11. usun.
 12. zapisz do pliku
 13. wyswietl z pliku
 14. usun z pliku
 co chcesz zrobic z historia:10
 1309873488▀479=1309868368
2-2=0
2^2=4
1309891696?479=1102239351
 KALKULATOR [4]
 1. dodwanie
 2. odejmowanie
 3. mnozenie
 4. dzielenie
 5. potegowanie
 6. historia
 co chcesz policzyc:

Body:
your problem is the you are not updating your array pointer (dzi in main)

example

void dodawanie(int x, int y, struct d* dzialania)
{
    ok++;
    int w = x+y;
    dzialania = realloc(dzialania, ok*sizeof(struct d));
    dzialania[ok-1].a = x;
    dzialania[ok-1].b = y;
    dzialania[ok-1].wynik = w;
    dzialania[ok-1].znak = '+';
    printf("\nWYKONUJE SIE\n");
}

You have passed dzi by value, any changes you make in this function are private to it. The value of dzi in main is unchanged. SO the next time you call realloc you are pointing to an area that was already realloced.

You need to pass dzi by reference. I have fixed one, you need to fix all.

void dodawanie(int x, int y, struct d** dzialania)
{
    ok++;
    int w = x + y;
    *dzialania = realloc(*dzialania, ok * sizeof(struct d));
    struct d* dz = *dzialania;
    dz[ok - 1].a = x;
    dz[ok - 1].b = y;
    dz[ok - 1].wynik = w;
    dz[ok - 1].znak = '+';
    printf("\nWYKONUJE SIE\n");
}

...
...

    dodawanie(A, B, &dzi);


来源: stackexchange

问:
Spring: How to inject a value to static field?
With this class

```<code>@Component
public class Sample {

    @Value("${my.name}")
    public static String name;

}
</code>```

If I try Sample.name, it is always 'null'. So I tried this.

```<code>public class Sample {

    public static String name;

    @PostConstruct
    public void init(){
        name = privateName;
    }

    @Value("${my.name}")
    private String privateName;

    public String getPrivateName() {
        return privateName;
    }

    public void setPrivateName(String privateName) {
        this.privateName = privateName;
    }

}
</code>```

This code works. Sample.name is set properly. Is this good way or not? If not, is there something more good way? And how to do it?

答:
Although workarounds may need to be implemented, one should try to avoid them in most scenarios if possible. Spring is great at handling dependency injection and treats most objects as Singletons. This means that Spring can handle the creation of objects for you, and the injection of these objects at runtime. When combining this with the fact that your Spring managed bean is likely a Singleton, the use of static methods and variables is largely unnecessary. You can simply autowire in an instance of the object you are looking for at the constructor level or variable level and reference the non-static version of the method or variable. This is ideal and behaves similarly to a static reference. Non static variables are basically static because you are only ever using one instance of the object in every part of the code and because of dependency injection you are never handling the instantiation of the object, just like with a static reference! Great! Now I'm sure there are instances where you need the work around (i.e. you aren't using dependency injection or class is not a singleton), but try to not use workarounds if possible. Also this is just my 2 cents. Someone may be able to offer 3. (:</p>
```<code>public class InjectableClass{
     @Value("${my.value}")
     private String myString;

     public String nonStaticMethod(){
           return myString;
     }
}

public class LogicClass{
    private InjectableClass injectableClass;
    @Autowire
    public LogicClass(InjectableClass injectableClass){
       this.injectableClass = injectableClass;
    }

    public void logicClassMethod(){
        System.out.println("Hey! Here is the value I set on myString: " +
                         injectableClass.nonStaticMethod() + ". That was
                          basically like using a static method!");
    }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
With this class

@Component
public class Sample {

    @Value("${my.name}")
    public static String name;

}

If I try Sample.name, it is always 'null'. So I tried this.

public class Sample {

    public static String name;

    @PostConstruct
    public void init(){
        name = privateName;
    }

    @Value("${my.name}")
    private String privateName;

    public String getPrivateName() {
        return privateName;
    }

    public void setPrivateName(String privateName) {
        this.privateName = privateName;
    }

}

This code works. Sample.name is set properly. Is this good way or not? If not, is there something more good way? And how to do it?

Body:
Although workarounds may need to be implemented, one should try to avoid them in most scenarios if possible. Spring is great at handling dependency injection and treats most objects as Singletons. This means that Spring can handle the creation of objects for you, and the injection of these objects at runtime. When combining this with the fact that your Spring managed bean is likely a Singleton, the use of static methods and variables is largely unnecessary. You can simply autowire in an instance of the object you are looking for at the constructor level or variable level and reference the non-static version of the method or variable. This is ideal and behaves similarly to a static reference. Non static variables are basically static because you are only ever using one instance of the object in every part of the code and because of dependency injection you are never handling the instantiation of the object, just like with a static reference! Great! Now I'm sure there are instances where you need the work around (i.e. you aren't using dependency injection or class is not a singleton), but try to not use workarounds if possible. Also this is just my 2 cents. Someone may be able to offer 3. (:

public class InjectableClass{
     @Value("${my.value}")
     private String myString;

     public String nonStaticMethod(){
           return myString;
     }
}

public class LogicClass{
    private InjectableClass injectableClass;
    @Autowire
    public LogicClass(InjectableClass injectableClass){
       this.injectableClass = injectableClass;
    }

    public void logicClassMethod(){
        System.out.println("Hey! Here is the value I set on myString: " +
                         injectableClass.nonStaticMethod() + ". That was
                          basically like using a static method!");
    }
 }


问:
Possible Object Cycle Detected
I am trying to add a ProductGateway to a database and assign it a user. I am getting an A possible object cycle was detected. error but I am unsure how I can overcome this.

This is a 1:M relationship using Entity Framework Core. I am also in .NET 6.

The idea is that a user can exist in the database without any products but a product must be assigned a user.

```<code>var user = _repository.GetAll<UserGateway>().FirstOrDefault(u => u.Id == userId);

        if (user == null) throw new InvalidUserException();

        var productGateways = productDtos.Select(productDto => new ProductGateway
            {
                DateCreated = DateTime.Now,
                DateLastModified = DateTime.Now,
                Description = productDto.Description,
                Quantity = productDto.Quantity,
                Title = productDto.Title,
                Gsku = productDto.Sku,
                ImageUrl = "",
                UserId = userId
            })
            .ToList();

        user.Products = productGateways;
        foreach (var product in user.Products)
        {
            product.User = user;
        }

        _repository.AddRange(productGateways);
        _repository.Update(user);
        _repository.Commit();

        return productGateways;
</code>```

Here is the properties on the UserGateway model

```<code>public string Auth0Id { get; set; }
public List<ProductGateway> Products { get; set; }
</code>```

And the ProductGateway model

```<code>public string Title { get; set; }
public string Gsku { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public string ImageUrl { get; set; }
public UserGateway User { get; set; }
public int UserId { get; set; }
</code>```

I appreciate any help in advance! Cheers

EDIT: Here is my context class

```<code>public class Context : DbContext
{
    private readonly IConfiguration _configuration;
    private DbSet<ProductGateway> Products { get; set; }
    private DbSet<UserGateway> Users { get; set; }

    public Context(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = _configuration.GetConnectionString("Context");
        optionsBuilder.UseSqlServer(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }
    }
}
</code>```

答:
You have userId in productGateways, so it already has a reference to the user. Then you put one more reference to User In productGateway. After that, you put a list of productGateways to a user list. And here the cycle User -> ProductGateway -> user -> productGateway -> infinite.

Try to remove foreach and _repository.Update(user); calls, maybe it will help. Any way you should leave only one statement (add or update)

Title: Possible Object Cycle Detected

Body:
I am trying to add a ProductGateway to a database and assign it a user. I am getting an A possible object cycle was detected. error but I am unsure how I can overcome this.

This is a 1:M relationship using Entity Framework Core. I am also in .NET 6.

The idea is that a user can exist in the database without any products but a product must be assigned a user.

var user = _repository.GetAll<UserGateway>().FirstOrDefault(u => u.Id == userId);

        if (user == null) throw new InvalidUserException();

        var productGateways = productDtos.Select(productDto => new ProductGateway
            {
                DateCreated = DateTime.Now,
                DateLastModified = DateTime.Now,
                Description = productDto.Description,
                Quantity = productDto.Quantity,
                Title = productDto.Title,
                Gsku = productDto.Sku,
                ImageUrl = "",
                UserId = userId
            })
            .ToList();

        user.Products = productGateways;
        foreach (var product in user.Products)
        {
            product.User = user;
        }

        _repository.AddRange(productGateways);
        _repository.Update(user);
        _repository.Commit();

        return productGateways;

Here is the properties on the UserGateway model

public string Auth0Id { get; set; }
public List<ProductGateway> Products { get; set; }

And the ProductGateway model

public string Title { get; set; }
public string Gsku { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public string ImageUrl { get; set; }
public UserGateway User { get; set; }
public int UserId { get; set; }

I appreciate any help in advance! Cheers

EDIT: Here is my context class

public class Context : DbContext
{
    private readonly IConfiguration _configuration;
    private DbSet<ProductGateway> Products { get; set; }
    private DbSet<UserGateway> Users { get; set; }

    public Context(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = _configuration.GetConnectionString("Context");
        optionsBuilder.UseSqlServer(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }
    }
}


问:
How to multiply with a constant a selected region of a gridded Netcdf file for all the variables with NCO or CDO?
I have a gridded netcdf file with several variables.

I want to multiply all the variables with a constant value c but ONLY for a selected region of the grid.

with NCO for one variable for example I do the following

```<code>ncap2 -s 'where((lat >= 40.55 && lat <= 40.7) && (lon >= 22.8 && lon <= 23)) var1=var1*0.55;' in.nc out.nc
</code>```

since I have over 20 variables in the netcdf file , how I could define to multiply all the variables?

答: Have you tried ncap2's  Vpointer functionality? Create a Vpointer list based on the variables you want. Loop through the list and apply the where statement you have above to each variable.

Body:
I have a gridded netcdf file with several variables.

I want to multiply all the variables with a constant value c but ONLY for a selected region of the grid.

with NCO for one variable for example I do the following

ncap2 -s 'where((lat >= 40.55 && lat <= 40.7) && (lon >= 22.8 && lon <= 23)) var1=var1*0.55;' in.nc out.nc

since I have over 20 variables in the netcdf file , how I could define to multiply all the variables?


问:
Manage the missing value in a dataframe with string and number
I have a dataframe with some string columns and number columns. I want to manage the missing values.
I want to change the "nan" values with mean of each row.
I saw the different question in this website, however, they are different from my question. Like this link: Pandas Dataframe: Replacing NaN with row average

If all the values of a rows are "Nan" values, I want to delete that rows. I have also provide a sample case as follows:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame()
df['id'] = ['a', 'b', 'c', 'n']
df['md'] = ['d', 'e', 'f', 'l']
df['c1'] = [2, np.nan,np.nan, 5]
df['c2'] = [0, 5, np.nan, 3]
df['c3'] = [8, 7, np.nan,np.nan]

df = pd.DataFrame()
df['id'] = ['a', 1, 'n']
df['md'] = ['d', 6, 'l']
df['c1'] = [2, 6, 5]
df['c2'] = [0, 5, 3]
df['c3'] = [8, 7,4]
df
</code>```

Note:
I have used the following code, however it is very slow and for a big dataframe it take a looong time to run.

```<code>index_colum = df.columns.get_loc("c1")
df_withno_id = df.iloc[:,index_colum:]

rowsidx_with_all_NaN = df_withno_id[df_withno_id.isnull().all(axis=1)].index.values
df = df.drop(df.index[rowsidx_with_all_NaN])

for i, cols in df_withno_id.iterrows():
   if i not in rowsidx_with_all_NaN:
      endsidx = len(cols)
      extract_data = list(cols[0:endsidx])
      mean = np.nanmean(extract_data)
      fill_nan = [mean for x in extract_data if np.isnan(x)]
      df.loc[i] = df.loc[i].replace(np.nan, mean)
</code>```

Can anybody help me with this? thanks.

答:
First, you can select only float columns types. Second, for these columns drop rows with all nan values. Finally, you can transpose dataframe (only float columns), calculate average value and later transpose again.</p>
```<code>import pandas as pd
import numpy as np
df = pd.DataFrame()
df['id'] = ['a', 'b', 'c', 'n']
df['md'] = ['d', 'e', 'f', 'l']
df['c1'] = [2, np.nan,np.nan, 5]
df['c2'] = [0, 5, np.nan, 3]
df['c3'] = [8, 7, np.nan,np.nan]

numeric_cols = df.select_dtypes(include='float64').columns
df.dropna(how = 'all', subset = numeric_cols, inplace = True)
df[numeric_cols] = df[numeric_cols].T.fillna(df[numeric_cols].T.mean()).T
df
</code>```

Body:
I have a dataframe with some string columns and number columns. I want to manage the missing values.
I want to change the "nan" values with mean of each row.
I saw the different question in this website, however, they are different from my question. Like this link: Pandas Dataframe: Replacing NaN with row average

If all the values of a rows are "Nan" values, I want to delete that rows. I have also provide a sample case as follows:

import pandas as pd
import numpy as np
df = pd.DataFrame()
df['id'] = ['a', 'b', 'c', 'n']
df['md'] = ['d', 'e', 'f', 'l']
df['c1'] = [2, np.nan,np.nan, 5]
df['c2'] = [0, 5, np.nan, 3]
df['c3'] = [8, 7, np.nan,np.nan]

df = pd.DataFrame()
df['id'] = ['a', 1, 'n']
df['md'] = ['d', 6, 'l']
df['c1'] = [2, 6, 5]
df['c2'] = [0, 5, 3]
df['c3'] = [8, 7,4]
df

Note:
I have used the following code, however it is very slow and for a big dataframe it take a looong time to run.

index_colum = df.columns.get_loc("c1")
df_withno_id = df.iloc[:,index_colum:]

rowsidx_with_all_NaN = df_withno_id[df_withno_id.isnull().all(axis=1)].index.values
df = df.drop(df.index[rowsidx_with_all_NaN])

for i, cols in df_withno_id.iterrows():
   if i not in rowsidx_with_all_NaN:
      endsidx = len(cols)
      extract_data = list(cols[0:endsidx])
      mean = np.nanmean(extract_data)
      fill_nan = [mean for x in extract_data if np.isnan(x)]
      df.loc[i] = df.loc[i].replace(np.nan, mean)

Can anybody help me with this? thanks.

Body:
First, you can select only float columns types. Second, for these columns drop rows with all nan values. Finally, you can transpose dataframe (only float columns), calculate average value and later transpose again.

import pandas as pd
import numpy as np
df = pd.DataFrame()
df['id'] = ['a', 'b', 'c', 'n']
df['md'] = ['d', 'e', 'f', 'l']
df['c1'] = [2, np.nan,np.nan, 5]
df['c2'] = [0, 5, np.nan, 3]
df['c3'] = [8, 7, np.nan,np.nan]

numeric_cols = df.select_dtypes(include='float64').columns
df.dropna(how = 'all', subset = numeric_cols, inplace = True)
df[numeric_cols] = df[numeric_cols].T.fillna(df[numeric_cols].T.mean()).T
df


问:
Transition with futter move object
how i can move my object with transform for start position object to a X position value
i tried this code but not work</p>
```<code>                  new Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
       for(var i = 0; i > 0;i++)
      {

        Transform.translate(
          child: Text(
              'Woolha.com',
              style: TextStyle(color: Colors.teal, fontSize: 20)
          ),
          offset: Offset(
             i
            ,
              0),
        )
      }
],
                  ),
</code>```

答:
you cant use for() method inside the widgets tree
insted you can use that code but im not recommend it

```<code>  import 'package:flutter/material.dart';

class DashBoardScreen extends StatefulWidget {
  @override
  _DashBoardScreenState createState() => _DashBoardScreenState();
}

class _DashBoardScreenState extends State<DashBoardScreen> {

  double a = 0 ;

  _startMoving(){
    for(double i = 0; i <=250;i++){

      setState(() {
        a = i;

      });
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
                  Transform.translate(
                    child: Text(
                        'Woolha.com ? what this',
                        style: TextStyle(color: Colors.teal, fontSize: 20)
                    ),

                    offset: Offset(
                        a
                        ,
                        0),
                  )
            ],

          ),
        ElevatedButton(onPressed: ()=> _startMoving(), child: Icon(Icons.arrow_forward))

        ],
      ),
    );
  }
}
</code>```

i recommend you to use
AnimatedPositioned

Title: Transition with futter move object

Body:
how i can move my object with transform for start position object to a X position value
i tried this code but not work

                  new Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
       for(var i = 0; i > 0;i++)
      {

        Transform.translate(
          child: Text(
              'Woolha.com',
              style: TextStyle(color: Colors.teal, fontSize: 20)
          ),
          offset: Offset(
             i
            ,
              0),
        )
      }
],
                  ),

Body:
you cant use for() method inside the widgets tree
insted you can use that code but im not recommend it

  import 'package:flutter/material.dart';

class DashBoardScreen extends StatefulWidget {
  @override
  _DashBoardScreenState createState() => _DashBoardScreenState();
}

class _DashBoardScreenState extends State<DashBoardScreen> {

  double a = 0 ;

  _startMoving(){
    for(double i = 0; i <=250;i++){

      setState(() {
        a = i;

      });
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
                  Transform.translate(
                    child: Text(
                        'Woolha.com ? what this',
                        style: TextStyle(color: Colors.teal, fontSize: 20)
                    ),

                    offset: Offset(
                        a
                        ,
                        0),
                  )
            ],

          ),
        ElevatedButton(onPressed: ()=> _startMoving(), child: Icon(Icons.arrow_forward))

        ],
      ),
    );
  }
}

i recommend you to use
AnimatedPositioned


问:
C++ Overriding private class attributes
Anyone can advise on how to simply reset a class' private attributes? (referring to int forward and int backwards from within Default class)

What I want to achieve:

Case 1: Use int forward and int backwards with default values VK_UP and VK_DOWN << This is done.

Case 2: I want to be able to reset the default into some other keypress. << ADVICE HERE needed

```<code>#include <iostream>
#include <windows.h>
#include <string>
#include<conio.h>

using namespace std;
bool reset_defaults = false;

class Replace_defaults {
public:
    void check() {
        switch (reset_defaults) {
        case true:
            cout << ("Now running with reset commands >>>\n");
            //// HERE override function ...
            break;
        }
    }
};

// Base class
class Default {
    int forward = VK_UP; // << **TO RESET!!**
    int backwards = VK_DOWN;
public:

    bool standBy = true;
    void get_default() {
        int new_def = forward;
    }
    int move() {
        while (reset_defaults == false) {
            if (GetAsyncKeyState(forward) < 0)
            {
                cout << ("FORWARDS >>>\n");
                if (GetAsyncKeyState(forward) == 0)
                {
                    cout << ("Stopped forwards\n");
                }
            }
            if (GetAsyncKeyState(backwards) < 0)
            {
                cout << ("BACKWARDS >>>\n");
                if (GetAsyncKeyState(backwards) == 0)
                {
                    cout << ("Stopped backwards\n");
                }
            }
            if (GetAsyncKeyState(VK_RIGHT) < 0)
            {
                reset_defaults = true;
                cout << ("RIGHT Key pressed - Stopped \n");
                Replace_defaults reset;
                reset.check();
            }
            if (GetAsyncKeyState(VK_SPACE) < 0) { break; }
        }
        return 0;
    }
    int accessPrivate() {
        return forward;
    }
};
class Replace_defaults_overload: public Replace_defaults {
public:
    void check() {
        switch (reset_defaults) {
        case false:
            cout << "Default comands running \n";
            Default test;
            test.move();
        }
    }
};

int main() {
    Replace_defaults_overload replace;
    Default def;
    replace.check();
    return 0;
}
</code>```

答:
Having them under the protected access modifier would allow an inherited class to change the values of forward and backward. Otherwise private is only accessible within the parent class</p>
```<code>    class Default {
protected
    int forward = VK_UP; // << **TO RESET!!**
    int backwards = VK_DOWN;
public: ...
</code>```

Title: C++ Overriding private class attributes

Body:
Anyone can advise on how to simply reset a class' private attributes? (referring to int forward and int backwards from within Default class)

What I want to achieve:

Case 1: Use int forward and int backwards with default values VK_UP and VK_DOWN << This is done.

Case 2: I want to be able to reset the default into some other keypress. << ADVICE HERE needed

#include <iostream>
#include <windows.h>
#include <string>
#include<conio.h>

using namespace std;
bool reset_defaults = false;

class Replace_defaults {
public:
    void check() {
        switch (reset_defaults) {
        case true:
            cout << ("Now running with reset commands >>>\n");
            //// HERE override function ...
            break;
        }
    }
};

// Base class
class Default {
    int forward = VK_UP; // << **TO RESET!!**
    int backwards = VK_DOWN;
public:

    bool standBy = true;
    void get_default() {
        int new_def = forward;
    }
    int move() {
        while (reset_defaults == false) {
            if (GetAsyncKeyState(forward) < 0)
            {
                cout << ("FORWARDS >>>\n");
                if (GetAsyncKeyState(forward) == 0)
                {
                    cout << ("Stopped forwards\n");
                }
            }
            if (GetAsyncKeyState(backwards) < 0)
            {
                cout << ("BACKWARDS >>>\n");
                if (GetAsyncKeyState(backwards) == 0)
                {
                    cout << ("Stopped backwards\n");
                }
            }
            if (GetAsyncKeyState(VK_RIGHT) < 0)
            {
                reset_defaults = true;
                cout << ("RIGHT Key pressed - Stopped \n");
                Replace_defaults reset;
                reset.check();
            }
            if (GetAsyncKeyState(VK_SPACE) < 0) { break; }
        }
        return 0;
    }
    int accessPrivate() {
        return forward;
    }
};
class Replace_defaults_overload: public Replace_defaults {
public:
    void check() {
        switch (reset_defaults) {
        case false:
            cout << "Default comands running \n";
            Default test;
            test.move();
        }
    }
};

int main() {
    Replace_defaults_overload replace;
    Default def;
    replace.check();
    return 0;
}

Body:
Having them under the protected access modifier would allow an inherited class to change the values of forward and backward. Otherwise private is only accessible within the parent class

    class Default {
protected
    int forward = VK_UP; // << **TO RESET!!**
    int backwards = VK_DOWN;
public: ...


问:
Print to web directly from the controller?
I have this controller function that returns cpu stats:

```<code>        public ActionResult GetStats()
        {
            Random rand = new Random();
            ViewData["cpu_temp"] = rand.Next(0, 100) + "%";

            return View();
        }
</code>```

And with a view it works 100%. Bu tI'm wondering if I could shorten the process, and just do something like:

```<code>        public ActionResult GetStats()
        {
            Random rand = new Random();

            something.writeline(rand.Next(0, 100) + "%");
        }
</code>```

Just so I can create controllers and not care about views for simple simple simple output :D

FIX, after a tip by Jamie Dixon i came up with this solution:

```<code>        public ActionResult GetStats()
        {
            Random rand = new Random();
            ViewData["cpu_temp"] = rand.Next(0, 100) + "%";

            return Json(ViewData, JsonRequestBehavior.AllowGet);
        }
</code>```

Works as intended :D

答:
It all depends on where you want to view the data.

If you want to view the data in your web browser through a web page then you'll need to return a view.

If you just want to see the data you could output it to the debug console with

```<code>Debug.WriteLine(mystring);
</code>```

Alternatively you could send it to the browser in any number of formats that can be downloaded by the user (JSON, XML, Text file) that won't require a view.

The key point here is that if you want the user to view the information in their browser in a way that's likely to show up for them, you're going to want to use a View.

UPDATE

To return a JSON object you can simply return JSON(object).

```<code>return JSON(new {foo = "foo", bar = "bar"});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this controller function that returns cpu stats:

        public ActionResult GetStats()
        {
            Random rand = new Random();
            ViewData["cpu_temp"] = rand.Next(0, 100) + "%";

            return View();
        }

And with a view it works 100%. Bu tI'm wondering if I could shorten the process, and just do something like:

        public ActionResult GetStats()
        {
            Random rand = new Random();

            something.writeline(rand.Next(0, 100) + "%");
        }

Just so I can create controllers and not care about views for simple simple simple output :D

FIX, after a tip by Jamie Dixon i came up with this solution:

        public ActionResult GetStats()
        {
            Random rand = new Random();
            ViewData["cpu_temp"] = rand.Next(0, 100) + "%";

            return Json(ViewData, JsonRequestBehavior.AllowGet);
        }

Works as intended :D

Body:
It all depends on where you want to view the data.

If you want to view the data in your web browser through a web page then you'll need to return a view.

If you just want to see the data you could output it to the debug console with

Debug.WriteLine(mystring);

Alternatively you could send it to the browser in any number of formats that can be downloaded by the user (JSON, XML, Text file) that won't require a view.

The key point here is that if you want the user to view the information in their browser in a way that's likely to show up for them, you're going to want to use a View.

UPDATE

To return a JSON object you can simply return JSON(object).

return JSON(new {foo = "foo", bar = "bar"});


问:
Jetpack Compose: react to Slider changed value
I want to show a slider that can be either updated by the user using drag/drop, or updated from the server in real-time.

When the user finishes their dragging gesture, I want to send the final value to the server.

My initial attempt is:

@Composable
fun LightView(
    channel: UiChannel,
    onDimmerChanged: (Float) -> Unit
) {
    val sliderValue = channel....
    Slider(value = sliderValue, onValueChange = onDimmerChanged)
}
```
<p>And the <code>onDimmerChanged</code> method comes from my ViewModel, which updates the server value.
It works well, however <code>onValueChange</code> is called for each move, which bombards the server with unneeded requests.</p>
<p>I tried to create a custom slider:</p>
<pre class="lang-kotlin prettyprint-override"><code>@Composable
fun LightView(
    channel: UiChannel,
    onDimmerChanged: (Float) -> Unit
) {
    val sliderValue = channel....
    Slider(initialValue = sliderValue, valueSetter = onDimmerChanged)
}

@Composable
fun Slider(initialValue: Float, valueSetter: (Float) -> Unit) {
    var value by remember { mutableStateOf(initialValue) }
    Slider(
        value = value,
        onValueChange = { value = it },
        onValueChangeFinished = { valueSetter(value) }
    )
}
</code>```

It works well on the app side, and the value is only sent once, when the user stops dragging.

However, it fails updating the view when there is an update from the server. I'm guessing this has something to do with remember. So I tried without remember:

@Composable
fun Slider(initialValue: Float, valueSetter: (Float) -> Unit) {
    var value by mutableStateOf(initialValue)
    Slider(
        value = value,
        onValueChange = { value = it },
        onValueChangeFinished = { valueSetter(value) }
    )
}
```
<p>This time the view updates correctly when the value is updated by the server, but does not move anymore when the user drags the slider.</p>
<p>I'm sure I'm missing something with state hoisting and all, but I can't figure out what.</p>
<p><strong>So my final question</strong>: how to create a Slider that can be either updated by the ViewModel, or by the user, and notifies the ViewModel of a new value only when the user finishes dragging?</p>
<p><strong>EDIT:</strong></p>
<p>I also tried what @CommonsWare suggested:</p>
<pre class="lang-kotlin prettyprint-override"><code>@Composable
fun LightView(
    channel: UiChannel,
    onDimmerChanged: (Float) -> Unit
) {
    val sliderValue = channel....
    val sliderState = mutableStateOf(sliderValue)
    Slider(state = sliderState, valueSet = { onDimmerChanged(sliderState.value) })
}

@Composable
fun Slider(state: MutableState<Float>, valueSet: () -> Unit) {
    Slider(
        value = state.value,
        onValueChange = { state.value = it },
        onValueChangeFinished = valueSet
    )
}
</code>```

And it does not work either. When using drag and drop, sliderState is correctly updated, and onDimmerChanged() is called with the correct value. But for some reason, when tapping of the sliding (rather than sliding), valueSet is called and sliderState.value does not contain the correct value. I don't understand where this value comes from.

答:
I encountered this problem. As jossiwolf pointed out, using the progress as a key for the remember{} is necessary to ensure that the Slider progress is updated after recomposition.

I had an additional issue though, where, if I updated the progress mid-seek, the Slider would recompose, and the thumb would revert back to its old position.

To work around this, I'm using a temporary slider position, which is only used while a drag is in progress:

```<code>@Composable
fun MySlider(
    progress: Float,
    onSeek: (progress: Float) -> Unit,
) {
    val sliderPosition = remember(progress) { mutableStateOf(progress) }
    val tempSliderPosition = remember { mutableStateOf(progress) }
    val interactionSource = remember { MutableInteractionSource() }
    val isDragged = interactionSource.collectIsDraggedAsState()

    Slider(
        value = if (isDragged.value) tempSliderPosition.value else sliderPosition.value,
        onValueChange = { progress ->
            sliderPosition.value = progress
            tempSliderPosition.value = progress
        },
        onValueChangeFinished = {
            sliderPosition.value = tempSliderPosition.value
            onSeek(tempSliderPosition.value)
        },
        interactionSource = interactionSource
    )
}
</code>```

Body:
I want to show a slider that can be either updated by the user using drag/drop, or updated from the server in real-time.

When the user finishes their dragging gesture, I want to send the final value to the server.

My initial attempt is:

@Composable
fun LightView(
    channel: UiChannel,
    onDimmerChanged: (Float) -> Unit
) {
    val sliderValue = channel....
    Slider(value = sliderValue, onValueChange = onDimmerChanged)
}

And the onDimmerChanged method comes from my ViewModel, which updates the server value.
It works well, however onValueChange is called for each move, which bombards the server with unneeded requests.

I tried to create a custom slider:

@Composable
fun LightView(
    channel: UiChannel,
    onDimmerChanged: (Float) -> Unit
) {
    val sliderValue = channel....
    Slider(initialValue = sliderValue, valueSetter = onDimmerChanged)
}

@Composable
fun Slider(initialValue: Float, valueSetter: (Float) -> Unit) {
    var value by remember { mutableStateOf(initialValue) }
    Slider(
        value = value,
        onValueChange = { value = it },
        onValueChangeFinished = { valueSetter(value) }
    )
}

It works well on the app side, and the value is only sent once, when the user stops dragging.

However, it fails updating the view when there is an update from the server. I'm guessing this has something to do with remember. So I tried without remember:

@Composable
fun Slider(initialValue: Float, valueSetter: (Float) -> Unit) {
    var value by mutableStateOf(initialValue)
    Slider(
        value = value,
        onValueChange = { value = it },
        onValueChangeFinished = { valueSetter(value) }
    )
}

This time the view updates correctly when the value is updated by the server, but does not move anymore when the user drags the slider.

I'm sure I'm missing something with state hoisting and all, but I can't figure out what.

So my final question: how to create a Slider that can be either updated by the ViewModel, or by the user, and notifies the ViewModel of a new value only when the user finishes dragging?

EDIT:

I also tried what @CommonsWare suggested:

@Composable
fun LightView(
    channel: UiChannel,
    onDimmerChanged: (Float) -> Unit
) {
    val sliderValue = channel....
    val sliderState = mutableStateOf(sliderValue)
    Slider(state = sliderState, valueSet = { onDimmerChanged(sliderState.value) })
}

@Composable
fun Slider(state: MutableState<Float>, valueSet: () -> Unit) {
    Slider(
        value = state.value,
        onValueChange = { state.value = it },
        onValueChangeFinished = valueSet
    )
}

And it does not work either. When using drag and drop, sliderState is correctly updated, and onDimmerChanged() is called with the correct value. But for some reason, when tapping of the sliding (rather than sliding), valueSet is called and sliderState.value does not contain the correct value. I don't understand where this value comes from.

Body:
I encountered this problem. As jossiwolf pointed out, using the progress as a key for the remember{} is necessary to ensure that the Slider progress is updated after recomposition.

I had an additional issue though, where, if I updated the progress mid-seek, the Slider would recompose, and the thumb would revert back to its old position.

To work around this, I'm using a temporary slider position, which is only used while a drag is in progress:

@Composable
fun MySlider(
    progress: Float,
    onSeek: (progress: Float) -> Unit,
) {
    val sliderPosition = remember(progress) { mutableStateOf(progress) }
    val tempSliderPosition = remember { mutableStateOf(progress) }
    val interactionSource = remember { MutableInteractionSource() }
    val isDragged = interactionSource.collectIsDraggedAsState()

    Slider(
        value = if (isDragged.value) tempSliderPosition.value else sliderPosition.value,
        onValueChange = { progress ->
            sliderPosition.value = progress
            tempSliderPosition.value = progress
        },
        onValueChangeFinished = {
            sliderPosition.value = tempSliderPosition.value
            onSeek(tempSliderPosition.value)
        },
        interactionSource = interactionSource
    )
}


问:
Application that uses WebBrowser control crashes after installing IE9
I've installed IE 9 last week and since, my c# .net application crashes about 20% of times. The debugger is unable to show something useful besides stopping at Program.cs Application.Run(new MyMainForm());  , btw the main form was already shown, so it's not that it's something in construction on main form.

I have Windows7.

```<code>The exception thrown is:
"An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll

Additional information: Value does not fall within the expected range.
</code>```

Screen shot of callstack -> http://img861.imageshack.us/f/ie9v.png/

When running outside of debugger, this info is shown:

```<code>Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: myexe.exe
  Application Version:  6.7.6.0
  Application Timestamp:    4d7fdffd
  Fault Module Name:    mshtml.dll
  Fault Module Version: 9.0.8112.16421
  Fault Module Timestamp:   4d76266c
  Exception Code:   c0000005
  Exception Offset: 0012c848
  OS Version:   6.1.7600.2.0.0.256.48
  Locale ID:    1037

And sometimes instead of mshtml.dll it says StackHash_f09d

Problem Event Name: APPCRASH
  Application Name: myexe.exe
  Application Version:  6.7.6.0
  Application Timestamp:    4d7fdffd
  Fault Module Name:    StackHash_f09d
  Fault Module Version: 0.0.0.0
  Fault Module Timestamp:   00000000
  Exception Code:   c0000005
  Exception Offset: 00000000
  OS Version:   6.1.7600.2.0.0.256.48
  Locale ID:    1037
</code>```

Thanks in advance

Edited:

That's what I see in windbg, with symbols:

```<code>0:000> kb
ChildEBP RetAddr  Args to Child
0020eda4 64d54f83 0566c988 00001012 00000000 mshtml!CDoc::ReduceMemoryPressureTask+0x1a
0020edb4 64d54f2c c6b991e4 0020ee78 00000113 mshtml!GWYieldToMsgOnCurrentThread+0x17b
0020edfc 770086ef 00192392 00000012 0000201b mshtml!GlobalWndProc+0x1f2
0020ee28 77008876 64d54afe 00192392 00000113 USER32!InternalCallWinProc+0x23
0020eea0 770089b5 00000000 64d54afe 00192392 USER32!UserCallWinProcCheckWow+0x14b
0020ef00 77008e9c 64d54afe 00000000 0020ef2c USER32!DispatchMessageWorker+0x35e
0020ef10 03b54726 0020ef9c fa69a961 00000000 USER32!DispatchMessageW+0xf
*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v2.0.50727_32\System.Windows.Forms\f92c882fd4e7005c005e208daa04c28d\System.Windows.Forms.ni.dll
WARNING: Frame IP not in any known module. Following frames may be wrong.
0020ef2c 5af78aee 01b743e4 00000001 01ac95cc 0x3b54726
0020efe0 5af78757 00000000 ffffffff 00000000 System_Windows_Forms_ni+0x208aee
0020f038 5af785a1 01b6c610 1f3a000e 00000000 System_Windows_Forms_ni+0x208757
0020f068 5af35911 01bb7d84 0020f10c 003b73d8 System_Windows_Forms_ni+0x2085a1
0020f0e0 6f221b5c 015b1141 00000001 0020f170 System_Windows_Forms_ni+0x1c5911
0020f0f0 6f232209 0020f1c0 00000000 0020f190 mscorwks!CallDescrWorker+0x33
0020f170 6f246511 0020f1c0 00000000 0020f190 mscorwks!CallDescrWorkerWithHandler+0xa3
0020f2b4 6f246544 0032c040 0020f380 0020f34c mscorwks!MethodDesc::CallDescr+0x19c
0020f2d0 6f246562 0032c040 0020f380 0020f34c mscorwks!MethodDesc::CallTargetWorker+0x1f
0020f2e8 6f2b0c45 0020f34c d847bc11 00000000 mscorwks!MethodDescCallSite::CallWithValueTypes+0x1a
0020f44c 6f2b0b65 003239c0 00000001 0020f488 mscorwks!ClassLoader::RunMain+0x223
0020f6b4 6f2b10b5 00000000 d847b3d9 00000001 mscorwks!Assembly::ExecuteMainMethod+0xa6
0020fb84 6f2b129f 013a0000 00000000 d847b389 mscorwks!SystemDomain::ExecuteMainMethod+0x456
</code>```

=====UPDATE(I'm not sure, if I'm supposed to post it as "Answer your question")============
Thanks to everyone trying to help, I appreciate it.

Being desperate, I started to remove pieces of code to understand which part of my code affects it(we use webrowser control in many forms). After removing call to LoginForm which also uses webrowser control, the problem disappeared.

The login form hosts webrowser control, it navigates to certain url, for example /login.php and if user is already logged-in, method UserLoggedIn inside form is invoked from html using ObjectForScripting. When UserLoggedIn was called, we were calling Close() to close form if the LoginForm was shown.  Even though LoginForm was doing all this, we weren't always showing it. We were, showing it only if after X seconds UserLoggedIn() was not called(i.e user needs to login).
For some reason, and thanks to MS for making us able to debug into .net sources, when we were calling Close, and the form was not Visible it was actually disposing the form and all it's children because IsHandleCreated was false. Now, the Close was called from UserLoggedIn(), which is an event fired by the browser control(the callstack shows ieframe.dll, mshtml.dll etc) , so the webbrowser object was being destoyed while being called from.
The hacky way to resolve this, was to call Close, only if form was Visible. BTW, I don't know, why IsHandleCreated is false, if we don't show the form. I tried to reproduce it, by writing a sample that creates a form, which is not shown, but it's IsHandleCreated is true.

---- from Forms.cs -----

```<code>        public void Close()
        {

        if (GetState(STATE_CREATINGHANDLE))
            throw new InvalidOperationException(SR.GetString(SR.ClosingWhileCreatingHandle, "Close"));

        if (IsHandleCreated) {
            closeReason = CloseReason.UserClosing;
            SendMessage(NativeMethods.WM_CLOSE, 0, 0);
        }
        else{
            // MSDN: When a form is closed, all resources created within the object are closed and the form is disposed.
            // For MDI child: MdiChildren collection gets updated (VSWhidbey# 368642 & 93550)
            Dispose(); // THIS WAS CALLED WHEN FORM WAS NOT VISIBLE
        }
    }
</code>```

答:
i get the same error/crash since i got the ie9 installed. it only happens whenever there is a youtube movie on the page. than it hangs/crashes with the exact same window you get Jack Juiceson.

but behind the "Fault Module Name" i dont get mshtml.dll, i get a d3d9.dll or something like that. veryyyyy odd.

Body:
I've installed IE 9 last week and since, my c# .net application crashes about 20% of times. The debugger is unable to show something useful besides stopping at Program.cs Application.Run(new MyMainForm());  , btw the main form was already shown, so it's not that it's something in construction on main form.

I have Windows7.

The exception thrown is:
"An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll

Additional information: Value does not fall within the expected range.

Screen shot of callstack -> http://img861.imageshack.us/f/ie9v.png/

When running outside of debugger, this info is shown:

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: myexe.exe
  Application Version:  6.7.6.0
  Application Timestamp:    4d7fdffd
  Fault Module Name:    mshtml.dll
  Fault Module Version: 9.0.8112.16421
  Fault Module Timestamp:   4d76266c
  Exception Code:   c0000005
  Exception Offset: 0012c848
  OS Version:   6.1.7600.2.0.0.256.48
  Locale ID:    1037

And sometimes instead of mshtml.dll it says StackHash_f09d

Problem Event Name: APPCRASH
  Application Name: myexe.exe
  Application Version:  6.7.6.0
  Application Timestamp:    4d7fdffd
  Fault Module Name:    StackHash_f09d
  Fault Module Version: 0.0.0.0
  Fault Module Timestamp:   00000000
  Exception Code:   c0000005
  Exception Offset: 00000000
  OS Version:   6.1.7600.2.0.0.256.48
  Locale ID:    1037

Thanks in advance

Edited:

That's what I see in windbg, with symbols:

0:000> kb
ChildEBP RetAddr  Args to Child
0020eda4 64d54f83 0566c988 00001012 00000000 mshtml!CDoc::ReduceMemoryPressureTask+0x1a
0020edb4 64d54f2c c6b991e4 0020ee78 00000113 mshtml!GWYieldToMsgOnCurrentThread+0x17b
0020edfc 770086ef 00192392 00000012 0000201b mshtml!GlobalWndProc+0x1f2
0020ee28 77008876 64d54afe 00192392 00000113 USER32!InternalCallWinProc+0x23
0020eea0 770089b5 00000000 64d54afe 00192392 USER32!UserCallWinProcCheckWow+0x14b
0020ef00 77008e9c 64d54afe 00000000 0020ef2c USER32!DispatchMessageWorker+0x35e
0020ef10 03b54726 0020ef9c fa69a961 00000000 USER32!DispatchMessageW+0xf
*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v2.0.50727_32\System.Windows.Forms\f92c882fd4e7005c005e208daa04c28d\System.Windows.Forms.ni.dll
WARNING: Frame IP not in any known module. Following frames may be wrong.
0020ef2c 5af78aee 01b743e4 00000001 01ac95cc 0x3b54726
0020efe0 5af78757 00000000 ffffffff 00000000 System_Windows_Forms_ni+0x208aee
0020f038 5af785a1 01b6c610 1f3a000e 00000000 System_Windows_Forms_ni+0x208757
0020f068 5af35911 01bb7d84 0020f10c 003b73d8 System_Windows_Forms_ni+0x2085a1
0020f0e0 6f221b5c 015b1141 00000001 0020f170 System_Windows_Forms_ni+0x1c5911
0020f0f0 6f232209 0020f1c0 00000000 0020f190 mscorwks!CallDescrWorker+0x33
0020f170 6f246511 0020f1c0 00000000 0020f190 mscorwks!CallDescrWorkerWithHandler+0xa3
0020f2b4 6f246544 0032c040 0020f380 0020f34c mscorwks!MethodDesc::CallDescr+0x19c
0020f2d0 6f246562 0032c040 0020f380 0020f34c mscorwks!MethodDesc::CallTargetWorker+0x1f
0020f2e8 6f2b0c45 0020f34c d847bc11 00000000 mscorwks!MethodDescCallSite::CallWithValueTypes+0x1a
0020f44c 6f2b0b65 003239c0 00000001 0020f488 mscorwks!ClassLoader::RunMain+0x223
0020f6b4 6f2b10b5 00000000 d847b3d9 00000001 mscorwks!Assembly::ExecuteMainMethod+0xa6
0020fb84 6f2b129f 013a0000 00000000 d847b389 mscorwks!SystemDomain::ExecuteMainMethod+0x456

=====UPDATE(I'm not sure, if I'm supposed to post it as "Answer your question")============
Thanks to everyone trying to help, I appreciate it.

Being desperate, I started to remove pieces of code to understand which part of my code affects it(we use webrowser control in many forms). After removing call to LoginForm which also uses webrowser control, the problem disappeared.

The login form hosts webrowser control, it navigates to certain url, for example /login.php and if user is already logged-in, method UserLoggedIn inside form is invoked from html using ObjectForScripting. When UserLoggedIn was called, we were calling Close() to close form if the LoginForm was shown.  Even though LoginForm was doing all this, we weren't always showing it. We were, showing it only if after X seconds UserLoggedIn() was not called(i.e user needs to login).
For some reason, and thanks to MS for making us able to debug into .net sources, when we were calling Close, and the form was not Visible it was actually disposing the form and all it's children because IsHandleCreated was false. Now, the Close was called from UserLoggedIn(), which is an event fired by the browser control(the callstack shows ieframe.dll, mshtml.dll etc) , so the webbrowser object was being destoyed while being called from.
The hacky way to resolve this, was to call Close, only if form was Visible. BTW, I don't know, why IsHandleCreated is false, if we don't show the form. I tried to reproduce it, by writing a sample that creates a form, which is not shown, but it's IsHandleCreated is true.

---- from Forms.cs -----

        public void Close()
        {

        if (GetState(STATE_CREATINGHANDLE))
            throw new InvalidOperationException(SR.GetString(SR.ClosingWhileCreatingHandle, "Close"));

        if (IsHandleCreated) {
            closeReason = CloseReason.UserClosing;
            SendMessage(NativeMethods.WM_CLOSE, 0, 0);
        }
        else{
            // MSDN: When a form is closed, all resources created within the object are closed and the form is disposed.
            // For MDI child: MdiChildren collection gets updated (VSWhidbey# 368642 & 93550)
            Dispose(); // THIS WAS CALLED WHEN FORM WAS NOT VISIBLE
        }
    }


问:
Obtaining all possible combinations with a minimum number per group
Apologies for lack of a reproducible example as I'm not too sure how to code this.

Let's say I have four groups: red, yellow, green, and blue.

I have fifteen marbles to distribute to each group, with a constraint that each group must have at least two marbles. How can I get all possible combinations that can be allotted to each group? My desired end result is a data frame along the following lines, where the number represents the number of marbles allocated to that group:

```<code>combo_id   red   yellow   green   blue
1          3     3        5       4
2          3     5        4       3
3          5     2        5       3
</code>```

And so on until all combinations have been enumerated.

答:
library(purrr)
library(dplyr, warn.conflicts = FALSE)

colors <- c("red", "yellow", "green", "blue")
names(colors) <- colors

all_possible_combinations <- expand.grid(map(colors, function(x) 2:9))

all_possible_combinations$sum <- rowSums(all_possible_combinations)

# Get all distributions that sum to 15 and therefore give out all marbles
all_possible_combinations %>%
  filter(sum == 15) %>%
  as_tibble()
#> # A tibble: 120 × 5
#>      red yellow green  blue   sum
#>    <int>  <int> <int> <int> <dbl>
#>  1     9      2     2     2    15
#>  2     8      3     2     2    15
#>  3     7      4     2     2    15
#>  4     6      5     2     2    15
#>  5     5      6     2     2    15
#>  6     4      7     2     2    15
#>  7     3      8     2     2    15
#>  8     2      9     2     2    15
#>  9     8      2     3     2    15
#> 10     7      3     3     2    15
#> # … with 110 more rows

# Include combinations where some of the marbles might be retained.
all_possible_combinations %>%
  filter(sum <= 15) %>%
  as_tibble()
#> # A tibble: 330 × 5
#>      red yellow green  blue   sum
#>    <int>  <int> <int> <int> <dbl>
#>  1     2      2     2     2     8
#>  2     3      2     2     2     9
#>  3     4      2     2     2    10
#>  4     5      2     2     2    11
#>  5     6      2     2     2    12
#>  6     7      2     2     2    13
#>  7     8      2     2     2    14
#>  8     9      2     2     2    15
#>  9     2      3     2     2     9
#> 10     3      3     2     2    10
#> # … with 320 more rows
```

Body:
Apologies for lack of a reproducible example as I'm not too sure how to code this.

Let's say I have four groups: red, yellow, green, and blue.

I have fifteen marbles to distribute to each group, with a constraint that each group must have at least two marbles. How can I get all possible combinations that can be allotted to each group? My desired end result is a data frame along the following lines, where the number represents the number of marbles allocated to that group:

combo_id   red   yellow   green   blue
1          3     3        5       4
2          3     5        4       3
3          5     2        5       3

And so on until all combinations have been enumerated.


问:
Scrollbar on mac OS mozilla firefox and mobile safari
Can someone help me with the scrollbar on Mac OS X in Mozilla firefox and in mobile safari?
scrollbar-color in css works only in windows machines, other js libraries not working on , always scrollbar has system default styles.
Maybe someone has already had some dealings with this?</p>

答:
it worked for me without any problems. ::-webkit-scrollbar-thumb ::-webkit-scrollbar-track and ::-webkit-scrollbar

More info developer.mozilla

div{
  width: 400px;
  height: 400px;
  background: yellow;
  overflow: auto;
}
::-webkit-scrollbar-thumb {
    background: #0a59e3;
    border-radius: 16px;
    box-shadow: inset 2px 2px 2px hsl(219deg 31% 32%), inset -2px -2px 2px rgb(18 24 38);
}
::-webkit-scrollbar-track {
    background: #0f1520;
}
::-webkit-scrollbar {
    width: 1.65em;
    height: 1.65em;
    background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="visible-scrollbar">
  Etiam sagittis sem sed lacus laoreet, eu fermentum eros auctor.
  Proin at nulla elementum, consectetur ex eget, commodo ante.
  Sed eros mi, bibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisquebibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisquebibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisque
  convallis nisi a diam malesuada mollis. Aliquam at enim ligula.
</div></code>```

Body:
it worked for me without any problems. ::-webkit-scrollbar-thumb ::-webkit-scrollbar-track and ::-webkit-scrollbar

More info developer.mozilla

div{
  width: 400px;
  height: 400px;
  background: yellow;
  overflow: auto;
}
::-webkit-scrollbar-thumb {
    background: #0a59e3;
    border-radius: 16px;
    box-shadow: inset 2px 2px 2px hsl(219deg 31% 32%), inset -2px -2px 2px rgb(18 24 38);
}
::-webkit-scrollbar-track {
    background: #0f1520;
}
::-webkit-scrollbar {
    width: 1.65em;
    height: 1.65em;
    background: red;
}

<div class="visible-scrollbar">
  Etiam sagittis sem sed lacus laoreet, eu fermentum eros auctor.
  Proin at nulla elementum, consectetur ex eget, commodo ante.
  Sed eros mi, bibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisquebibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisquebibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisque
  convallis nisi a diam malesuada mollis. Aliquam at enim ligula.
</div>


问:
Oracle Database | Calculate Days in between two dates
I'm trying to calculate number of days in between to DATES stored in my database, but I was not able to get any data using DATEDIFF or Extract.

Brief Example:

TABLE (PROJECT)
PROJECT START, PROJECT END

What I'm looking to get is the amount of days each project lasted.

Any hint will help!

答:
When you subtract one date from another in Oracle, you get a decimal value. The numbers to the left of the decimal point are the days, the numbers to the right is the decimal fraction.

```<code>  select sysdate - date '2022-01-03' as delta from dual;
</code>```

The resulting value on the day I am running this is 37.65. Since you asked for days, I'll leave it to you to truncate this to 37 days or round it to 38.

Body:
When you subtract one date from another in Oracle, you get a decimal value. The numbers to the left of the decimal point are the days, the numbers to the right is the decimal fraction.

  select sysdate - date '2022-01-03' as delta from dual;

The resulting value on the day I am running this is 37.65. Since you asked for days, I'll leave it to you to truncate this to 37 days or round it to 38.


问:
Iterating Through CSS Elements
I'm re-learning CSS and I was wondering how I would do something like this:

```<code>li:nth-child(n) {
    display: block;
    animation: animate 500ms ease-in-out forwards;
    animation-delay: calc(n * 200ms);
}
</code>```

Where n is the current li element and the delay is equal to n * 200ms

答:
Currently, there are no ways for CSS to create selectors by iterating over a range.

However, you can use SCSS, which is a CSS preprocessor that extends the language and produces in output a valid CSS file.

In SCSS, your code would look like:

```<code>@for $i from 1 through 3 {
  li:nth-child(#{$i}) {
    display: block;
    animation: animate 500ms ease-in-out forwards;
    animation-delay: calc($i * 200ms);
  }
}
</code>```

Title: Iterating Through CSS Elements

Body:
I'm re-learning CSS and I was wondering how I would do something like this:

li:nth-child(n) {
    display: block;
    animation: animate 500ms ease-in-out forwards;
    animation-delay: calc(n * 200ms);
}

Where n is the current li element and the delay is equal to n * 200ms

Body:
Currently, there are no ways for CSS to create selectors by iterating over a range.

However, you can use SCSS, which is a CSS preprocessor that extends the language and produces in output a valid CSS file.

In SCSS, your code would look like:

@for $i from 1 through 3 {
  li:nth-child(#{$i}) {
    display: block;
    animation: animate 500ms ease-in-out forwards;
    animation-delay: calc($i * 200ms);
  }
}


问:
How to measure process migration time from one core to another on linux?
On linux we can make a cpu core offline by the command :

```<code>echo 0 > /sys/devices/system/cpu/<core num>/online.
</code>```

This causes the processes running on that core to be migrated to other cores.
What I need to do is to measure the time it takes to migrate a process from one
core to another. How should I do this ?

答: You can take a look to cpuid. I suppose you could pool the cpu serial number and see when it changes. The problem is that it will include not only the migration time but also the time the process has been waiting for to be executed in the new cpu it's been allocated to.</p>

Body:
On linux we can make a cpu core offline by the command :

echo 0 > /sys/devices/system/cpu/<core num>/online.

This causes the processes running on that core to be migrated to other cores.
What I need to do is to measure the time it takes to migrate a process from one
core to another. How should I do this ?


问:
Install Tensorflow-GPU on WSL2
Has anyone successfully installed Tensorflow-GPU on WSL2 with NVIDIA GPUs? I have Ubuntu 18.04 on WSL2, but am struggling to get NVIDIA drivers installed. Any help would be appreciated as I'm lost.</p>

答:
I just want to point out that using anaconda to install cudatoolkit and cudnn does not seem to work in wsl.

Maybe there is some problem with paths that make TF look for the needed files only in the system paths instead of the conda enviroments.

Title: Install Tensorflow-GPU on WSL2


问:
JavaScript Proxy which returns an empty array by default
I want to define some object so that every property provides an empty array if it's not defined.

Example: consider the list of users, every user is {id: number, age: string, ...}. We want to group users by age:

```<code>const users = [{id: 1, age: 42}, {id: 2, age: 42}, {id: 3, age: 43}]

const usersByAge = users.reduce((out, user) => {
  if (!out.hasOwnProperty(user.age)) {
    out[user.age] = []
  }
  out[user.age].push(user)
  return out
}, {})

console.log(usersByAge[42]) -> [{id: 1, age: 42}, {id: 2, age: 42}]
console.log(usersByAge[43]) -> [{id: 3, age: 43}]
console.log(usersByAge[18]) -> undefined
console.log(Object.keys(usersByAge)) -> ['42', '43']
</code>```

This code works, but I want to shorten it by using special JavaScript Proxy. It should return an empty array if the property is not defined. It should be possible to push items into the property even if it's not defined. It should provide the same array for different undefined properties:

```<code>const getMapFromIdToArray = () => {
  return new Proxy({}, {
    get: (target, name) => {
      if (!target.hasOwnProperty(name)) {
        target[name] = []
      }
      return target[name]
    }
  })
}

const usersByAge = users.reduce((out, user) => {
  out[user.age].push(user) // <- this should work, array initialization should not be required
  return out
}, getMapFromIdToArray())

console.log(usersByAge[42]) -> [{id: 1, age: 42}, {id: 2, age: 42}] - OK
console.log(usersByAge[18]) -> [] - OK
console.log(usersByAge[18] === usersByAge[19]) -> true - FAIL
console.log(Object.keys(usersByAge)) -> ['42', '43'] - FAIL
</code>```

This code works partly. If the property is not defined, it's initialized as []. So the getter actually mutates the target. I would like to avoid this. But the same time I want to be able to call .push on an undefined property without initialization. Is it possible to achieve?

答:
It should provide the same array for different undefined properties

I'm not sure what you meant in this sentence, but you definitely don't want two different properties to return reference to the same array and then items belonging to different properties being pushed to that array.

If the property is not defined, it's initialized as []. So the getter
actually mutates the target. I would like to avoid this. But the same
time I want to be able to call .push on an undefined property without
initialization. Is it possible to achieve?

I would say yes and no. The push method has to work on an actual array, and the object must hold a reference to that array in order to retrive the pushed items later. But if you don't want the empty array to create an actual property in the target object right away, then you can store it separately in the proxy until it requested after being mutated:

```<code>new Proxy({}, {
  tempProps: {},
  get: (target, name, reciever) => {
    if (target.hasOwnProperty(name)) {
      return target[name];
    }

    if (tempProps.hasOwnProperty(name)) {
      if tempProps[name].length {
        // array is not empty - bring into target
        target[name] = tempProps[name];
        delete tempProps[name];
        return target[name];
      } else {
        return tempProps[name];
      }
    }

    tempProps[name] = [];
    return tempProps[name];
  }
})
</code>```

It may also be possible to hold the reference to the returned empty array in a WeakRef object, so that if the caller drops all references to the array it will finally be garbage collected. But that seems unnecessarily complicated unless in very specific circumstances.

Body:
I want to define some object so that every property provides an empty array if it's not defined.

Example: consider the list of users, every user is {id: number, age: string, ...}. We want to group users by age:

const users = [{id: 1, age: 42}, {id: 2, age: 42}, {id: 3, age: 43}]

const usersByAge = users.reduce((out, user) => {
  if (!out.hasOwnProperty(user.age)) {
    out[user.age] = []
  }
  out[user.age].push(user)
  return out
}, {})

console.log(usersByAge[42]) -> [{id: 1, age: 42}, {id: 2, age: 42}]
console.log(usersByAge[43]) -> [{id: 3, age: 43}]
console.log(usersByAge[18]) -> undefined
console.log(Object.keys(usersByAge)) -> ['42', '43']

This code works, but I want to shorten it by using special JavaScript Proxy. It should return an empty array if the property is not defined. It should be possible to push items into the property even if it's not defined. It should provide the same array for different undefined properties:

const getMapFromIdToArray = () => {
  return new Proxy({}, {
    get: (target, name) => {
      if (!target.hasOwnProperty(name)) {
        target[name] = []
      }
      return target[name]
    }
  })
}

const usersByAge = users.reduce((out, user) => {
  out[user.age].push(user) // <- this should work, array initialization should not be required
  return out
}, getMapFromIdToArray())

console.log(usersByAge[42]) -> [{id: 1, age: 42}, {id: 2, age: 42}] - OK
console.log(usersByAge[18]) -> [] - OK
console.log(usersByAge[18] === usersByAge[19]) -> true - FAIL
console.log(Object.keys(usersByAge)) -> ['42', '43'] - FAIL

This code works partly. If the property is not defined, it's initialized as []. So the getter actually mutates the target. I would like to avoid this. But the same time I want to be able to call .push on an undefined property without initialization. Is it possible to achieve?

Body:
It should provide the same array for different undefined properties

I'm not sure what you meant in this sentence, but you definitely don't want two different properties to return reference to the same array and then items belonging to different properties being pushed to that array.

If the property is not defined, it's initialized as []. So the getter
actually mutates the target. I would like to avoid this. But the same
time I want to be able to call .push on an undefined property without
initialization. Is it possible to achieve?

I would say yes and no. The push method has to work on an actual array, and the object must hold a reference to that array in order to retrive the pushed items later. But if you don't want the empty array to create an actual property in the target object right away, then you can store it separately in the proxy until it requested after being mutated:

new Proxy({}, {
  tempProps: {},
  get: (target, name, reciever) => {
    if (target.hasOwnProperty(name)) {
      return target[name];
    }

    if (tempProps.hasOwnProperty(name)) {
      if tempProps[name].length {
        // array is not empty - bring into target
        target[name] = tempProps[name];
        delete tempProps[name];
        return target[name];
      } else {
        return tempProps[name];
      }
    }

    tempProps[name] = [];
    return tempProps[name];
  }
})

It may also be possible to hold the reference to the returned empty array in a WeakRef object, so that if the caller drops all references to the array it will finally be garbage collected. But that seems unnecessarily complicated unless in very specific circumstances.


问:
How to educate a development manager about the difficulties of software design?
I have had a few development managers who don't seem to understand or appreciate the difficulties of software design and implementation.

Such managers believe that processes and methodologies completely solve the problem and I have a tough time explaining to them that it is not so and that you cannot read a book on the latest process fad and hope to get results by applying them as is.

The latest frustration I have is to convince my manager to
(a) Give me requirements not piece-meal but a larger set as far as possible.
(b) Give my team lead time to think about how to design, thrash out a few alternatives, work out an implementation sketch, to plan out the tasks etc.

The frustrations are compounded because of Agile methodology and the interpretation of it that says not to do up-front design (as against BIG up-front design in Waterfall), product owner can change requirements at any time and so son.

So far I haven't had much success and have to put up with the resulting frustrations.
Can you give me some arguments that can convince such managers?

EDIT-1:
Retrospectives are done, though not always at the end of every sprint, and the problems are brought up. But as I mentioned, my manager doesn't appreciate the need for design lead time and the frustrations with piece-meal requirements.

EDIT-2
I don't have a problem with changing requirements. I understand that it will be so, but imagine this: You want a small feature to begin with and then you keep adding more around it. After a few iterations, the design cannot handle it anymore and a redesign (not refactoring) is required. This could have been solved better with an upfront design in the first place, had the related features been investigated together. Its not BDUF, its the natural way of doing it (what I call software engineering common sense).

My manager doesn't understand why I ask for time to redesign (a few times I just call it refactoring so that it fits the Agile way of doing it, but it really is redesign) and not developing and demoing new features.

答:
Business requirements are going to change no matter where you work. It's not your fault, it's not your boss's fault, it's not anybody's fault. The entire point of taking the requirements on piecemeal is to encourage you to think about the problem at hand, not some other problem that you might or might not need to solve. It's quite liberating once you get into the rhythm of it.

Think of upfront design as premature optimization. You may not need it, and even if you know you need it, you'll know more about your design two weeks from now than you know about it today. It'll help you solve your engineering problem with the best possible knowledge about the state of your code.

That having been said, edg is absolutely right. When you add more requirements, the estimate changes. This isn't the fault of the developers or anyone else; more work means more work no matter how you square it. If your boss doesn't realize that adding requirements will result in a larger estimate for the project you need to explain to him that Agile isn't a magic bullet that allows you to add more features without paying anything for them.

OwnerDisplayName: trshiv

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: trshiv

OwnerDisplayName: Brian Guthrie


问:
Need a help with a jquery click count
So far I have got this JavaScript:

```<code>$(document).ready(function() {
    $("#flash").click(function() {
        $(this).html('<img src="http://ruh.kz/sites/default/files/ajax-loader.gif" />');
        $(this).load("http://ruh.kz/sites/all/themes/ruh/sunit.php");
        $('#counter').html(function(i, val) {
            return val * 1 + 1
        });
    });
});
</code>```

Accompanying this HTML:

```<code><div id="flash">
    <img src="http://ruh.kz/sites/default/files/sunit.jpg" />
</div>
<div id="counter">0</div>
</code>```

(Demo)

One problem is that it resets after the page refreshes... How can I save the count number?

In the example on jsfiddle.net, it works well. On my Drupal page however, it doesn't. When I press on the
 the counter "0" dissapears. What might be the problem here?

答: You will have to use cookies to store the number of clicks between page requests, as on each reload the javascript will be reloaded and so your click counts will be lost.

Title: Need a help with a jquery click count

Body:
So far I have got this JavaScript:

$(document).ready(function() {
    $("#flash").click(function() {
        $(this).html('');
        $(this).load("http://ruh.kz/sites/all/themes/ruh/sunit.php");
        $('#counter').html(function(i, val) {
            return val * 1 + 1
        });
    });
});

Accompanying this HTML:

0

(Demo)

One problem is that it resets after the page refreshes... How can I save the count number?

In the example on jsfiddle.net, it works well. On my Drupal page however, it doesn't. When I press on the
 the counter "0" dissapears. What might be the problem here?


问:
Problem concatenating strings using JavaScript template literals
I'm using the prisma.io library and having trouble working with template literals to do what I want. Maybe I don't understand them well enough.

I have this call:

```<code>const result = await prisma.$queryRaw`SELECT * FROM User WHERE active = ${activeSetting}`
</code>```

And this works exactly the way I want.

However, I want to optionally append a string at the end without having to redo the full statement.

That is, I want something like:

```<code>let result;
if (orderBy === "ASC") {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY ASC`
} else if {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY DESC`
}

</code>```

Basically, I don't want to have to have to complete statements that start with const result = await.  I realize this is a short example, but my problem is when I have fairly long SQL statements and I find myself doing a lot of cutting and pasting huge SQL which gets error prone.

答:
I realize I could have made a much bigger sql statement as well as concatenating bigger chunks of code and that would have made the problem more clear.  Thanks to @CertainPerformance and @Phil for the ideas.

Here is what I was really looking for that solves my bigger problem and still keeps me safe I'm pretty sure.

```<code>    const orderByAsc = Prisma.sql`ORDER BY ASC`;
    const orderByDesc = Prisma.sql`ORDER BY DESC`;
    const result =
      await prisma.$queryRaw`SELECT * FROM User WHERE active = ${activeSetting} ${
        orderBy === 'ASC' ? orderByAsc : orderByDesc
      }`;
</code>```

And it also let's me put expressions in my sub clauses if need be.

Body:
I'm using the prisma.io library and having trouble working with template literals to do what I want. Maybe I don't understand them well enough.

I have this call:

const result = await prisma.$queryRaw`SELECT * FROM User WHERE active = ${activeSetting}`

And this works exactly the way I want.

However, I want to optionally append a string at the end without having to redo the full statement.

That is, I want something like:

let result;
if (orderBy === "ASC") {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY ASC`
} else if {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY DESC`
}

Basically, I don't want to have to have to complete statements that start with const result = await.  I realize this is a short example, but my problem is when I have fairly long SQL statements and I find myself doing a lot of cutting and pasting huge SQL which gets error prone.

Body:
I realize I could have made a much bigger sql statement as well as concatenating bigger chunks of code and that would have made the problem more clear.  Thanks to @CertainPerformance and @Phil for the ideas.

Here is what I was really looking for that solves my bigger problem and still keeps me safe I'm pretty sure.

    const orderByAsc = Prisma.sql`ORDER BY ASC`;
    const orderByDesc = Prisma.sql`ORDER BY DESC`;
    const result =
      await prisma.$queryRaw`SELECT * FROM User WHERE active = ${activeSetting} ${
        orderBy === 'ASC' ? orderByAsc : orderByDesc
      }`;

And it also let's me put expressions in my sub clauses if need be.