问:
How to communicate between callbacks in gtk+ c
I'm working on a project right now, and I am trying to make 2 callbacks communicate with each other by passing to them the same variable (the callbacks share the same variable). Since the callbacks cannot return a value, I have passed a pointer to the value which is assigned in the main loop (main function).
However, it isn't working at all!

This is my code:

```<code>#include <gtk/gtk.h>

static void inc_val (GtkWidget *widget, gpointer data)
{
    int* value =  data;
    *value++;
    printf("value is: %d\n", *value);
}

static void inc_val_ten (GtkWidget *widget, gpointer data)
{
    int* value =  data;
    *value+=10;
    printf("value is: %d\n", *value);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *grid;
    GtkWidget *button;
    int value = 0;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Add 1 to value");
    g_signal_connect (button, "clicked", G_CALLBACK (inc_val), &value);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);

    button = gtk_button_new_with_label ("Add 10 to value");
    g_signal_connect (button, "clicked", G_CALLBACK (inc_val_ten), &value);
    gtk_grid_attach (GTK_GRID (grid), button, 1, 0, 1, 1);

    button = gtk_button_new_with_label ("Quit");
    g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}
</code>```

The program has 3 buttons in the window:

adding 1 to value

adding 10 to value

quitting the program

value is an integer on the main loop. When one of the buttons (first or second) are pressed, the value getting bigger (by 1 or by ten) and the program prints the new value.

I have run the program and clicked the buttons and that's what I've got:

```<code>value is: 46525384
value is: 46525384
value is: 46157330
value is: -830528646
value is: 56
value is: 10
</code>```

instead of:

```<code>value is: 1
value is: 2
value is: 12
value is: 22
value is: 23
value is: 33
</code>```

Anyone knows why does it happen?

Thanks for helping!

Edit: I have tried the same thing, just instead of adding numbers to a value, I've tried to add button to the grid. Since the solution from the answer (under the question) worked at the previous code, I've made the grid global.

So here is the new code:

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

GtkWidget *grid;

static void add_button (GtkWidget *widget, gpointer data)
{
    static int value = 0;
    GtkWidget* grid = data;
    value++;
    printf("attach to line %d\n", value);
    gtk_grid_attach(GTK_GRID(grid), gtk_button_new_from_stock(GTK_STOCK_NEW), 0, value, 1, 1);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *button;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Add Button");
    g_signal_connect (button, "clicked", G_CALLBACK (add_button), grid);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}
</code>```

However, it didn't work from some reason. Help will be appreciated!

答:
Answer to the EDIT:

You must show the widgets in order for them to be realized. Simplest way is to call gtk_widget_show_all on the parent container:

```<code>static void add_button (GtkWidget *widget, gpointer data)
{
    static int value = 0;
    GtkWidget* grid = data;
    value++;
    printf("attach to line %d\n", value);
    gtk_grid_attach(GTK_GRID(grid),
    gtk_button_new_from_stock(GTK_STOCK_NEW), 0, value, 1, 1);
    gtk_widget_show_all(grid);
}
</code>```

Another option, would be to keep a reference to the button and call gtk_widget_show on that instance. e.g.:

```<code>static void add_button (GtkWidget *widget, gpointer data)
{
    static int value = 0;
    GtkWidget* grid = data;
    GtkWidget* button = gtk_button_new_from_stock(GTK_STOCK_NEW);

    value++;
    printf("attach to line %d\n", value);

    gtk_grid_attach(GTK_GRID(grid), button, 0, value, 1, 1);
    gtk_widget_show (button);
}
</code>```

Body:
I'm working on a project right now, and I am trying to make 2 callbacks communicate with each other by passing to them the same variable (the callbacks share the same variable). Since the callbacks cannot return a value, I have passed a pointer to the value which is assigned in the main loop (main function).
However, it isn't working at all!

This is my code:

#include <gtk/gtk.h>

static void inc_val (GtkWidget *widget, gpointer data)
{
    int* value =  data;
    *value++;
    printf("value is: %d\n", *value);
}

static void inc_val_ten (GtkWidget *widget, gpointer data)
{
    int* value =  data;
    *value+=10;
    printf("value is: %d\n", *value);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *grid;
    GtkWidget *button;
    int value = 0;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Add 1 to value");
    g_signal_connect (button, "clicked", G_CALLBACK (inc_val), &value);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);

    button = gtk_button_new_with_label ("Add 10 to value");
    g_signal_connect (button, "clicked", G_CALLBACK (inc_val_ten), &value);
    gtk_grid_attach (GTK_GRID (grid), button, 1, 0, 1, 1);

    button = gtk_button_new_with_label ("Quit");
    g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

The program has 3 buttons in the window:

adding 1 to value

adding 10 to value

quitting the program

value is an integer on the main loop. When one of the buttons (first or second) are pressed, the value getting bigger (by 1 or by ten) and the program prints the new value.

I have run the program and clicked the buttons and that's what I've got:

value is: 46525384
value is: 46525384
value is: 46157330
value is: -830528646
value is: 56
value is: 10

instead of:

value is: 1
value is: 2
value is: 12
value is: 22
value is: 23
value is: 33

Anyone knows why does it happen?

Thanks for helping!

Edit: I have tried the same thing, just instead of adding numbers to a value, I've tried to add button to the grid. Since the solution from the answer (under the question) worked at the previous code, I've made the grid global.

So here is the new code:

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

GtkWidget *grid;

static void add_button (GtkWidget *widget, gpointer data)
{
    static int value = 0;
    GtkWidget* grid = data;
    value++;
    printf("attach to line %d\n", value);
    gtk_grid_attach(GTK_GRID(grid), gtk_button_new_from_stock(GTK_STOCK_NEW), 0, value, 1, 1);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *button;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Add Button");
    g_signal_connect (button, "clicked", G_CALLBACK (add_button), grid);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

However, it didn't work from some reason. Help will be appreciated!

Body:
Answer to the EDIT:

You must show the widgets in order for them to be realized. Simplest way is to call gtk_widget_show_all on the parent container:

static void add_button (GtkWidget *widget, gpointer data)
{
    static int value = 0;
    GtkWidget* grid = data;
    value++;
    printf("attach to line %d\n", value);
    gtk_grid_attach(GTK_GRID(grid),
    gtk_button_new_from_stock(GTK_STOCK_NEW), 0, value, 1, 1);
    gtk_widget_show_all(grid);
}

Another option, would be to keep a reference to the button and call gtk_widget_show on that instance. e.g.:

static void add_button (GtkWidget *widget, gpointer data)
{
    static int value = 0;
    GtkWidget* grid = data;
    GtkWidget* button = gtk_button_new_from_stock(GTK_STOCK_NEW);

    value++;
    printf("attach to line %d\n", value);

    gtk_grid_attach(GTK_GRID(grid), button, 0, value, 1, 1);
    gtk_widget_show (button);
}


来源: stackexchange

问:
Alternate methods to supply data for machine learning (Other than using CSV files)
I have a question which is relating to machine learning application in real world. It might be sounds stupid lol.

I've been self study machine learning for a while and most of the exercise was using the csv file as data source (both processed and raw). I would like to ask is there any other methods other than import csv file to channel/supply data for machine learning?

Example: Streaming Facebook/ Twitter live feed's data for machine learning in real-time, rather than collect old data and stored them into CSV file.

答:
The data source can be anything. Usually, it's provided as a CSV or JSON file. But in the real world, say you have a website such as Twitter, as you're mentioning, you'd be storing your data in a rational DB such as SQL databases, and for some data you'd be putting them in an in-memory cache.

You can basically utilize both of these to retrieve your data and process it. The thing here is when you have too much data to fit in the memory, you can't really just query everything and process it, in that case, you'll be utilizing some smart algorithms to process data in chunks.

Good thing about some databases such as SQL is that they provide you with a set of functions that you can invoke right in your SQL script to efficiently calculate some data. For example you can get a sum of a column across the whole table or something using SUM() function SQL, which allows for efficient and easy data manipulation

ContentLicense: CC BY-SA 3.0


问:
add text to image with convert
I am being stuck at some image editing using bash commands.
I have 414 images labelled 1file.png 2file.png ... 414file.png. To each of these I would like to add the number, which is already present in the name. The goal is to create a .gif which will show the counts of images in one corner counting up. (Creating the .gif using convert * result.gif works)

The problem is it will not add my number in the image but literally print $i. Does somebody know how to read in the loop variable?

I have tried:

```<code>for i in {0..9}; do
convert -pointsize 80 -fill black -draw 'text 1650 400 "$i"' "$i"file.png "$i"file.png;
done
</code>```

Many thanks in advance.

答:
Problem solved:</p>

```<code>for i in {0..1}; do
convert -pointsize 80 -fill black -draw 'text 1650 400 '\"$i\"'' "$i"file.png "$i"file.png;
done
</code>```

Title: add text to image with convert

Body:
I am being stuck at some image editing using bash commands.
I have 414 images labelled 1file.png 2file.png ... 414file.png. To each of these I would like to add the number, which is already present in the name. The goal is to create a .gif which will show the counts of images in one corner counting up. (Creating the .gif using convert * result.gif works)

The problem is it will not add my number in the image but literally print $i. Does somebody know how to read in the loop variable?

I have tried:

for i in {0..9}; do
convert -pointsize 80 -fill black -draw 'text 1650 400 "$i"' "$i"file.png "$i"file.png;
done

Many thanks in advance.

Body:
Problem solved:

for i in {0..1}; do
convert -pointsize 80 -fill black -draw 'text 1650 400 '\"$i\"'' "$i"file.png "$i"file.png;
done


问:
Using hierarchical blocks in redhawk
Is there a way to use hirarchical blocks in redhawk?
For example, say I want to make a digital modulator that is a composition of filters, upsamplers, etc, and I want to use it as a single block in a waveform project, that has other hierarchical components as well. How would I combine the already made filter and upsampler blocks into the digital modulator block using redhawk?</p>

答:
There isn't a construct for a component of components (other than a waveform).  As of the REDHAWK 2.1 beta release there is a 'shared address' construct that allows you to do something similar to what you seem to be asking for.  The 'shared address' BULKIO pattern was specifically developed to create high-speed connections between components and reduce the processing load caused by IO.  Take a look at https://github.com/RedhawkSDR/core-framework/tree/develop-2.1/docs/shared-address and see if this is what you are looking for.  It will allow you to launch 'N' components built according to the shared address pattern into a single component host and still retain each individual components property interfaces etc.

If you are more specific about why you want to use a hierarchical block, a more targeted answer may be possible.

Title: Using hierarchical blocks in redhawk


问:
Undefined Reference to yylval in lex program
I am working on Lex and Yacc program but I am getting error as :

/tmp/ccTP9YY1.o: In function yylex':
  lex.yy.c:(.text+0x289): undefined reference toyylval'
  lex.yy.c:(.text+0x2a8): undefined reference to `yylval'
  collect2: error: ld returned 1 exit status

