问:
ORA-03113: end-of-file on communication channel after ~ 2 hours and 10 mins
I have a sql script with a procedure. I run it using
sqlplus -s @script.sql logfile.log myparam1 myparam2

But after ~ 2 hour and 10 mins, my script ends with

```<code>ERROR:
ORA-03114: not connected to ORACLE

DECLARE
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 12345
Session ID: 33 Serial number: 54321
</code>```

I have following tcp settings

```<code>-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_time (which is two hours)
7200
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9
</code>```

When the script was running, I checked that TCP connection was established at my end , but on the database side (database server machine) there was no such connection.

My theory is that somehow database server is dropping the connection. And when my system sends first keepalive probe after 2 hours (7200 seconds), it finds that connection is no more active and closes the connection and script returns.

I am unable to understand why would a database system drop a connection?
Are there any settings at database end to increase verbosity? Or could this be related to some firewall settings? Also, in 2 hours and 10 mins, we can guess that 2 hours portion is coming from tcp_keepalive_time, what would be 10 mins portion. Any database side retries?

EDIT: DBA and I looked at the issue, I see the TCP connection as ESTABLISHED at my end and he didn't see any connection coming from my side.

答:
We had something similar where our firewall was dropping our Pro*C connections after about two hours if we did not have any activity in that period.  Our solution was to do a:

```<code>select 1 from dual;
</code>```

every 15 minutes on each database connection to keep things active.

If I recall correctly, the tcp keep alive times you refer to above are only used if the connection has a setsockopt call with SO_KEEPALIVE.  Since the actual connection with Oracle is managed by Oracle, we have no way of knowing if it is set or not.

In looking at this, I saw on the web a few places (this and this) a reference to sqlnet.expire_time=minutes_to_check  in the $ORACLE_HOME/network/admin/sqlnet.ora file.  They say:

With this parameter in place, after 10 minutes of inactivity, the
  server send a small 10 bytes probe packet to the client. If this
  packet is not acknowledge, the connection will be closed...

The next time I have our DBA's attention, I will have to get them to change this value and see how that affects things.  Later in the second link, they say:

If the SQLNET.EXPIRE_TIME is less than the FW connection idle
  time-out, then the firewall will consider this packet as activity, and
  the idle time-out (firewall blackout) will never happen until both the
  client and the server processes are alive.

I expect this is exactly what we need.

Body:
I have a sql script with a procedure. I run it using
sqlplus -s @script.sql logfile.log myparam1 myparam2

But after ~ 2 hour and 10 mins, my script ends with

ERROR:
ORA-03114: not connected to ORACLE

DECLARE
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 12345
Session ID: 33 Serial number: 54321

I have following tcp settings

-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_time (which is two hours)
7200
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9

When the script was running, I checked that TCP connection was established at my end , but on the database side (database server machine) there was no such connection.

My theory is that somehow database server is dropping the connection. And when my system sends first keepalive probe after 2 hours (7200 seconds), it finds that connection is no more active and closes the connection and script returns.

I am unable to understand why would a database system drop a connection?
Are there any settings at database end to increase verbosity? Or could this be related to some firewall settings? Also, in 2 hours and 10 mins, we can guess that 2 hours portion is coming from tcp_keepalive_time, what would be 10 mins portion. Any database side retries?

EDIT: DBA and I looked at the issue, I see the TCP connection as ESTABLISHED at my end and he didn't see any connection coming from my side.

Body:
We had something similar where our firewall was dropping our Pro*C connections after about two hours if we did not have any activity in that period.  Our solution was to do a:

select 1 from dual;

every 15 minutes on each database connection to keep things active.

If I recall correctly, the tcp keep alive times you refer to above are only used if the connection has a setsockopt call with SO_KEEPALIVE.  Since the actual connection with Oracle is managed by Oracle, we have no way of knowing if it is set or not.

In looking at this, I saw on the web a few places (this and this) a reference to sqlnet.expire_time=minutes_to_check  in the $ORACLE_HOME/network/admin/sqlnet.ora file.  They say:

With this parameter in place, after 10 minutes of inactivity, the
  server send a small 10 bytes probe packet to the client. If this
  packet is not acknowledge, the connection will be closed...

The next time I have our DBA's attention, I will have to get them to change this value and see how that affects things.  Later in the second link, they say:

If the SQLNET.EXPIRE_TIME is less than the FW connection idle
  time-out, then the firewall will consider this packet as activity, and
  the idle time-out (firewall blackout) will never happen until both the
  client and the server processes are alive.

I expect this is exactly what we need.


来源: stackexchange

问:
Can't customize the appearance of EditText select handle / anchor on landscape
I am having a hard time customizing the EditText select handle. I am following this thread:

How to change color / appearance of EditText select handle / anchor?

It looks like pretty straight forward. Yet, I can't get it to work on landscape. Can anyone spot what I am doing wrong? I pretty much pasted the same code on a test activity but the anchor handles' are always the same. I tried using styles as suggested and programmatically. Still I always get the same default blue anchors :(

I am on Nougat not sure if makes any difference.

Test activity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyCustomTheme);
    setContentView(R.layout.activity_main);
    final EditText editText = (EditText) findViewById(R.id.edit1);
    // tried programatically too and no success
    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight =
                editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter =
                editor.getClass().getDeclaredField("mSelectHandleCenter");
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
        fSelectHandleLeft.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleRight.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleCenter.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
    } catch (final Exception e) {
        Log.d("CUSTOM_ANCHORS", e.toString());
    }
}
</code>```

Layout:

```<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">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Hello World"
        android:textSize="20sp" />

</LinearLayout>
</code>```

My styles:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="MyCustomTheme" parent="@style/AppTheme">
    <item name="android:textSelectHandle">@drawable/small_rect</item>
    <item name="android:textSelectHandleLeft">@drawable/small_rect</item>
    <item name="android:textSelectHandleRight">@drawable/small_rect</item>
</style>
</code>```

the drawable (small_rect.xml)

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="20dp"
        android:height="20dp" />
    <gradient
        android:angle="90"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:startColor="#6586F0" />
    <corners android:radius="0dp" />
</shape>
</code>```

the result:

答:
I think that your custom EditText handle can be implemented with just xml.

Define the handle's style in your styles.xml:

```<code><style name="CustomSelectHandle">
    <item name="android:textSelectHandle">@drawable/small_rect</item>
    <item name="android:textSelectHandleLeft">@drawable/small_rect</item>
    <item name="android:textSelectHandleRight">@drawable/small_rect</item>
</style>
</code>```

Add the style attribute to your EditText:

```<code><EditText
    android:id="@+id/edit1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="Hello World"
    style="@style/CustomSelectHandle"
    android:textSize="20sp" />
</code>```

I just ran a quick test of this on a KitKat device, and the custom handles were there.

Update: I duplicated the problem with landscape mode on the KitKat phone. However, the bug doesn't affect all devices. In particular, when I ran the code in landscape mode on a tablet, the custom handles worked fine.

Additional Observation: The EditText that I tested this on also had a background drawable. This drawable appears as expected in both portrait and landscape mode, on both phones and tablets. However, if I actually edit the field in landscape mode on a phone, the custom background disappears, and the field has a plain white background until I leave edit mode.

Conjecture: It looks like Android runs through a different code path (that ignores custom formatting) when editing fields in landscape mode on small devices. When a soft keyboard is displayed in landscape mode, that doesn't leave much room to display the field being edited on a phone. So maybe the developers made a compromise at some point (that it's better to display a very plain text field for the user to edit, than to risk having the entire field obscured). Without delving into the source code, that's my best guess for what's going on here...

ContentLicense: CC BY-SA 3.0

Body:
I am having a hard time customizing the EditText select handle. I am following this thread:

How to change color / appearance of EditText select handle / anchor?

It looks like pretty straight forward. Yet, I can't get it to work on landscape. Can anyone spot what I am doing wrong? I pretty much pasted the same code on a test activity but the anchor handles' are always the same. I tried using styles as suggested and programmatically. Still I always get the same default blue anchors :(

I am on Nougat not sure if makes any difference.

Test activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyCustomTheme);
    setContentView(R.layout.activity_main);
    final EditText editText = (EditText) findViewById(R.id.edit1);
    // tried programatically too and no success
    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight =
                editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter =
                editor.getClass().getDeclaredField("mSelectHandleCenter");
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
        fSelectHandleLeft.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleRight.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleCenter.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
    } catch (final Exception e) {
        Log.d("CUSTOM_ANCHORS", e.toString());
    }
}

Layout:

<?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">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Hello World"
        android:textSize="20sp" />

</LinearLayout>

My styles:

the drawable (small_rect.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="20dp"
        android:height="20dp" />
    <gradient
        android:angle="90"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:startColor="#6586F0" />
    <corners android:radius="0dp" />
</shape>

the result:

Body:
I think that your custom EditText handle can be implemented with just xml.

Define the handle's style in your styles.xml:

<style name="CustomSelectHandle">
    <item name="android:textSelectHandle">@drawable/small_rect</item>
    <item name="android:textSelectHandleLeft">@drawable/small_rect</item>
    <item name="android:textSelectHandleRight">@drawable/small_rect</item>
</style>

Add the style attribute to your EditText:

<EditText
    android:id="@+id/edit1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="Hello World"
    style="@style/CustomSelectHandle"
    android:textSize="20sp" />

I just ran a quick test of this on a KitKat device, and the custom handles were there.

Update: I duplicated the problem with landscape mode on the KitKat phone. However, the bug doesn't affect all devices. In particular, when I ran the code in landscape mode on a tablet, the custom handles worked fine.

Additional Observation: The EditText that I tested this on also had a background drawable. This drawable appears as expected in both portrait and landscape mode, on both phones and tablets. However, if I actually edit the field in landscape mode on a phone, the custom background disappears, and the field has a plain white background until I leave edit mode.

Conjecture: It looks like Android runs through a different code path (that ignores custom formatting) when editing fields in landscape mode on small devices. When a soft keyboard is displayed in landscape mode, that doesn't leave much room to display the field being edited on a phone. So maybe the developers made a compromise at some point (that it's better to display a very plain text field for the user to edit, than to risk having the entire field obscured). Without delving into the source code, that's my best guess for what's going on here...


问:
Good algorithm to convert timestamp to a shorter alphanumeric representation
What would be a good algorithm for taking a timestamp that contains year, month, day, hour, minute, second and convert it into a 7 digit or less(but consistent) alphanumeric representation. The alphanumeric representation won't distinguish between upper and lower case letters.

答:
Consider a higher than decimal numeral system. For example, the hexadecimal numeral system is base-16. Let's say in our new numeral system, we have digits 0-9, the lower-case alphabet (a-z) and the upper case alphabet (A-Z). This gives us 62 possible digits, so we can use a base-62 numeral system. Here's some Javascript code to do the conversion -

```<code>function createConverter() {
    var charRange = (start, end) => Array.from(Array(end-start),
                                         (v, i) => String.fromCharCode(i + start))

    var digits = charRange(48, 48+10)             // 0 to 9
                   .concat(charRange(97, 97+26))  // a to b
                   .concat(charRange(65, 65+26))  // A to B

    var base = digits.length

    return function(decimal) {
            var result = ""
            while (decimal >= base) {
                result = digits[decimal % base] + result
                decimal = parseInt(decimal / base)
            }
            result = digits[decimal] + result
            return result
        }
}

