问:
App Getting Crash while Continuous open and close Activity between 2 activities
My Android App having multiple activities, now my problem is unable to findable.

A Activity have one recyclerView it get data from local database, If I click the items it will open B Activity, this same flow continuously then app getting crash(like open B Activity come back to A Activity and open again B activity- up to 5 to 6 time do same action then app getting crash)

The Crash message is related to SQLite DATABASE but unable to find where it occurs. Please help me... already spend more time for this...

Note: open DB on Oncreate and Close DB on OnDestroy in both activities

Error Message

```<code>E/SQLiteQuery: exception: unable to open database file (code 14); query: SELECT DISTINCT * FROM parameters WHERE inspection_no LIKE '%TEST-123%'
E/InputChannel-JNI: Error 24 dup channel fd 1023.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.testapp.testprocess, PID: 13078
                  java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
                      at android.view.InputChannel.nativeReadFromParcel(Native Method)
                      at android.view.InputChannel.readFromParcel(InputChannel.java:148)
                      at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:841)
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:640)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3518)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2733)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6121)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

答:
Whenever we access or update database we should have to open and close database after operation is performed. have look.

```<code>DataBaseHelper db = new DataBaseHelper(this);
db.open();
Cursor cursor = db.getAllItems();
maxCount = cursor.getCount();
Random gen = new Random();
row = gen.nextInt(maxCount);
 if (cursor.moveToPosition(row)) {
    String myString = cursor.getString(1);
}
cursor.close();
db.close();
</code>```

here is getAllItems() which will return items.

```<code>public Cursor getAllItems()
{
return db.query(DATABASE_TABLE, new String[] {
        KEY_ROWID,
        KEY_NAME
        },
        null,
        null,
        null,
        null,
        null);
}
</code>```

so in your case, when you click on list item you have to open/close database carefully.

Happy coding!!

Body:
My Android App having multiple activities, now my problem is unable to findable.

A Activity have one recyclerView it get data from local database, If I click the items it will open B Activity, this same flow continuously then app getting crash(like open B Activity come back to A Activity and open again B activity- up to 5 to 6 time do same action then app getting crash)

The Crash message is related to SQLite DATABASE but unable to find where it occurs. Please help me... already spend more time for this...

Note: open DB on Oncreate and Close DB on OnDestroy in both activities

Error Message

E/SQLiteQuery: exception: unable to open database file (code 14); query: SELECT DISTINCT * FROM parameters WHERE inspection_no LIKE '%TEST-123%'
E/InputChannel-JNI: Error 24 dup channel fd 1023.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.testapp.testprocess, PID: 13078
                  java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
                      at android.view.InputChannel.nativeReadFromParcel(Native Method)
                      at android.view.InputChannel.readFromParcel(InputChannel.java:148)
                      at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:841)
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:640)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3518)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2733)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6121)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Body:
Whenever we access or update database we should have to open and close database after operation is performed. have look.

DataBaseHelper db = new DataBaseHelper(this);
db.open();
Cursor cursor = db.getAllItems();
maxCount = cursor.getCount();
Random gen = new Random();
row = gen.nextInt(maxCount);
 if (cursor.moveToPosition(row)) {
    String myString = cursor.getString(1);
}
cursor.close();
db.close();

here is getAllItems() which will return items.

public Cursor getAllItems()
{
return db.query(DATABASE_TABLE, new String[] {
        KEY_ROWID,
        KEY_NAME
        },
        null,
        null,
        null,
        null,
        null);
}

so in your case, when you click on list item you have to open/close database carefully.

Happy coding!!


来源: stackexchange

问:
How can I determine what architectures gcc supports?
GCC supports a -march switch that allows you to specify the architecture you are targeting - allowing it to tune instruction sequences for that platform as well as using instructions that might be available on the platform which aren't available on the "default" or base version of the architecture.

For example, -march=skylake will tell the compiler to target Skylake CPUs, including using instruction sets available on Skylake such as AVX2.

How can I tell what values for -march the local version of gcc supports? Newer versions helpfully list the valid arguments when an invalid argument is passed, but older versions do not.

答:
For gcc-7.2.0, it's here:
https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/x86-Options.html#x86-Options

You could go to gcc online documentation. Then, find the manual for the version you are interested. Following that, go to machine dependent options section. If you are looking into x86, jump to the "x86 options" section. Now, search "-march."

I haven't checked the old gcc versions. Another way you could try is to check out the source code, and open the source code that keeps the literal strings for the supported arch.

```<code>svn checkout svn://gcc.gnu.org/svn/gcc/trunk gcc_trunk
cd gcc_trunk
</code>```

Then, maybe, you could try like this:

```<code>find . -type f | egrep "*\.(c|cc|cpp|h|hpp)$" | xargs egrep '"skylake-avx'
</code>```

As of today, the literal strings are kept in ./gcc/config/i386/i386.c in case of x86 architectures.

%P.S.

As Peter mentioned, it seems machine-specific. I suspect that there isn't a standard/desired behavior that lists available march values. For example, if gcc has been just ported to a brand-new instruction set architecture, LEG--as opposed to ARM--, it does not necessarily have a command-line option to list all supported march values.

Fortunately, it seems like some newer gcc versions provide a way to do so. If you do need such an option for old gccs, writing a gcc plugin, which might work from gcc 4.5 or so, could be taken into consideration:

gcc plugin

simple gcc plugin how to

Gcc plugins are plugged-in to an existing gcc by adding some command-line options. Gcc has APIs for plugins. All you need would be to write a code that checks the information such as gcc version, the arch that runs gcc, etc, and that prints out the list of the supported march.

ContentLicense: CC BY-SA 3.0

Body:
For gcc-7.2.0, it's here:
https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/x86-Options.html#x86-Options

You could go to gcc online documentation. Then, find the manual for the version you are interested. Following that, go to machine dependent options section. If you are looking into x86, jump to the "x86 options" section. Now, search "-march."

I haven't checked the old gcc versions. Another way you could try is to check out the source code, and open the source code that keeps the literal strings for the supported arch.

svn checkout svn://gcc.gnu.org/svn/gcc/trunk gcc_trunk
cd gcc_trunk

Then, maybe, you could try like this:

find . -type f | egrep "*\.(c|cc|cpp|h|hpp)$" | xargs egrep '"skylake-avx'

As of today, the literal strings are kept in ./gcc/config/i386/i386.c in case of x86 architectures.

%P.S.

As Peter mentioned, it seems machine-specific. I suspect that there isn't a standard/desired behavior that lists available march values. For example, if gcc has been just ported to a brand-new instruction set architecture, LEG--as opposed to ARM--, it does not necessarily have a command-line option to list all supported march values.

Fortunately, it seems like some newer gcc versions provide a way to do so. If you do need such an option for old gccs, writing a gcc plugin, which might work from gcc 4.5 or so, could be taken into consideration:

gcc plugin

simple gcc plugin how to

Gcc plugins are plugged-in to an existing gcc by adding some command-line options. Gcc has APIs for plugins. All you need would be to write a code that checks the information such as gcc version, the arch that runs gcc, etc, and that prints out the list of the supported march.


问:
Run a PowerShell script with Administrator privileges on other computer
My user haven't got access to run PowerShell.exe

Using C# I want to be able to run

```<code>(Get-Service -ComputerName 172.x.x.x -Name mssqlserver).Start()
</code>```

on another computer, as the domain administrator account.

I can run PowerShell as administrator's username and password.

I searched in StackOverFlow... but I did not found my answer.

答:
If you need an administrative privilege when executing your application, you should add below element in the application's manifest file:

```<code><requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</code>```

For executing a PowerShell script you can also use the below link. I have used this library before and it works fine.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

Body:
My user haven't got access to run PowerShell.exe

Using C# I want to be able to run

(Get-Service -ComputerName 172.x.x.x -Name mssqlserver).Start()

on another computer, as the domain administrator account.

I can run PowerShell as administrator's username and password.

I searched in StackOverFlow... but I did not found my answer.

Body:
If you need an administrative privilege when executing your application, you should add below element in the application's manifest file:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

For executing a PowerShell script you can also use the below link. I have used this library before and it works fine.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/


问:
Java Years between 2 Instants
In Joda, we can calculate years between 2 Datetime using

```<code>Years.between(dateTime1, dateTime2);
</code>```

Is there any easy way to find years between 2 instants using the java.time API instead without much logic?

```<code>ChronoUnit.YEARS.between(instant1, instant2)
</code>```

fails:

```<code>Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
        at java.time.Instant.until(Instant.java:1157)
        at java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
        ...