I have searched a lot on Internet like stackoverflow and other sites but none of them seems to capable of solving my problem. I might be implementing those suggestions incorrectly. Can anyone please suggest me anything about this ?
Thanks in advance.

```<code>%{
#include <stdlib.h>
#include "y.tab.h"
void yyerror(char *);
%}
%%
[a-z]  {
      yylval = *yytext - 'a';
      return VARIABLE;
       }
[0-9]+ {
      yylval = atoi(yytext);
      return INTEGER;
   }
[-+()=/*\n] { return *yytext; }
[ \t]        ;
.  {  yyerror("invalid character");   }

%%

void yyerror(char *s) {
   fprintf(stderr, "%s\n", s);
}

int yywrap(void) {
   return 1;
}
</code>```

Commands used :

```<code>rohit@rohit-HP-Pavilion-g4-Notebook-PC:~$ lex echo.l
rohit@rohit-HP-Pavilion-g4-Notebook-PC:~$ yacc -d yaccCalc.y
rohit@rohit-HP-Pavilion-g4-Notebook-PC:~$ gcc lex.yy.c y.tab.h -ll
/tmp/ccTP9YY1.o: In function `yylex':
lex.yy.c:(.text+0x289): undefined reference to `yylval'
lex.yy.c:(.text+0x2a8): undefined reference to `yylval'
collect2: error: ld returned 1 exit status
</code>```

Yacc file :

```<code>%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'

%{
   void yyerror(char *);
   int yylex(void);
   int sym[26];
%}

%%

program:
    program statement '\n'
    |
    ;

statement:
    expr                      { printf("%d\n", $1); }
    | VARIABLE '=' expr       { sym[$1] = $3; }
    ;

expr:
    INTEGER
    | VARIABLE                { $$ = sym[$1]; }
    | expr '+' expr           { $$ = $1 + $3; }
    | expr '-' expr           { $$ = $1 - $3; }
    | expr '*' expr           { $$ = $1 * $3; }
    | expr '/' expr           { $$ = $1 / $3; }
    | '(' expr ')'            { $$ = $2; }
    ;

%%

void yyerror(char *s) {
   fprintf(stderr, "%s\n", s);
}

int main(void) {
   yyparse();
   return 0;
}
</code>```

答:
Two files are generated by Yacc (and Bison), namely y.tab.h and y.tab.c assuming you do not override the output file with option -o.  Include y.tab.h in your source code and compile y.tab.c. So perhaps you made a typo when trying to compile:

```<code>gcc lex.yy.c y.tab.c -ll
-------------------^-------- compile y.tab.c, not y.tab.h
</code>```

Body:
I am working on Lex and Yacc program but I am getting error as :

/tmp/ccTP9YY1.o: In function yylex':
  lex.yy.c:(.text+0x289): undefined reference toyylval'
  lex.yy.c:(.text+0x2a8): undefined reference to `yylval'
  collect2: error: ld returned 1 exit status

I have searched a lot on Internet like stackoverflow and other sites but none of them seems to capable of solving my problem. I might be implementing those suggestions incorrectly. Can anyone please suggest me anything about this ?
Thanks in advance.

%{
#include <stdlib.h>
#include "y.tab.h"
void yyerror(char *);
%}
%%
[a-z]  {
      yylval = *yytext - 'a';
      return VARIABLE;
       }
[0-9]+ {
      yylval = atoi(yytext);
      return INTEGER;
   }
