问:
Handle C-q with XLookupString
This is a working example of X11 code that handles Ctrl-q event to quit application:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>

void exitOnCondition(char cond, const char *msg, int exitCode, Display *dpy, Window *w, GC *gc) {
    if(cond) {
        printf("%s\n", msg);
        if(dpy && gc) XFreeGC(dpy, *gc);
        if(dpy && w) XDestroyWindow(dpy, *w);
        if(dpy) XCloseDisplay(dpy);
        exit(exitCode);
    }
}

int main(int argc, char **argv) {
      Display *dpy = XOpenDisplay(0);
      exitOnCondition(dpy == 0, "Error: XOpenDisplay failed", -1, dpy, 0, 0);

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));

      Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0,
                     200, 100, 0, blackColor, blackColor);

      //Tell X Server to send MapNotify events
      XSelectInput(dpy, w, StructureNotifyMask | KeyPressMask);

      //Make window appear
      XMapWindow(dpy, w);

      //Graphics Context
      GC gc = XCreateGC(dpy, w, 0, 0);

      //Set white color for drawing
      XSetForeground(dpy, gc, whiteColor);

      //Wait for the MapNotify event
      for(;;) {
        XEvent e;
        XNextEvent(dpy, &e);
        if (e.type == MapNotify) {
          break;
        }
      }

      //Draw the line
      XDrawLine(dpy, w, gc, 10, 60, 180, 20);

      //Send the "DrawLine" request to the server
      XFlush(dpy);

      char text[255];
      XEvent e;
      KeySym key;
      int numKeys = 0;
      for(;;) {
          XNextEvent(dpy, &e);
          if(e.type == KeyPress) {
              //With modifier XLookupString will return garbage(?) in text[0] and key as latin1
              if((numKeys = XLookupString(&e.xkey, text, 255, &key, 0))) {
                  printf("lookup returned:\n");
                  for(int i = 0; i < numKeys; i++) {
                      printf("text[%d]=%x\n", i, text[i]);
                  }

                  if(e.xkey.state == ControlMask && key == XK_q) {
                      exitOnCondition(1, "C-Q pressed", 0, dpy, &w, &gc);
                  }
              }
          }
      }

      XFreeGC(dpy, gc);
      XDestroyWindow(dpy,w);
      XCloseDisplay(dpy);
}
</code>```

Will this code correctly handle Ctrl-q event on any system?

Can I use e.xkey.state to check for Ctrl modifier after XLookupString for any keyboard layout even when Ctrl is rebound to CAPS Lock(or anything else)?

Why does XLookupString return one symbol text[0]==0x11 for Ctrl-q event and not text[0]==CtrlModifierCode text[1]=='q'?

答: XLookupString returns a sequence of ISO-8859-1 characters (at least according to the manual I have; I do not know how up-to-date it is). There is no character code in ISO-8859-1 for the "ctrl" key by itself. Strictly speaking, there isn't one for the ctrl-q combination either, but tradition dictates that ctrl + (A...Z) map to the 1...26 range. </p>

Title: Handle C-q with XLookupString

Body:
This is a working example of X11 code that handles Ctrl-q event to quit application:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>

void exitOnCondition(char cond, const char *msg, int exitCode, Display *dpy, Window *w, GC *gc) {
    if(cond) {
        printf("%s\n", msg);
        if(dpy && gc) XFreeGC(dpy, *gc);
        if(dpy && w) XDestroyWindow(dpy, *w);
        if(dpy) XCloseDisplay(dpy);
        exit(exitCode);
    }
}

int main(int argc, char **argv) {
      Display *dpy = XOpenDisplay(0);
      exitOnCondition(dpy == 0, "Error: XOpenDisplay failed", -1, dpy, 0, 0);

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));

      Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0,
                     200, 100, 0, blackColor, blackColor);

      //Tell X Server to send MapNotify events
      XSelectInput(dpy, w, StructureNotifyMask | KeyPressMask);

      //Make window appear
      XMapWindow(dpy, w);

      //Graphics Context
      GC gc = XCreateGC(dpy, w, 0, 0);

      //Set white color for drawing
      XSetForeground(dpy, gc, whiteColor);

      //Wait for the MapNotify event
      for(;;) {
        XEvent e;
        XNextEvent(dpy, &e);
        if (e.type == MapNotify) {
          break;
        }
      }

      //Draw the line
      XDrawLine(dpy, w, gc, 10, 60, 180, 20);

      //Send the "DrawLine" request to the server
      XFlush(dpy);

      char text[255];
      XEvent e;
      KeySym key;
      int numKeys = 0;
      for(;;) {
          XNextEvent(dpy, &e);
          if(e.type == KeyPress) {
              //With modifier XLookupString will return garbage(?) in text[0] and key as latin1
              if((numKeys = XLookupString(&e.xkey, text, 255, &key, 0))) {
                  printf("lookup returned:\n");
                  for(int i = 0; i < numKeys; i++) {
                      printf("text[%d]=%x\n", i, text[i]);
                  }

                  if(e.xkey.state == ControlMask && key == XK_q) {
                      exitOnCondition(1, "C-Q pressed", 0, dpy, &w, &gc);
                  }
              }
          }
      }

      XFreeGC(dpy, gc);
      XDestroyWindow(dpy,w);
      XCloseDisplay(dpy);
}

Will this code correctly handle Ctrl-q event on any system?

Can I use e.xkey.state to check for Ctrl modifier after XLookupString for any keyboard layout even when Ctrl is rebound to CAPS Lock(or anything else)?

Why does XLookupString return one symbol text[0]==0x11 for Ctrl-q event and not text[0]==CtrlModifierCode text[1]=='q'?


来源: stackexchange

问:
How can I make a Greasemonkey script to auto-download a file?
I go to the page, it has 1 zip file, but I don't know the name, other than its a .zip.

I want Greasemonkey to download this zip automatically, maybe using flashgot or something?

So I need it to activate on page load, then look for *.zip, and add that to downloads automatically.

Any ideas?

答:
This is a code that i have used in greasmonkey to download a zip file from a location provided by url at the @include statement.

```<code>// ==UserScript==
// @name        zipexport
// @namespace   refresh page
// @include     https://control.com/export.php
// @version     1
// @grant       none
// ==/UserScript==

var timerVar= setInterval(function() {DoMeEverySecond (); }, 60000);