</code>```

答:
The number of years between two instants is considered undefined (apparently - I was surprised by this), but you can easily convert instants into ZonedDateTime and get a useful result:

```<code>Instant now = Instant.now();
Instant ago = Instant.ofEpochSecond(1234567890L);

System.out.println(ChronoUnit.YEARS.between(
  ago.atZone(ZoneId.systemDefault()),
  now.atZone(ZoneId.systemDefault())));
</code>```

Prints:

```<code>8
</code>```

I suspect the reason you can't directly compare instants is because the location of the year boundary depends on the time zone. That means that ZoneId.systemDefault() may not be what you want! ZoneOffset.UTC would be a reasonable choice, otherwise if there's a time zone that's more meaningful in your context (e.g. the time zone of the user who will see the result) you'd want to use that.

Title: Java Years between 2 Instants

Body:
In Joda, we can calculate years between 2 Datetime using

Years.between(dateTime1, dateTime2);

Is there any easy way to find years between 2 instants using the java.time API instead without much logic?

ChronoUnit.YEARS.between(instant1, instant2)

fails:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
        at java.time.Instant.until(Instant.java:1157)
        at java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
        ...

Body:
The number of years between two instants is considered undefined (apparently - I was surprised by this), but you can easily convert instants into ZonedDateTime and get a useful result:

Instant now = Instant.now();
Instant ago = Instant.ofEpochSecond(1234567890L);

System.out.println(ChronoUnit.YEARS.between(
  ago.atZone(ZoneId.systemDefault()),
  now.atZone(ZoneId.systemDefault())));

Prints:

8

I suspect the reason you can't directly compare instants is because the location of the year boundary depends on the time zone. That means that ZoneId.systemDefault() may not be what you want! ZoneOffset.UTC would be a reasonable choice, otherwise if there's a time zone that's more meaningful in your context (e.g. the time zone of the user who will see the result) you'd want to use that.


问:
Primary key for a table where DATETIME col is used for almost all SELECT operations
I'm wondering what kind of PK I should be choosing for this table in MySQL. Almost all the SELECT operations will involve the DATETIME (date ranges, a specific date, etc.).

Is there a best practice for this?

答: I wouldn't recommend that the DATETIME be your PK, but you should certainly create an index on that column.</p>

ContentLicense: CC BY-SA 2.5


问:
While executing the below code getting an error bad geometry specifier in python
While trying the below code:

```<code>import tkinter

print(tkinter.TkVersion)

print(tkinter.TclVersion)

mainWindow = tkinter.Tk()

mainWindow.title("Hello Python")

mainWindow.geometry("1200X1024")

mainWindow.mainloop()
</code>```

I am getting an error:

```<code> Traceback (most recent call last):
   File "C:\Users\Satya\IdeaProjects\GUO_python\tkinter1.py", line 11, in <module>
     mainWindow.geometry("1200X1024")
   File "C:\Users\Satya\Anaconda3\lib\tkinter\__init__.py", line 1835, in wm_geometry
     return self.tk.call('wm', 'geometry', self._w, newGeometry)
 _tkinter.TclError: bad geometry specifier "1200X1024"
</code>```

https://i.stack.imgur.com/EJyn6.jpg

答:
The arguments you passed to geometry aren't quite right.

You have written 1200X1024 - but that X needs to be lowercased.

Try mainWindow.geometry("1200x1024").

Body:
While trying the below code:

import tkinter

print(tkinter.TkVersion)

print(tkinter.TclVersion)

mainWindow = tkinter.Tk()

mainWindow.title("Hello Python")

mainWindow.geometry("1200X1024")

mainWindow.mainloop()

I am getting an error:

 Traceback (most recent call last):
   File "C:\Users\Satya\IdeaProjects\GUO_python\tkinter1.py", line 11, in <module>
     mainWindow.geometry("1200X1024")
   File "C:\Users\Satya\Anaconda3\lib\tkinter\__init__.py", line 1835, in wm_geometry
     return self.tk.call('wm', 'geometry', self._w, newGeometry)
 _tkinter.TclError: bad geometry specifier "1200X1024"

https://i.stack.imgur.com/EJyn6.jpg


问:
how to initializing a hash table in C
I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.

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

#define HSZ 127
#define HASHING(x) ((x)%HSZ)

struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

void init(void){
    int i;
    //memset(hash_table,0,sizeof(hash_table));
    for(i=0; i<HSZ; i++){
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
    }
}

void insert_hash(int value){
    int key = HASHING(value);
    struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));

    newNode->val = value;
    newNode->next = NULL;

    if(hash_table[key] == NULL){
        hash_table[key] = newNode;
    } else {
        newNode->next = hash_table[key];
        hash_table[key] = newNode;
    }
}

int delete_hash(int value){
    int key = HASHING(value);
    if (hash_table[key] == NULL)
        return 0;

    struct node_t *delNode = NULL;

    if (hash_table[key]->val == value){
        delNode = hash_table[key];
        hash_table[key] = hash_table[key]->next;
    } else {
        struct node_t *node = &hash_table[key];
        struct node_t *next = hash_table[key]->next;
        while (next){
            if (next->val == value){
                node->next = next->next;
                delNode = next;
                break;
            }
            node = next;
            next = node->next;
        }
    }
    return 1;
    free(delNode);
}
void PrintAllHashData()
{
    printf("###Print All Hash Data###\n");
    for (int i = 0; i < HSZ; i++){
        if (hash_table[i] != NULL){
            printf("idx : %d ", i);
            struct node_t *node = hash_table[i];
            while (node->next){
                printf("%d ", node->val);
                node = node->next;
            }
            printf("%d\n", node->val);
        }
    }
}

int main(void){
    init();
    insert_hash(1);
    insert_hash(3);
    insert_hash(128);
    PrintAllHashData();
}
</code>```

look at this code.

```<code>for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}
</code>```

The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.

then, I changed this line to

```<code>for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}
</code>```

but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'

I think that I don't understand clearly about struct in C.
How to fix this problem?

答:
What you are dealing with is Undefined Behavior.

See, struct node_t *hash_table[HSZ];
So, hash_table is an array of HSZ (127) pointers of the data type struct node_t.

When you do,

```<code>for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}
</code>```

hash_table[0] to hash_table[126] pointers are not pointing to anything.
So, each of them (or all of them) should be initialized first to point to an object of the type struct node_t and then you can initialize them. For that matter, Using a memset does not cause a problem because memset is filling the contents of the pointers with all zeros. There is difference between filling the pointers with all zeros and filling all zeros to the memory pointed by pointers.

Trying this,

```<code>for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}
</code>```

is plain wrong.

To fix the issue you are facing, you need to allocate memory dynamically using malloc. You can do the in your for loop.

```<code>for(i = 0; i < HSZ; i++)
{
    //Allocate memory of the size struct_node_t
    hash_table[i] = malloc(sizeof(struct node_t)); //Do not cast!
    //Check if memory is allocated
    if(hash_table[i] == NULL)
    {
        //Memory not allocated, set some error state to handle and break
        break;
    }
    //Initialize to zero
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}
</code>```

Title: how to initializing a hash table in C

Body:
I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.

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