var convert = createConverter()
convert(parseInt(Date.now() / 1000)) // returns a 6-digit alphanumeric string
</code>```

charRange is just a utility arrow function to create a range of characters from ASCII codes

digits represents all the valid digits in our numeral system. You can add more valid digits (like special chars) to this list

base is the number (in decimal) of available digits

Output encoded in this base-62 numeral system will stay 6 digits long for more than 1,700 years.

EDIT: Realized Date.now() returns timestamp in milliseconds not seconds, so I've updated my answer to reflect that

ContentLicense: CC BY-SA 2.5

Body:
Consider a higher than decimal numeral system. For example, the hexadecimal numeral system is base-16. Let's say in our new numeral system, we have digits 0-9, the lower-case alphabet (a-z) and the upper case alphabet (A-Z). This gives us 62 possible digits, so we can use a base-62 numeral system. Here's some Javascript code to do the conversion -

function createConverter() {
    var charRange = (start, end) => Array.from(Array(end-start),
                                         (v, i) => String.fromCharCode(i + start))

    var digits = charRange(48, 48+10)             // 0 to 9
                   .concat(charRange(97, 97+26))  // a to b
                   .concat(charRange(65, 65+26))  // A to B

    var base = digits.length

    return function(decimal) {
            var result = ""
            while (decimal >= base) {
                result = digits[decimal % base] + result
                decimal = parseInt(decimal / base)
            }
            result = digits[decimal] + result
            return result
        }
}

var convert = createConverter()
convert(parseInt(Date.now() / 1000)) // returns a 6-digit alphanumeric string

charRange is just a utility arrow function to create a range of characters from ASCII codes

digits represents all the valid digits in our numeral system. You can add more valid digits (like special chars) to this list

base is the number (in decimal) of available digits

Output encoded in this base-62 numeral system will stay 6 digits long for more than 1,700 years.

EDIT: Realized Date.now() returns timestamp in milliseconds not seconds, so I've updated my answer to reflect that


问:
OpenCV3 installation on Mac
I tried to install OpenCV3 for Mac with the following command in terminal:

```<code>brew install opencv3 --with-contrib -with-ffmpeg
</code>```

It repeatedly gets stuck at this point:

```<code>cmake .. -DCMAKE_C_FLAGS_RELEASE=-DNDEBUG -DCMAKE_CXX_FLAGS_RELEASE=-DNDEBUG -DCMAKE
</code>```

Can someone please tell me how to fix this?

答:
I also had the exact same issue. Someone else had also reported this problem on the brew github, but they could also not reproduce the issue. In my case though, it would go a step further and get stuck after calling make for hours:

```<code>cmake .. -DCMAKE_C_FLAGS_RELEASE=-DNDEBUG -DCMAKE_CXX_FLAGS_RELEASE=-DNDEBUG -DCMAKE
make
</code>```

I went ahead and tracked the processes in the Activity Monitor on my Mac and found out that it kicks off a batch of clang processes in sequence on multiple threads. But I had several apps running that were robbing it of CPU and Memory resources. So I shut down Safari, Finder, IDEs (XCode, PyCharm) etc, and this time it did complete.

Solution: was to just let it run with as much CPU and memory overhead it needs. And with no other power-hungry apps running in the background, it finished in 25mins.

CMake Approach:
Your next best approach is to bypass using package manager, like brew, and follow the instructions given on PyImageSearch to build OpenCV manually using CMake:

Install dependencies like CMake, pkg-config (and possibly others...)

Clone OpenCV and OpenCV_Contrib git repos:

https://github.com/opencv/opencv

https://github.com/opencv/opencv_contrib

Checkout version [e.g. 3.2.0]

Make build directory inside opencv directory

Run CMake with the appropriate parameters for your system:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local/opencv3 \
-D PYTHON2_PACKAGES_PATH=/usr/local/lib/python2.7/site-packages \
-D PYTHON2_LIBRARY=/usr/local/opt/python/bin \
-D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers \
-D BUILD_OPENCV_PYTHON2=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D BUILD_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH=/Users/Salman_Naqvi/Downloads/opencv_contrib/modules ..

Compile using: make -j4

Install it on MacOS: make install

--> It'll be installed in the directory specified by: CMAKE_INSTALL_PREFIX=/usr/local/opencv3

Title: OpenCV3 installation on Mac

Body:
I tried to install OpenCV3 for Mac with the following command in terminal:

brew install opencv3 --with-contrib -with-ffmpeg

It repeatedly gets stuck at this point:

cmake .. -DCMAKE_C_FLAGS_RELEASE=-DNDEBUG -DCMAKE_CXX_FLAGS_RELEASE=-DNDEBUG -DCMAKE

Can someone please tell me how to fix this?

Body:
I also had the exact same issue. Someone else had also reported this problem on the brew github, but they could also not reproduce the issue. In my case though, it would go a step further and get stuck after calling make for hours:

cmake .. -DCMAKE_C_FLAGS_RELEASE=-DNDEBUG -DCMAKE_CXX_FLAGS_RELEASE=-DNDEBUG -DCMAKE
make

I went ahead and tracked the processes in the Activity Monitor on my Mac and found out that it kicks off a batch of clang processes in sequence on multiple threads. But I had several apps running that were robbing it of CPU and Memory resources. So I shut down Safari, Finder, IDEs (XCode, PyCharm) etc, and this time it did complete.

Solution: was to just let it run with as much CPU and memory overhead it needs. And with no other power-hungry apps running in the background, it finished in 25mins.

CMake Approach:
Your next best approach is to bypass using package manager, like brew, and follow the instructions given on PyImageSearch to build OpenCV manually using CMake:

Install dependencies like CMake, pkg-config (and possibly others...)

Clone OpenCV and OpenCV_Contrib git repos:

https://github.com/opencv/opencv

https://github.com/opencv/opencv_contrib

Checkout version [e.g. 3.2.0]

Make build directory inside opencv directory

Run CMake with the appropriate parameters for your system:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local/opencv3 \
-D PYTHON2_PACKAGES_PATH=/usr/local/lib/python2.7/site-packages \
-D PYTHON2_LIBRARY=/usr/local/opt/python/bin \
-D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers \
-D BUILD_OPENCV_PYTHON2=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D BUILD_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH=/Users/Salman_Naqvi/Downloads/opencv_contrib/modules ..

Compile using: make -j4

Install it on MacOS: make install

--> It'll be installed in the directory specified by: CMAKE_INSTALL_PREFIX=/usr/local/opencv3


问:
How to use Math.LN(x) in ActionScript 3
How to use Math.LN(x) in ActionScript 3?

I have a formula to convert:

```<code>17.867 * LN(x)-29.263
</code>```

How to write in ActionScript 3? I'm confused about how to write it.

What I've tried :

```<code>var Kc:Number;
var value_x:Number;

function enterFrameHandler () : void
{
    value_x=80;
    Kc=(17.867)*Math.LN10(value_x) - 29.263;
    value_Kc.text=String(Kc);
    trace(Kc);
    //y = 17.867ln(x) - 29.263//

}