function DoMeEverySecond ()
{
  setInterval('window.location.reload()',10000);

 $(document).ready(function()
{

 setTimeout(function(){

document.getElementsByClassName("btn btn-lg btn-primary")[0].click();
}, 1000);});

}
</code>```

To get some idea, please go through this..

```<code>// @include     https://control.com/export.php
</code>```

Use the link of the source page here

```<code>setInterval(function() {DoMeEverySecond (); }, 60000);
</code>```

Helps you to invoke the function DoMeEverySecond (); after 60000ms(60s=1min)

```<code>setInterval('window.location.reload()',10000);
</code>```

Used to reload the page every 10s. It is used by me just to ensure the web page is updated to the latest state(i had a file to download which was updated every hour). You can avoid if this is not needed for you.

```<code>$(document).ready(function()
</code>```

function() will be only called after fully reloading the webpage if we use this statement.

```<code>document.getElementsByClassName("btn btn-lg btn-primary")[0].click();
</code>```

getElementsByClassName/getElementsById etc can be used here based on what can point to the file you wanted to download (Use inspect element by rightclicking in the source page to know if which one of the class/id can point to your zip file).

[0] may help you if you have more than one variable to call under same class.

```<code>click()
</code>```

performs a mouse click in the specified element.(this should help to download the file)

ContentLicense: CC BY-SA 3.0

Body:
This is a code that i have used in greasmonkey to download a zip file from a location provided by url at the @include statement.

// ==UserScript==
// @name        zipexport
// @namespace   refresh page
// @include     https://control.com/export.php
// @version     1
// @grant       none
// ==/UserScript==

var timerVar= setInterval(function() {DoMeEverySecond (); }, 60000);

function DoMeEverySecond ()
{
  setInterval('window.location.reload()',10000);

 $(document).ready(function()
{

 setTimeout(function(){

document.getElementsByClassName("btn btn-lg btn-primary")[0].click();
}, 1000);});

}

To get some idea, please go through this..

// @include     https://control.com/export.php

Use the link of the source page here

setInterval(function() {DoMeEverySecond (); }, 60000);

Helps you to invoke the function DoMeEverySecond (); after 60000ms(60s=1min)

setInterval('window.location.reload()',10000);

Used to reload the page every 10s. It is used by me just to ensure the web page is updated to the latest state(i had a file to download which was updated every hour). You can avoid if this is not needed for you.

$(document).ready(function()

function() will be only called after fully reloading the webpage if we use this statement.

document.getElementsByClassName("btn btn-lg btn-primary")[0].click();

getElementsByClassName/getElementsById etc can be used here based on what can point to the file you wanted to download (Use inspect element by rightclicking in the source page to know if which one of the class/id can point to your zip file).

[0] may help you if you have more than one variable to call under same class.

click()

performs a mouse click in the specified element.(this should help to download the file)


问:
selecting rank from millions of records
I will ask SO for help since I could not find similar situation, questions/post with my question

Assuming I have millions of records, columns are

user_id - assuming its recorded from 1 to 1,000,000

name - assume its also recorded up to 20 characters in alphabet

score - 0 to 100 assuming its also recorded

date - date it was recorded (timestamp)

```<code>user_id |   name   | score |        date       |
------------------------------------------------
23131   |   name1  |   15  | 2017-01-04 02:01:25
26824   |   name2  |   63  | 2017-01-04 02:41:33
19684   |   name3  |   28  | 2017-01-04 02:56:15
74937   |   name4  |   01  | 2017-01-04 04:07:55
27486   |   name5  |   75  | 2017-01-04 13:07:45
86476   |   name6  |   56  | 2017-01-04 14:21:47
36479   |   name7  |   19  | 2017-01-04 17:11:15
86752   |   name8  |   38  | 2017-01-04 18:22:23
11267   |   name9  |  100  | 2017-01-04 20:34:42
88763   |   name10 |   89  | 2017-01-04 22:45:43
</code>```

I want to know my own rank assuming I know what my user_id is

I also want to get other 10 user records above and below my ranking, let's say my rank is 100, I also want to select user with rank of 90 to 99 (above my rank) and 101 to 110 (below my rank).

if different user has same score order rank by date recorded, earlier record has higher rank.

is it possible?

assuming all records are unique and no index are set.

I know how to sort ranking

```<code>SELECT * FROM record order by score
</code>```

but this would let me select all the records, what are the practical way of selecting specific data without selecting every record?

here is what I would like to achieve

```<code>user_id |   name   | score |        date          |     rank     |
------------------------------------------------------------------
12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
11322   |   namee  |   71  | 2017-01-04 22:51:54  |     109      |
86633   |   namew  |   70  | 2017-01-04 22:55:33  |     110      |
</code>```

ok so here is what I got as of now, sorry that I did not mention anything about not using union or union all, I cannot use that in my project.

but anyway here is my query
I used "multi_query()" function

```<code>$sql = "SELECT score, date FROM table_name WHERE user_id=your_user_id;" //assume you already know your user_id
$sql .= "SELECT name, score, date FROM table_name WHERE score >= your_score ORDER BY score, date LIMIT 10;"; //to get 10 rows that have greater or same score of your score order by date, earlier date is higher rank if score is the same with other user.
$sql .= "SELECT name, score, date table_name WHERE score <= your_score DESC, date ASC LIMIT 10"; //select score less than or equal to my score order by score and date
</code>```

and I get something like this

```<code>my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
</code>```

```<code>12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
</code>```

```<code>74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
</code>```

my problem is when using multiple query, it is still the same as doing 3 different query since I have 3 queries, how can I combine it as one? without using union or union all?

and on the 3rd query how can I set my starting point from my data?

答:
Possible way to do it, but there are issues which will need work. This gets the records either side (score wise) of the chosen user, along with the rank of that user. Then orders that by score and calculates the ranking. This does work normally, but will mess up if the chosen user is the top / bottom scorer. Would be possible to sort this, but not sure with real data it will be usable anyway. But will give you some ideas.

This is using user id 86474 as the one you are interested in, and just getting 1 either side - just to suit the test data you have given:-

```<code>SELECT user_id,
        name,
        score,
        date,
        def_rank - (@ranking := @ranking -1) AS rank
FROM
(
    SELECT *
    FROM
    (
        (SELECT r1.user_id,
                r1.name,
                r1.score,
                r1.date,
                sub0.def_rank
        FROM record r1
        INNER JOIN record r2 ON r2.user_id = 86476
        CROSS JOIN
        (
            SELECT COUNT(*) def_rank
            FROM record r1
            INNER JOIN record r2 ON r2.user_id = 86476
            WHERE r1.score >= r2.score
        ) sub0
        WHERE r1.score >= r2.score
        ORDER BY score ASC
        LIMIT 2)
        UNION
        (SELECT r1.user_id,
                r1.name,
                r1.score,
                r1.date,
                sub0.def_rank
        FROM record r1
        INNER JOIN record r2 ON r2.user_id = 86476
        CROSS JOIN
        (
            SELECT COUNT(*) def_rank
            FROM record r1
            INNER JOIN record r2 ON r2.user_id = 86476
            WHERE r1.score >= r2.score
        ) sub0
        WHERE r1.score <= r2.score
        ORDER BY score DESC
        LIMIT 2)
    ) sub97
    ORDER BY score
) sub1
CROSS JOIN
(
    SELECT @ranking := 2
) sub2
</code>```

Title: selecting rank from millions of records

Body:
I will ask SO for help since I could not find similar situation, questions/post with my question

Assuming I have millions of records, columns are

user_id - assuming its recorded from 1 to 1,000,000

name - assume its also recorded up to 20 characters in alphabet

score - 0 to 100 assuming its also recorded

date - date it was recorded (timestamp)

user_id |   name   | score |        date       |
------------------------------------------------
23131   |   name1  |   15  | 2017-01-04 02:01:25
26824   |   name2  |   63  | 2017-01-04 02:41:33
19684   |   name3  |   28  | 2017-01-04 02:56:15
74937   |   name4  |   01  | 2017-01-04 04:07:55
27486   |   name5  |   75  | 2017-01-04 13:07:45
86476   |   name6  |   56  | 2017-01-04 14:21:47
36479   |   name7  |   19  | 2017-01-04 17:11:15
86752   |   name8  |   38  | 2017-01-04 18:22:23
11267   |   name9  |  100  | 2017-01-04 20:34:42
88763   |   name10 |   89  | 2017-01-04 22:45:43

I want to know my own rank assuming I know what my user_id is

I also want to get other 10 user records above and below my ranking, let's say my rank is 100, I also want to select user with rank of 90 to 99 (above my rank) and 101 to 110 (below my rank).

if different user has same score order rank by date recorded, earlier record has higher rank.

is it possible?

assuming all records are unique and no index are set.

I know how to sort ranking

SELECT * FROM record order by score

but this would let me select all the records, what are the practical way of selecting specific data without selecting every record?

here is what I would like to achieve

user_id |   name   | score |        date          |     rank     |
------------------------------------------------------------------
12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |
11322   |   namee  |   71  | 2017-01-04 22:51:54  |     109      |
86633   |   namew  |   70  | 2017-01-04 22:55:33  |     110      |

ok so here is what I got as of now, sorry that I did not mention anything about not using union or union all, I cannot use that in my project.

but anyway here is my query
I used "multi_query()" function

$sql = "SELECT score, date FROM table_name WHERE user_id=your_user_id;" //assume you already know your user_id
$sql .= "SELECT name, score, date FROM table_name WHERE score >= your_score ORDER BY score, date LIMIT 10;"; //to get 10 rows that have greater or same score of your score order by date, earlier date is higher rank if score is the same with other user.
$sql .= "SELECT name, score, date table_name WHERE score <= your_score DESC, date ASC LIMIT 10"; //select score less than or equal to my score order by score and date

and I get something like this

my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |

12341   |   namep  |   90  | 2017-01-01 04:02:36  |      90      |
45341   |   nameo  |   88  | 2017-01-02 00:05:45  |      91      |
24341   |   namex  |   88  | 2017-01-03 00:11:15  |      92      |
26867   |   namec  |   83  | 2017-01-03 01:41:23  |      93      |
19156   |   nameb  |   81  | 2017-01-03 02:36:45  |      94      |
74973   |   namem  |   79  | 2017-01-03 04:07:55  |      95      |
23134   |   namek  |   78  | 2017-01-04 02:01:25  |      96      |
21424   |   namet  |   77  | 2017-01-04 02:41:33  |      97      |
19534   |   nameg  |   77  | 2017-01-04 02:56:15  |      98      |
74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |

74912   |   namez  |   75  | 2017-01-04 04:07:55  |      99      |
my_uid  |  my_name |   75  | 2017-01-04 13:07:45  |     100      |
86766   |   namen  |   75  | 2017-01-04 14:21:47  |     101      |
67976   |   namey  |   74  | 2017-01-04 16:22:23  |     102      |
34676   |   nameu  |   74  | 2017-01-04 17:33:32  |     103      |
86236   |   namei  |   73  | 2017-01-04 18:11:09  |     104      |
98636   |   nameo  |   73  | 2017-01-04 19:21:47  |     105      |
14326   |   namep  |   73  | 2017-01-04 20:33:22  |     106      |
45333   |   namet  |   72  | 2017-01-04 20:44:12  |     107      |
33323   |   namer  |   72  | 2017-01-04 21:34:26  |     108      |

my problem is when using multiple query, it is still the same as doing 3 different query since I have 3 queries, how can I combine it as one? without using union or union all?

and on the 3rd query how can I set my starting point from my data?

Body:
Possible way to do it, but there are issues which will need work. This gets the records either side (score wise) of the chosen user, along with the rank of that user. Then orders that by score and calculates the ranking. This does work normally, but will mess up if the chosen user is the top / bottom scorer. Would be possible to sort this, but not sure with real data it will be usable anyway. But will give you some ideas.

This is using user id 86474 as the one you are interested in, and just getting 1 either side - just to suit the test data you have given:-

SELECT user_id,
        name,
        score,
        date,
        def_rank - (@ranking := @ranking -1) AS rank
FROM
(
    SELECT *
    FROM
    (
        (SELECT r1.user_id,
                r1.name,
                r1.score,
                r1.date,
                sub0.def_rank
        FROM record r1
        INNER JOIN record r2 ON r2.user_id = 86476
        CROSS JOIN
        (
            SELECT COUNT(*) def_rank
            FROM record r1
            INNER JOIN record r2 ON r2.user_id = 86476
            WHERE r1.score >= r2.score
        ) sub0
        WHERE r1.score >= r2.score
        ORDER BY score ASC
        LIMIT 2)
        UNION
        (SELECT r1.user_id,
                r1.name,
                r1.score,
                r1.date,
                sub0.def_rank
        FROM record r1
        INNER JOIN record r2 ON r2.user_id = 86476
        CROSS JOIN
        (
            SELECT COUNT(*) def_rank
            FROM record r1
            INNER JOIN record r2 ON r2.user_id = 86476
            WHERE r1.score >= r2.score
        ) sub0
        WHERE r1.score <= r2.score
        ORDER BY score DESC
        LIMIT 2)
    ) sub97
    ORDER BY score
) sub1
CROSS JOIN
(
    SELECT @ranking := 2
) sub2


问:
SQL Data Filtering approach
I have a stored procedure that receives 3 parameters that are used to dynamically filter the result set

```<code>create proc MyProc
@Parameter1 int,
@Parameter2 int,
@Paremeter3 int
as
select * from My_table
where
1 = case when @Parameter1 = 0 then 1 when @Parameter1 = Column1 then 1 else 0 end
and
1 = case when @Parameter2 = 0 then 1 when @Parameter2 = Column2 then 1 else 0 end
and
1 = case when @Parameter3 = 0 then 1 when @Parameter3 = Column3 then 1 else 0 end
return
</code>```

The values passed for each parameter can be 0 (for all items) or non-zero for items matching on specific column.

I may have upwards of 20 parameters (example shown only has 3).  Is there a more elegant approach to allow this to scale when the database gets large?

答: Unfortunately dynamic SQL is the best solution performance/stability wise. While all the other methods commonly used ( @param is not or Col = @param, COALESCE, CASE... ) work, they are unpredictable and unreliable, execution plan can (and will) vary for each execution and you may find yourself spending lots of hours trying to figure out, why your query performs really bad when it was working fine yesterday.

ContentLicense: CC BY-SA 2.5

Title: SQL Data Filtering approach

Body:
I have a stored procedure that receives 3 parameters that are used to dynamically filter the result set

create proc MyProc
@Parameter1 int,
@Parameter2 int,
@Paremeter3 int
as
select * from My_table
where
1 = case when @Parameter1 = 0 then 1 when @Parameter1 = Column1 then 1 else 0 end
and
1 = case when @Parameter2 = 0 then 1 when @Parameter2 = Column2 then 1 else 0 end
and
1 = case when @Parameter3 = 0 then 1 when @Parameter3 = Column3 then 1 else 0 end
return

The values passed for each parameter can be 0 (for all items) or non-zero for items matching on specific column.

I may have upwards of 20 parameters (example shown only has 3).  Is there a more elegant approach to allow this to scale when the database gets large?


问:
Picking date from id element in a form
I'm trying to pick a date from an id with this code. Actually I'm able to get correct data only if I manually declare it the date, so I guess that mistake is in document.getElementById('fromDate').value;

```<code><input id="fromDate" type="date">
<input id="toDate" type="date">

<button type="button" onclick="loadDoc()">Invia richiesta</button>

<p id="stampain"></p>
<p id="stampafi"></p>
<p id="stampali"></p>

 <script>

    // Define the data start
    var datastart = document.getElementById('fromDate').value; // doesn't pick data
    // var datastart = '30/03/2017'; // manually
    var datastart1 = datastart.split('/').reverse().join('-');
    var ds = new Date(datastart1);
    var start_dt = ds.toISOString().substring(0,10);

    // Define the data start
    var dataend = document.getElementById('toDate').value; // doesn't pick data
    // var dataend = '30/03/2017'; // manually
    var dataend1 = dataend.split('/').reverse().join('-');
    var de = new Date(dataend1);
    var end_dt = de.toISOString().substring(0,10);

    var CALENDAR_ID = 'my-id';
    var TOKEN = 'my-token';

    function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById('print').innerHTML = this.responseText;
        }
      };
          xhttp.open('GET', 'https://api.teamup.com/'+CALENDAR_ID+'/events?_teamup_token='+TOKEN+'&startDate='+start_dt+'&endDate='+end_dt, true);
      xhttp.send();

    var e = document.getElementById('stampain').innerHTML = start_dt;
    var f = document.getElementById('stampafi').innerHTML = end_dt;

    }
    </script>