#define HSZ 127
#define HASHING(x) ((x)%HSZ)

struct node_t{
    int val;
    struct node_t *next;
};

struct node_t *hash_table[HSZ];

void init(void){
    int i;
    //memset(hash_table,0,sizeof(hash_table));
    for(i=0; i<HSZ; i++){
        hash_table[i]->val = 0;
        hash_table[i]->next = NULL;
    }
}

void insert_hash(int value){
    int key = HASHING(value);
    struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));

    newNode->val = value;
    newNode->next = NULL;

    if(hash_table[key] == NULL){
        hash_table[key] = newNode;
    } else {
        newNode->next = hash_table[key];
        hash_table[key] = newNode;
    }
}

int delete_hash(int value){
    int key = HASHING(value);
    if (hash_table[key] == NULL)
        return 0;

    struct node_t *delNode = NULL;

    if (hash_table[key]->val == value){
        delNode = hash_table[key];
        hash_table[key] = hash_table[key]->next;
    } else {
        struct node_t *node = &hash_table[key];
        struct node_t *next = hash_table[key]->next;
        while (next){
            if (next->val == value){
                node->next = next->next;
                delNode = next;
                break;
            }
            node = next;
            next = node->next;
        }
    }
    return 1;
    free(delNode);
}
void PrintAllHashData()
{
    printf("###Print All Hash Data###\n");
    for (int i = 0; i < HSZ; i++){
        if (hash_table[i] != NULL){
            printf("idx : %d ", i);
            struct node_t *node = hash_table[i];
            while (node->next){
                printf("%d ", node->val);
                node = node->next;
            }
            printf("%d\n", node->val);
        }
    }
}

int main(void){
    init();
    insert_hash(1);
    insert_hash(3);
    insert_hash(128);
    PrintAllHashData();
}

look at this code.

for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}

The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.

then, I changed this line to

for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}

but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'

I think that I don't understand clearly about struct in C.
How to fix this problem?

Body:
What you are dealing with is Undefined Behavior.

See, struct node_t *hash_table[HSZ];
So, hash_table is an array of HSZ (127) pointers of the data type struct node_t.

When you do,

for(i=0; i<HSZ; i++){
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}

hash_table[0] to hash_table[126] pointers are not pointing to anything.
So, each of them (or all of them) should be initialized first to point to an object of the type struct node_t and then you can initialize them. For that matter, Using a memset does not cause a problem because memset is filling the contents of the pointers with all zeros. There is difference between filling the pointers with all zeros and filling all zeros to the memory pointed by pointers.

Trying this,

for(i=0; i<HSZ; i++){
    hash_table[i].val = 0;
    hash_table[i]->next = NULL;
}

is plain wrong.

To fix the issue you are facing, you need to allocate memory dynamically using malloc. You can do the in your for loop.

for(i = 0; i < HSZ; i++)
{
    //Allocate memory of the size struct_node_t
    hash_table[i] = malloc(sizeof(struct node_t)); //Do not cast!
    //Check if memory is allocated
    if(hash_table[i] == NULL)
    {
        //Memory not allocated, set some error state to handle and break
        break;
    }
    //Initialize to zero
    hash_table[i]->val = 0;
    hash_table[i]->next = NULL;
}


问:
What to write so that when "enter" is pressed, then code proceeds further?
Please help me in the below code :

```<code>import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}
</code>```

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.

答:
Try using code in this class but this works only form command line . you can't use it in IDE's console .c.reader will return null if you use in IDE

```<code>import java.io.Console;
import java.io.IOException;
import java.io.Reader;
public class GetChar {

public static void main(String  args[]) {

    int num=0;
    Console c =System.console();
    Reader r = c.reader();
try {
    num=    r.read();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

System.out.println(num);

}

}
</code>```

The value of num will be 10 if '\n' is pressed pressed i,e Enter . I hope your code can use this logic

Body:
Please help me in the below code :

import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.

Body:
Try using code in this class but this works only form command line . you can't use it in IDE's console .c.reader will return null if you use in IDE

import java.io.Console;
import java.io.IOException;
import java.io.Reader;
public class GetChar {

public static void main(String  args[]) {

    int num=0;
    Console c =System.console();
    Reader r = c.reader();
try {
    num=    r.read();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

System.out.println(num);

}

}

The value of num will be 10 if '\n' is pressed pressed i,e Enter . I hope your code can use this logic


问:
Windows 7 - How to gain full admin rights when already part of administrators group?
I have a Windows 7 development machine and I am constantly encountering the "you do not have enough permissions" when running certain programs or trying to access log files. I am the only user on the machine and my account is part of the administrators group. Is this part of Microsoft's UAC "protection"? If so, is there a way to remove it so that an administrator account has full admin rights.</p>

答: Usually, you can right click and select "Run as Administrator" to elevate the privilege. I believe, You can also turn it off from control panel (search for "User access control" in control panel). I would not recommend it though. If you have applications to start up with that privilege, you might want to modify the shortcut to have "Run as Administrator" set so that it will challenge you as soon as it starts.</p>


问:
Want to display Modal pop up with changes in the Edit form in ASP.NET MVC application
I want a Modal to display all the changes made in the Edit form in ASP.NET MVC application. If user has not made any changes then Modal should not appear.

I have written JavaScript code which shows the changes but I do not think that this is the proper way to do this.

I have a Modal which opens on click of Submit button.

My JavaScript Code is:

```<code><script type="text/javascript">
    var FirstName = "@Html.Raw(ViewBag.FName)";
    var LastName = "@Html.Raw(ViewBag.LName)";
    var NameAddress = "@Html.Raw(ViewBag.NameAddress)";
    $(document).ready(function () {
        $("#btnSubmit").click(function () {
            if ($("#FName").val() == FirstName  && ("#LName").val() == LastName  && ("#Address").val() == NameAddress ) {

                alert("There is no value changed in textbox");
            }
            else {
              alert("First Name changed from:" + FirstName + " to " + $("#FName").val());
            }

        });

    });
</script>
</code>```

Modal to display the changes:

```<code><input type="submit" id="btnSubmit" value="Save" class="btn btn-primary" data-toggle="modal" data-target="#ListofChanges" />

 <div id="ListofChanges" class="modal fade" role="dialog">
        <div class="modal-dialog">

               <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">PhoneBook Details changed from</h4>
                </div>
                <div class="modal-body">

                    <ul>
                        <li>
                            "@Html.Raw(ViewBag.FName)"
                        </li>
                        <li>
                            "@Html.Raw(ViewBag.LName)"
                        </li>
                        <li>
                            "@Html.Raw(ViewBag.NameAddress)"
                        </li>
                    </ul>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>
</code>```

Please guide me. I got stuck in this. Thank you.

答:
You have to use a modal method to open it up:

```<code><script type="text/javascript">
    var FirstName = "@Html.Raw(ViewBag.FName)";
    var LastName = "@Html.Raw(ViewBag.LName)";
    var NameAddress = "@Html.Raw(ViewBag.NameAddress)";
    $(document).ready(function () {
        $("#btnSubmit").click(function () {
            if ($("#FName").val() == FirstName  && ("#LName").val() == LastName  && ("#Address").val() == NameAddress ) {

                alert("There is no value changed in textbox");
            }
            else {
              $('#ListofChanges').modal('show')  // <-- HERE
            }

        });

    });
</script>
</code>```

Docs here to Modal methods

Body:
I want a Modal to display all the changes made in the Edit form in ASP.NET MVC application. If user has not made any changes then Modal should not appear.

I have written JavaScript code which shows the changes but I do not think that this is the proper way to do this.

I have a Modal which opens on click of Submit button.

My JavaScript Code is:

Modal to display the changes:

<input type="submit" id="btnSubmit" value="Save" class="btn btn-primary" data-toggle="modal" data-target="#ListofChanges" />

                    <button type="button" class="close" data-dismiss="modal">×</button>

PhoneBook Details changed from