enterFrameHandler();
</code>```

Getting error :

Error : Scene 1, Layer 'Layer 1', Frame 1, Line 7, Column 19 1195 :

  Attempted access of inaccessible method LN10 through a reference with
  static type Class.

答:
thanks for your replied @Organis  may be directly show  problem in my code

```<code>var Kc:Number;
var value_x:Number;

function enterFrameHandler () : void
{
    value_x=80;
    Kc=(17.867)*Math.LN10(value_x) - 29.263;
    value_Kc.text=String(Kc);
    trace(Kc);
    //y = 17.867ln(x) - 29.263//

}

enterFrameHandler();
</code>```

///get error Scene 1, Layer 'Layer 1', Frame 1, Line 7, Column 19   1195: Attempted access of inaccessible method LN10 through a reference with static type Class.//

Title: How to use Math.LN(x) in ActionScript 3

Body:
How to use Math.LN(x) in ActionScript 3?

I have a formula to convert:

17.867 * LN(x)-29.263

How to write in ActionScript 3? I'm confused about how to write it.

What I've tried :

var Kc:Number;
var value_x:Number;

function enterFrameHandler () : void
{
    value_x=80;
    Kc=(17.867)*Math.LN10(value_x) - 29.263;
    value_Kc.text=String(Kc);
    trace(Kc);
    //y = 17.867ln(x) - 29.263//

}

enterFrameHandler();

Getting error :

Error : Scene 1, Layer 'Layer 1', Frame 1, Line 7, Column 19 1195 :

  Attempted access of inaccessible method LN10 through a reference with
  static type Class.

Body:
thanks for your replied @Organis  may be directly show  problem in my code

var Kc:Number;
var value_x:Number;

function enterFrameHandler () : void
{
    value_x=80;
    Kc=(17.867)*Math.LN10(value_x) - 29.263;
    value_Kc.text=String(Kc);
    trace(Kc);
    //y = 17.867ln(x) - 29.263//

}

enterFrameHandler();

///get error Scene 1, Layer 'Layer 1', Frame 1, Line 7, Column 19   1195: Attempted access of inaccessible method LN10 through a reference with static type Class.//


问:
Authenticate App Services backend using Microsoft Graph token?
Edit:

I have added the "id_token" but still get an "Unauthorized" response.
Here is my login code:

```<code>PublicClientApplication myApp = new PublicClientApplication("My-AppID-From-App-Registration-Portal");
string[] scopes = new string[] { "User.Read" };
AuthenticationResult authenticationResult = await myApp.AcquireTokenAsync(scopes).ConfigureAwait(false);

JObject payload = new JObject();
payload["access_token"] = authenticationResult.AccessToken;
payload["id_token"] = authenticationResult.IdToken;

user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, payload);
</code>```

Original Post:

Is it possible to authenticate to a App Services backend using the token retrieved from Microsoft Graph?
I have already tried using this token and calling LoginAsync() with AzureActiveDirectory as the provider, this doesn't work.

```<code>JObject payload = new JObject();
payload["access_token"] = GraphAuthenticationHelper.TokenForUser;
user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);
</code>```

Is this possible?

答:
UPDATE: In my original answer, I said you cannot do this. But in reality, you can do this but it's a dangerous thing to do since anyone with a valid Microsoft Graph token could theoretically access your APIs. Before I walk you down that path, let me describe the "right" way to access the Microsoft Graph on behalf of your end user.

The right way to do this is to use the on-behalf-of flow in the mobile backend code to exchange the user's ID token for a Microsoft Graph token.  The flow looks like the following:

Client initiates a login with AAD using MSAL and sets the resource to the mobile backend (not the Graph). The result should be a set of tokens.

Client uses the mobile SDK to do a login with BOTH the access_token AND the id_token from #1.

Example code:

```<code>JObject payload = new JObject();
payload["access_token"] = {access_token.from.msal};
payload["id_token"] = {id_token.from.msal};
var user = await MobileService.LoginAsync(
    MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
    payload);
</code>```

The backend code exchanges the user's ID token (from the x-ms-token-aad-id-token request header) for a graph token. This token exchange is known as "on-behalf-of" and is documented here. I think this can be done using ADAL or MSAL libraries, but I wasn't able to find documentation. It's also simple enough that you could implement the HTTP protocol directly without too much trouble.

The backend uses the newly acquired MS Graph token and makes the graph API call.

You can also cache the graph token that you acquire on the backend so that each API call doesn't require more AAD API calls to do token exchange.

Body:
Edit:

I have added the "id_token" but still get an "Unauthorized" response.
Here is my login code:

PublicClientApplication myApp = new PublicClientApplication("My-AppID-From-App-Registration-Portal");
string[] scopes = new string[] { "User.Read" };
AuthenticationResult authenticationResult = await myApp.AcquireTokenAsync(scopes).ConfigureAwait(false);

JObject payload = new JObject();
payload["access_token"] = authenticationResult.AccessToken;
payload["id_token"] = authenticationResult.IdToken;

user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, payload);

Original Post:

Is it possible to authenticate to a App Services backend using the token retrieved from Microsoft Graph?
I have already tried using this token and calling LoginAsync() with AzureActiveDirectory as the provider, this doesn't work.

JObject payload = new JObject();
payload["access_token"] = GraphAuthenticationHelper.TokenForUser;
user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);

Is this possible?

Body:
UPDATE: In my original answer, I said you cannot do this. But in reality, you can do this but it's a dangerous thing to do since anyone with a valid Microsoft Graph token could theoretically access your APIs. Before I walk you down that path, let me describe the "right" way to access the Microsoft Graph on behalf of your end user.

The right way to do this is to use the on-behalf-of flow in the mobile backend code to exchange the user's ID token for a Microsoft Graph token.  The flow looks like the following:

Client initiates a login with AAD using MSAL and sets the resource to the mobile backend (not the Graph). The result should be a set of tokens.

Client uses the mobile SDK to do a login with BOTH the access_token AND the id_token from #1.

Example code:

JObject payload = new JObject();
payload["access_token"] = {access_token.from.msal};
payload["id_token"] = {id_token.from.msal};
var user = await MobileService.LoginAsync(
    MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
    payload);

The backend code exchanges the user's ID token (from the x-ms-token-aad-id-token request header) for a graph token. This token exchange is known as "on-behalf-of" and is documented here. I think this can be done using ADAL or MSAL libraries, but I wasn't able to find documentation. It's also simple enough that you could implement the HTTP protocol directly without too much trouble.

The backend uses the newly acquired MS Graph token and makes the graph API call.

You can also cache the graph token that you acquire on the backend so that each API call doesn't require more AAD API calls to do token exchange.


问:
Visual Studio 2008 projects from Visual Studio 2010 without conversion
Is there a way?
Can I use and build Visual Studio 2008 projects from Visual Studio 2010 without conversion?

I found this explanation:

http://blogs.msdn.com/b/visualstudio/archive/2010/03/15/why-does-visual-studio-2010-convert-my-projects.aspx

Is there any "hack" for this? :)

In my team, we need this in order to work on same VS version of project(source is on svn) and from different IDE's.

答: Fairly sure that that's not possible. But possibly you could have two project/solution files linking the exact same files, one called xxx8.sln and the other xxx10.sln and then you could use the correct one according to your needs. If you make a point of only adding things in the 2008 one, you could just do a new conversion when needed. Otherwise maybe you could write a small tool to copy changes from one to the other. I think the solution files haven't changed very much.</p>


问:
Counting Sheep (Beatrix Trotter) Javascript
I am trying to solve a question on CodeWars that was part of the Google CodeJam 2016 qualification rounds.
https://www.codewars.com/kata/bleatrix-trotter-the-counting-sheep/train/javascript

I believe my code accounts for all test cases, my only issue is that it cannot be submitted on codewars because it has a runtime greater than 12000 ms.

How Can I make my Code more efficient?? also is there a best practice for testing whether the loop will be infinite.

```<code>function trotter(n) {
  var tracker = [];
  var sum = [];
  var snacker = n;
  for(var i = 0; tracker.length < 10; i++){
    sum = snacker.toString().split('');
    sum.forEach(function(num) {
        if (tracker.indexOf(num) == -1) {
             tracker.push(num);
        }
    });
    snacker += n;
  }
  return tracker.length === 10 ? snacker - n : "INSOMNIA";
}
</code>```

答:
The following code has no special optimisations and uses all ECMA-262 ed 3 methods. It ran the full suite of tests in 339 ms.

function trotter(n){
  var nums = ['0','1','2','3','4','5','6','7','8','9'];
  var i = 1;

  // Zero creates an infinite loop, so skip it
  if (n !== 0) {

    // While there are numbers to remove, keep going
    // Limit loops to 100 just in case
    while (nums.length && i < 100) {
      // Get test number as an array of digits
      var d = ('' + (n * i)).split('');

      // For each digit, if in nums remove it
      for (var j=0, jLen=d.length; j<jLen; j++) {
        var idx = nums.indexOf(d[j]);

        if (idx > -1) nums.splice(idx, 1);
      }

      i++;
    }
  }
  // If there are numbers left, didn't get to sleep
  // Otherwise, return last number seen (put d back together and make a numer)
  return nums.length? 'INSOMNIA' : Number(d.join(''));
}

console.log('0   : ' + trotter(0));
console.log('125 : ' + trotter(125));
console.log('1625: ' + trotter(1625));```
</div>
</div>
</p>