</code>```

But output is undefined, ofcourse i'm missing something! Any solution?

答:
Apply the variable declaration inside the loadDoc() function.If declare as global .Its load on document load.At the time the value are not set.so there is undefined after button click.

function loadDoc() {
// Define the data start
var datastart = document.getElementById('fromDate').value; // doesn't pick data
console.log(datastart)
// var datastart = '30/03/2017'; // manually
var datastart1 = datastart.split('/').reverse().join('-');
var ds = new Date(datastart1);
var start_dt = ds.toISOString().substring(0, 10);

// Define the data start
var dataend = document.getElementById('toDate').value; // doesn't pick data
// var dataend = '30/03/2017'; // manually
var dataend1 = dataend.split('/').reverse().join('-');
var de = new Date(dataend1);
var end_dt = de.toISOString().substring(0, 10);

var CALENDAR_ID = 'my-id';
var TOKEN = 'my-token';

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById('print').innerHTML = this.responseText;
    }
  };
  xhttp.open('GET', 'https://api.teamup.com/' + CALENDAR_ID + '/events?_teamup_token=' + TOKEN + '&startDate=' + start_dt + '&endDate=' + end_dt, true);
  xhttp.send();

  var e = document.getElementById('stampain').innerHTML = start_dt;
  var f = document.getElementById('stampafi').innerHTML = end_dt;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="fromDate" type="date">
<input id="toDate" type="date">

<button type="button" onclick="loadDoc()">Invia richiesta</button>

<p id="stampain"></p>
<p id="stampafi"></p>
<p id="stampali"></p></code>```