                            "@Html.Raw(ViewBag.FName)"

                            "@Html.Raw(ViewBag.LName)"

                            "@Html.Raw(ViewBag.NameAddress)"

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Please guide me. I got stuck in this. Thank you.

Body:
You have to use a modal method to open it up:

<script type="text/javascript">
    var FirstName = "@Html.Raw(ViewBag.FName)";
    var LastName = "@Html.Raw(ViewBag.LName)";
    var NameAddress = "@Html.Raw(ViewBag.NameAddress)";
    $(document).ready(function () {
        $("#btnSubmit").click(function () {
            if ($("#FName").val() == FirstName  && ("#LName").val() == LastName  && ("#Address").val() == NameAddress ) {

                alert("There is no value changed in textbox");
            }
            else {
              $('#ListofChanges').modal('show')  // <-- HERE
            }

        });

    });
</script>

Docs here to Modal methods


问:
Disable sidebar menu in login page laravel
just want to ask a question, if I want to disable the sidebar menu page in my login page, how would I do that? In the first place, is it possible? If it is possible could you show me some example or even give me a link for me to reference to see how to do it. Because I still can access my data even without logging in through the sidebar so I want to disable it if possible. Thanks in advance

If you need me to show my code just ask, I will put it in asap.

app.blade.php

```<code><!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

   <title>@yield('title')</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/title.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @include('layouts.testSidebar')

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}" style="color: white">
                        @yield('title')
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @guest
                            <li><a href="{{ route('login') }}">Login</a></li>
                            <li><a href="{{ route('register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true" style="background-color:blue">
                                    <b style="color: white">{{ Auth::user()->name }}</b> <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" style="background-color: blue">
                                    <li>
                                        <a href="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();" style="background-color: blue">
                                            <b style="color: white">Logout</b>
                                        </a>

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

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

答:
If u dont want to show the Left Side Of Navbar for the not logged in user try the below

```<code>@if(Auth::check())
    <!-- Left Side Of Navbar -->
    <ul class="nav navbar-nav">

    </ul>
@endif
</code>```

Body:
just want to ask a question, if I want to disable the sidebar menu page in my login page, how would I do that? In the first place, is it possible? If it is possible could you show me some example or even give me a link for me to reference to see how to do it. Because I still can access my data even without logging in through the sidebar so I want to disable it if possible. Thanks in advance

If you need me to show my code just ask, I will put it in asap.

app.blade.php

<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

   <title>@yield('title')</title>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/title.css') }}" rel="stylesheet">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        Toggle Navigation

                    </button>
                    @include('layouts.testSidebar')

                        @yield('title')

                        @guest

Login

Register

                        @else

                                    {{ Auth::user()->name }}

                                            Logout

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>

                        @endguest

        @yield('content')

Body:
If u dont want to show the Left Side Of Navbar for the not logged in user try the below

@if(Auth::check())
    <!-- Left Side Of Navbar -->
    <ul class="nav navbar-nav">
        &nbsp;
    </ul>
@endif


问:
Convert textual document to tf.data in tensorflow for reading sequentially
In a textual corpus, there are 50 textual documents that each document approximately is about 80 lines.
I want to feed my corpus as an input to tensorflow, but I want to batch each document when system read each document? actually same as TfRecord that used for images I want to by using Tf.Data make batch each document in my corpus for reading it sequentially?

How can I solve this issue?

答:
You can create a TextLineDataset that will contain the lines of your documents:

```<code>dataset = tf.data.TextLineDataset(['doc1.txt', 'doc2.txt', ...])
</code>```

After you create the dataset, you can split the strings into batches using the batch method and other methods of the Dataset class.

Body:
You can create a TextLineDataset that will contain the lines of your documents:

dataset = tf.data.TextLineDataset(['doc1.txt', 'doc2.txt', ...])

After you create the dataset, you can split the strings into batches using the batch method and other methods of the Dataset class.


问:
What's the difference between retrieving WindowsPrincipal from WindowsIdentity and Thread.CurrentPrincipal?
I am trying to work out why attribute based security isn't working as I'd expect in WCF and I suspect it might have something to do with the following:

```<code>AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

var identity = new WindowsIdentity("ksarfo");
var principal = new WindowsPrincipal(identity);
Console.WriteLine("\nChecking whether current user [" + identity.Name + "] is member of [" + groupName + "]");
Console.WriteLine(principal.IsInRole(groupName)); // returns true

principal = (WindowsPrincipal)Thread.CurrentPrincipal;
identity = (WindowsIdentity) principal.Identity;
Console.WriteLine("\nChecking whether current user [" + identity.Name + "] is member of [" + groupName + "]");
Console.WriteLine(principal.IsInRole(groupName)); // returns false
</code>```

I don't understand why the results differ for the function call:

```<code>principal.IsInRole(groupName)
</code>```

For the sake of completeness the point at which the code actually fails is here:

```<code>PrincipalPermission(SecurityAction.Demand, Role = "PortfolioManager")]
</code>```

Help appreciated.

答: I believe the difference is between the logged in user and the account running the app (thread). These will not always be the same.</p>

Body:
I am trying to work out why attribute based security isn't working as I'd expect in WCF and I suspect it might have something to do with the following:

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

var identity = new WindowsIdentity("ksarfo");
var principal = new WindowsPrincipal(identity);
Console.WriteLine("\nChecking whether current user [" + identity.Name + "] is member of [" + groupName + "]");
Console.WriteLine(principal.IsInRole(groupName)); // returns true

principal = (WindowsPrincipal)Thread.CurrentPrincipal;
identity = (WindowsIdentity) principal.Identity;
Console.WriteLine("\nChecking whether current user [" + identity.Name + "] is member of [" + groupName + "]");
Console.WriteLine(principal.IsInRole(groupName)); // returns false

I don't understand why the results differ for the function call:

principal.IsInRole(groupName)

For the sake of completeness the point at which the code actually fails is here:

PrincipalPermission(SecurityAction.Demand, Role = "PortfolioManager")]

Help appreciated.


问:
PdfViewr proplem save page
I am using PdfViewr.

I want to open pdf on the last page, which is not working. I have tried many times but its not working.

I used this code

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpdf);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}
</code>```

How can I save pdf's last page, and I need to implement this for my app. Any help?

Thank you.

答:
Save your last page number every time and pass when you initialise pdf like:</p>

```<code>pdfView.fromAsset(SAMPLE_FILE)

            .defaultPage(pageNumber) // enter your last page number
            .enableSwipe(true)
            .swipeHorizontal(false)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .spacing(10)
            .load();
</code>```

Title: PdfViewr proplem save page

Body:
I am using PdfViewr.

I want to open pdf on the last page, which is not working. I have tried many times but its not working.

I used this code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpdf);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}

How can I save pdf's last page, and I need to implement this for my app. Any help?

Thank you.

Body:
Save your last page number every time and pass when you initialise pdf like:

pdfView.fromAsset(SAMPLE_FILE)

            .defaultPage(pageNumber) // enter your last page number
            .enableSwipe(true)
            .swipeHorizontal(false)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .spacing(10)
            .load();


问:
Flyway check if database exists and was baselined in java
I'm trying to use Flyway in my web application. I've read the docs, but couldn't find an answer to the following question:

Is it possible to check if a database was baselined before running migrate?

The web application already uses a large database. So I need to run baseline for it. I want the application to run baseline and/or migrate on startup. The database should be created if it doesn't exist and it should be baselined if it exists, but wasn't baselined before.

I already added 3 SQL files to the migration package:

```<code>V4_0_0__schema.sql
V4_0_1__index.sql
V4_0_2__initial_inserts.sql
</code>```

I want to do it like this:

DataSource dataSource = new MysqlDataSource();
String[] locations = {"path/to/location"};

Flyway flyway = new Flyway();
flyway.setCleanDisabled(true);
flyway.setLocations(locations);
flyway.setDataSource(dataSource);