[-+()=/*\n] { return *yytext; }
[ \t]        ;
.  {  yyerror("invalid character");   }

%%

void yyerror(char *s) {
   fprintf(stderr, "%s\n", s);
}

int yywrap(void) {
   return 1;
}

Commands used :

rohit@rohit-HP-Pavilion-g4-Notebook-PC:~$ lex echo.l
rohit@rohit-HP-Pavilion-g4-Notebook-PC:~$ yacc -d yaccCalc.y
rohit@rohit-HP-Pavilion-g4-Notebook-PC:~$ gcc lex.yy.c y.tab.h -ll
/tmp/ccTP9YY1.o: In function `yylex':
lex.yy.c:(.text+0x289): undefined reference to `yylval'
lex.yy.c:(.text+0x2a8): undefined reference to `yylval'
collect2: error: ld returned 1 exit status

Yacc file :

%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'

%{
   void yyerror(char *);
   int yylex(void);
   int sym[26];
%}

%%

program:
    program statement '\n'
    |
    ;

statement:
    expr                      { printf("%d\n", $1); }
    | VARIABLE '=' expr       { sym[$1] = $3; }
    ;

expr:
    INTEGER
    | VARIABLE                { $$ = sym[$1]; }
    | expr '+' expr           { $$ = $1 + $3; }
    | expr '-' expr           { $$ = $1 - $3; }
    | expr '*' expr           { $$ = $1 * $3; }
    | expr '/' expr           { $$ = $1 / $3; }
    | '(' expr ')'            { $$ = $2; }
    ;

%%

void yyerror(char *s) {
   fprintf(stderr, "%s\n", s);
}

int main(void) {
   yyparse();
   return 0;
}

Body:
Two files are generated by Yacc (and Bison), namely y.tab.h and y.tab.c assuming you do not override the output file with option -o.  Include y.tab.h in your source code and compile y.tab.c. So perhaps you made a typo when trying to compile:

gcc lex.yy.c y.tab.c -ll
-------------------^-------- compile y.tab.c, not y.tab.h


问:
How to do a nightly build using Gradle?
I can build my android project in command line with ./gradlew assembleDebug but how do I automate this so Gradle builds itself once every day? Is there any way to do this without downloading something additional like Jenkins?</p>

答:
Use can use crontab to automate without downloading any package type crontab -e

```<code>*     *     *     *     *  Command to be executed
</code>```

Min (0 - 59)

Hour (0 - 23)

Day of month (1 - 31)

Month (1 - 12)

Day of week (0-7)

lets say if you want to automate everyday around 22:00

```<code>0 21 * * * ./gradlew assembleDebug
</code>```

Title: How to do a nightly build using Gradle?

Body:
Use can use crontab to automate without downloading any package type crontab -e

*     *     *     *     *  Command to be executed

Min (0 - 59)

Hour (0 - 23)

Day of month (1 - 31)

Month (1 - 12)

Day of week (0-7)

lets say if you want to automate everyday around 22:00

0 21 * * * ./gradlew assembleDebug


问:
How to set multilevel index in a dataframe with existing columns
I have a dataframe as below:

```<code>     A      B     C     D
0    hola   32    43    54
1    hey    87    67    45
2    hi     10    54    89
3    hola   19    34    12
4    hi     11    59    09
</code>```

I need to set a multilevel index using A and B , which is grouped by A
I need the following dataframe

```<code> A      B     C     D
hola   32    43    54
       19    34    12
hey    87    67    45
hi     10    54    89
       11    59    09
</code>```

I have tried using df.set_index(['A','B'])
and i get

```<code>A      B     C     D
hola   32    43    54
hola   19    34    12
hey    87    67    45
hi     10    54    89
hi     11    59    09
</code>```

答:
Sorting first is not necessary- you are setting the MultiIndex but it is not lexsorted:

```<code>df.set_index(['A','B']).index.is_lexsorted()
False
</code>```

As an alternate method, set the index as you already have and sort it after the fact:

```<code>df.set_index(['A','B']).sort_index()
          C   D
A    B
hey  87  67  45
hi   10  54  89
     11  59   9
hola 19  34  12
     32  43  54
</code>```

Body:
I have a dataframe as below:

     A      B     C     D
0    hola   32    43    54
1    hey    87    67    45
2    hi     10    54    89
3    hola   19    34    12
4    hi     11    59    09

I need to set a multilevel index using A and B , which is grouped by A
I need the following dataframe

 A      B     C     D
hola   32    43    54
       19    34    12
hey    87    67    45
hi     10    54    89
       11    59    09

I have tried using df.set_index(['A','B'])
and i get

A      B     C     D
hola   32    43    54
hola   19    34    12
hey    87    67    45
hi     10    54    89
hi     11    59    09

Body:
Sorting first is not necessary- you are setting the MultiIndex but it is not lexsorted:

df.set_index(['A','B']).index.is_lexsorted()
False

As an alternate method, set the index as you already have and sort it after the fact:

df.set_index(['A','B']).sort_index()
          C   D
A    B
hey  87  67  45
hi   10  54  89
     11  59   9
hola 19  34  12
     32  43  54


问:
Magento 2 : Replace labels in invoice pdf
I am new in magento 2. I am facing problem in replacing labels in pdf invoice. I need to replace "Tax" label by "GST" label which is present at right hand bottom. I have wasted more than 6 hours on this but not getting any solution.

Please help me in this.

答: I got the solution. I have replaced "Tax" label to "GST" in vendor/magento/module-tax/i18n/en_US.csv file. This change got reflected throughout the website.


问:
Android, Layout: How do I get my button to overlay existing layout in axml?
As for most of you: we design our screens for our app in photoshop and then try to transfer them into Visual Studio.

This is a screenshot of our app FROM PHOTOSHOP:

You could imagine, the further we go the harder it gets. The center screen was easy but the left and right one - oh boy...

Anyway, today I'm here for the right one.

As you can see, there are these headlines such as: "Show Us Love For Asia".
This whole box shows a photo, a headline, a few extra infos AND:
a profile picture.

The whole is a scrollview and the white bars underneath each box are actually pngs. The reason is, that we need them to be equally sized on each different platform. Anyway - the profile picture is overlapping the picture box and the white divider png in between the picture boxes.

And here is the question: how the hell would we implement that into our axml?

As far as the screen is, this is it in xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutadventure"
    android:background="@android:color/white"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_weight="17"
        android:layout_height="0dp"
        android:background="#23313e"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="0dp"
            android:src="@drawable/sub_category_europe"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_weight="30"
            android:id="@+id/imgSubchallenge" />
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="40"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_gravity="center|bottom"
                android:id="@+id/txtSub"
                android:layout_weight="60"
                android:gravity="center|bottom"
                android:text="Positive Thinking"
                android:textColor="#FFFFFF"
                android:textSize="18sp"
                android:textStyle="bold|italic" />
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="5"
                android:layout_gravity="top|center"
                android:gravity="top|center"
                android:src="@drawable/dotted_line_challenges" />
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_weight="35"
                android:layout_height="0dp"
                android:orientation="vertical" />
        </LinearLayout>
        <ImageView
            android:layout_width="0dp"
            android:src="@drawable/bar2"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_weight="5" />
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="25"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="50"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="30"
                    android:orientation="vertical" />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Total"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Done"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Exp"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="25"
                    android:orientation="vertical" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="50"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="30"
                    android:orientation="vertical" />
                <TextView
                    android:id="@+id/totalChallenges"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Total"
                    android:gravity="right"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:id="@+id/totalChallengesDone"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Done"
                    android:gravity="right"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:id="@+id/totalXP"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Exp"
                    android:gravity="right"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="25"
                    android:orientation="vertical" />
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:orientation="vertical" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:orientation="vertical" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="82.5"
        android:scrollbars="none"
        android:id="@+id/scrlview">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/linlayout"
            android:orientation="vertical" />
    </ScrollView>
</LinearLayout>
</code>```

So you probably see the dilemma: the profile picture is halfway in one column of the scrollview and halfway in another column.

Can you provide any help for that? THANKS SO MUCH :)

答:
Try this i hope this will help you. This is for only "Show Us Love For Asia" one item only.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="500dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="500dp"
            android:orientation="vertical"
            android:background="@color/colorAccent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".8"
                android:background="@color/colorPrimary">

            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".2"
                android:background="@color/colorAccent">

            </LinearLayout>

        </LinearLayout>
        <android.support.v4.widget.CircleImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher_round"
            android:layout_gravity="bottom"
            android:layout_marginBottom="75dp"/>
    </FrameLayout>
</LinearLayout>
</code>```

Body:
As for most of you: we design our screens for our app in photoshop and then try to transfer them into Visual Studio.

This is a screenshot of our app FROM PHOTOSHOP:

You could imagine, the further we go the harder it gets. The center screen was easy but the left and right one - oh boy...

Anyway, today I'm here for the right one.

As you can see, there are these headlines such as: "Show Us Love For Asia".
This whole box shows a photo, a headline, a few extra infos AND:
a profile picture.

The whole is a scrollview and the white bars underneath each box are actually pngs. The reason is, that we need them to be equally sized on each different platform. Anyway - the profile picture is overlapping the picture box and the white divider png in between the picture boxes.

And here is the question: how the hell would we implement that into our axml?

As far as the screen is, this is it in xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutadventure"
    android:background="@android:color/white"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_weight="17"
        android:layout_height="0dp"
        android:background="#23313e"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="0dp"
            android:src="@drawable/sub_category_europe"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_weight="30"
            android:id="@+id/imgSubchallenge" />
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="40"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_gravity="center|bottom"
                android:id="@+id/txtSub"
                android:layout_weight="60"
                android:gravity="center|bottom"
                android:text="Positive Thinking"
                android:textColor="#FFFFFF"
                android:textSize="18sp"
                android:textStyle="bold|italic" />
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="5"
                android:layout_gravity="top|center"
                android:gravity="top|center"
                android:src="@drawable/dotted_line_challenges" />
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_weight="35"
                android:layout_height="0dp"
                android:orientation="vertical" />
        </LinearLayout>
        <ImageView
            android:layout_width="0dp"
            android:src="@drawable/bar2"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_weight="5" />
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="25"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="50"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="30"
                    android:orientation="vertical" />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Total"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Done"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Exp"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="25"
                    android:orientation="vertical" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_weight="50"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="30"
                    android:orientation="vertical" />
                <TextView
                    android:id="@+id/totalChallenges"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Total"
                    android:gravity="right"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:id="@+id/totalChallengesDone"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Done"
                    android:gravity="right"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <TextView
                    android:id="@+id/totalXP"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="15"
                    android:text="Exp"
                    android:gravity="right"
                    android:textColor="#FFFFFF"
                    android:textSize="10sp" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="25"
                    android:orientation="vertical" />
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:orientation="vertical" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:orientation="vertical" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="82.5"
        android:scrollbars="none"
        android:id="@+id/scrlview">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/linlayout"
            android:orientation="vertical" />
    </ScrollView>
</LinearLayout>

So you probably see the dilemma: the profile picture is halfway in one column of the scrollview and halfway in another column.

Can you provide any help for that? THANKS SO MUCH :)

Body:
Try this i hope this will help you. This is for only "Show Us Love For Asia" one item only.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="500dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="500dp"
            android:orientation="vertical"
            android:background="@color/colorAccent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".8"
                android:background="@color/colorPrimary">

            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight=".2"
                android:background="@color/colorAccent">

            </LinearLayout>

        </LinearLayout>
        <android.support.v4.widget.CircleImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher_round"
            android:layout_gravity="bottom"
            android:layout_marginBottom="75dp"/>
    </FrameLayout>
</LinearLayout>


问:
Skip null values with custom resolver
I want to use automapper to map between my public data contracts and my DB models. I have created a class which automatically goes through all the contracts are creates mappings. The only problem I have is that I only want to map values from the contract to the DB model if the value is not null. I have looked at other question on here but cant see examples that use custom resolvers.

Here is some of my code

```<code>var mapToTarget = AutoMapper.Mapper.CreateMap(contract, mappedTo);
foreach (var property in contract.GetProperties().Where(property => property.CustomAttributes.Any(a => a.AttributeType == typeof(MapsToProperty))))
{
  var attribute = property.GetCustomAttributes(typeof(MapsToProperty), true).FirstOrDefault() as MapsToProperty;

  if (attribute == null) continue;

  mapToTarget.ForMember(attribute.MappedToName,
                    opt =>
                        opt.ResolveUsing<ContractToSourceResolver>()
                            .ConstructedBy(() => new ContractToSourceResolver(new MapsToProperty(property.Name, attribute.SourceToContractMethod, attribute.ContractToSourceMethod))));
}

private class ContractToSourceResolver : ValueResolver<IDataContract, object>
{
  private MapsToProperty Property { get; set; }

  public ContractToSourceResolver(MapsToProperty property)
  {
     Property = property;
  }

  protected override object ResolveCore(IDataContract contract)
  {
     object result = null;
     if (Property.ContractToSourceMethod != null)
     {
         var method = contract.GetType()
                    .GetMethod(Property.ContractToSourceMethod, BindingFlags.Public | BindingFlags.Static);
          result = method != null ? method.Invoke(null, new object[] {contract}) : null;
      }
      else
      {
         var property =
                    contract.GetType().GetProperties().FirstOrDefault(p => p.Name == Property.MappedToName);
         if (property != null)
         {
             result = property.GetValue(contract);
         }
      }

      return result;
   }
}
</code>```

And this is how I want to use it

```<code>AutoMapper.Mapper.Map(dataContract, dbModel)
</code>```

This currently works great but if there is a NULL value in the dataContract then it will replace the existing value in the dbModel, this is not what I want. How do I make AutoMapper ignore null source values?

EDIT

As pointed out in one of the answers there is this

```<code>Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
</code>```

This would be ideal except for the fact that .ForAllMembers is not accessible from

```<code>Mapper.CreateMap(SourceType, DestinationType)
</code>```

答:
The solution here works for my project, which is using AutoMapper 6.0.2. In previous projects using AutoMapper 4, I had used IsSourceValueNull to achieve similar behavior. I have nullable types mapped to non-nullable types in my project, this solution is able to handle that scenario.

I made a small change to the original solution. Instead of checking the type of the property to be mapped, I set the filter in ForAllPropertyMaps to check the type of the source object, so that the custom resolver only applies to maps from that source object. But the filter can be set to anything as needed.

```<code>var config = new MapperConfiguration(cfg =>
{
    cfg.ForAllPropertyMaps(
        pm => pm.TypeMap.SourceType == typeof(<class of source object>),
        (pm, c) => c.ResolveUsing<object, object, object, object>(new IgnoreNullResolver(), pm.SourceMember.Name));
});

class IgnoreNullResolver : IMemberValueResolver<object, object, object, object>
{
    public object Resolve(object source, object destination, object sourceMember, object destinationMember, ResolutionContext context)
    {
        return sourceMember ?? destinationMember;
    }
}
</code>```

Title: Skip null values with custom resolver

Body:
I want to use automapper to map between my public data contracts and my DB models. I have created a class which automatically goes through all the contracts are creates mappings. The only problem I have is that I only want to map values from the contract to the DB model if the value is not null. I have looked at other question on here but cant see examples that use custom resolvers.

Here is some of my code

var mapToTarget = AutoMapper.Mapper.CreateMap(contract, mappedTo);
foreach (var property in contract.GetProperties().Where(property => property.CustomAttributes.Any(a => a.AttributeType == typeof(MapsToProperty))))
{
  var attribute = property.GetCustomAttributes(typeof(MapsToProperty), true).FirstOrDefault() as MapsToProperty;

  if (attribute == null) continue;

  mapToTarget.ForMember(attribute.MappedToName,
                    opt =>
                        opt.ResolveUsing<ContractToSourceResolver>()
                            .ConstructedBy(() => new ContractToSourceResolver(new MapsToProperty(property.Name, attribute.SourceToContractMethod, attribute.ContractToSourceMethod))));
}

private class ContractToSourceResolver : ValueResolver<IDataContract, object>
{
  private MapsToProperty Property { get; set; }

  public ContractToSourceResolver(MapsToProperty property)
  {
     Property = property;
  }

  protected override object ResolveCore(IDataContract contract)
  {
     object result = null;
     if (Property.ContractToSourceMethod != null)
     {
         var method = contract.GetType()
                    .GetMethod(Property.ContractToSourceMethod, BindingFlags.Public | BindingFlags.Static);
          result = method != null ? method.Invoke(null, new object[] {contract}) : null;
      }
      else
      {
         var property =
                    contract.GetType().GetProperties().FirstOrDefault(p => p.Name == Property.MappedToName);
         if (property != null)
         {
             result = property.GetValue(contract);
         }
      }

      return result;
   }
}

And this is how I want to use it

AutoMapper.Mapper.Map(dataContract, dbModel)

This currently works great but if there is a NULL value in the dataContract then it will replace the existing value in the dbModel, this is not what I want. How do I make AutoMapper ignore null source values?

EDIT

As pointed out in one of the answers there is this

Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

This would be ideal except for the fact that .ForAllMembers is not accessible from

Mapper.CreateMap(SourceType, DestinationType)

Body:
The solution here works for my project, which is using AutoMapper 6.0.2. In previous projects using AutoMapper 4, I had used IsSourceValueNull to achieve similar behavior. I have nullable types mapped to non-nullable types in my project, this solution is able to handle that scenario.

I made a small change to the original solution. Instead of checking the type of the property to be mapped, I set the filter in ForAllPropertyMaps to check the type of the source object, so that the custom resolver only applies to maps from that source object. But the filter can be set to anything as needed.

var config = new MapperConfiguration(cfg =>
{
    cfg.ForAllPropertyMaps(
        pm => pm.TypeMap.SourceType == typeof(<class of source object>),
        (pm, c) => c.ResolveUsing<object, object, object, object>(new IgnoreNullResolver(), pm.SourceMember.Name));
});

class IgnoreNullResolver : IMemberValueResolver<object, object, object, object>
{
    public object Resolve(object source, object destination, object sourceMember, object destinationMember, ResolutionContext context)
    {
        return sourceMember ?? destinationMember;
    }
}


问:
How do i display people who are older than a particular person SQL?
What function shall i use to display all those people who are older than a specific person. DOB in my table is given in the format 19-JAN-88  </p>

```<code>select * from student
where
order by firstname;
</code>```

答:
If you can't change the dob field into a sensible format then you will need to use the
str_to_date( your_dob_field, '%d-%b-%y' ) so you would write

select * from student where str_to_date( your_dob_field, '%d-%b-%y' ) < str_to_date( dob_of_student_to_compare_to, '%d-%b-%y' );

Body:
What function shall i use to display all those people who are older than a specific person. DOB in my table is given in the format 19-JAN-88

select * from student
where
order by firstname;


问:
NSubstitue mock IEnumerable Where() method
I have the following code:

45  var listMock = Substitute.For<List<EntityTestObject>>();
 46  listMock.Where(Arg.Any<Func<EntityTestObject, bool>>()).Returns(Something);

But I'm getting the following error:

System.ArgumentNullException : Value cannot be null.
Parameter name: predicate
   at System.Linq.Enumerable.Where[TSource](IEnumerable'1 source, Func'2 predicate)
   at line 46.

However, methods that does not take func<> arguments, such as Any(), do not fail.

My questions are:

How to avoid this mistake if it possible?

If not, how to mock Enumerable Extension methods?

答: NSubstitute can not mock extension methods like Enumerable.Where<T>. For the case of a List I would advise not mocking it at all. Use a real list and add the items you need for your test, so that the real Where(..) extension method will filter the items and provide the items required.


问:
What to name a variable which you want to name after its type?
Let's say I have an enum class breed and I want to initialize a variable of type breed and I want to name the variable "breed"

```<code>struct dog{
    enum class breed{
        shepherd, husky, terrier
    };
    breed breed; // I don't know what to name this.
};
</code>```

dog::breed makes sense, but dog.breed also makes sense. I don't know what to name these so they don't clash.

答:
A common practice that (I guess) swapped over from Java is to start the class / enum name with a capital letter:</p>

```<code>Breed breed
</code>```

Body:
Let's say I have an enum class breed and I want to initialize a variable of type breed and I want to name the variable "breed"

struct dog{
    enum class breed{
        shepherd, husky, terrier
    };
    breed breed; // I don't know what to name this.
};

dog::breed makes sense, but dog.breed also makes sense. I don't know what to name these so they don't clash.

Body:
A common practice that (I guess) swapped over from Java is to start the class / enum name with a capital letter:

Breed breed


问:
Change background-color with different shades of color
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

```<code>background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)
</code>```

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

答:
background changing with all the shades of the rainbow:

    setInterval(function () {
        document.body.style.background = "red";
        setTimeout(function () { document.body.style.background = "orange" }, 1000);
        setTimeout(function () { document.body.style.background = "yellow" }, 2000);
        setTimeout(function () { document.body.style.background = "green" }, 3000);
        setTimeout(function () { document.body.style.background = "blue" }, 4000);
        setTimeout(function () { document.body.style.background = "indigo" }, 5000);
        setTimeout(function () { document.body.style.background = "violet" }, 6000);
    }, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
transition:background 1s linear;
}</code>```

background moving with the colors of the rainbow:

body{
  color:white
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><marquee scrollamount="20" style="position:fixed;top:0;left:0;bottom:0;right:0;width:100%;height:100vh;z-index:-9999999;margin:0;padding:0">
<div style="width:200%;height:100vh;margin-left:-100%;background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet,red,orange,yellow,green,blue,indigo,violet);"></div>
</marquee>

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

Body:
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

Body:
background changing with all the shades of the rainbow:

    setInterval(function () {
        document.body.style.background = "red";
        setTimeout(function () { document.body.style.background = "orange" }, 1000);
        setTimeout(function () { document.body.style.background = "yellow" }, 2000);
        setTimeout(function () { document.body.style.background = "green" }, 3000);
        setTimeout(function () { document.body.style.background = "blue" }, 4000);
        setTimeout(function () { document.body.style.background = "indigo" }, 5000);
        setTimeout(function () { document.body.style.background = "violet" }, 6000);
    }, 1000);

body{
transition:background 1s linear;
}

background moving with the colors of the rainbow:

body{
  color:white
}

<marquee scrollamount="20" style="position:fixed;top:0;left:0;bottom:0;right:0;width:100%;height:100vh;z-index:-9999999;margin:0;padding:0">
<div style="width:200%;height:100vh;margin-left:-100%;background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet,red,orange,yellow,green,blue,indigo,violet);"></div>
</marquee>

body body body body body body body body body body body body body body body body body


问:
select more than one checkbox to execute condition
I want a text file to show contents in memo1 once I have selected 2 checkboxes.
How would I do this?

I tried the code below but I can't seem to get it right.

```<code>if CheckBox1.Checked and CheckBox2.Checked then
begin
memo1.lines.LoadFromFile('files\RS.txt');
end;
</code>```

I also want to be able to select the checkboxes individually Like:
(pointing this out in case combining them prevents checking them individually)

Checkbox1:

```<code>procedure TForm1.CheckBox1Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\R.txt');
end;
</code>```

Checkbox2:

```<code>procedure TForm1.CheckBox2Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\S.txt');
end;
</code>```

Any suggestions/Improvements will be appreciated.

Running Lazarus IDE v1.6.4

Windows 10 x64

答:
As far as I understood you want the following behaviour:

There are two check boxes

There is one memo field

Depending on the state of the two check boxes the text in the memo field shall change

If this understanding is correct:

I typically don't use Pascal but your problem seems to be independent of the programming language used. I would do it like this:

The two procedures TForm1.CheckBox1Change and TForm1.CheckBox2Change are called whenever the corresponding check box'es state changes.

I would write a third procedure and call this third procedure from both procedures. I would do nothing else than calling this third procedure in the other two procedures.

In the third procedure I would evaluate what to do - depending on the state of both check boxes.

Body:
I want a text file to show contents in memo1 once I have selected 2 checkboxes.
How would I do this?

I tried the code below but I can't seem to get it right.

if CheckBox1.Checked and CheckBox2.Checked then
begin
memo1.lines.LoadFromFile('files\RS.txt');
end;

I also want to be able to select the checkboxes individually Like:
(pointing this out in case combining them prevents checking them individually)

Checkbox1:

procedure TForm1.CheckBox1Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\R.txt');
end;

Checkbox2:

procedure TForm1.CheckBox2Change(Sender: TObject);
begin
   memo1.lines.LoadFromFile('files\S.txt');
end;

Any suggestions/Improvements will be appreciated.

Running Lazarus IDE v1.6.4

Windows 10 x64


问:
i am using angularjs and django-cors-headers then give "which is disallowed for cross-origin requests that require preflight."
I have a Django local sever that refer to 8000 port number, And a local nginx that load 2080 port number html page.

I install django-cross-header package for resolving cross-domain error.

django-cross-header config in settings.py:

```<code>CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

  CORS_ALLOW_HEADERS = (
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
         'authorization',
         'x-csrftoken'
 )

  CORS_ORIGIN_WHITELIST = (
          '127.0.0.1:2080',
          'localhost:2080'
  )
</code>```

Config angularjs  is like this:

```<code>portman.config(function ($routeProvider, $interpolateProvider, $httpProvider) {
     $routeProvider.otherwise('/');
     $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken;
     $interpolateProvider.startSymbol('{$').endSymbol('$}');
     delete $httpProvider.defaults.headers.common['X-Requested-With'];

 });
 portman.constant('ip','http://127.0.0.1:8000/');
</code>```

Get method code in angularjs is:

```<code>$http({
         method: 'GET',
         url: ip+'api/v1/dslam/events',
     }).then(function (result) {
        $scope.dslam_events = result.data;
     }, function (err) {

    });
</code>```

request header is :
Provisional headers are shown

```<code>Accept:application/json, text/plain, */*
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
X-CSRFToken:ztouFO8vldho97bWzY9mHQioFk3j6h5V
</code>```

After loading the page I see this error:

```<code>XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/dslam/events.The request was redirected to 'http://127.0.0.1:8000/api/v1/dslam/events/', which is disallowed for cross-origin requests that require preflight.
</code>```

But when i send request from console it will corectly response from django server, my jquery code :

```<code>$.ajax({
            type: 'GET',
            url: "http://5.202.129.160:8020/api/v1/dslam/events/",
            success:function(data){
             console.log(data);
            }
        });
</code>```

request header is:

```<code>Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6,pt;q=0.4
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
</code>```

please help me.

答:
Try this for enabling  cross origin </p>

```<code>https://github.com/ottoyiu/django-cors-headers
</code>```

Body:
I have a Django local sever that refer to 8000 port number, And a local nginx that load 2080 port number html page.

I install django-cross-header package for resolving cross-domain error.

django-cross-header config in settings.py:

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

  CORS_ALLOW_HEADERS = (
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
         'authorization',
         'x-csrftoken'
 )

  CORS_ORIGIN_WHITELIST = (
          '127.0.0.1:2080',
          'localhost:2080'
  )

Config angularjs  is like this:

portman.config(function ($routeProvider, $interpolateProvider, $httpProvider) {
     $routeProvider.otherwise('/');
     $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken;
     $interpolateProvider.startSymbol('{$').endSymbol('$}');
     delete $httpProvider.defaults.headers.common['X-Requested-With'];

 });
 portman.constant('ip','http://127.0.0.1:8000/');

Get method code in angularjs is:

$http({
         method: 'GET',
         url: ip+'api/v1/dslam/events',
     }).then(function (result) {
        $scope.dslam_events = result.data;
     }, function (err) {

    });

request header is :
Provisional headers are shown

Accept:application/json, text/plain, */*
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
X-CSRFToken:ztouFO8vldho97bWzY9mHQioFk3j6h5V

After loading the page I see this error:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/dslam/events.The request was redirected to 'http://127.0.0.1:8000/api/v1/dslam/events/', which is disallowed for cross-origin requests that require preflight.

But when i send request from console it will corectly response from django server, my jquery code :

$.ajax({
            type: 'GET',
            url: "http://5.202.129.160:8020/api/v1/dslam/events/",
            success:function(data){
             console.log(data);
            }
        });

request header is:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6,pt;q=0.4
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36

please help me.

Body:
Try this for enabling  cross origin

https://github.com/ottoyiu/django-cors-headers


答:
What type of date do you have it formatted as? Just because there are various date types.
Is there anyway you can get an AGE rather than a date so it's working with an int rather than a date?

You could potentially make the adjustment in the SELECT statement (instead of select *)

Let's assume DATE which is YYYY-MM-DD (of course it could be date time, etc.)

WHERE date (your_field_name) > (1988-01-19)

Title: How do i display people who are older than a particular person SQL?


问:
how to get the request_id from the below json string in C#
Please help, I'm stuck with this

```<code>using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     Console.WriteLine(result);
}
</code>```

output :

```<code>{
    "request_number":"REQ0010201",
    "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca",
    "sys_id":"35c8ba46db3ffa807ea0f4e9bf9619ca"
}
</code>```

But I want output as only request_id to be printed  : b1c8ba46db3ffa807ea0f4e9bf9619ca

答:
create a class like this:

```<code>public class myresultclass
{
    public string request_number {get;set;}
    public string request_id {get;set;}
    public string sys_id {get;set;}
}
</code>```

then you chango your function so:

```<code>using System.Web.Script.Serialization;
using System.IO;