Title: Picking date from id element in a form

Body:
I'm trying to pick a date from an id with this code. Actually I'm able to get correct data only if I manually declare it the date, so I guess that mistake is in document.getElementById('fromDate').value;

<input id="fromDate" type="date">
<input id="toDate" type="date">

<button type="button" onclick="loadDoc()">Invia richiesta</button>

But output is undefined, ofcourse i'm missing something! Any solution?

Body:
Apply the variable declaration inside the loadDoc() function.If declare as global .Its load on document load.At the time the value are not set.so there is undefined after button click.

function loadDoc() {
// Define the data start
var datastart = document.getElementById('fromDate').value; // doesn't pick data
console.log(datastart)
// var datastart = '30/03/2017'; // manually
var datastart1 = datastart.split('/').reverse().join('-');
var ds = new Date(datastart1);
var start_dt = ds.toISOString().substring(0, 10);

// Define the data start
var dataend = document.getElementById('toDate').value; // doesn't pick data
// var dataend = '30/03/2017'; // manually
var dataend1 = dataend.split('/').reverse().join('-');
var de = new Date(dataend1);
var end_dt = de.toISOString().substring(0, 10);

var CALENDAR_ID = 'my-id';
var TOKEN = 'my-token';

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById('print').innerHTML = this.responseText;
    }
  };
  xhttp.open('GET', 'https://api.teamup.com/' + CALENDAR_ID + '/events?_teamup_token=' + TOKEN + '&startDate=' + start_dt + '&endDate=' + end_dt, true);
  xhttp.send();

  var e = document.getElementById('stampain').innerHTML = start_dt;
  var f = document.getElementById('stampafi').innerHTML = end_dt;

}

<input id="fromDate" type="date">
<input id="toDate" type="date">

<button type="button" onclick="loadDoc()">Invia richiesta</button>

<p id="stampain"></p>
<p id="stampafi"></p>
<p id="stampali"></p>


问:
Alternative of List Within List?
It is recommended Everywhere that List Within List shouldnot be used but i have to use same as List Within list.Is there any way that would work same as list within list.I have watched Expandable ListView and this but not able to solve my issue.my requirement Look like

```<code>  **ListView**
         **TextView**
         **TextView**
         **ListView**(i have used Linear layout in here)
</code>```

In my Layout i have placed Linear Layout in the Place of inner listView.Inner ListView(Linear Layout in my case) is only setting one JSON Data in the innerView.I want to display that same as outer ListView in Inner.How can this be possible?
fragment_fee

```<code><LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <LinearLayout
                    android:id="@+id/linear_receipt1_fee"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#008b8b"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/student_profile_fee_ReceiptIssuedDate"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="6dp"
                        android:text="Date"
                        android:textColor="#fff"
                        android:textStyle="bold" />

                    <View
                        android:layout_width="1dp"
                        android:layout_height="match_parent"
                        android:background="#FFFFFF" />

                    <TextView
                        android:id="@+id/student_profile_fee_ReceiptIssuedNumber"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="6dp"
                        android:text="Receipt number"
                        android:textColor="#fff"
                        android:textStyle="bold" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/receipt1_fee"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#A4ACB0"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:gravity="center_horizontal"
                            android:padding="5dp"
                            android:text="Description"
                            android:textSize="12dp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:gravity="center_horizontal"
                            android:padding="5dp"
                            android:text="Amount (Nrs) "
                            android:textSize="12dp"
                            android:textStyle="bold">

                        </TextView>

                    </LinearLayout>

////this is the replacement of ListView in Inner
                    <LinearLayout
                        android:id="@+id/student_profile_fee_linearlayout1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                       <TextView
                            android:id="@+id/student_profile_fee_description"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:gravity="left|center"
                            android:paddingLeft="70dp"
                            android:paddingTop="10dp"
                            android:text="Sports"
                            android:textSize="10dp" />

                        <TextView
                            android:id="@+id/student_profile_fee_amount"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:gravity="left|center"
                            android:paddingLeft="70dp"
                            android:paddingTop="10dp"
                            android:text="1000"
                            android:textSize="10dp" />

                    </LinearLayout>
  <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="#C5CED1" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#DCE2E8"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Total"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="552"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="#C5CED1" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#DCE2E8"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Status"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/student_profile_fee_status"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Paid"
                            android:textColor="#108B89"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="#C5CED1" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#DCE2E8"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Received Date"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/student_profile_fee_FeeReceiptDate"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="9 March,2017"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                    </LinearLayout>
                </LinearLayout>

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#fff" />

        </LinearLayout>
</LinearLayout>
</code>```

student_fees_listview

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2E353D"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="30dp"
                android:layout_height="match_parent"
                android:padding="3dp"
                android:src="@mipmap/fee" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="8dp"
                android:text="Fees"
                android:textColor="#fff"
                android:textSize="17dp"
                android:textStyle="bold" />

        </LinearLayout>
    </LinearLayout>

    <ListView
        android:id="@+id/list_student_fees"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