if (databaseExists()) { // how to determine that the db already exists?
    if (databaseWasBaselined() == false) { // How to check this?
        flyway.setBaselineVersion(MigrationVersion.LATEST); // will this set the version to 4_0_2?
        flyway.baseline();
    }
}
flyway.migrate();
```

I need a little help to do it the right way. I hope, that someone can point me into the right direction.

答:
Use the baselineOnMigrate option as documented on the Flyway site:

Whether to automatically call baseline when migrate is executed against a non-empty schema with no metadata table. This schema will then be baselined with the baselineVersion before executing the migrations. Only migrations above baselineVersion will then be applied.

This is useful for initial Flyway production deployments on projects with an existing DB.

Be careful when enabling this as it removes the safety net that ensures Flyway does not migrate the wrong database in case of a configuration mistake!

Body:
I'm trying to use Flyway in my web application. I've read the docs, but couldn't find an answer to the following question:

Is it possible to check if a database was baselined before running migrate?

The web application already uses a large database. So I need to run baseline for it. I want the application to run baseline and/or migrate on startup. The database should be created if it doesn't exist and it should be baselined if it exists, but wasn't baselined before.

I already added 3 SQL files to the migration package:

V4_0_0__schema.sql
V4_0_1__index.sql
V4_0_2__initial_inserts.sql

I want to do it like this:

DataSource dataSource = new MysqlDataSource();
String[] locations = {"path/to/location"};

Flyway flyway = new Flyway();
flyway.setCleanDisabled(true);
flyway.setLocations(locations);
flyway.setDataSource(dataSource);

if (databaseExists()) { // how to determine that the db already exists?
    if (databaseWasBaselined() == false) { // How to check this?
        flyway.setBaselineVersion(MigrationVersion.LATEST); // will this set the version to 4_0_2?
        flyway.baseline();
    }
}
flyway.migrate();

I need a little help to do it the right way. I hope, that someone can point me into the right direction.


问:
getchar(), putchar(char), EOF
```<code>#include<stdio.h>
int main(){
   int c = getchar();
   while(c != EOF){
      putchar(c);
      c = getchar();
   }
}
</code>```

In above code why does not the program terminates by itself after c becomes EOF?
Reference of the code > Book: K&R's The C Programming Language 2nd Edition,
Page: 18

答:
getchar() will return EOF only if the end of file is reached. The ‘file’ here is the standard input itself.
This can be written as:</p>

```<code>#include <stdio.h>
   int main()
  {
   int c;
   while ((c = getchar()) != EOF)
    {
     /*getchar() returns the the next available value which is in the input
     buffer*/
     putchar(c);
    }
  }
</code>```

Title: getchar(), putchar(char), EOF

Body:
#include<stdio.h>
int main(){
   int c = getchar();
   while(c != EOF){
      putchar(c);
      c = getchar();
   }
}

In above code why does not the program terminates by itself after c becomes EOF?
Reference of the code > Book: K&R's The C Programming Language 2nd Edition,
Page: 18

Body:
getchar() will return EOF only if the end of file is reached. The ‘file’ here is the standard input itself.
This can be written as:

#include <stdio.h>
   int main()
  {
   int c;
   while ((c = getchar()) != EOF)
    {
     /*getchar() returns the the next available value which is in the input
     buffer*/
     putchar(c);
    }
  }


问:
Another word for Business Logic?
What is another good word for Business Logic?

Software might also run in civil service offices or for hobbyists, so I never felt that comfortable with using that term in certain modules and documentation.

App Logic is too specific as well, because logic modules might also be used in services.

答: Orchestration Layer or just Orchestration.

Title: Another word for Business Logic?


问:
How to center two letters inside this css drawn circle?
Using this Codepen example and additional CSS, how would I center the letters "AB" within the circle?
https://codepen.io/joseph-mueller/pen/bNEeGw
This is what I want:

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div></code>```

答:
Try this :

.referral-credit-outer-circle{
  background: #fff;
  width: 92px;
  height:92px;
  border-radius:90px;
 box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;

}