public string mymethod()
{

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
            var result = streamReader.ReadToEnd();

        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(result)))
        {
            // Deserialization from JSON
            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(myresultclass));
        myresultclass obj = (myresultclass)deserializer.ReadObject(ms);

        }

            Console.WriteLine(result);

        Console.WriteLine(myresultclass.request_id);
    }
}
</code>```

Note: I write this with notepad if doesn't work get me the error :)

Body:
Please help, I'm stuck with this

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     Console.WriteLine(result);
}

output :

{
    "request_number":"REQ0010201",
    "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca",
    "sys_id":"35c8ba46db3ffa807ea0f4e9bf9619ca"
}

But I want output as only request_id to be printed  : b1c8ba46db3ffa807ea0f4e9bf9619ca

Body:
create a class like this:

public class myresultclass
{
    public string request_number {get;set;}
    public string request_id {get;set;}
    public string sys_id {get;set;}
}

then you chango your function so:

using System.Web.Script.Serialization;
using System.IO;

public string mymethod()
{

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
            var result = streamReader.ReadToEnd();

        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(result)))
        {
            // Deserialization from JSON
            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(myresultclass));
        myresultclass obj = (myresultclass)deserializer.ReadObject(ms);

        }

            Console.WriteLine(result);

        Console.WriteLine(myresultclass.request_id);
    }
}

Note: I write this with notepad if doesn't work get me the error :)


问:
How to get particular details based on category using angular 2
I have given below is my json object how to get citydetails where city_id=50?

```<code>{
"status": 0,
"message": "success",
"citydetails": [
  {
        "city_id": "50",
        "city_name": "Pune"

    },
    {
        "city_id": "53",
        "city_name": "Mumbai"

    },
    {
        "city_id": "50",
        "city_name": "Pune"
    },
    {
        "city_id": "52",
        "city_name": "Banglore"

    },
    {
        "city_id": "50",
        "city_name": "Pune"

    }
]
}
</code>```

答:
```<code>let json = {
 "status":0,
 "message":"success",
 "citydetails":[
  {
     "city_id":"50",
     "city_name":"Pune"
  },
  {
     "city_id":"53",
     "city_name":"Mumbai"
  },
  {
     "city_id":"50",
     "city_name":"Pune"
  },
  {
     "city_id":"52",
     "city_name":"Banglore"

  },
  {
     "city_id":"50",
     "city_name":"Pune"
  }]
};
</code>```

Assuming above in your JSON, below code will filter the city objects.

```<code>let filteredCities = json.citydetails.filter(data => {
  return data.city_id === "50";
});
</code>```

filteredCities object will contain only the filtered city objects as an Array

Body:
I have given below is my json object how to get citydetails where city_id=50?

{
"status": 0,
"message": "success",
"citydetails": [
  {
        "city_id": "50",
        "city_name": "Pune"

    },
    {
        "city_id": "53",
        "city_name": "Mumbai"

    },
    {
        "city_id": "50",
        "city_name": "Pune"
    },
    {
        "city_id": "52",
        "city_name": "Banglore"

    },
    {
        "city_id": "50",
        "city_name": "Pune"

    }
]
}

Body:
let json = {
 "status":0,
 "message":"success",
 "citydetails":[
  {
     "city_id":"50",
     "city_name":"Pune"
  },
  {
     "city_id":"53",
     "city_name":"Mumbai"
  },
  {
     "city_id":"50",
     "city_name":"Pune"
  },
  {
     "city_id":"52",
     "city_name":"Banglore"

  },
  {
     "city_id":"50",
     "city_name":"Pune"
  }]
};

Assuming above in your JSON, below code will filter the city objects.

let filteredCities = json.citydetails.filter(data => {
  return data.city_id === "50";
});

filteredCities object will contain only the filtered city objects as an Array


问:
How could I show all the AMI images
I just want to list AMIs that I have or I can use

However, I couldn't find an easy way to do this with aws cli

When I type aws ec2 describe-images --filters Name=image-type,Values=kernel

lots of information that I don't know how they come

Expected results are ami-id, Name, Tag, AMI Name, Owner

答:
You can list your own images by command</p>

```<code>aws ec2 describe-images --owners self
</code>```

Title: How could I show all the AMI images

Body:
You can list your own images by command

aws ec2 describe-images --owners self


问:
Windows Identity Framework on ASP.NET MVC - how to authorize user per action basis?
Windows Identity Framework on ASP.NET MVC - how to authorize user per action basis?

Like:

```<code>    [Authorize]
    public ActionResult About()
    {
        return View();
    }