</LinearLayout>
</code>```

CustomFeeListStudentAdapter

```<code>public class CustomFeeListStudentAdapter extends BaseAdapter {

    LinearLayout receipt1, receipt2, receipt3, receipt4;
    LinearLayout receipt1detail, receipt2detail, receipt3detail, receipt4detail;

    Context mContext;

    ArrayList<StudentFeeInformation> student_list;
    String TAG = "HomeTab_adapter";

    public CustomFeeListStudentAdapter(Context mContext, ArrayList<StudentFeeInformation> student_list) {
        super();
        this.mContext = mContext;
        this.student_list = student_list;
    }

    @Override
    public int getCount() {
        return student_list.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(final int postion, View convertView, ViewGroup parent) {
        final Holder viewHolder;
        if (convertView == null) {
            // inflate the layout
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.fragment_fee, parent, false);

            // well set up the ViewHolder
            viewHolder = new Holder();
            viewHolder.student_profile_fee_status = (TextView) convertView.findViewById(R.id.student_profile_fee_status);
            viewHolder.student_profile_ReceiptIssuedDate = (TextView) convertView.findViewById(R.id.student_profile_fee_ReceiptIssuedDate);
            viewHolder.student_profile_ReceiptIssuedNumber = (TextView) convertView.findViewById(R.id.student_profile_fee_ReceiptIssuedNumber);
            viewHolder.student_profile_FeeReceivedDate = (TextView) convertView.findViewById(R.id.student_profile_fee_FeeReceiptDate);
            viewHolder.student_profile_Fee_Amount = (TextView) convertView.findViewById(R.id.student_profile_fee_amount);
            viewHolder.student_profile_Fee_Description = (TextView) convertView.findViewById(R.id.student_profile_fee_description);

        } else {
            // we've just avoided calling findViewById() on resource everytime
            // just use the viewHolder
            viewHolder = (Holder) convertView.getTag();
        }

        viewHolder.student_profile_fee_status.setText(student_list.get(postion).getStatus());
        viewHolder.student_profile_ReceiptIssuedDate.setText(student_list.get(postion).getReceiptIssuedDate());
        viewHolder.student_profile_ReceiptIssuedNumber.setText(student_list.get(postion).getReceiptIssuedNumber());
        viewHolder.student_profile_FeeReceivedDate.setText(student_list.get(postion).getFeeReceivedDate());

        viewHolder.student_profile_Fee_Amount.setText(student_list.get(postion).getAmount());

        viewHolder.student_profile_Fee_Description.setText(student_list.get(postion).getFeeDescription());

        convertView.setTag(viewHolder);
        return convertView;
    }

    class Holder {
        TextView student_profile_fee_status;
        TextView student_profile_ReceiptIssuedDate;
        TextView student_profile_ReceiptIssuedNumber;
        TextView student_profile_FeeReceivedDate;
        TextView student_profile_Fee_Amount;
        TextView student_profile_Fee_Description;

    }
}
</code>```

Fee

```<code>public class Fee extends Fragment /*implements View.OnClickListener   */ {

    LinearLayout receipt1, receipt2, receipt3, receipt4;
    LinearLayout receipt1detail, receipt2detail, receipt3detail, receipt4detail;
    LinearLayout DescriptionAmount;

    TextView statustextView;
    ListView listViewfees, listviewfeedetail;
    List<StudentFeeInformation> yourData = new ArrayList<StudentFeeInformation>();

    public static final String Navigation_URL = "http://192.168.100.5:84/Api/financeApi/getAllFees";
    String Amount;
    String Descriptionlist, status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate;
    String master_id;

    LinearLayout linearLayout;

    //   View view1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.student_fees_listview, container, false);
        inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //    view1 = inflater.inflate(R.layout.student_fees_description_data, null);
        //    linearLayout = (LinearLayout) view1.findViewById(R.id.student_profile_fee_linearlayout1);

        // view1 = inflater.inflate(R.layout.student_fees_description_data, container, false);

        setHasOptionsMenu(true);
        receipt1 = (LinearLayout) view.findViewById(R.id.linear_receipt1_fee);

        //  receipt4 = (LinearLayout) view.findViewById(R.id.linear_receipt4_fee);

        //  receipt1detail = (LinearLayout) view.findViewById(R.id.receipt1_fee);
        //  receipt2detail = (LinearLayout) view.findViewById(R.id.receipt2_fee);
        //  receipt3detail = (LinearLayout) view.findViewById(R.id.receipt3_fee);
        //  receipt4detail = (LinearLayout) view.findViewById(R.id.receipt4_fee);

        //   receipt1.setOnClickListener(this);
        //   receipt2.setOnClickListener(this);
        //   receipt3.setOnClickListener(this);
        //   receipt4.setOnClickListener(this);

        //   receipt1detail.setVisibility(View.VISIBLE);
        //   receipt2detail.setVisibility(View.GONE);
        //   receipt3detail.setVisibility(View.GONE);
        //   receipt4detail.setVisibility(View.GONE);

        statustextView = (TextView) view.findViewById(R.id.student_profile_fee_status);
        SessionManagement sessionManagement = new SessionManagement(getContext());
        master_id = sessionManagement.getMasterId();
        listViewfees = (ListView) view.findViewById(R.id.list_student_fees);
        // listviewfeedetail = (ListView) view.findViewById(R.id.listtest);

        //  DescriptionAmount = (LinearLayout) view.findViewById(R.id.student_profile_fee_linearlayout1);
        // DescriptionAmount.addView(view);

        getUsersListData();

        return view;
    }

    private void getUsersListData() {

        String URL = Navigation_URL + "?id=" + master_id;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            ArrayList<StudentFeeInformation> student_list = new ArrayList<>();
                            ArrayList<FeeDescriptionStudent> student_list_description = new ArrayList<>();

                            JSONArray jArray = new JSONArray(response);
                            //  studentFeeInformation = new StudentFeeInformation(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);

                                status = jsonObject.getString("Status");
                                DateofReceiptIssued = jsonObject.getString("DateOfReciept").substring(0, 10);
                                ReceiptNumber = jsonObject.getString("RecieptNo");
                                FeeReceivedDate = jsonObject.getString("recivedDate").substring(0, 10);

                                String Description = jsonObject.getString("Description");
                                JSONArray jArray1 = new JSONArray(Description);

                                for (int j = 0; j < jArray1.length(); j++) {

                                    JSONObject jsonObjectinner = jArray1.getJSONObject(j);
                                    Descriptionlist = jsonObjectinner.getString("des");
                                    Amount = jsonObjectinner.getString("Amount");

                                    //  TextView txtQuestion = (TextView) view1.findViewById(R.id.student_profile_fee_description);
                                    //  TextView tx = (TextView) view1.findViewById(R.id.student_profile_fee_amount);

                                    //  System.out.println(txtQuestion);
                                    //  System.out.println(tx);

                                    //  txtQuestion.setText(Descriptionlist);
                                    //  tx.setText(Amount);
                                    // linearLayout.addView(view1);

                                    Descriptionlist = jsonObjectinner.getString("des");
                                    Amount = jsonObjectinner.getString("Amount");

                                }

                                student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate, Descriptionlist, Amount));
                                //student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate));

                            }

                            System.out.println("student_list size:" + student_list.size());
                            CustomFeeListStudentAdapter customFeeListStudentAdapter = new CustomFeeListStudentAdapter(getActivity(), student_list);
                            listViewfees.setAdapter(customFeeListStudentAdapter);

                        } catch (JSONException e) {

                            System.out.println("This is not good");

                            e.printStackTrace();

                        }

                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // Toast.makeText(view.Fee.this, error.toString(), Toast.LENGTH_LONG).show();

            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                return headers;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