<p>Most cases are resolved in about 10 iterations, however 125, 1250, 12500, etc. take 73 iterations, which I think is the most that any number takes.</p>

<p>Since <em>Array</em> methods may be slow, here's a string version that's about <em>twice as fast</em>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function trotter(n){
  var found = '';
  if (n !== 0) {
    var i = 1;
    while (found.length < 10) {
      var d = i * n + '';
      var j = d.length;
      while (j) {
        var c = d[--j];
        var idx = found.indexOf(c);
        if (idx == -1) found += c;
      }
      i++;
    }
  }
  return found.length == 10? +d : 'INSOMNIA';
}

[0,    // Infinte loop case
 125,  // Max loop case
 1625] // just a number
 .forEach(function (n) {
  console.log(n + ' : ' + trotter(n));
});</code>```

While doing while (found.length) is not optimal, it's typically only computed about 10 times, so not really significant to move outside the condition. An alternative is to include a counter that is incremented each time a digit is added to found, but this isn't really about optimising performance as much as finding something reasonable that works and passes the (undisclosed) tests at codewars.

Body:
I am trying to solve a question on CodeWars that was part of the Google CodeJam 2016 qualification rounds.
https://www.codewars.com/kata/bleatrix-trotter-the-counting-sheep/train/javascript

I believe my code accounts for all test cases, my only issue is that it cannot be submitted on codewars because it has a runtime greater than 12000 ms.

How Can I make my Code more efficient?? also is there a best practice for testing whether the loop will be infinite.

function trotter(n) {
  var tracker = [];
  var sum = [];
  var snacker = n;
  for(var i = 0; tracker.length < 10; i++){
    sum = snacker.toString().split('');
    sum.forEach(function(num) {
        if (tracker.indexOf(num) == -1) {
             tracker.push(num);
        }
    });
    snacker += n;
  }
  return tracker.length === 10 ? snacker - n : "INSOMNIA";
}

Body:
The following code has no special optimisations and uses all ECMA-262 ed 3 methods. It ran the full suite of tests in 339 ms.

function trotter(n){
  var nums = ['0','1','2','3','4','5','6','7','8','9'];
  var i = 1;

  // Zero creates an infinite loop, so skip it
  if (n !== 0) {

    // While there are numbers to remove, keep going
    // Limit loops to 100 just in case
    while (nums.length && i < 100) {
      // Get test number as an array of digits
      var d = ('' + (n * i)).split('');

      // For each digit, if in nums remove it
      for (var j=0, jLen=d.length; j<jLen; j++) {
        var idx = nums.indexOf(d[j]);

        if (idx > -1) nums.splice(idx, 1);
      }

      i++;
    }
  }
  // If there are numbers left, didn't get to sleep
  // Otherwise, return last number seen (put d back together and make a numer)
  return nums.length? 'INSOMNIA' : Number(d.join(''));
}

console.log('0   : ' + trotter(0));
console.log('125 : ' + trotter(125));
console.log('1625: ' + trotter(1625));

Most cases are resolved in about 10 iterations, however 125, 1250, 12500, etc. take 73 iterations, which I think is the most that any number takes.

Since Array methods may be slow, here's a string version that's about twice as fast:

function trotter(n){
  var found = '';
  if (n !== 0) {
    var i = 1;
    while (found.length < 10) {
      var d = i * n + '';
      var j = d.length;
      while (j) {
        var c = d[--j];
        var idx = found.indexOf(c);
        if (idx == -1) found += c;
      }
      i++;
    }
  }
  return found.length == 10? +d : 'INSOMNIA';
}

[0,    // Infinte loop case
 125,  // Max loop case
 1625] // just a number
 .forEach(function (n) {
  console.log(n + ' : ' + trotter(n));
});

While doing while (found.length) is not optimal, it's typically only computed about 10 times, so not really significant to move outside the condition. An alternative is to include a counter that is incremented each time a digit is added to found, but this isn't really about optimising performance as much as finding something reasonable that works and passes the (undisclosed) tests at codewars.


问:
How to remove the content of a checkbox when it is unchecked in Java : Android
This is the code I used for checking and unchecking a CheckBox.

The problem is,
For a CheckBox,

When I Check, I'm getting the text of that checkbox and storing that text in a String.

Even when I Uncheck, the data is still present. It shows the value of a checked CheckBox.

What code can be inserted in the else statement in order to remove the checked data on unchecking a CheckBox.

```<code>public void onCheckboxClicked(View view) {
  // Is the view now checked?
  boolean checked = ((CheckBox) view).isChecked();
  // Check which checkbox was clicked
  switch (view.getId()) {
    case R.id.checkbox_child1:
      if (checked) {
        child1 = child1CheckBox.getText().toString();
        Log.d(TAG, "Child 1 : " + child1 + " Checked");
      } else {
        Log.d(TAG, "Child 1 : " + child1 + " unChecked");
      }
      break;
  }
}
</code>```

答:
Use this:</p>

```<code>editText.getText().clear()
</code>```

Body:
This is the code I used for checking and unchecking a CheckBox.

The problem is,
For a CheckBox,

When I Check, I'm getting the text of that checkbox and storing that text in a String.

Even when I Uncheck, the data is still present. It shows the value of a checked CheckBox.

What code can be inserted in the else statement in order to remove the checked data on unchecking a CheckBox.

public void onCheckboxClicked(View view) {
  // Is the view now checked?
  boolean checked = ((CheckBox) view).isChecked();
  // Check which checkbox was clicked
  switch (view.getId()) {
    case R.id.checkbox_child1:
      if (checked) {
        child1 = child1CheckBox.getText().toString();
        Log.d(TAG, "Child 1 : " + child1 + " Checked");
      } else {
        Log.d(TAG, "Child 1 : " + child1 + " unChecked");
      }
      break;
  }
}

Body:
Use this:

editText.getText().clear()


问:
Unable to start Resin application server
I have two resin web servers(41,47) in same folder. Actually am changing server version from 47 to 41 when I deployed and started project in 41 its hitting some error like below,

```<code>[admin@localhost bin]$ ./resin.sh start;
 Resin/4.0.41 can't start -server 'app-0' for watchdog at 127.0.0.1:6600.
 Unexpected resin.home mismatch:
 CLI resin.home: /home/admin/resin-pro-4.0.41/
 watchdog resin.home: /home/admin/resin-4.0.46/
</code>```

can anyone help me out this?

答:
Try to fix resix.xml

<server-multi id-prefix="app-" address-list="${app_servers}" port="6800" watchdog-port="6601"/>```

Body:
I have two resin web servers(41,47) in same folder. Actually am changing server version from 47 to 41 when I deployed and started project in 41 its hitting some error like below,

[admin@localhost bin]$ ./resin.sh start;
 Resin/4.0.41 can't start -server 'app-0' for watchdog at 127.0.0.1:6600.
 Unexpected resin.home mismatch:
 CLI resin.home: /home/admin/resin-pro-4.0.41/
 watchdog resin.home: /home/admin/resin-4.0.46/

can anyone help me out this?


问:
Ruby regular expression non capture group
I'm trying to grab id number from the string, say

```<code>id/number/2000GXZ2/ref=sr
</code>```

using

```<code>(?:id\/number\/)([a-zA-Z0-9]{8})
</code>```

for some reason non capture group is not worked, giving me:

```<code>id/number/2000GXZ2
</code>```

答:
This is Ruby Regexp expected match consistency evilness. Some Regexp-style methods will return the global-match while others will return specified matches.

In this case, one method we can use to get the behavior you're looking for is scan.

I don't think anyone here actually mentions how to get your Regexp working as you originally intended, which was to get the capture-only match. To do that, you would use the scan method like so with your original pattern:

test_me.rb

```<code>test_string="id/number/2000GXZ2/ref=sr"
result = test_string.scan(/(?:id\/number\/)([a-zA-Z0-9]{8})/)
puts result
</code>```

```<code>2000GXZ2
</code>```

That said, replacing (?:) with (?<=) for non-capture groups for look-behinds will benefit you both when you use scan as well as other parts of ruby that use Regexps.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to grab id number from the string, say

id/number/2000GXZ2/ref=sr

using

(?:id\/number\/)([a-zA-Z0-9]{8})

for some reason non capture group is not worked, giving me:

id/number/2000GXZ2

Body:
This is Ruby Regexp expected match consistency evilness. Some Regexp-style methods will return the global-match while others will return specified matches.

In this case, one method we can use to get the behavior you're looking for is scan.

I don't think anyone here actually mentions how to get your Regexp working as you originally intended, which was to get the capture-only match. To do that, you would use the scan method like so with your original pattern:

test_me.rb

test_string="id/number/2000GXZ2/ref=sr"
result = test_string.scan(/(?:id\/number\/)([a-zA-Z0-9]{8})/)
puts result

2000GXZ2