.mask-referral-credit-inner-circle{
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle{
  width: 80px;
  height:80px;
  border-radius:80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}
.referral-text{
  text-align:center;
  display:block;
  line-height:92px;
  position:relative;
  z-index:2;
  font-size:20px

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "referral-credit-outer-circle">
  <span class="referral-text">AB</span>
<span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class = "mask-referral-credit-inner-circle" style = "height: 70%">
    <div class = "referral-credit-inner-circle"></div>
  </div>
</div></code>```

Body:
Try this :

.referral-credit-outer-circle{
  background: #fff;
  width: 92px;
  height:92px;
  border-radius:90px;
 box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;

}

.mask-referral-credit-inner-circle{
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle{
  width: 80px;
  height:80px;
  border-radius:80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}
.referral-text{
  text-align:center;
  display:block;
  line-height:92px;
  position:relative;
  z-index:2;
  font-size:20px

}

<div class = "referral-credit-outer-circle">
  <span class="referral-text">AB</span>
<span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class = "mask-referral-credit-inner-circle" style = "height: 70%">
    <div class = "referral-credit-inner-circle"></div>
  </div>
</div>


问:
How to rotate an image on command using Codename One's Transform class?
I am currently doing a school project where we are creating an Asteroids game using Codename One. My current functionality works well, except for when it comes to rotating the image of the ship. Using the Transform class has been ineffective; the image does not rotate, no matter how the Transform is applied or the image is drawn.

Here is a sample portion of the code used to turn:

```<code>public void turnRight() //Rotates the ship 5 degrees clockwise
{
    if (direction==355)
        direction = 0;
    else
        direction+=5;
    Transform tmpTransform = Transform.makeIdentity();
    theImage.getGraphics().getTransform(tmpTransform);
    tmpTransform.rotate((float)Math.toRadians(5), x, y);
    theImage.getGraphics().setTransform(tmpTransform);
    theImage.getGraphics().drawImage(shipPic, 0, 0);
}
</code>```

Where:

theImage is a mutable Image (100x100)

shipPic is an Image created via Image.createImage(String path)

In addition, I have tried using the draw(Graphics g, Point p) method and passing theImage.getGraphics(), as well as passing shipPic.getGraphics()
I am at a loss, and Codename One's documentation on the subject is unhelpful.

Could I get some assistance, please?

答:
You need to use one graphics object so something like this:

Graphics g = theImage.getGraphics();

Would be more correct. You also must test for transform support when rendering onto an image as low level graphics isn't always portable to all OS's in all surfaces. A good example is iOS where rendering onto an image uses a completely different low level implementation than the display rendering.

Normally I would render directly to the display as that is hardware accelerated on modern devices and images are often implemented in software.

About the documentation, did you read the graphics section in the developer guide?

It should contain explanations of everything and if something is missing there is search. If you still can't find something and figure it out by yourself notice you can also edit the docs and help us improve them.

Body:
I am currently doing a school project where we are creating an Asteroids game using Codename One. My current functionality works well, except for when it comes to rotating the image of the ship. Using the Transform class has been ineffective; the image does not rotate, no matter how the Transform is applied or the image is drawn.

Here is a sample portion of the code used to turn:

public void turnRight() //Rotates the ship 5 degrees clockwise
{
    if (direction==355)
        direction = 0;
    else
        direction+=5;
    Transform tmpTransform = Transform.makeIdentity();
    theImage.getGraphics().getTransform(tmpTransform);
    tmpTransform.rotate((float)Math.toRadians(5), x, y);
    theImage.getGraphics().setTransform(tmpTransform);
    theImage.getGraphics().drawImage(shipPic, 0, 0);
}

Where:

theImage is a mutable Image (100x100)

shipPic is an Image created via Image.createImage(String path)

In addition, I have tried using the draw(Graphics g, Point p) method and passing theImage.getGraphics(), as well as passing shipPic.getGraphics()
I am at a loss, and Codename One's documentation on the subject is unhelpful.

Could I get some assistance, please?


问:
How can I make this Oracle SQL query More efficient and less redundant to avoid a "snapshot" error on large datasets?
I'm trying to improve my skills querying large data sets.

I want payments during a specific date range with an 'xyz' paycode,
where the "id1" is not 0 and not null, and if there are more than 13 payments to a specific "id1" This should be in the result of my query.

I feel like I'm being redundant querying the payment table twice, but I'm not sure how to get the id1 count and the payments with the specific paycode in a single query.

If I run this on a lot of data it's extremely slow and will not complete. I get a "snapshot" error.

All the table / data relations are indicated correctly in my joins / queries below, but how can I make this more elegant and more performant?

```<code>SELECT
    emp.emp_fname first_name,
    emp.emp_lname last_name,
    pmt.id1,
    pmt.id2,
    pmt.pay_date,
    pmt.pay_key,
    pmt.check_num,
    case.file_num
FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

    /*join on allotments where pay_key matches and allotment pay_code is xyz*/
    INNER JOIN allotment alt ON
        upper(TRIM(alt.deleted) ) = 'N'
    AND
        alt.pay_code = 'xyz'
    AND
        alt.pay_key = pmt.pay_key
   /*join on case to return the requested file-num*/
    INNER JOIN case ON case.event_num = alt.event_num
  /*join on emp to return payee / employee name */
    INNER JOIN  emp ON emp.event_num = case.event_num;
</code>```

答:
some initial ideas

1.) remove trunc on payment.pay_date as this will disable index usage on this column. if no index on this column add one.

```<code>trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
</code>```

make it

```<code>payment.pay_date BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')+(86399/86400)
</code>```

2.) remove distinct on the query on the inside of the IN

```<code>SELECT /*DISTINCT*/ pay_key FROM allotment WHERE pay_code = 'xyz'
</code>```

make sure there is an index on pay_code as well. In fact any reference directly to pay_code = 'xyz' make sure there is an index on that column.

Without going into complete detail put an index on any column that has high selectevity, ie < 10% of rows. Combine these columns into the same index on the same table.

Remove any function on a column as this renders the index useless.

3.) Add a having clause to this part of your query to stop returning data that you just want to filter out anyway

```<code>            SELECT id1
            FROM payment pmt
            WHERE pay_key IN (SELECT pay_key
                              FROM allotment
                              WHERE pay_code = 'xyz'
                     )
                AND id1 <> 0
                AND id1 IS NOT NULL
                AND pmt.pay_date BETWEEN TO_DATE('01-JUL-17') AND
                                       TO_DATE('01-OCT-17')+(86399/86400)
                AND upper(TRIM(deleted) ) = 'N'
            GROUP BY id1
            having  count(*)>13
</code>```

Body:
I'm trying to improve my skills querying large data sets.

I want payments during a specific date range with an 'xyz' paycode,
where the "id1" is not 0 and not null, and if there are more than 13 payments to a specific "id1" This should be in the result of my query.

I feel like I'm being redundant querying the payment table twice, but I'm not sure how to get the id1 count and the payments with the specific paycode in a single query.

If I run this on a lot of data it's extremely slow and will not complete. I get a "snapshot" error.

All the table / data relations are indicated correctly in my joins / queries below, but how can I make this more elegant and more performant?

SELECT
    emp.emp_fname first_name,
    emp.emp_lname last_name,
    pmt.id1,
    pmt.id2,
    pmt.pay_date,
    pmt.pay_key,
    pmt.check_num,
    case.file_num
FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

    /*join on allotments where pay_key matches and allotment pay_code is xyz*/
    INNER JOIN allotment alt ON
        upper(TRIM(alt.deleted) ) = 'N'
    AND
        alt.pay_code = 'xyz'
    AND
        alt.pay_key = pmt.pay_key
   /*join on case to return the requested file-num*/
    INNER JOIN case ON case.event_num = alt.event_num
  /*join on emp to return payee / employee name */
    INNER JOIN  emp ON emp.event_num = case.event_num;

Body:
some initial ideas

1.) remove trunc on payment.pay_date as this will disable index usage on this column. if no index on this column add one.

trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')

make it

payment.pay_date BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')+(86399/86400)

2.) remove distinct on the query on the inside of the IN

SELECT /*DISTINCT*/ pay_key FROM allotment WHERE pay_code = 'xyz'

make sure there is an index on pay_code as well. In fact any reference directly to pay_code = 'xyz' make sure there is an index on that column.

Without going into complete detail put an index on any column that has high selectevity, ie < 10% of rows. Combine these columns into the same index on the same table.

Remove any function on a column as this renders the index useless.

3.) Add a having clause to this part of your query to stop returning data that you just want to filter out anyway

            SELECT id1
            FROM payment pmt
            WHERE pay_key IN (SELECT pay_key
                              FROM allotment
                              WHERE pay_code = 'xyz'
                     )
                AND id1 <> 0
                AND id1 IS NOT NULL
                AND pmt.pay_date BETWEEN TO_DATE('01-JUL-17') AND
                                       TO_DATE('01-OCT-17')+(86399/86400)
                AND upper(TRIM(deleted) ) = 'N'
            GROUP BY id1
            having  count(*)>13


问:
how to scroll table horizontally in android
I am trying to implement table layout in android.I have table Header and row designed in one xml file and am passing data using adapter.So What is happening is I got scrolling horizontally but with multiple table header repeating on each row.
What I want to achieve is table header should be seen only once and all the rows below it should scroll along with table header.

Here's my xml file

```<code><?xml version="1.0" encoding="utf-8"?>

<HorizontalScrollView  android:id="@+id/horizontalView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:scrollbars="horizontal|vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="left"
    android:stretchColumns="*"
    android:divider="@color/black"
    android:showDividers="middle"
    >
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        >

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Type"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Fare"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Tax"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Airline Pnr"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"

            android:text="Ticekt Numner"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"

            android:text="Cancel"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />
    </TableRow>
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        >

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:textColor="@color/black"
            android:textSize="18sp"
            android:id="@+id/name"/>
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/type"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/fare"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/tax"
            android:textColor="@color/black"
            android:textSize="18sp" />
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/air_pnr"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:id="@+id/ticket"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <CheckBox
        android:id="@+id/check_bx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="CANCEL" />
    </TableRow>

   </TableLayout>
   </HorizontalScrollView>
</code>```

And here's the image what it looks likescrolling table

UPDATE (2) HERE's Adapter Code

```<code>public class Flight_cancel_Adapter extends BaseAdapter {
Context context;
public static ArrayList<Flight_cancel_Details> rowItems;
public static int available_seats;
public static PolicyAdapter adapter;
int TOTAL;
public static ArrayList<String> arraySeat=new ArrayList<String>();

    Flight_cancel_Adapter(Context context,  ArrayList<Flight_cancel_Details> rowItems) {

    this.context = context;
    this.rowItems = rowItems;

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

@Override
public Object getItem(int position) {
    return rowItems.get(position);
}

@Override
public long getItemId(int position)
{
    return rowItems.indexOf(getItem(position));
}

/* private view holder class */
private class ViewHolder {
    TextView type;
    TextView fare;
    TextView tax;
    TextView air_pnr;
    TextView ticket;
    TextView namee;
    CheckBox box;

}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    final ViewHolder holder;
    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.test, null);
        holder = new ViewHolder();
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.namee = (TextView) convertView.findViewById(R.id.name);
    holder.type = (TextView) convertView.findViewById(R.id.type);
    holder.fare = (TextView) convertView.findViewById(R.id.fare);
    holder.tax = (TextView) convertView.findViewById(R.id.tax);
    holder.air_pnr = (TextView) convertView.findViewById(R.id.air_pnr);
    holder.ticket = (TextView) convertView.findViewById(R.id.ticket);
    holder.box = (CheckBox) convertView.findViewById(R.id.check_bx);
    holder.box.setTag(position);

    try
    {
        final Flight_cancel_Details row_pos = rowItems.get(position);
        String name=String.valueOf(row_pos.getName());
        String typ=String.valueOf(row_pos.gettypes());
        String far=String.valueOf(row_pos.getfares());
        String tax=String.valueOf(row_pos.gettax());
        String pnr=String.valueOf(row_pos.getair_pnr());
        String ticket=String.valueOf(row_pos.getticket());

        System.out.print("ROW POS-"+row_pos.getStatus());
        if(row_pos.getStatus().equals("CANCELLED"))
        {
            holder.namee.setText(name);
            holder.type.setText(typ);
            holder.fare.setText(far);
            holder.tax.setText(tax);
            holder.air_pnr.setText(pnr);
            holder.ticket.setText(ticket);

            holder.box.setEnabled(false);
            holder.box.setText("CANCELLED");

        }else {

            holder.namee.setText(name);
            holder.type.setText(typ);
            holder.fare.setText(far);
            holder.tax.setText(tax);
            holder.air_pnr.setText(pnr);
            holder.ticket.setText(ticket);

            holder.box.setEnabled(true);
            holder.box.setText("CANCEL");
        }
        if(row_pos.getTarvel_Status().equals("TRAVELLED"))
        {
            holder.namee.setText(name);
            holder.type.setText(typ);
            holder.fare.setText(far);
            holder.tax.setText(tax);
            holder.air_pnr.setText(pnr);
            holder.ticket.setText(ticket);

        }

    }
    catch (Exception e)
    {
        Log.e("BUS_CANCEL_ADAP ERROR:", e.getMessage());
    }
    convertView.setTag(holder);

    holder.box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           if(isChecked) {
               int position = (int) buttonView.getTag();
               System.out.println("--CLICKED--" + position);
               String contactId = (holder.air_pnr.getText().toString());
               System.out.println("--VALUE--" + contactId);
               arraySeat.add(contactId);
           }
           else
               {
                   int position = (int) buttonView.getTag();
                   System.out.println("--UNCHEKED--" + position);
                   String contactId = (holder.air_pnr.getText().toString());
                   System.out.println("--UNCHEKED VALUE--" + contactId);
                   arraySeat.remove(contactId);
               }
        }
    });

    return convertView;

}
}
</code>```

答:
Use Recyclerview for horizontal scrollview for a better performance

test.xml

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

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAllCaps="false"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:textStyle="bold|italic" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="name"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:id="@+id/name"/>
    </LinearLayout>
</code>```