</code>```

I have watched many example of ExpandableListView as well as TableView
  but cannot be able to show item as listView.I have used Linear layout
  in place of ListView but only one JSON data is Displayed.Where is
  error i am not able to get it.

logcat

```<code>03-29 16:52:20.023 1558-1569/system_process I/WindowManager: Destroying surface Surface(name=com.example.user.mis/com.example.user.mis.activity.Login) called by com.android.server.wm.WindowStateAnimator.destroySurface:2014 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:881 com.android.server.wm.WindowState.destroyOrSaveSurface:2073 com.android.server.wm.AppWindowToken.destroySurfaces:363 com.android.server.wm.AppWindowToken.notifyAppStopped:389 com.android.server.wm.WindowManagerService.notifyAppStopped:4456 com.android.server.am.ActivityStack.activityStoppedLocked:1252 com.android.server.am.ActivityManagerService.activityStopped:6895
03-29 16:52:22.656 11984-11984/com.example.user.mis I/System.out: student_list size:3
03-29 16:52:22.656 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.656 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.672 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.672 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.676 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:0 getTeacherNameLate Charge
03-29 16:52:22.677 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:1 getTeacherNameMonthly Fee
03-29 16:52:22.678 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:2 getTeacherNameExtra Charge
03-29 16:52:22.678 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.679 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:0 getTeacherNameLate Charge
03-29 16:52:22.682 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:1 getTeacherNameMonthly Fee
03-29 16:52:22.684 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:2 getTeacherNameExtra Charge
03-29 16:52:23.039 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:23.039 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:23.041 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:0 getTeacherNameLate Charge
03-29 16:52:23.042 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:1 getTeacherNameMonthly Fee
03-29 16:52:23.042 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:2 getTeacherNameExtra Charge
03-29 16:52:23.042 11984-11984/com.example.user.mis I/System.out: 3
</code>```

答:
You can use expandable recycler view as explained in Expandable Recycler view

All you need to do is define child for parents 1 and 6. For other positions you can simply treat them as parent with no child.

You need to define proper model class and pass the data in model.

Title: Alternative of List Within List?

Body:
It is recommended Everywhere that List Within List shouldnot be used but i have to use same as List Within list.Is there any way that would work same as list within list.I have watched Expandable ListView and this but not able to solve my issue.my requirement Look like

  **ListView**
         **TextView**
         **TextView**
         **ListView**(i have used Linear layout in here)

In my Layout i have placed Linear Layout in the Place of inner listView.Inner ListView(Linear Layout in my case) is only setting one JSON Data in the innerView.I want to display that same as outer ListView in Inner.How can this be possible?
fragment_fee

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <LinearLayout
                    android:id="@+id/linear_receipt1_fee"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#008b8b"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/student_profile_fee_ReceiptIssuedDate"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="6dp"
                        android:text="Date"
                        android:textColor="#fff"
                        android:textStyle="bold" />

                    <View
                        android:layout_width="1dp"
                        android:layout_height="match_parent"
                        android:background="#FFFFFF" />

                    <TextView
                        android:id="@+id/student_profile_fee_ReceiptIssuedNumber"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="6dp"
                        android:text="Receipt number"
                        android:textColor="#fff"
                        android:textStyle="bold" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/receipt1_fee"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#A4ACB0"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:gravity="center_horizontal"
                            android:padding="5dp"
                            android:text="Description"
                            android:textSize="12dp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:gravity="center_horizontal"
                            android:padding="5dp"
                            android:text="Amount (Nrs) "
                            android:textSize="12dp"
                            android:textStyle="bold">

                        </TextView>

                    </LinearLayout>

////this is the replacement of ListView in Inner
                    <LinearLayout
                        android:id="@+id/student_profile_fee_linearlayout1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                       <TextView
                            android:id="@+id/student_profile_fee_description"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:gravity="left|center"
                            android:paddingLeft="70dp"
                            android:paddingTop="10dp"
                            android:text="Sports"
                            android:textSize="10dp" />

                        <TextView
                            android:id="@+id/student_profile_fee_amount"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:gravity="left|center"
                            android:paddingLeft="70dp"
                            android:paddingTop="10dp"
                            android:text="1000"
                            android:textSize="10dp" />

                    </LinearLayout>
  <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="#C5CED1" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#DCE2E8"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Total"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="552"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="#C5CED1" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#DCE2E8"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Status"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/student_profile_fee_status"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Paid"
                            android:textColor="#108B89"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="#C5CED1" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#DCE2E8"
                        android:orientation="horizontal"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="Received Date"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/student_profile_fee_FeeReceiptDate"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:paddingLeft="70dp"
                            android:text="9 March,2017"
                            android:textSize="10dp"
                            android:textStyle="bold" />

                    </LinearLayout>
                </LinearLayout>

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#fff" />

        </LinearLayout>
</LinearLayout>

student_fees_listview

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2E353D"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="30dp"
                android:layout_height="match_parent"
                android:padding="3dp"
                android:src="@mipmap/fee" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="8dp"
                android:text="Fees"
                android:textColor="#fff"
                android:textSize="17dp"
                android:textStyle="bold" />

        </LinearLayout>
    </LinearLayout>

    <ListView
        android:id="@+id/list_student_fees"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

</LinearLayout>

CustomFeeListStudentAdapter

public class CustomFeeListStudentAdapter extends BaseAdapter {

    LinearLayout receipt1, receipt2, receipt3, receipt4;
    LinearLayout receipt1detail, receipt2detail, receipt3detail, receipt4detail;

    Context mContext;

    ArrayList<StudentFeeInformation> student_list;
    String TAG = "HomeTab_adapter";

    public CustomFeeListStudentAdapter(Context mContext, ArrayList<StudentFeeInformation> student_list) {
        super();
        this.mContext = mContext;
        this.student_list = student_list;
    }

    @Override
    public int getCount() {
        return student_list.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(final int postion, View convertView, ViewGroup parent) {
        final Holder viewHolder;
        if (convertView == null) {
            // inflate the layout
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.fragment_fee, parent, false);

            // well set up the ViewHolder
            viewHolder = new Holder();
            viewHolder.student_profile_fee_status = (TextView) convertView.findViewById(R.id.student_profile_fee_status);
            viewHolder.student_profile_ReceiptIssuedDate = (TextView) convertView.findViewById(R.id.student_profile_fee_ReceiptIssuedDate);
            viewHolder.student_profile_ReceiptIssuedNumber = (TextView) convertView.findViewById(R.id.student_profile_fee_ReceiptIssuedNumber);
            viewHolder.student_profile_FeeReceivedDate = (TextView) convertView.findViewById(R.id.student_profile_fee_FeeReceiptDate);
            viewHolder.student_profile_Fee_Amount = (TextView) convertView.findViewById(R.id.student_profile_fee_amount);
            viewHolder.student_profile_Fee_Description = (TextView) convertView.findViewById(R.id.student_profile_fee_description);

        } else {
            // we've just avoided calling findViewById() on resource everytime
            // just use the viewHolder
            viewHolder = (Holder) convertView.getTag();
        }

        viewHolder.student_profile_fee_status.setText(student_list.get(postion).getStatus());
        viewHolder.student_profile_ReceiptIssuedDate.setText(student_list.get(postion).getReceiptIssuedDate());
        viewHolder.student_profile_ReceiptIssuedNumber.setText(student_list.get(postion).getReceiptIssuedNumber());
        viewHolder.student_profile_FeeReceivedDate.setText(student_list.get(postion).getFeeReceivedDate());

        viewHolder.student_profile_Fee_Amount.setText(student_list.get(postion).getAmount());

        viewHolder.student_profile_Fee_Description.setText(student_list.get(postion).getFeeDescription());

        convertView.setTag(viewHolder);
        return convertView;
    }

    class Holder {
        TextView student_profile_fee_status;
        TextView student_profile_ReceiptIssuedDate;
        TextView student_profile_ReceiptIssuedNumber;
        TextView student_profile_FeeReceivedDate;
        TextView student_profile_Fee_Amount;
        TextView student_profile_Fee_Description;

    }
}

Fee

public class Fee extends Fragment /*implements View.OnClickListener   */ {

    LinearLayout receipt1, receipt2, receipt3, receipt4;
    LinearLayout receipt1detail, receipt2detail, receipt3detail, receipt4detail;
    LinearLayout DescriptionAmount;

    TextView statustextView;
    ListView listViewfees, listviewfeedetail;
    List<StudentFeeInformation> yourData = new ArrayList<StudentFeeInformation>();

    public static final String Navigation_URL = "http://192.168.100.5:84/Api/financeApi/getAllFees";
    String Amount;
    String Descriptionlist, status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate;
    String master_id;

    LinearLayout linearLayout;

    //   View view1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.student_fees_listview, container, false);
        inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //    view1 = inflater.inflate(R.layout.student_fees_description_data, null);
        //    linearLayout = (LinearLayout) view1.findViewById(R.id.student_profile_fee_linearlayout1);

        // view1 = inflater.inflate(R.layout.student_fees_description_data, container, false);

        setHasOptionsMenu(true);
        receipt1 = (LinearLayout) view.findViewById(R.id.linear_receipt1_fee);

        //  receipt4 = (LinearLayout) view.findViewById(R.id.linear_receipt4_fee);

        //  receipt1detail = (LinearLayout) view.findViewById(R.id.receipt1_fee);
        //  receipt2detail = (LinearLayout) view.findViewById(R.id.receipt2_fee);
        //  receipt3detail = (LinearLayout) view.findViewById(R.id.receipt3_fee);
        //  receipt4detail = (LinearLayout) view.findViewById(R.id.receipt4_fee);

        //   receipt1.setOnClickListener(this);
        //   receipt2.setOnClickListener(this);
        //   receipt3.setOnClickListener(this);
        //   receipt4.setOnClickListener(this);

        //   receipt1detail.setVisibility(View.VISIBLE);
        //   receipt2detail.setVisibility(View.GONE);
        //   receipt3detail.setVisibility(View.GONE);
        //   receipt4detail.setVisibility(View.GONE);

        statustextView = (TextView) view.findViewById(R.id.student_profile_fee_status);
        SessionManagement sessionManagement = new SessionManagement(getContext());
        master_id = sessionManagement.getMasterId();
        listViewfees = (ListView) view.findViewById(R.id.list_student_fees);
        // listviewfeedetail = (ListView) view.findViewById(R.id.listtest);

        //  DescriptionAmount = (LinearLayout) view.findViewById(R.id.student_profile_fee_linearlayout1);
        // DescriptionAmount.addView(view);

        getUsersListData();

        return view;
    }

    private void getUsersListData() {

        String URL = Navigation_URL + "?id=" + master_id;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            ArrayList<StudentFeeInformation> student_list = new ArrayList<>();
                            ArrayList<FeeDescriptionStudent> student_list_description = new ArrayList<>();

                            JSONArray jArray = new JSONArray(response);
                            //  studentFeeInformation = new StudentFeeInformation(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);

                                status = jsonObject.getString("Status");
                                DateofReceiptIssued = jsonObject.getString("DateOfReciept").substring(0, 10);
                                ReceiptNumber = jsonObject.getString("RecieptNo");
                                FeeReceivedDate = jsonObject.getString("recivedDate").substring(0, 10);

                                String Description = jsonObject.getString("Description");
                                JSONArray jArray1 = new JSONArray(Description);

                                for (int j = 0; j < jArray1.length(); j++) {

                                    JSONObject jsonObjectinner = jArray1.getJSONObject(j);
                                    Descriptionlist = jsonObjectinner.getString("des");
                                    Amount = jsonObjectinner.getString("Amount");

                                    //  TextView txtQuestion = (TextView) view1.findViewById(R.id.student_profile_fee_description);
                                    //  TextView tx = (TextView) view1.findViewById(R.id.student_profile_fee_amount);

                                    //  System.out.println(txtQuestion);
                                    //  System.out.println(tx);

                                    //  txtQuestion.setText(Descriptionlist);
                                    //  tx.setText(Amount);
                                    // linearLayout.addView(view1);

                                    Descriptionlist = jsonObjectinner.getString("des");
                                    Amount = jsonObjectinner.getString("Amount");

                                }

                                student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate, Descriptionlist, Amount));
                                //student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate));

                            }

                            System.out.println("student_list size:" + student_list.size());
                            CustomFeeListStudentAdapter customFeeListStudentAdapter = new CustomFeeListStudentAdapter(getActivity(), student_list);
                            listViewfees.setAdapter(customFeeListStudentAdapter);

                        } catch (JSONException e) {

                            System.out.println("This is not good");

                            e.printStackTrace();

                        }

                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // Toast.makeText(view.Fee.this, error.toString(), Toast.LENGTH_LONG).show();

            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                return headers;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

I have watched many example of ExpandableListView as well as TableView
  but cannot be able to show item as listView.I have used Linear layout
  in place of ListView but only one JSON data is Displayed.Where is
  error i am not able to get it.

logcat

03-29 16:52:20.023 1558-1569/system_process I/WindowManager: Destroying surface Surface(name=com.example.user.mis/com.example.user.mis.activity.Login) called by com.android.server.wm.WindowStateAnimator.destroySurface:2014 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:881 com.android.server.wm.WindowState.destroyOrSaveSurface:2073 com.android.server.wm.AppWindowToken.destroySurfaces:363 com.android.server.wm.AppWindowToken.notifyAppStopped:389 com.android.server.wm.WindowManagerService.notifyAppStopped:4456 com.android.server.am.ActivityStack.activityStoppedLocked:1252 com.android.server.am.ActivityManagerService.activityStopped:6895
03-29 16:52:22.656 11984-11984/com.example.user.mis I/System.out: student_list size:3
03-29 16:52:22.656 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.656 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.672 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.672 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.676 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:0 getTeacherNameLate Charge
03-29 16:52:22.677 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:1 getTeacherNameMonthly Fee
03-29 16:52:22.678 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:2 getTeacherNameExtra Charge
03-29 16:52:22.678 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:22.679 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:0 getTeacherNameLate Charge
03-29 16:52:22.682 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:1 getTeacherNameMonthly Fee
03-29 16:52:22.684 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:2 getTeacherNameExtra Charge
03-29 16:52:23.039 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:23.039 11984-11984/com.example.user.mis I/System.out: 3
03-29 16:52:23.041 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:0 getTeacherNameLate Charge
03-29 16:52:23.042 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:1 getTeacherNameMonthly Fee
03-29 16:52:23.042 11984-11984/com.example.user.mis D/HomeTab_adapter: @@ postion:2 getTeacherNameExtra Charge
03-29 16:52:23.042 11984-11984/com.example.user.mis I/System.out: 3


问:
Implement AES encryption in Image
```<code>if (i < 1 && j < textBox3.TextLength)
{
    char letter = Convert.ToChar(textBox3.Text.Substring(j, 1));
    // int value = Convert.ToInt32(letter);
    //Encryption Mechanism here
    AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
    int quote = Convert.ToInt32(textBox3.Text);
    string quote1 = Convert.ToString(quote) + 12;
    aesCSP.GenerateKey();
    aesCSP.GenerateIV();
    byte[] encQuote = EncryptString(aesCSP, quote1);
    string enc = Convert.ToBase64String(encQuote);
    int nerd = Convert.ToInt32(enc);
    img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, nerd));
}
</code>```

here i am  trying to implement an AES encryption on the string which i want to input from the user which i will then store those encrypted values in an array of integers. My problem is that even tough after converting a string to an int variable , i am not able to put that int value into the setpixel() method.

答:
Edit:

First, define methods for encrypting and decrypting a String. There is a good example here: https://stackoverflow.com/a/27484425/7790901

Those methods will return Base64 strings, that are composed only of ASCII characters, whose values can be cast into numbers from 0 to 127, valid for RGB values (0 to 255).

Then,

To mix the characters of the encrypted String into the color values:

```<code>public void MixStringIntoImage(String s, Bitmap img)
{
    int i, x, y;
    i = 0;
    x = 0;
    y = 0;
    while(i<s.Length)
    {
        Color pixelColor = img.GetPixel(x, y);
        pixelColor = Color.FromArgb(pixelColor.R, pixelColor.G, (int)s[i]); //Here you mix the blue component of the color with the character value
        img.SetPixel(x, y, pixelColor);
        i++;
        x++;
        if(x == img.Width)
        {
            x = 0;
            y++;
            if(y == img.Height) throw new Exception("String is too long for this image!!!");
        }
    }
}
</code>```

To get the encrypted string from the image:

```<code>public String GetStringFromMixedImage(int stringLength, Bitmap img)
{
    String s = "";
    int i, x, y;
    i = 0;
    x = 0;
    y = 0;
    while(i<stringLength)
    {
        s = s + (char)(img.GetPixel(x,y).B); //Get the blue component from the pixel color and then cast to char
        i++;
        x++;
        if(x == img.Width)
        {
            x = 0;
            y++;
            if(y == img.Height) throw new Exception("String is too long for this image!!!");
        }
    }
    return s;
}
</code>```

Title: Implement AES encryption in Image

Body:
if (i < 1 && j < textBox3.TextLength)
{
    char letter = Convert.ToChar(textBox3.Text.Substring(j, 1));
    // int value = Convert.ToInt32(letter);
    //Encryption Mechanism here
    AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
    int quote = Convert.ToInt32(textBox3.Text);
    string quote1 = Convert.ToString(quote) + 12;
    aesCSP.GenerateKey();
    aesCSP.GenerateIV();
    byte[] encQuote = EncryptString(aesCSP, quote1);
    string enc = Convert.ToBase64String(encQuote);
    int nerd = Convert.ToInt32(enc);
    img.SetPixel(i, j, Color.FromArgb(pixel.R, pixel.G, nerd));
}

here i am  trying to implement an AES encryption on the string which i want to input from the user which i will then store those encrypted values in an array of integers. My problem is that even tough after converting a string to an int variable , i am not able to put that int value into the setpixel() method.

Body:
Edit:

First, define methods for encrypting and decrypting a String. There is a good example here: https://stackoverflow.com/a/27484425/7790901

Those methods will return Base64 strings, that are composed only of ASCII characters, whose values can be cast into numbers from 0 to 127, valid for RGB values (0 to 255).

Then,

To mix the characters of the encrypted String into the color values:

public void MixStringIntoImage(String s, Bitmap img)
{
    int i, x, y;
    i = 0;
    x = 0;
    y = 0;
    while(i<s.Length)
    {
        Color pixelColor = img.GetPixel(x, y);
        pixelColor = Color.FromArgb(pixelColor.R, pixelColor.G, (int)s[i]); //Here you mix the blue component of the color with the character value
        img.SetPixel(x, y, pixelColor);
        i++;
        x++;
        if(x == img.Width)
        {
            x = 0;
            y++;
            if(y == img.Height) throw new Exception("String is too long for this image!!!");
        }
    }
}

To get the encrypted string from the image:

public String GetStringFromMixedImage(int stringLength, Bitmap img)
{
    String s = "";
    int i, x, y;
    i = 0;
    x = 0;
    y = 0;
    while(i<stringLength)
    {
        s = s + (char)(img.GetPixel(x,y).B); //Get the blue component from the pixel color and then cast to char
        i++;
        x++;
        if(x == img.Width)
        {
            x = 0;
            y++;
            if(y == img.Height) throw new Exception("String is too long for this image!!!");
        }
    }
    return s;
}


问:
Method that returns new object of anonymous class
Let say that I have interface I1 like this:

```<code>interface I1 {
   public void setNumber(int num);
}
</code>```

I want to create let say public class named MyClass that will include method getI1 that will return new object of anonymous class that implements interface I1.

答:
A little supplement to Japu_D_Cret's answer: for JDK 8, it could be as short as:</p>

```<code>public I1 getI1() {
    return num -> {
        // your implementation goes here
    };
}
</code>```

Body:
Let say that I have interface I1 like this:

interface I1 {
   public void setNumber(int num);
}

I want to create let say public class named MyClass that will include method getI1 that will return new object of anonymous class that implements interface I1.

Body:
A little supplement to Japu_D_Cret's answer: for JDK 8, it could be as short as:

public I1 getI1() {
    return num -> {
        // your implementation goes here
    };
}


问:
Answer incoming call using android.telecom and InCallService
Since API 21, Google has been adding features to android.telecom in general, especially by implementing more members of TelecomManager and the addition of InCallService. This last one is is supposed to allow non-system, 3rd-party apps to provide and replace the functionality of the system Calls app in-call screen - the Window that pops up and allows action on EXTRA_STATE_OFFHOOK or EXTRA_STATE_RINGING broadcasts (i.e. incoming and outgoing phone calls).

Currently, only this screen has full control of ringing and active calls and associated system callbacks with fine-grained information, by means of the root-restricted MODIFY_PHONE_STATE permission and a lot of secured AOSP code not even accessible by reflection. It's notably one of the most changed pieces of code in different manufacturers' ROM flavours, together with the launcher, contacts and camera.

This is all very pretty but...

How do you actually develop a 3rd-party InCallService?

Namely:

How do you get notified about, and acquire instances of GSM Calls

How does one answer these calls

What is the life-cycle of the callbacks on this class

Does Google provide any actual tutorial for this that I haven't found

I won't ask answers for all of these at once, but any one answer probably associates to the other questions. This is broad but intrinsically it needs to be: there's no example on the web I've stumbled upon other than AOSP-code, and that code is based on the assumption of root-privileges, which makes it unusable for 3rd-party app development purposes.

答:
I guess Google must've read this question, because apparently on Android 8, a new permission finally allows answering calls through a 3rd party dev-facing permission.

android.permission.ANSWER_PHONE_CALLS (...) allows apps to answer
  incoming phone calls programmatically

No details yet though, since the documentation for API 26 hasn't been released yet. I'll make sure to update this answer when they do.

EDIT: user arekolek provided an answer that works perfectly on the original API version of this question (at the time of asking, API was 23, even though the question mentions API 21), thus he gets the tick for right answer. Refer to his answer if you want to implement an incall screen that targets minimum SDK of 23. Note you might need API-dependant code or compat library tweaks if you want it to work on more recent APIs that deprecate (or restrict) usage of the provided sample code. the github repo works as I initially intended.


问:
ROR + Detect ClassName from text-field & Replace it by another one
In TextField of Ruby Code, I want to check whether the specified class is applied or not, on blur event. Please suggest some technique or way. Sample code is given below used by me.

Ruby Code for TextField::

```<code>    <%=f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name,
:autocomplete => "off", :onblur=> $$$$$ %>
</code>```

Suppose class_name : 'changeView' is applied on above textfield, then I have to detect this particular class & replace by another one like 'changeExtraview'. By using any of the javascript, we can replace that class name but suggest if you have any better option.

Thanks

答:
Just a guessed answer...

So your class_name might be contain a value of changeView, and if in the case, you want to replace the changeView class name to changeExtraview, right?

If it is, then the following should be ok:

```<code><%=f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name.gsub(/changeView/, "changeExtraview"), :autocomplete => "off", :onblur=> $$$$$ %>
</code>```

========================

Another try:

```<code><%=
  f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name, :autocomplete => "off",
    :onblur => "if($(this).hasClass('changeView')) {$(this).removeClass('changeView'); $(this).addClass('changeExtraview')}"