</code>```

Instead of the whole site level security as is the default WIF site integration behaviour?

UPDATE:
Maybe should the question goes like, how to allow anonymous users to access the site too?

答:
Well as it turns out, authorization element has to be properly set in web.config.

Default is something like:

```<code>    <authorization>
        <deny users="?" />
    </authorization>
</code>```

Which simply mean deny all anonymous users.

But in MVC it should be like:

```<code>    <authorization>
        <!--<deny users="?" />-->
    </authorization>
</code>```

Which mean allow all users, and leave application to handle the authentication.

So that mean default WIF setting have to be reverted:

From:

```<code><authentication mode="None" />
</code>```

To something like:

```<code><authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
</code>```

That so, per action authorization in MVC works. Nice. :)

More on Authorization: http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx

ContentLicense: CC BY-SA 2.5

Body:
Windows Identity Framework on ASP.NET MVC - how to authorize user per action basis?

Like:

    [Authorize]
    public ActionResult About()
    {
        return View();
    }

Instead of the whole site level security as is the default WIF site integration behaviour?

UPDATE:
Maybe should the question goes like, how to allow anonymous users to access the site too?

Body:
Well as it turns out, authorization element has to be properly set in web.config.

Default is something like:

    <authorization>
        <deny users="?" />
    </authorization>

Which simply mean deny all anonymous users.

But in MVC it should be like:

    <authorization>
        <!--<deny users="?" />-->
    </authorization>

Which mean allow all users, and leave application to handle the authentication.

So that mean default WIF setting have to be reverted:

From:

<authentication mode="None" />

To something like:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

That so, per action authorization in MVC works. Nice. :)

More on Authorization: http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx


问:
Other elements does not listening to CustomEvent
This is simplified problem I am facing.

I have a button. When this button is clicked it will dispatch custom event customClick. So I want other DOM elements, like input, to listen for this custom events.

But input does not listen. Only button which dispatch event would listen to customClick.

What I am doing wrong? How can I make input element listen to customClick event?

var button = document.getElementById('customClick');
button.addEventListener('click', function(e){
    var clickedButton = e.currentTarget;
    var newEvent = new CustomEvent("customClick");

    //console.log(newEvent);
    clickedButton.dispatchEvent(newEvent);
})

button.addEventListener('customClick', function(e){

    alert('button listening customClick');
})

var input = document.getElementById('input');
    input.addEventListener('customClick', function(e){

    alert('input listening customClick');
})
   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="customClick">custom click</button>
<input id="input" type="text" /></code>```