recyclerview.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.RecyclerView  android:id="@+id/horizontalView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dip"
    android:scrollbars="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:listitem="@layout/layout">
</android.support.v7.widget.RecyclerView>
</code>```

Body:
I am trying to implement table layout in android.I have table Header and row designed in one xml file and am passing data using adapter.So What is happening is I got scrolling horizontally but with multiple table header repeating on each row.
What I want to achieve is table header should be seen only once and all the rows below it should scroll along with table header.

Here's my xml file

<?xml version="1.0" encoding="utf-8"?>

<HorizontalScrollView  android:id="@+id/horizontalView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:scrollbars="horizontal|vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="left"
    android:stretchColumns="*"
    android:divider="@color/black"
    android:showDividers="middle"
    >
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        >

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Type"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Fare"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Tax"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:text="Airline Pnr"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"

            android:text="Ticekt Numner"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"

            android:text="Cancel"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold|italic" />
    </TableRow>
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        >

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"

            android:textColor="@color/black"
            android:textSize="18sp"
            android:id="@+id/name"/>
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/type"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/fare"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/tax"
            android:textColor="@color/black"
            android:textSize="18sp" />
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/air_pnr"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:id="@+id/ticket"
            android:textColor="@color/black"
            android:textSize="18sp" />

        <CheckBox
        android:id="@+id/check_bx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="CANCEL" />
    </TableRow>

   </TableLayout>
   </HorizontalScrollView>

And here's the image what it looks likescrolling table

UPDATE (2) HERE's Adapter Code

public class Flight_cancel_Adapter extends BaseAdapter {
Context context;
public static ArrayList<Flight_cancel_Details> rowItems;
public static int available_seats;
public static PolicyAdapter adapter;
int TOTAL;
public static ArrayList<String> arraySeat=new ArrayList<String>();

    Flight_cancel_Adapter(Context context,  ArrayList<Flight_cancel_Details> rowItems) {

    this.context = context;
    this.rowItems = rowItems;

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

@Override
public Object getItem(int position) {
    return rowItems.get(position);
}

@Override
public long getItemId(int position)
{
    return rowItems.indexOf(getItem(position));
}

/* private view holder class */
private class ViewHolder {
    TextView type;
    TextView fare;
    TextView tax;
    TextView air_pnr;
    TextView ticket;
    TextView namee;
    CheckBox box;

}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    final ViewHolder holder;
    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.test, null);
        holder = new ViewHolder();
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.namee = (TextView) convertView.findViewById(R.id.name);
    holder.type = (TextView) convertView.findViewById(R.id.type);
    holder.fare = (TextView) convertView.findViewById(R.id.fare);
    holder.tax = (TextView) convertView.findViewById(R.id.tax);
    holder.air_pnr = (TextView) convertView.findViewById(R.id.air_pnr);
    holder.ticket = (TextView) convertView.findViewById(R.id.ticket);
    holder.box = (CheckBox) convertView.findViewById(R.id.check_bx);
    holder.box.setTag(position);

    try
    {
        final Flight_cancel_Details row_pos = rowItems.get(position);
        String name=String.valueOf(row_pos.getName());
        String typ=String.valueOf(row_pos.gettypes());
        String far=String.valueOf(row_pos.getfares());
        String tax=String.valueOf(row_pos.gettax());
        String pnr=String.valueOf(row_pos.getair_pnr());
        String ticket=String.valueOf(row_pos.getticket());

        System.out.print("ROW POS-"+row_pos.getStatus());
        if(row_pos.getStatus().equals("CANCELLED"))
        {
            holder.namee.setText(name);
            holder.type.setText(typ);
            holder.fare.setText(far);
            holder.tax.setText(tax);
            holder.air_pnr.setText(pnr);
            holder.ticket.setText(ticket);

            holder.box.setEnabled(false);
            holder.box.setText("CANCELLED");

        }else {

            holder.namee.setText(name);
            holder.type.setText(typ);
            holder.fare.setText(far);
            holder.tax.setText(tax);
            holder.air_pnr.setText(pnr);
            holder.ticket.setText(ticket);

            holder.box.setEnabled(true);
            holder.box.setText("CANCEL");
        }
        if(row_pos.getTarvel_Status().equals("TRAVELLED"))
        {
            holder.namee.setText(name);
            holder.type.setText(typ);
            holder.fare.setText(far);
            holder.tax.setText(tax);
            holder.air_pnr.setText(pnr);
            holder.ticket.setText(ticket);

        }

    }
    catch (Exception e)
    {
        Log.e("BUS_CANCEL_ADAP ERROR:", e.getMessage());
    }
    convertView.setTag(holder);

    holder.box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           if(isChecked) {
               int position = (int) buttonView.getTag();
               System.out.println("--CLICKED--" + position);
               String contactId = (holder.air_pnr.getText().toString());
               System.out.println("--VALUE--" + contactId);
               arraySeat.add(contactId);
           }
           else
               {
                   int position = (int) buttonView.getTag();
                   System.out.println("--UNCHEKED--" + position);
                   String contactId = (holder.air_pnr.getText().toString());
                   System.out.println("--UNCHEKED VALUE--" + contactId);
                   arraySeat.remove(contactId);
               }
        }
    });

    return convertView;

}
}

Body:
Use Recyclerview for horizontal scrollview for a better performance

test.xml

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

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAllCaps="false"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:textStyle="bold|italic" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="name"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:id="@+id/name"/>
    </LinearLayout>

recyclerview.xml

 <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.RecyclerView  android:id="@+id/horizontalView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dip"
    android:scrollbars="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:listitem="@layout/layout">
</android.support.v7.widget.RecyclerView>


问:
Does an RSpec2 matcher for matching Hashes exist?
Note to future readers: think RSpec does not consider your Hashes equal? One might be an OrderedHash, but from the regular RSpec output you can't tell. This was the problem that prompted this post.

Original question:

Suppose I have a spec where I want to test that a method generates the appropriate Hash.

```<code>it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.should == expected
end
</code>```

This often fails, because different Hashes with the same key-value pairs may return their pairs in a different ordered. Results look like:

```<code>Failure/Error: subject.some_method_that_should_generate_the_hash.should == expected
expected: {:foo => 1, 'baz' => 2},
     got: {'baz' => 2, :foo => 1}