That said, replacing (?:) with (?<=) for non-capture groups for look-behinds will benefit you both when you use scan as well as other parts of ruby that use Regexps.


问:
Handling of two forms in one webpage
I have a webpage with a div area. In this area, there can be two different forms.
It looks like this:

Form 1:

```<code><div id="data" ...>
    <form action="/action1" method="post">
        <label for="label1">ID</label>
        <input type="text" name="id" id="label1" value="" />
        <label for="label2">Name</label>
        <input type="text" name="name" id="label2" value="" />
        <label for="label3">Description</label>
        <input type="text" name="desc" id="label3" value="" />
        <label for="label4">Address</label>
        <input type="text" name="address" id="label4" value="" />
     </form>
</div>
</code>```

Form 2:

```<code><div id="data" ...>
    <form action="/action2" method="post">
        <label for="label1">ID</label>
        <input type="text" name="id" id="label1" value="" />
        <label for="label2">Firstname</label>
        <input type="text" name="first" id="label2" value="" />
        <label for="label3">Lastname</label>
        <input type="text" name="last" id="label3" value="" />
        <label for="label4">Address</label>
        <input type="text" name="address" id="label4" value="" />
        <label for="label5">eMail</label>
        <input type="text" name="mail" id="label5" value="" />
     </form>
</div>
</code>```

So there are two different forms. The values will be set with jQuery (Ajax call to the backend).

What is the best way to handle these two forms? Should I create two files with only the form and the load the form when they are needed? (Form 1 is needed if some clicks on button 1, form 2 is needed if someoe clicks on button 2 - the events are handled on client-side).
Or should I place both form into the single HTML file and enable or disable the form?

答:
I think you should keep both the forms in the same page. And show/hide the required form as per the requirement.

Because if you keep the forms in separate HTML files, and user clicks on any button, then you'll have to make a XMLHttpRequest to get the HTML of form, whereas you can easily avoid this extra HTML request by including the HTML of the form in the same page.

I don't know if your website audience is so large or not. But saving a single HttpRequest should be very helpful.

See the article Minimize HTTP Requests by Yahoo developers. They clearly suggest to minimize HTTP requests.

Title: Handling of two forms in one webpage

Body:
I have a webpage with a div area. In this area, there can be two different forms.
It looks like this:

Form 1:

    <form action="/action1" method="post">
        ID
        <input type="text" name="id" id="label1" value="" />
        Name
        <input type="text" name="name" id="label2" value="" />
        Description
        <input type="text" name="desc" id="label3" value="" />
        Address
        <input type="text" name="address" id="label4" value="" />
     </form>

Form 2:

    <form action="/action2" method="post">
        ID
        <input type="text" name="id" id="label1" value="" />
        Firstname
        <input type="text" name="first" id="label2" value="" />
        Lastname
        <input type="text" name="last" id="label3" value="" />
        Address
        <input type="text" name="address" id="label4" value="" />
        eMail
        <input type="text" name="mail" id="label5" value="" />
     </form>

So there are two different forms. The values will be set with jQuery (Ajax call to the backend).

What is the best way to handle these two forms? Should I create two files with only the form and the load the form when they are needed? (Form 1 is needed if some clicks on button 1, form 2 is needed if someoe clicks on button 2 - the events are handled on client-side).
Or should I place both form into the single HTML file and enable or disable the form?


问:
ImageIO.read() infinite loop
ImageIO.read() just seems to be stuck in an infinite loop.

My code:

```<code>import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Texture {
    BufferedImage _img;

    public Texture(String path) {
        try {
            _img = ImageIO.read(new File(path));
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Other class:

```<code>private Texture _tex;
_tex = new Texture("/res/img.png");
</code>```

I have tried loading the image this URL and File, none works.

I am using eclipse, on a mac, and I am using LWJGL 3 if that has anything to do with anything.

Hope you can help me! :-)

答:
Instead of using a File, try using an input stream like this:

```<code>InputStream stream = Texture.class.getResourceAsStream(path);
_img = ImageIO.read(stream);
</code>```

I'm actually experiencing a similar issue, but it's related to the creation of BufferedImages.

Title: ImageIO.read() infinite loop

Body:
ImageIO.read() just seems to be stuck in an infinite loop.

My code:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Texture {
    BufferedImage _img;

    public Texture(String path) {
        try {
            _img = ImageIO.read(new File(path));
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}

Other class:

private Texture _tex;
_tex = new Texture("/res/img.png");

I have tried loading the image this URL and File, none works.

I am using eclipse, on a mac, and I am using LWJGL 3 if that has anything to do with anything.

Hope you can help me! :-)

Body:
Instead of using a File, try using an input stream like this:

InputStream stream = Texture.class.getResourceAsStream(path);
_img = ImageIO.read(stream);

I'm actually experiencing a similar issue, but it's related to the creation of BufferedImages.


问:
AJAX and PHP has problems
I'm pretty new to coding so sorry if this is a dumb question.  I'm wondering if I'm doing something wrong or if there's possibly a better way to troubleshoot my problem.  I'm using AJAX to submit information to a php handler and then basically replace the data on my page with updated info so that the page doesn't have to refresh everytime.

This is my AJAX code.

```<code><script>
     $(document).ready(function(){
         $("#start<?php echo $rowCount; ?>").click(function(){
                        $("#displayJobs").load("assemblyStartHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            startTime: '<?php echo $assemblyS; ?>'
                        });
                        $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    });
                });
</script>
</code>```

And my PHP code is

```<code><?php include "../../../includes/db.php"; ?>
<?php
    $startBtnColor = "";
    $completeBtnColor = "";
    $onQlistStatus = "On Q-List";
?>

<!--IF START BUTTON UPDATE DATA-->
<?php
date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");

    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    }
    elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    };

$querySetStart = "UPDATE rooms SET assemblyS = '$startTime' WHERE jobID = $jobID AND finishColor = '$finishColor'";
$resultSetStart = mysqli_query($connect, $querySetStart);

if(!$resultSetStart) {
    echo "Start Button Failed " . mysqli_error($connect);
};
?>

<!--GET AND DISPLAY JOBS-->
    <table>
            <tr>
                <th class="rowStart">Start</th>
                <th class="rowJobName">Job Name</th>
                <th class="rowWoodType">Wood Type</th>
                <th class="rowFinishColor">Finish Color</th>
                <th class="rowComplete">Complete</th>
            </tr>
<?php
    $query = "SELECT
        jobs.jobID,
        jobs.jobName,
        rooms.roomID,
        rooms.roomName,
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs
        LEFT JOIN rooms
        ON jobs.jobID = rooms.jobID
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100";

    $result = mysqli_query($connect, $query);

    $x = 1;
    $rowCount = 1;

    if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $jobID = $row['jobID'];
        $jobName = $row['jobName'];
        $woodType = $row['woodType'];
        $finishColor = $row['finishColor'];
        $roomID = $row['roomID'];
        $assemblyS = $row['assemblyS'];
        $assemblyF = $row['assemblyF'];
//SET BUTTON BACKGROUND COLOR
        if ($assemblyS != NULL) {
            $startBtnColor = "green";
        };
        if ($assemblyS == NULL || $assemblyS == 0) {
            $startBtnColor = "white";
        };
//ALTERNATE ROW COLOR
        $x++;
        if ($x%2 == 0) {
            $class1 = "backgroundColor1";
        }
        else {
            $class1 = "backgroundColor2";
        };
//DISPLAY ROW INFORMATION
        $start = "<td class='rowStart'><button id='start$rowCount' style='background-color: $startBtnColor'>Start</button></td>";
        ?>
            <script>
                $(document).ready(function(){
                    $("#start<?php echo $rowCount; ?>").click(function(){
                        $("#displayJobs").load("assemblyStartHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            startTime: '<?php echo $assemblyS; ?>'
                        });
                        $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    });
                });
            </script>
        <?php
        $jobName = "<td class='$class1 rowJobName'>$jobName</td>";
        $woodType = "<td class='$class1 rowWoodType'>$woodType</td>";
        $finishColorRow = "<td class='$class1 rowFinishColor'>$finishColor</td>";

        $complete = "<td class='rowComplete'><button id='complete$rowCount' style='background-color: $completeBtnColor'>Complete</button></td>";
            ?>
            <script>
                $(document).ready(function() {
                    $("#complete<?php echo $rowCount; ?>").click(function() {
                        $("#displayJobs").load("assemblyCompleteHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            completeTime: '<?php echo $assemblyS; ?>'
                        }, function(responseTxt, statusTxt, xhr) {
                            if(statusTxt == "success") {
                            //DO NOTHING
                            };
                            if(statusTxt == "error") {
                                alert("Error: " + xhr.status + ": " + xhr.statusText);
                            };
                        });

                    $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    $("#recentlyCompleted").load("assemblyRecentlyCompletedHandler.php", {
                        complete: 1
                    }, function(responseTxt, statusTxt, xhr) {
                            if(statusTxt == "success") {
                            //DO NOTHING
                            };
                            if(statusTxt == "error") {
                                alert("Error: " + xhr.status + ": " + xhr.statusText);
                            };
                        });
                    });
                });
            </script>
            <?php
        echo "<tr>" . $start . $jobName . $woodType . $finishColorRow . $complete . "</tr>";
        $rowCount++;
    };
    };