答:
With the setup you have, you would need to dispatchEvent to the input, with:

```<code>input.dispatchEvent(newEvent);
</code>```

However, keep in mind any element on the page can be selected within the original click event listener on the button. Meaning you could select all input elements with something like `document.querySelectorAll('input'). This would eliminate the need for dispatching a secondary event.

var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customClick");

button.addEventListener('click', function(e) {
  var clickedButton = e.currentTarget;

  clickedButton.dispatchEvent(newEvent);
  input.dispatchEvent(newEvent);
})

button.addEventListener('customClick', function(e) {
  alert('button listening customClick');
})

input.addEventListener('customClick', function(e) {
  alert('input listening customClick');
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="customClick">custom click</button>
<input id="input" type="text" /></code>```

A better way to handle this, possibly, would be to attach the customClick listener event to the window object instead of the specific input. Like this:

var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customButtonClick");

button.addEventListener('click', function(e) {
  var clickedButton = e.currentTarget;

  window.dispatchEvent(newEvent);

  // Any element on the page can be accessed in here. For example,
  // document.querySelectorAll('input') would select all `input`
  // elements.
})

window.addEventListener('customButtonClick', function(e) {
  alert('button listening customClick');

  // and access the input using `document.getElementById('input')
  // in here. However, you could just access the `input` within
  // the original button `click` event.
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="customClick">custom click</button>
<input id="input" type="text" /></code>```

Body:
This is simplified problem I am facing.

I have a button. When this button is clicked it will dispatch custom event customClick. So I want other DOM elements, like input, to listen for this custom events.

But input does not listen. Only button which dispatch event would listen to customClick.

What I am doing wrong? How can I make input element listen to customClick event?

var button = document.getElementById('customClick');
button.addEventListener('click', function(e){
    var clickedButton = e.currentTarget;
    var newEvent = new CustomEvent("customClick");

    //console.log(newEvent);
    clickedButton.dispatchEvent(newEvent);
})

button.addEventListener('customClick', function(e){

    alert('button listening customClick');
})

var input = document.getElementById('input');
    input.addEventListener('customClick', function(e){

    alert('input listening customClick');
})

<button id="customClick">custom click</button>
<input id="input" type="text" />

Body:
With the setup you have, you would need to dispatchEvent to the input, with:

input.dispatchEvent(newEvent);

However, keep in mind any element on the page can be selected within the original click event listener on the button. Meaning you could select all input elements with something like `document.querySelectorAll('input'). This would eliminate the need for dispatching a secondary event.

var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customClick");

button.addEventListener('click', function(e) {
  var clickedButton = e.currentTarget;

  clickedButton.dispatchEvent(newEvent);
  input.dispatchEvent(newEvent);
})

button.addEventListener('customClick', function(e) {
  alert('button listening customClick');
})

input.addEventListener('customClick', function(e) {
  alert('input listening customClick');
})

<button id="customClick">custom click</button>
<input id="input" type="text" />

A better way to handle this, possibly, would be to attach the customClick listener event to the window object instead of the specific input. Like this:

var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customButtonClick");

button.addEventListener('click', function(e) {
  var clickedButton = e.currentTarget;

  window.dispatchEvent(newEvent);

  // Any element on the page can be accessed in here. For example,
  // document.querySelectorAll('input') would select all `input`
  // elements.
})

window.addEventListener('customButtonClick', function(e) {
  alert('button listening customClick');

  // and access the input using `document.getElementById('input')
  // in here. However, you could just access the `input` within
  // the original button `click` event.
})

<button id="customClick">custom click</button>
<input id="input" type="text" />


答:
You can easy do it via JSON.NET</p>

```<code>using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     var jObject = JObject.Parse(result);
     var value = (string)jObject["request_id"];
     Console.WriteLine(value);
}
</code>```

Title: how to get the request_id from the below json string in C#

Body:
You can easy do it via JSON.NET

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     var jObject = JObject.Parse(result);
     var value = (string)jObject["request_id"];
     Console.WriteLine(value);
}


问:
display calendar when i hover the mouse in text box
I've been looking around for some time now and can't seem to find anything for what I'd like. I want it to be that when you hover over a text box named the month, my PHP calendar will appear. And then provides a manipulation on that calendar. I'm just a beginner and a student who doesn't have enough knowledge to program a system using javascript and jQuery so I suggest you to use PHP language :)
`

```<code>//to read the date today
$currentMonth = date ("m");

//timezone
date_default_timezone_set('Asia/Tokyo');

//Today
$today = date ('Y-m-d',time());

// For H3 Title
$html_title = date('m / Y', $timestamp);

//create prev & next month link  (hour,min,sec,mon,day,day,year

$prev = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)-1, 1, date('Y', $timestamp)));
$next = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)+1, 1, date('Y', $timestamp)));