%>
</code>```

========================

As @Faisal pointed out, using binding in JS side would be better. Although the answer was long time ago, I decided to update the answer again:

```<code><%= f.text_field :Username, :size => 4, :tabindex => 2, :class => class_name, :autocomplete => "off" %>
</code>```

And in any ways (I use content_for in this example), add the following js code:

```<code><%= content_for :javascripts do %>
  <script type="text/javascript">
    jQuery(document).ready(function($) {
      $("<%= class_name %>").bind("blur", function() {
        var $this = $(this);
        if ($this.hasClass('changeView')) {
          $this.removeClass('changeView');
          $this.addClass('changeExtraView');
        }
      });
    });
  </script>
<% end %>
</code>```

Note that the above code requires you have <%= yield :javascripts %> in your layout file,

Body:
In TextField of Ruby Code, I want to check whether the specified class is applied or not, on blur event. Please suggest some technique or way. Sample code is given below used by me.

Ruby Code for TextField::

    <%=f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name,
:autocomplete => "off", :onblur=> $$$$$ %>

Suppose class_name : 'changeView' is applied on above textfield, then I have to detect this particular class & replace by another one like 'changeExtraview'. By using any of the javascript, we can replace that class name but suggest if you have any better option.

Thanks

Body:
Just a guessed answer...

So your class_name might be contain a value of changeView, and if in the case, you want to replace the changeView class name to changeExtraview, right?

If it is, then the following should be ok:

<%=f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name.gsub(/changeView/, "changeExtraview"), :autocomplete => "off", :onblur=> $$$$$ %>

========================

Another try:

<%=
  f.text_field :Username, :size=>4, :tabindex=>2, :class=>class_name, :autocomplete => "off",
    :onblur => "if($(this).hasClass('changeView')) {$(this).removeClass('changeView'); $(this).addClass('changeExtraview')}"
%>

========================

As @Faisal pointed out, using binding in JS side would be better. Although the answer was long time ago, I decided to update the answer again:

<%= f.text_field :Username, :size => 4, :tabindex => 2, :class => class_name, :autocomplete => "off" %>

And in any ways (I use content_for in this example), add the following js code:

<%= content_for :javascripts do %>
  <script type="text/javascript">
    jQuery(document).ready(function($) {
      $("<%= class_name %>").bind("blur", function() {
        var $this = $(this);
        if ($this.hasClass('changeView')) {
          $this.removeClass('changeView');
          $this.addClass('changeExtraView');
        }
      });
    });
  </script>
<% end %>

Note that the above code requires you have <%= yield :javascripts %> in your layout file,


问:
from jquery $.ajax to angular $http
I have this piece of jQuery code that works fine cross origin:

```<code>jQuery.ajax({
    url: "http://example.appspot.com/rest/app",
    type: "POST",
    data: JSON.stringify({"foo":"bar"}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        console.log("success");
    },
    error: function (response) {
        console.log("failed");
    }
});
</code>```

Now I'm tring to convert this to Angular.js code without any success:

```<code>$http({
    url: "http://example.appspot.com/rest/app",
    dataType: "json",
    method: "POST",
    data: JSON.stringify({"foo":"bar"}),
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});
</code>```

Any help appreciated.

答:
You may use this :

Download  "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

Title: from jquery $.ajax to angular $http

Body:
I have this piece of jQuery code that works fine cross origin:

jQuery.ajax({
    url: "http://example.appspot.com/rest/app",
    type: "POST",
    data: JSON.stringify({"foo":"bar"}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        console.log("success");
    },
    error: function (response) {
        console.log("failed");
    }
});

Now I'm tring to convert this to Angular.js code without any success:

$http({
    url: "http://example.appspot.com/rest/app",
    dataType: "json",
    method: "POST",
    data: JSON.stringify({"foo":"bar"}),
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

Any help appreciated.