?>
            </table>
<?php
}
?>
</code>```

I know it's pretty messy.  Basically all the information is being pulled into a table and echoing the rows out through a while loop.  Then if I select a button associated with a "job" or "row" it 1st marks a start time, 2nd changes the color, and 3rd gives me a new count.
Is there a better way to do this or a way to make sure my code won't fire unless it's a success.

The weird thing to me is that my code is duplicated in the PHP handler.  If I refresh the page everything is displayed correctly every time with no problems.

答:
As was suggested, I would create a standalone PHP script that can be used with AJAX. This might look like:

PHP

```<code><?php
include "../../../includes/db.php";
$startBtnColor = "";
$completeBtnColor = "";
$onQlistStatus = "On Q-List";

date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");
    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    } elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    }

    if($stmt = $connection->prepare("UPDATE rooms SET assemblyS = '?' WHERE jobID = ? AND finishColor = '?'")){
        $stmt->bind_param("sis", $startTime, $jobID, $finishColor);
        if($stmt->execute()){
            $stmt->close();
            echo "Update Start Button Failed " . mysqli_error($connect);
            $connection->close();
            die();
        }
    }
    $connection->close();
    die();
}

$query = $connection->prepare("SELECT
        jobs.jobID,
        jobs.jobName,
        rooms.roomID,
        rooms.roomName,
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs
        LEFT JOIN rooms
        ON jobs.jobID = rooms.jobID
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '?' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '?' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100");
if($query){
    $query->bind_param("ss",$onQlistStatus,$onQlistStatus);
    $query->execute();
    $query->bind_result($result);

    $x = 1;
    $rowCount = 1;
    $results = array();

    if ($result) {
        while($row = mysqli_fetch_assoc($result)) {
            $results[] = array(
                'jobID' => $row['jobID'],
                'jobName' => $row['jobName'],
                'woodType' => $row['woodType'],
                'finishColor' => $row['finishColor'],
                'roomID' => $row['roomID'],
                'assemblyS' => $row['assemblyS'],
                'assemblyF' => $row['assemblyF'],
                //SET BUTTON BACKGROUND COLOR
                'assemblyS' => ($startBtnColor != NULL) ? "green" : "white",
                //ALTERNATE ROW COLOR
                'class1' => (!$x++%2) ? "backgroundColor1" : "backgroundColor2"
            );
            $rowCount++;
        }
    }
    $query->close();
}
$connection->close();
header('Content-Type: application/json');
echo json_encode($results);
?>
</code>```

If you POST to this, it will update the database. If you run GET to this, you will get the JSON data as a result.

This allows you to keep all your JavaScript within you HTML. This makes things a lot easier to troubleshoot too. It also allows you to call for data at any point. Just use $.getJSON() to pull the data.

MySQLi offers prepare which I strongly suggest using. This will help protect again SQL Injection attempts. Your current code is vulnerable to these attacks.

Your data will come back as an array of objects. Similar to:

```<code>[{
  'jobID': 1,
  'jobName': "job1",
  'woodType': "hardwood",
  'finishColor': "cherry",
  'roomID': "room1",
  'assemblyS': "2017-06-30 09:00:00",
  'assemblyF': "2017-06-30 16:00:00",
  'startBtnColor': "green",
  'class1': "backgroundColor1"
}, {
  'jobID': 2,
  'jobName': "job1",
  'woodType': "hardwood",
  'finishColor': "cherry",
  'roomID': "room2",
  'assemblyS': "2017-07-01 09:00:00",
  'assemblyF': "2017-07-01 16:00:00",
  'startBtnColor': "green",
  'class1': "backgroundColor2"
}, {
  'jobID': 3,
  'jobName': "job1",
  'woodType': "hardwood",
  'finishColor': "cherry",
  'roomID': "room3",
  'assemblyS': "2017-07-02 09:00:00",
  'assemblyF': "2017-07-02 16:00:00",
  'startBtnColor': "green",
  'class1': "backgroundColor1"
}];
</code>```

I would advise using $.each() to iterate over the data. You can build your table off this like so:

https://jsfiddle.net/Twisty/wkt9jnrq/

HTML

```<code><table id="startJobs">
  <thead>
    <tr>
      <th class="rowStart">Start</th>
      <th class="rowJobName">Job Name</th>
      <th class="rowWoodType">Wood Type</th>
      <th class="rowFinishColor">Finish Color</th>
      <th class="rowComplete">Complete</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</code>```

JavaScript

```<code>  $.each(myData, function(k, o) {
    var btn = $("<button>", {
        id: "start-" + o.jobID
      })
      .css("background-color", o.startBtnColor)
      .html("Start")
      .click(function(e) {
        $.post("assemblyStartHandlerCopy.php", {
          jobID: o.jobID,
          roomID: o.roomID,
          finishColor: o.finishColor,
          startTime: o.assemblyS
        }, function(result) {
          if (result.length) {
            alert(result);
          }
        });
      });
    var row = $("<tr>").appendTo("#startJobs tbody");
    row.append($("<td>", {
        class: "rowStart " + o.class1
      }).append(btn),
      $("<td>", {
        class: "rowJobName " + o.class1
      }).html(o.jobName),
      $("<td>", {
        class: "rowWoodType " + o.class1
      }).html(o.woodType),
      $("<td>", {
        class: "rowFinishColor " + o.class1
      }).html(o.finishColor),
      $("<td>", {
        class: "rowComplete " + o.class1
      }).html(o.assemblyF));
  });
</code>```

You can feed $.each() from within the success callback for $.getJSON().

Title: AJAX and PHP has problems

Body:
I'm pretty new to coding so sorry if this is a dumb question.  I'm wondering if I'm doing something wrong or if there's possibly a better way to troubleshoot my problem.  I'm using AJAX to submit information to a php handler and then basically replace the data on my page with updated info so that the page doesn't have to refresh everytime.

This is my AJAX code.

And my PHP code is

<?php include "../../../includes/db.php"; ?>
<?php
    $startBtnColor = "";
    $completeBtnColor = "";
    $onQlistStatus = "On Q-List";
?>

<?php
date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");

    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    }
    elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    };

$querySetStart = "UPDATE rooms SET assemblyS = '$startTime' WHERE jobID = $jobID AND finishColor = '$finishColor'";
$resultSetStart = mysqli_query($connect, $querySetStart);

if(!$resultSetStart) {
    echo "Start Button Failed " . mysqli_error($connect);
};
?>

                Start
                Job Name
                Wood Type
                Finish Color
                Complete

<?php
    $query = "SELECT
        jobs.jobID,
        jobs.jobName,
        rooms.roomID,
        rooms.roomName,
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs
        LEFT JOIN rooms
        ON jobs.jobID = rooms.jobID
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100";

    $result = mysqli_query($connect, $query);

    $x = 1;
    $rowCount = 1;

    if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $jobID = $row['jobID'];
        $jobName = $row['jobName'];
        $woodType = $row['woodType'];
        $finishColor = $row['finishColor'];
        $roomID = $row['roomID'];
        $assemblyS = $row['assemblyS'];
        $assemblyF = $row['assemblyF'];
//SET BUTTON BACKGROUND COLOR
        if ($assemblyS != NULL) {
            $startBtnColor = "green";
        };
        if ($assemblyS == NULL || $assemblyS == 0) {
            $startBtnColor = "white";
        };
//ALTERNATE ROW COLOR
        $x++;
        if ($x%2 == 0) {
            $class1 = "backgroundColor1";
        }
        else {
            $class1 = "backgroundColor2";
        };
//DISPLAY ROW INFORMATION
        $start = "<button id='start$rowCount' style='background-color: $startBtnColor'>Start</button>	";
        ?>

        <?php
        $jobName = "$jobName	";
        $woodType = "$woodType	";
        $finishColorRow = "$finishColor	";

        $complete = "<button id='complete$rowCount' style='background-color: $completeBtnColor'>Complete</button>	";
            ?>

            <?php
        echo "
" . $start . $jobName . $woodType . $finishColorRow . $complete . "
";
        $rowCount++;
    };
    };
?>

<?php
}
?>

I know it's pretty messy.  Basically all the information is being pulled into a table and echoing the rows out through a while loop.  Then if I select a button associated with a "job" or "row" it 1st marks a start time, 2nd changes the color, and 3rd gives me a new count.
Is there a better way to do this or a way to make sure my code won't fire unless it's a success.

The weird thing to me is that my code is duplicated in the PHP handler.  If I refresh the page everything is displayed correctly every time with no problems.

Body:
As was suggested, I would create a standalone PHP script that can be used with AJAX. This might look like:

PHP

<?php
include "../../../includes/db.php";
$startBtnColor = "";
$completeBtnColor = "";
$onQlistStatus = "On Q-List";

date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");
    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    } elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    }

    if($stmt = $connection->prepare("UPDATE rooms SET assemblyS = '?' WHERE jobID = ? AND finishColor = '?'")){
        $stmt->bind_param("sis", $startTime, $jobID, $finishColor);
        if($stmt->execute()){
            $stmt->close();
            echo "Update Start Button Failed " . mysqli_error($connect);
            $connection->close();
            die();
        }
    }
    $connection->close();
    die();
}

$query = $connection->prepare("SELECT
        jobs.jobID,
        jobs.jobName,
        rooms.roomID,
        rooms.roomName,
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs
        LEFT JOIN rooms
        ON jobs.jobID = rooms.jobID
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '?' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '?' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100");
if($query){
    $query->bind_param("ss",$onQlistStatus,$onQlistStatus);
    $query->execute();
    $query->bind_result($result);

    $x = 1;
    $rowCount = 1;
    $results = array();

    if ($result) {
        while($row = mysqli_fetch_assoc($result)) {
            $results[] = array(
                'jobID' => $row['jobID'],
                'jobName' => $row['jobName'],
                'woodType' => $row['woodType'],
                'finishColor' => $row['finishColor'],
                'roomID' => $row['roomID'],
                'assemblyS' => $row['assemblyS'],
                'assemblyF' => $row['assemblyF'],
                //SET BUTTON BACKGROUND COLOR
                'assemblyS' => ($startBtnColor != NULL) ? "green" : "white",
                //ALTERNATE ROW COLOR
                'class1' => (!$x++%2) ? "backgroundColor1" : "backgroundColor2"
            );
            $rowCount++;
        }
    }
    $query->close();
}
$connection->close();
header('Content-Type: application/json');
echo json_encode($results);
?>

If you POST to this, it will update the database. If you run GET to this, you will get the JSON data as a result.

This allows you to keep all your JavaScript within you HTML. This makes things a lot easier to troubleshoot too. It also allows you to call for data at any point. Just use $.getJSON() to pull the data.

MySQLi offers prepare which I strongly suggest using. This will help protect again SQL Injection attempts. Your current code is vulnerable to these attacks.

Your data will come back as an array of objects. Similar to:

[{
  'jobID': 1,
  'jobName': "job1",
  'woodType': "hardwood",
  'finishColor': "cherry",
  'roomID': "room1",
  'assemblyS': "2017-06-30 09:00:00",
  'assemblyF': "2017-06-30 16:00:00",
  'startBtnColor': "green",
  'class1': "backgroundColor1"
}, {
  'jobID': 2,
  'jobName': "job1",
  'woodType': "hardwood",
  'finishColor': "cherry",
  'roomID': "room2",
  'assemblyS': "2017-07-01 09:00:00",
  'assemblyF': "2017-07-01 16:00:00",
  'startBtnColor': "green",
  'class1': "backgroundColor2"
}, {
  'jobID': 3,
  'jobName': "job1",
  'woodType': "hardwood",
  'finishColor': "cherry",
  'roomID': "room3",
  'assemblyS': "2017-07-02 09:00:00",
  'assemblyF': "2017-07-02 16:00:00",
  'startBtnColor': "green",
  'class1': "backgroundColor1"
}];

I would advise using $.each() to iterate over the data. You can build your table off this like so:

https://jsfiddle.net/Twisty/wkt9jnrq/

HTML

<table id="startJobs">
  <thead>
    <tr>
      <th class="rowStart">Start</th>
      <th class="rowJobName">Job Name</th>
      <th class="rowWoodType">Wood Type</th>
      <th class="rowFinishColor">Finish Color</th>
      <th class="rowComplete">Complete</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

JavaScript

  $.each(myData, function(k, o) {
    var btn = $("<button>", {
        id: "start-" + o.jobID
      })
      .css("background-color", o.startBtnColor)
      .html("Start")
      .click(function(e) {
        $.post("assemblyStartHandlerCopy.php", {
          jobID: o.jobID,
          roomID: o.roomID,
          finishColor: o.finishColor,
          startTime: o.assemblyS
        }, function(result) {
          if (result.length) {
            alert(result);
          }
        });
      });
    var row = $("<tr>").appendTo("#startJobs tbody");
    row.append($("<td>", {
        class: "rowStart " + o.class1
      }).append(btn),
      $("<td>", {
        class: "rowJobName " + o.class1
      }).html(o.jobName),
      $("<td>", {
        class: "rowWoodType " + o.class1
      }).html(o.woodType),
      $("<td>", {
        class: "rowFinishColor " + o.class1
      }).html(o.finishColor),
      $("<td>", {
        class: "rowComplete " + o.class1
      }).html(o.assemblyF));
  });

You can feed $.each() from within the success callback for $.getJSON().


问:
Failed to Refresh data in RecyclerViewAdapter
I'm using the RecyclerViewAdapter. It's perfectly working.

My problem comes in when I am trying to populate the list from the server.

My DataHandaling class, I am trying to get the array to refresh the ListView from here...

```<code>void getEvents() {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(enviroClass.url() + "/api/events/" + 7)
            .build();

    client.newCall(request)
            .enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject eventObject = new JSONObject(response.body().string());
                        JSONArray eventJsonArray = eventObject.getJSONArray("events");
                        System.out.println(eventJsonArray.length());
                        for (int i = 0; i<2; i++) {
                            eventObject = eventJsonArray.getJSONObject(i);
                            eventObject = eventObject.getJSONObject("event");
                            eventArray.add(new Object_Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100" ,eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
                        }
                        System.out.println("This is from the http request in the datahandeling class" + "\n" + eventArray.get(0).getName());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
}
</code>```

Adapter Class I do have a method here to refresh the view

(NOTE: I have no idea if the swap method will work because I can't try it.)

```<code>import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.EventListFragment.OnListFragmentInteractionListener;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 * specified {@link OnListFragmentInteractionListener}.
 * TODO: Replace the implementation with code for your data type.
 */
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {

    private final List<Object_Event> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyItemRecyclerViewAdapter(List<Object_Event> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    public void swap(String hello){
//        mValues.clear();
//        DataHandaling dh = new DataHandaling();
//        System.out.println("This is the name of the event from the adapter" + "\n" + dh.getEventArray().get(0).getName());
//        mValues.addAll(eventArray);
//        notifyDataSetChanged();

        System.out.println(hello);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mItem = mValues.get(position);
        holder.mIdView.setText(mValues.get(position).getId() + "");
        holder.mContentView.setText(mValues.get(position).getName());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;
        public Object_Event mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.id);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}
</code>```

Fragment class

(NOTE: This should be done right because it does initially populate the ListView)

```<code>import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.dummy.DummyContent;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import org.w3c.dom.Text;

import java.util.ArrayList;

import static android.R.attr.data;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class EventListFragment extends Fragment {

    DataHandaling dh = new DataHandaling();

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public EventListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static EventListFragment newInstance(int columnCount) {
        EventListFragment fragment = new EventListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(dh.getEventArray(), mListener));
        }
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(int item);
    }
</code>```

I try to (refresh list) refresh data which i fetch from server.where I am failing miserably.

Can anyone help me? Thanks.

答:
You have to notify the change.</p>

```<code>MyItemRecyclerViewAdapter.notifyDataSetChanged();
</code>```

Body:
I'm using the RecyclerViewAdapter. It's perfectly working.

My problem comes in when I am trying to populate the list from the server.

My DataHandaling class, I am trying to get the array to refresh the ListView from here...

void getEvents() {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(enviroClass.url() + "/api/events/" + 7)
            .build();

    client.newCall(request)
            .enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject eventObject = new JSONObject(response.body().string());
                        JSONArray eventJsonArray = eventObject.getJSONArray("events");
                        System.out.println(eventJsonArray.length());
                        for (int i = 0; i<2; i++) {
                            eventObject = eventJsonArray.getJSONObject(i);
                            eventObject = eventObject.getJSONObject("event");
                            eventArray.add(new Object_Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100" ,eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
                        }
                        System.out.println("This is from the http request in the datahandeling class" + "\n" + eventArray.get(0).getName());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
}

Adapter Class I do have a method here to refresh the view

(NOTE: I have no idea if the swap method will work because I can't try it.)

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.EventListFragment.OnListFragmentInteractionListener;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 * specified {@link OnListFragmentInteractionListener}.
 * TODO: Replace the implementation with code for your data type.
 */
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {

    private final List<Object_Event> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyItemRecyclerViewAdapter(List<Object_Event> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    public void swap(String hello){
//        mValues.clear();
//        DataHandaling dh = new DataHandaling();
//        System.out.println("This is the name of the event from the adapter" + "\n" + dh.getEventArray().get(0).getName());
//        mValues.addAll(eventArray);
//        notifyDataSetChanged();

        System.out.println(hello);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mItem = mValues.get(position);
        holder.mIdView.setText(mValues.get(position).getId() + "");
        holder.mContentView.setText(mValues.get(position).getName());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;
        public Object_Event mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.id);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}

Fragment class

(NOTE: This should be done right because it does initially populate the ListView)

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.garethbecker.socializer.dummy.DummyContent;
import com.app.garethbecker.socializer.dummy.DummyContent.DummyItem;

import org.w3c.dom.Text;

import java.util.ArrayList;

import static android.R.attr.data;

/**
 * A fragment representing a list of Items.
 *

 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class EventListFragment extends Fragment {

    DataHandaling dh = new DataHandaling();

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public EventListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static EventListFragment newInstance(int columnCount) {
        EventListFragment fragment = new EventListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(dh.getEventArray(), mListener));
        }
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(int item);
    }

I try to (refresh list) refresh data which i fetch from server.where I am failing miserably.

Can anyone help me? Thanks.

Body:
You have to notify the change.

MyItemRecyclerViewAdapter.notifyDataSetChanged();


问:
Java PDF Viewer
I am using java and RCP and I am trying to show pdf Document with Acrobat on my views.
I don't need to change them.
I have this error with this code. Any idea how to resolve this problem?. P.s.: it works good same times.

```<code>PDFFile pdfFile;
pdfFile = PdfFileLoader.loadPdf(file, new NullProgressMonitor());
PdfDocument pdfDocument = new OneDimensionalPdfDocument(pdfFile, new NullProgressMonitor());
pdfViewer.setPdfDocument(pdfDocument);

Error from PdfDocument pdfDocument = new OneDimensionalPdfDocument(pdfFile, new NullProgressMonitor()) : Unsupport CMap format: 6
java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Unknown Source)
at java.nio.HeapByteBuffer.getShort(Unknown Source)
at com.sun.pdfview.font.ttf.HmtxTable.setData(HmtxTable.java:79)
at com.sun.pdfview.font.ttf.TrueTypeTable.createTable(TrueTypeTable.java:113)
at com.sun.pdfview.font.ttf.TrueTypeFont.getTable(TrueTypeFont.java:106)
at com.sun.pdfview.font.TTFFont.getOutline(TTFFont.java:129)
at com.sun.pdfview.font.TTFFont.getOutline(TTFFont.java:89)
at com.sun.pdfview.font.OutlineFont.getGlyph(OutlineFont.java:118)
at com.sun.pdfview.font.PDFFont.getCachedGlyph(PDFFont.java:307)
at com.sun.pdfview.font.PDFFontEncoding.getGlyphFromEncoding(PDFFontEncoding.java:132)
at com.sun.pdfview.font.PDFFontEncoding.getGlyphs(PDFFontEncoding.java:98)
at com.sun.pdfview.font.PDFFont.getGlyphs(PDFFont.java:273)
at com.sun.pdfview.PDFTextFormat.doText(PDFTextFormat.java:283)
at com.sun.pdfview.PDFParser.iterate(PDFParser.java:742)
at com.sun.pdfview.BaseWatchable.run(BaseWatchable.java:88)
at java.lang.Thread.run(Unknown Source)
</code>```

Regards,
Haythem

答:
Have a look at these free pdf renderer ...

Some links ...

http://www.icepdf.org/ (now at http://www.icesoft.org/java/projects/ICEpdf/overview.jsf - Apache 2 Open Source)

http://www.jpedal.org/support_siEclipse.php (now at https://www.idrsolutions.com/jpedal/ - commercial)

https://java.net/projects/pdf-renderer (still available https://github.com/yarick123/pdf-renderer - LGPL-2.1)

UPDATE

As per http://www.icepdf.org/ ,

ICEpdf is an open source Java PDF
  engine that can render, convert, or
  extract PDF content within any Java
  application or on a Web server.

For basic functionality you have to include icepdf-core.jar and icepdf-viewer.jar in your class path. Depending upon the requirement you can also add the SVG support.

Taken from iceface sample folder:

```<code>import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;

import javax.swing.*;

/**
 * The <code>ViewerComponentExample</code> class is an example of how to use
 * <code>SwingController</code> and <code>SwingViewBuilder</code>
 * to build a PDF viewer component.  A file specified at the command line is
 * opened in a JFrame which contains the viewer component.
 *
 * @since 2.0
 */
public class ViewerComponentExample {
    public static void main(String[] args) {
        // Get a file from the command line to open
        String filePath = args[0];

        // build a component controller
        SwingController controller = new SwingController();

        SwingViewBuilder factory = new SwingViewBuilder(controller);

        JPanel viewerComponentPanel = factory.buildViewerPanel();

        // add interactive mouse link annotation support via callback
        controller.getDocumentViewController().setAnnotationCallback(
                new org.icepdf.ri.common.MyAnnotationCallback(
                        controller.getDocumentViewController()));

        JFrame applicationFrame = new JFrame();
        applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        applicationFrame.getContentPane().add(viewerComponentPanel);

        // Now that the GUI is all in place, we can try openning a PDF
        controller.openDocument(filePath);

        // show the component
        applicationFrame.pack();
        applicationFrame.setVisible(true);
    }
}
</code>```

The above code helps you in displaying a PDF on a swing component. You can do the same in the SWT environment (have a look at SwingViewBuilder .. kind of hard, but will SWT look and feel ) or use org.eclipse.swt.awt.SWT_AWT (kind of easy... but will have swing + swt look and feel)... though both approach will solve your purpose. Also check the applicable licenses in the license folder.

Hope this will help.

Title: Java PDF Viewer

Body:
I am using java and RCP and I am trying to show pdf Document with Acrobat on my views.
I don't need to change them.
I have this error with this code. Any idea how to resolve this problem?. P.s.: it works good same times.

PDFFile pdfFile;
pdfFile = PdfFileLoader.loadPdf(file, new NullProgressMonitor());
PdfDocument pdfDocument = new OneDimensionalPdfDocument(pdfFile, new NullProgressMonitor());
pdfViewer.setPdfDocument(pdfDocument);

Error from PdfDocument pdfDocument = new OneDimensionalPdfDocument(pdfFile, new NullProgressMonitor()) : Unsupport CMap format: 6
java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Unknown Source)
at java.nio.HeapByteBuffer.getShort(Unknown Source)
at com.sun.pdfview.font.ttf.HmtxTable.setData(HmtxTable.java:79)
at com.sun.pdfview.font.ttf.TrueTypeTable.createTable(TrueTypeTable.java:113)
at com.sun.pdfview.font.ttf.TrueTypeFont.getTable(TrueTypeFont.java:106)
at com.sun.pdfview.font.TTFFont.getOutline(TTFFont.java:129)
at com.sun.pdfview.font.TTFFont.getOutline(TTFFont.java:89)
at com.sun.pdfview.font.OutlineFont.getGlyph(OutlineFont.java:118)
at com.sun.pdfview.font.PDFFont.getCachedGlyph(PDFFont.java:307)
at com.sun.pdfview.font.PDFFontEncoding.getGlyphFromEncoding(PDFFontEncoding.java:132)
at com.sun.pdfview.font.PDFFontEncoding.getGlyphs(PDFFontEncoding.java:98)
at com.sun.pdfview.font.PDFFont.getGlyphs(PDFFont.java:273)
at com.sun.pdfview.PDFTextFormat.doText(PDFTextFormat.java:283)
at com.sun.pdfview.PDFParser.iterate(PDFParser.java:742)
at com.sun.pdfview.BaseWatchable.run(BaseWatchable.java:88)
at java.lang.Thread.run(Unknown Source)

Regards,
Haythem

Body:
Have a look at these free pdf renderer ...

Some links ...

http://www.icepdf.org/ (now at http://www.icesoft.org/java/projects/ICEpdf/overview.jsf - Apache 2 Open Source)

http://www.jpedal.org/support_siEclipse.php (now at https://www.idrsolutions.com/jpedal/ - commercial)

https://java.net/projects/pdf-renderer (still available https://github.com/yarick123/pdf-renderer - LGPL-2.1)

UPDATE

As per http://www.icepdf.org/ ,

ICEpdf is an open source Java PDF
  engine that can render, convert, or
  extract PDF content within any Java
  application or on a Web server.

For basic functionality you have to include icepdf-core.jar and icepdf-viewer.jar in your class path. Depending upon the requirement you can also add the SVG support.

Taken from iceface sample folder:

import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;

import javax.swing.*;

/**
 * The <code>ViewerComponentExample</code> class is an example of how to use
 * <code>SwingController</code> and <code>SwingViewBuilder</code>
 * to build a PDF viewer component.  A file specified at the command line is
 * opened in a JFrame which contains the viewer component.
 *
 * @since 2.0
 */
public class ViewerComponentExample {
    public static void main(String[] args) {
        // Get a file from the command line to open
        String filePath = args[0];

        // build a component controller
        SwingController controller = new SwingController();

        SwingViewBuilder factory = new SwingViewBuilder(controller);

        JPanel viewerComponentPanel = factory.buildViewerPanel();

        // add interactive mouse link annotation support via callback
        controller.getDocumentViewController().setAnnotationCallback(
                new org.icepdf.ri.common.MyAnnotationCallback(
                        controller.getDocumentViewController()));

        JFrame applicationFrame = new JFrame();
        applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        applicationFrame.getContentPane().add(viewerComponentPanel);

        // Now that the GUI is all in place, we can try openning a PDF
        controller.openDocument(filePath);

        // show the component
        applicationFrame.pack();
        applicationFrame.setVisible(true);
    }
}

The above code helps you in displaying a PDF on a swing component. You can do the same in the SWT environment (have a look at SwingViewBuilder .. kind of hard, but will SWT look and feel ) or use org.eclipse.swt.awt.SWT_AWT (kind of easy... but will have swing + swt look and feel)... though both approach will solve your purpose. Also check the applicable licenses in the license folder.

Hope this will help.