//Number Of days in the month
$day_count = date('t' , $timestamp);

//0:Sun 1:Mon 2:tue
$str = date('w' , mktime(0, 0, 0, date('m', $timestamp), 1,date('Y',$timestamp)));

//create calendar
$weeks = array();
$week = '';

//add empty cellpadding
$week .= str_repeat('<td></td>', $str);
for ( $day = 1; $day <=$day_count; $day++, $str++) {

$date = $ym.'-'.$day;

if ($today == $date) {
    $week .= '<td class="today">'.$day;
    }
    else{
        $week .= '<td>'. $day;
        }
    $week .= '</td>';

    //end of the week or of the moth
    if ($str % 7 == 6 || $day == $day_count) {

        if($day == $day_count) {
        //add empty cell
        $week .= str_repeat ('<td></td>' , 6 - ($str % 7));
        }

        $weeks[] = '<tr>'.$week.'</tr>';

        //prepare for new week
        $week = '';

}

}

?>
<!DOCTYPE.html>
<html.lang"ja">
<head>
</head>
<body>

<div class="container">
<div id="c2">
<h3><div class="title"><a href="?ym=<?php echo $prev; ?>"><</a><?php echo $html_title; ?><a href="?ym=<?php echo $next; ?>">>  </a></div></h3>
<br>
<table class="table table-bordered" id = "calendar" >
    <tr>
    <th>Sun</th>
    <th>Mon</th>
    <th>Tues</th>
    <th>Wed</th>
    <th>Thur</th>
    <th>Fri</th>
    <th>Sat</th>
    </tr>
    <center>
    <?php
    foreach ($weeks as $week) {
            echo $week;
        }
        ?>
    </center>

</table>
</div>

<div id="booking">
        <center>
        <h1>This is your month</h1>
        <input  id="result" type="text" name="month" value="<?php echo $month ?>" readonly>
        <br>
        <h1>Check In </h1>
        <Input type="number" min="<?php echo $day_today; ?>" max="<?php echo $day_count; ?>" value = "<?php echo $day_today; ?>">
        <br>
        <h1>Adults</h1>
        <input type="number" name="adult" min="1" max="10">
        <br>
        <h1>Kids</h1>
        <input type="number" name="kid" min="1" max="10">
        <br>
        </center>
</div>
</div>
</body>
</html>
</code>```

<p>`</p>

答:
So in this  example JS is triggered with the Keyword focus like:

```<code>`$("#result").focus(function() {
  $(".calendar").addClass("someCss")
});`
</code>```