</code>```

For arrays, this is solved using the =~ operator. However, that does not work for Hashes. For now, I've resorted to

```<code>it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.each {|k,v|
    v.should == expected[k]
  }
end
</code>```

but that seems unnecessarily verbose. I expect there to be an obvious solution for this. Am I overlooking something in the docs or doesn't RSpec have a proper Matcher for orderless Hash equality?

答:
I believe the eql? method checks only that the two hashes have the same content
So IIRC in Rspec2 you can do:

```<code>    expected = {:foo => 1, 'baz' => 2}
    expected.should be_eql({'baz' => 2, :foo => 1})
</code>```

And the test should pass

Body:
Note to future readers: think RSpec does not consider your Hashes equal? One might be an OrderedHash, but from the regular RSpec output you can't tell. This was the problem that prompted this post.

Original question:

Suppose I have a spec where I want to test that a method generates the appropriate Hash.

it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.should == expected
end

This often fails, because different Hashes with the same key-value pairs may return their pairs in a different ordered. Results look like:

Failure/Error: subject.some_method_that_should_generate_the_hash.should == expected
expected: {:foo => 1, 'baz' => 2},
     got: {'baz' => 2, :foo => 1}

For arrays, this is solved using the =~ operator. However, that does not work for Hashes. For now, I've resorted to

it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.each {|k,v|
    v.should == expected[k]
  }
end

but that seems unnecessarily verbose. I expect there to be an obvious solution for this. Am I overlooking something in the docs or doesn't RSpec have a proper Matcher for orderless Hash equality?

Body:
I believe the eql? method checks only that the two hashes have the same content
So IIRC in Rspec2 you can do:

    expected = {:foo => 1, 'baz' => 2}
    expected.should be_eql({'baz' => 2, :foo => 1})

And the test should pass


问:
RecyclerView Infinite Scroll listener being called twice
I have a RecyclerView that im trying to implement an infinite scroll feature into. The issue is, the code inside the if statements in the OnScrolled method is being executed twice. Heres my current code:

```<code>public abstract class InfiniteScroll extends RecyclerView.OnScrollListener {

private LinearLayoutManager mLayoutManager;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 1;

public InfiniteScroll(LinearLayoutManager layoutManager) {
    mLayoutManager = layoutManager;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

    visibleItemCount = recyclerView.getChildCount();
    totalItemCount = mLayoutManager.getItemCount();
    firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
        if (totalItemCount > previousTotal) {
            loading = false;
            previousTotal = totalItemCount;
        }
    }
    if (!loading && (totalItemCount - visibleItemCount)
            <= (firstVisibleItem + visibleThreshold)) {
        // End has been reached

        // Do something
        current_page++;
        Log.d("moreitems", "why is this being called twice?");
        loadMore(current_page);

        loading = true;
    }
}

public abstract void loadMore(int current_page);
}
</code>```

This code was posted as an answer to a separate SO question, and other examples seem to function similar, but I still get the loadMore() method executing twice when reaching the bottom of the RecyclerView, and im not sure why.

答:
```<code>if (layoutManager.findLastCompletelyVisibleItemPosition() ==
recyclerAdapter.getItemCount() - 1) {
     //load more items code is here
}
</code>```

This will work.

Body:
I have a RecyclerView that im trying to implement an infinite scroll feature into. The issue is, the code inside the if statements in the OnScrolled method is being executed twice. Heres my current code:

public abstract class InfiniteScroll extends RecyclerView.OnScrollListener {

private LinearLayoutManager mLayoutManager;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 1;

public InfiniteScroll(LinearLayoutManager layoutManager) {
    mLayoutManager = layoutManager;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

    visibleItemCount = recyclerView.getChildCount();
    totalItemCount = mLayoutManager.getItemCount();
    firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
        if (totalItemCount > previousTotal) {
            loading = false;
            previousTotal = totalItemCount;
        }
    }
    if (!loading && (totalItemCount - visibleItemCount)
            <= (firstVisibleItem + visibleThreshold)) {
        // End has been reached

        // Do something
        current_page++;
        Log.d("moreitems", "why is this being called twice?");
        loadMore(current_page);

        loading = true;
    }
}

public abstract void loadMore(int current_page);
}

This code was posted as an answer to a separate SO question, and other examples seem to function similar, but I still get the loadMore() method executing twice when reaching the bottom of the RecyclerView, and im not sure why.

Body:
if (layoutManager.findLastCompletelyVisibleItemPosition() ==
recyclerAdapter.getItemCount() - 1) {
     //load more items code is here
}

This will work.


问:
Getting values from select elements in *ngFor
Let's say I have this template:

```<code><div *ngFor="let div of divs">
  <select #ref (change)="print(ref)">
    <option *ngFor = "let opt of options">{{opt}}</option>
  </select>
</div>
</code>```

and this component:

```<code>export class AppComponent {
  divs = ["1", "2", "3"];
  options = ["opt1", "opt2", "opt3"];

  print(value){
    console.log(value.value);
  };
}
</code>```

Now I can get the value of each individual select element whenever a new option is selected. However, with this method I'm creating a template reference variable on the select (#ref) in the *ngFor loop, which means I will have 3 selects with the same reference at the end of the loop. It says the following on the angular.io website:

"Do not define the same variable name more than once in the same template. The runtime value will be unpredictable."

Therefore, I'm assuming it's a bad idea to use this method. My question is if there is another way to do this?

答:
I don't think, there is need of local varible just for getting selected values :

Just use (change)="print($event.target.value)" and [value]='opt'

```<code><div *ngFor="let div of divs">
  <select (change)="print(div ,$event.target.value)">
    <option *ngFor = "let opt of options" [value]='opt'>{{opt}}</option>
  </select>
</div>

print(value_of , value) {
   console.log('value of' , value_of , 'is' , value );
}
</code>```

Body:
Let's say I have this template:

  <select #ref (change)="print(ref)">
    <option *ngFor = "let opt of options">{{opt}}</option>
  </select>

and this component:

export class AppComponent {
  divs = ["1", "2", "3"];
  options = ["opt1", "opt2", "opt3"];

  print(value){
    console.log(value.value);
  };
}

Now I can get the value of each individual select element whenever a new option is selected. However, with this method I'm creating a template reference variable on the select (#ref) in the *ngFor loop, which means I will have 3 selects with the same reference at the end of the loop. It says the following on the angular.io website:

"Do not define the same variable name more than once in the same template. The runtime value will be unpredictable."

Therefore, I'm assuming it's a bad idea to use this method. My question is if there is another way to do this?

Body:
I don't think, there is need of local varible just for getting selected values :

Just use (change)="print($event.target.value)" and [value]='opt'

<div *ngFor="let div of divs">
  <select (change)="print(div ,$event.target.value)">
    <option *ngFor = "let opt of options" [value]='opt'>{{opt}}</option>
  </select>
</div>

print(value_of , value) {
   console.log('value of' , value_of , 'is' , value );
}