and adds and removes a CSS class when the user clicks into the field or leaves it. You can do the same thing with $("#result").on("mouseenter", function() the mouseenter in JS like hover in CSS. To make the calendar disappear you would use mouseleave.

When you really want to do it with hover I would suggest to use bootstraps popover function. and display your calendar inside the popover. Hope that helps

Body:
I've been looking around for some time now and can't seem to find anything for what I'd like. I want it to be that when you hover over a text box named the month, my PHP calendar will appear. And then provides a manipulation on that calendar. I'm just a beginner and a student who doesn't have enough knowledge to program a system using javascript and jQuery so I suggest you to use PHP language :)
`

//to read the date today
$currentMonth = date ("m");

//timezone
date_default_timezone_set('Asia/Tokyo');

//Today
$today = date ('Y-m-d',time());

// For H3 Title
$html_title = date('m / Y', $timestamp);

//create prev & next month link  (hour,min,sec,mon,day,day,year

$prev = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)-1, 1, date('Y', $timestamp)));
$next = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)+1, 1, date('Y', $timestamp)));

//Number Of days in the month
$day_count = date('t' , $timestamp);

//0:Sun 1:Mon 2:tue
$str = date('w' , mktime(0, 0, 0, date('m', $timestamp), 1,date('Y',$timestamp)));

//create calendar
$weeks = array();
$week = '';

//add empty cellpadding
$week .= str_repeat('	', $str);
for ( $day = 1; $day <=$day_count; $day++, $str++) {

$date = $ym.'-'.$day;

if ($today == $date) {
    $week .= ''.$day;
    }
    else{
        $week .= ''. $day;
        }
    $week .= '	';

    //end of the week or of the moth
    if ($str % 7 == 6 || $day == $day_count) {

        if($day == $day_count) {
        //add empty cell
        $week .= str_repeat ('	' , 6 - ($str % 7));
        }

        $weeks[] = '
'.$week.'
';

        //prepare for new week
        $week = '';

}

}

?>
<!DOCTYPE.html>

<a href="?ym=<?php echo $prev; ?>"><<?php echo $html_title; ?><a href="?ym=<?php echo $next; ?>">>

    Sun
    Mon
    Tues
    Wed
    Thur
    Fri
    Sat

    <?php
    foreach ($weeks as $week) {
            echo $week;
        }
        ?>

This is your month

        <input  id="result" type="text" name="month" value="<?php echo $month ?>" readonly>

Check In

        <Input type="number" min="<?php echo $day_today; ?>" max="<?php echo $day_count; ?>" value = "<?php echo $day_today; ?>">

Adults

        <input type="number" name="adult" min="1" max="10">

Kids

        <input type="number" name="kid" min="1" max="10">

`

Body:
So in this  example JS is triggered with the Keyword focus like:

`$("#result").focus(function() {
  $(".calendar").addClass("someCss")
});`

and adds and removes a CSS class when the user clicks into the field or leaves it. You can do the same thing with $("#result").on("mouseenter", function() the mouseenter in JS like hover in CSS. To make the calendar disappear you would use mouseleave.

When you really want to do it with hover I would suggest to use bootstraps popover function. and display your calendar inside the popover. Hope that helps


问:
Adding time that totals more than 24 hrs in SQL
I am trying to add time from several rows, and when they add up to more than hours I do not get correct results I am looking for. Would like to script TotalTime to allow more than 24 in HH. Does not have to be a datetime datatype.

StartTime and FinishTime are varchar(8) data types.

here is code and output where TotalTime is less than 24 hours and correct results

```<code>SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/5101*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HP' AND OpCode = 'FC'
GROUP BY DeptCode, OpCode
</code>```

Results are correct

```<code>Codes   TotalTime   Units   UPH   Goal%
HP-FC   12:37:00    47200   3741    73%
</code>```

Here is actual breakdown to prove

```<code>ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2409193 HP-FC   00:21:00    2161    6174    121%    NAME
2507191 HP-FC   00:23:00    2000    5217    102%    NAME
90290   HP-FC   00:20:00    1704    5112    100%    NAME
31676   HP-FC   02:35:00    11234   4349    85%     NAME
2372437 HP-FC   01:50:00    7884    4300    84%     NAME
2378337 HP-FC   07:08:00    22217   3115    61%     NAME
</code>```

So when I attempt this on a larger table with more rows of data this is what I get. Out put will show TotalTime as an incorrect time.

```<code>SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/1552*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HS' AND OpCode = 'HY'
GROUP BY DeptCode, OpCode
</code>```

Results from query are below. This can not be true time.

```<code>Codes   TotalTime   Units   UPH     Goal%
HS-HY   14:07:00    69204   1114    72%
</code>```

Breakdown to show you that TotalTime should be more than 14:07:00

```<code>ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2377    HS-HY   11:25:00    20891   1830    118%    NAME
3476    HS-HY   04:50:00    6978    1444    93%     NAME
43864   HS-HY   12:20:00    17628   1429    92%     NAME
2372127 HS-HY   03:20:00    4748    1424    92%     NAME
2372129 HS-HY   07:00:00    9158    1308    84%     NAME
2422946 HS-HY   00:47:00    949     1211    78%     NAME
21437   HS-HY   06:02:00    6530    1082    70%     NAME
2372090 HS-HY   11:00:00    2322    211     14%     NAME
63448   HS-HY   03:43:00    0       0       0%      NAME
2372061 HS-HY   01:40:00    0       0       0%      NAME
</code>```

答:
For intervals that may exceed 24 hours you will need to concatenate a set of expressions that calculate each piece like so:

```<code>select
    Codes     = (DeptCode + '-' + OpCode)
  , TotalTime = right('0' + convert(varchar(9),(sum(datediff(second,StartTime,FinishTime)) / 3600 )),2) + ':'
              + right('0' + convert(varchar(2),(sum(datediff(second,StartTime,FinishTime)) / 60) % 60 ),2) + ':'
              + right('0' + convert(varchar(2),(sum(datediff(second,StartTime,FinishTime)) % 60 )),2)
  , Units     = sum(Units)
  , UPH       = cast(isnull(sum(Units) / nullif(sum(datediff(minute, StartTime, FinishTime)) * 1.0, 0), 0.0) * 60 as decimal(10, 0))
  , [Goal%]   = (convert(varchar, cast((isnull(sum(Units) / nullif(sum(datediff(minute, StartTime, FinishTime)) * 1.0, 0), 0.0) * 60) / 5101 * 100 as decimal(10, 0))) + '%')
from ptw.dbo.TimeLog
where DeptCode = 'HP'
  and OpCode = 'FC'
group by
    DeptCode
  , OpCode
</code>```

Also, you should not use string literals for aliases, for aliases that do not conform to the rules for regular identifiers, enclose them in square brackets instead of single quotes.

Database Identifiers - docs

Body:
I am trying to add time from several rows, and when they add up to more than hours I do not get correct results I am looking for. Would like to script TotalTime to allow more than 24 in HH. Does not have to be a datetime datatype.

StartTime and FinishTime are varchar(8) data types.

here is code and output where TotalTime is less than 24 hours and correct results

SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/5101*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HP' AND OpCode = 'FC'
GROUP BY DeptCode, OpCode

Results are correct

Codes   TotalTime   Units   UPH   Goal%
HP-FC   12:37:00    47200   3741    73%

Here is actual breakdown to prove

ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2409193 HP-FC   00:21:00    2161    6174    121%    NAME
2507191 HP-FC   00:23:00    2000    5217    102%    NAME
90290   HP-FC   00:20:00    1704    5112    100%    NAME
31676   HP-FC   02:35:00    11234   4349    85%     NAME
2372437 HP-FC   01:50:00    7884    4300    84%     NAME
2378337 HP-FC   07:08:00    22217   3115    61%     NAME

So when I attempt this on a larger table with more rows of data this is what I get. Out put will show TotalTime as an incorrect time.

SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/1552*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HS' AND OpCode = 'HY'
GROUP BY DeptCode, OpCode

Results from query are below. This can not be true time.

Codes   TotalTime   Units   UPH     Goal%
HS-HY   14:07:00    69204   1114    72%

Breakdown to show you that TotalTime should be more than 14:07:00

ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2377    HS-HY   11:25:00    20891   1830    118%    NAME
3476    HS-HY   04:50:00    6978    1444    93%     NAME
43864   HS-HY   12:20:00    17628   1429    92%     NAME
2372127 HS-HY   03:20:00    4748    1424    92%     NAME
2372129 HS-HY   07:00:00    9158    1308    84%     NAME
2422946 HS-HY   00:47:00    949     1211    78%     NAME
21437   HS-HY   06:02:00    6530    1082    70%     NAME
2372090 HS-HY   11:00:00    2322    211     14%     NAME
63448   HS-HY   03:43:00    0       0       0%      NAME
2372061 HS-HY   01:40:00    0       0       0%      NAME

Body:
For intervals that may exceed 24 hours you will need to concatenate a set of expressions that calculate each piece like so:

select
    Codes     = (DeptCode + '-' + OpCode)
  , TotalTime = right('0' + convert(varchar(9),(sum(datediff(second,StartTime,FinishTime)) / 3600 )),2) + ':'
              + right('0' + convert(varchar(2),(sum(datediff(second,StartTime,FinishTime)) / 60) % 60 ),2) + ':'
              + right('0' + convert(varchar(2),(sum(datediff(second,StartTime,FinishTime)) % 60 )),2)
  , Units     = sum(Units)
  , UPH       = cast(isnull(sum(Units) / nullif(sum(datediff(minute, StartTime, FinishTime)) * 1.0, 0), 0.0) * 60 as decimal(10, 0))
  , [Goal%]   = (convert(varchar, cast((isnull(sum(Units) / nullif(sum(datediff(minute, StartTime, FinishTime)) * 1.0, 0), 0.0) * 60) / 5101 * 100 as decimal(10, 0))) + '%')
from ptw.dbo.TimeLog
where DeptCode = 'HP'
  and OpCode = 'FC'
group by
    DeptCode
  , OpCode

Also, you should not use string literals for aliases, for aliases that do not conform to the rules for regular identifiers, enclose them in square brackets instead of single quotes.

Database Identifiers - docs


问:
Android Room Database: How to handle Arraylist in an Entity?
I just implemented Room for offline data saving. But in an Entity class, I am getting the following error:

```<code>Error:(27, 30) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
</code>```

And the class is as following:

```<code>@Entity(tableName = "firstPageData")
public class MainActivityData {

    @PrimaryKey
    private String userId;

    @ColumnInfo(name = "item1_id")
    private String itemOneId;

    @ColumnInfo(name = "item2_id")
    private String itemTwoId;

    // THIS IS CAUSING THE ERROR... BASICALLY IT ISN'T READING ARRAYS
    @ColumnInfo(name = "mylist_array")
    private ArrayList<MyListItems> myListItems;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public ArrayList<MyListItems> getMyListItems() {
        return myListItems;
    }

    public void setCheckListItems(ArrayList<MyListItems> myListItems) {
        this.myListItems = myListItems;
    }

}
</code>```

So basically I want to save the ArrayList in the database but I was not able to find anything relevant to it. Can you guide me regarding how to save an Array using Room?

NOTE: MyListItems Pojo class contains 2 Strings (as of now)

答:
Option #1: Have MyListItems be an @Entity, as MainActivityData is. MyListItems would set up a @ForeignKey back to MainActivityData. In this case, though, MainActivityData cannot have private ArrayList<MyListItems> myListItems, as in Room, entities do not refer to other entities. A view model or similar POJO construct could have a MainActivityData and its associated ArrayList<MyListItems>, though.

Option #2: Set up a pair of @TypeConverter methods to convert ArrayList<MyListItems> to and from some basic type (e.g., a String, such as by using JSON as a storage format). Now, MainActivityData can have its ArrayList<MyListItems> directly. However, there will be no separate table for MyListItems, and so you cannot query on MyListItems very well.

ContentLicense: CC BY-SA 4.0

Body:
I just implemented Room for offline data saving. But in an Entity class, I am getting the following error:

Error:(27, 30) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

And the class is as following:

@Entity(tableName = "firstPageData")
public class MainActivityData {

    @PrimaryKey
    private String userId;

    @ColumnInfo(name = "item1_id")
    private String itemOneId;

    @ColumnInfo(name = "item2_id")
    private String itemTwoId;

    // THIS IS CAUSING THE ERROR... BASICALLY IT ISN'T READING ARRAYS
    @ColumnInfo(name = "mylist_array")
    private ArrayList<MyListItems> myListItems;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public ArrayList<MyListItems> getMyListItems() {
        return myListItems;
    }

    public void setCheckListItems(ArrayList<MyListItems> myListItems) {
        this.myListItems = myListItems;
    }

}

So basically I want to save the ArrayList in the database but I was not able to find anything relevant to it. Can you guide me regarding how to save an Array using Room?

NOTE: MyListItems Pojo class contains 2 Strings (as of now)