问:
Gluon mobile cross-platform adsView
Is there any way to integrate ads such as Google's Admob library into gluon mobile on either android or iOS or hopefully both?

This is the gradle file, I have downloaded the Google Play Services library and the google Repository :

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.2.0'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'graphing.calculator.Calculator'

dependencies {
    compile 'com.gluonhq:charm:4.3.0'
    androidCompile 'com.google.android.gms:play-services-ads:9.4.0'
}

jfxmobile {
    downConfig {
        version = '3.2.0'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
        androidSdk = '/Users/aniket/Library/Android/sdk'
    }
    ios {
        arch = "arm64"
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

project.afterEvaluate {
    explodeAarDependencies(project.configurations.androidCompile)
}
</code>```

答:
Yes, there is a way, for both Android and iOS.

This answer already contains a snippet of how it could be done on Android. But I'll update it here using and extending the Charm Down library. I won't include the iOS solution, though, as it requires modifications in the jfxmobile plugin, as I'll explain later.

Create a new project with the Gluon plugin, and modify the following. You'll have to keep the package names I mention, but you can name your project (and package) as you want.

build.gradle script

You need to include the Google Play Services library:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.3.4'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'com.gluonhq.adview.GluonAdView' // this can be changed

dependencies {
    compile 'com.gluonhq:charm:4.3.2'

    androidCompile 'com.google.android.gms:play-services-ads:9.4.0'
}

jfxmobile {
    downConfig {
        version '3.2.4'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

project.afterEvaluate {
    explodeAarDependencies(project.configurations.androidCompile)
}
</code>```

Note the last task: it explodes the aar files on the android/google local repositories, to extract the jars (in this case the Google Play Services jar and all its dependencies).

Note also that after modifying the build file, you need to reload the project (to sync the project and manage the new dependencies).

Source Packages/Java

Besides the project files, you need to add this package: com.gluonhq.charm.down.plugins, and these classes:

AdViewService interface

```<code>public interface AdViewService {
    void setAdUnit(String unitId, String testDeviceId, boolean test);
}
</code>```

AdViewServiceFactory class

```<code>public class AdViewServiceFactory extends DefaultServiceFactory<AdViewService> {

    public AdViewServiceFactory() {
        super(AdViewService.class);
    }

}
</code>```

Android/Java Packages

In the Android/Java package, add this package: com.gluonhq.charm.down.plugins.android, and this class:

AndroidAdViewService class

```<code>import android.view.Gravity;
import android.widget.LinearLayout;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.LifecycleEvent;
import com.gluonhq.charm.down.plugins.LifecycleService;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import javafxports.android.FXActivity;
import com.gluonhq.charm.down.plugins.AdViewService;

public class AndroidAdViewService implements AdViewService {

    private AdView adView;

    @Override
    public void setAdUnit(String unitId, String testDeviceId, boolean test) {
        FXActivity.getInstance().runOnUiThread(() -> {
            LinearLayout layout = new LinearLayout(FXActivity.getInstance());
            layout.setVerticalGravity(Gravity.BOTTOM);
            layout.setOrientation(LinearLayout.VERTICAL);

            adView = new AdView(FXActivity.getInstance());
            adView.setAdSize(AdSize.SMART_BANNER);
            adView.setAdUnitId(unitId);

            AdRequest adRequest;
            if (test) {
                adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
                    .addTestDevice(testDeviceId)        // from logcat!
                    .build();
            } else {
                adRequest = new AdRequest.Builder().build();
            }

            adView.loadAd(adRequest);
            adView.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    super.onAdLoaded();
                }
            });

            layout.addView(adView);

            FXActivity.getViewGroup().addView(layout);
        });

        Services.get(LifecycleService.class).ifPresent(service -> {
            service.addListener(LifecycleEvent.RESUME, () -> FXActivity.getInstance().runOnUiThread(() -> adView.resume()));
            service.addListener(LifecycleEvent.PAUSE, () -> FXActivity.getInstance().runOnUiThread(() -> adView.pause()));
        });
    }

}
</code>```

It makes use of com.google.android.gms.ads.AdView. If your Android dependencies already include Google Play Services, you won't have any problem with the imports. Otherwise, go back to step 1.

Note that I'm setting a layout where the banner will go to the bottom of the screen. Change this at your convenience.

AndroidManifest.xml

You need to add this to the manifest:

```<code><?xml version="1.0" encoding="UTF-8"?>
<manifest ...>
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <application ...>
                <activity .../>
                <meta-data android:name="com.google.android.gms.version" android:value="9452000" />
                <activity android:name="com.google.android.gms.ads.AdActivity"
                          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                          android:theme="@android:style/Theme.Translucent"/>
        </application>
</manifest>
</code>```

Note the Google Play Services value corresponds with the 9.4.0 version.

Sample

Now you can add the service to your project. For that you'll need an Ad unit Id. You can create an account on Google AdMob to add your app, and get the App ID for the banner unit.

To get the test device id, you'll have to run the app first, and find in the console the id with adb logcat.

```<code>public BasicView(String name) {
    super(name);

    Services.get(AdViewService.class).ifPresent(ads -> {
        ads.setAdUnit("ca-app-pub-17652XXXXXXXXXX/83XXXXXXXX", "0283A9A0758XXXXXXXXXXXXXXXX", true);
    });

    Label label = new Label("Hello JavaFX World!");
    ...
}
</code>```

Run the sample on your Android device

You should see the ads at the bottom, and some logs at the console as well.

```<code>04-02 12:42:45.352 25520 25520 I Ads     : Starting ad request.
04-02 12:42:47.844 25520 25520 I Ads     : Scheduling ad refresh 60000 milliseconds from now.
04-02 12:42:47.889 25520 25520 I Ads     : Ad finished loading.
</code>```

iOS

For iOS it is possible as well. The problem is that it requires downloading the Google Mobile Ads SDK, and adding the GoogleMobileAds.framework to the list of frameworks, so when compiling the native code it finds it.

This should be done in the jfxmobile-plugin, so it is out of scope in this question for now.

Title: Gluon mobile cross-platform adsView

Body:
Is there any way to integrate ads such as Google's Admob library into gluon mobile on either android or iOS or hopefully both?

This is the gradle file, I have downloaded the Google Play Services library and the google Repository :

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.2.0'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'graphing.calculator.Calculator'

dependencies {
    compile 'com.gluonhq:charm:4.3.0'
    androidCompile 'com.google.android.gms:play-services-ads:9.4.0'
}

jfxmobile {
    downConfig {
        version = '3.2.0'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
        androidSdk = '/Users/aniket/Library/Android/sdk'
    }
    ios {
        arch = "arm64"
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

project.afterEvaluate {
    explodeAarDependencies(project.configurations.androidCompile)
}

Body:
Yes, there is a way, for both Android and iOS.

This answer already contains a snippet of how it could be done on Android. But I'll update it here using and extending the Charm Down library. I won't include the iOS solution, though, as it requires modifications in the jfxmobile plugin, as I'll explain later.

Create a new project with the Gluon plugin, and modify the following. You'll have to keep the package names I mention, but you can name your project (and package) as you want.

build.gradle script

You need to include the Google Play Services library:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.3.4'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'com.gluonhq.adview.GluonAdView' // this can be changed

dependencies {
    compile 'com.gluonhq:charm:4.3.2'

    androidCompile 'com.google.android.gms:play-services-ads:9.4.0'
}

jfxmobile {
    downConfig {
        version '3.2.4'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

project.afterEvaluate {
    explodeAarDependencies(project.configurations.androidCompile)
}

Note the last task: it explodes the aar files on the android/google local repositories, to extract the jars (in this case the Google Play Services jar and all its dependencies).

Note also that after modifying the build file, you need to reload the project (to sync the project and manage the new dependencies).

Source Packages/Java

Besides the project files, you need to add this package: com.gluonhq.charm.down.plugins, and these classes:

AdViewService interface

public interface AdViewService {
    void setAdUnit(String unitId, String testDeviceId, boolean test);
}

AdViewServiceFactory class

public class AdViewServiceFactory extends DefaultServiceFactory<AdViewService> {

    public AdViewServiceFactory() {
        super(AdViewService.class);
    }

}

Android/Java Packages

In the Android/Java package, add this package: com.gluonhq.charm.down.plugins.android, and this class:

AndroidAdViewService class

import android.view.Gravity;
import android.widget.LinearLayout;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.LifecycleEvent;
import com.gluonhq.charm.down.plugins.LifecycleService;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import javafxports.android.FXActivity;
import com.gluonhq.charm.down.plugins.AdViewService;

public class AndroidAdViewService implements AdViewService {

    private AdView adView;

    @Override
    public void setAdUnit(String unitId, String testDeviceId, boolean test) {
        FXActivity.getInstance().runOnUiThread(() -> {
            LinearLayout layout = new LinearLayout(FXActivity.getInstance());
            layout.setVerticalGravity(Gravity.BOTTOM);
            layout.setOrientation(LinearLayout.VERTICAL);

            adView = new AdView(FXActivity.getInstance());
            adView.setAdSize(AdSize.SMART_BANNER);
            adView.setAdUnitId(unitId);

            AdRequest adRequest;
            if (test) {
                adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
                    .addTestDevice(testDeviceId)        // from logcat!
                    .build();
            } else {
                adRequest = new AdRequest.Builder().build();
            }

            adView.loadAd(adRequest);
            adView.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    super.onAdLoaded();
                }
            });

            layout.addView(adView);

            FXActivity.getViewGroup().addView(layout);
        });

        Services.get(LifecycleService.class).ifPresent(service -> {
            service.addListener(LifecycleEvent.RESUME, () -> FXActivity.getInstance().runOnUiThread(() -> adView.resume()));
            service.addListener(LifecycleEvent.PAUSE, () -> FXActivity.getInstance().runOnUiThread(() -> adView.pause()));
        });
    }

}

It makes use of com.google.android.gms.ads.AdView. If your Android dependencies already include Google Play Services, you won't have any problem with the imports. Otherwise, go back to step 1.

Note that I'm setting a layout where the banner will go to the bottom of the screen. Change this at your convenience.

AndroidManifest.xml

You need to add this to the manifest:

<?xml version="1.0" encoding="UTF-8"?>
<manifest ...>
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <application ...>
                <activity .../>
                <meta-data android:name="com.google.android.gms.version" android:value="9452000" />
                <activity android:name="com.google.android.gms.ads.AdActivity"
                          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                          android:theme="@android:style/Theme.Translucent"/>
        </application>
</manifest>

Note the Google Play Services value corresponds with the 9.4.0 version.

Sample

Now you can add the service to your project. For that you'll need an Ad unit Id. You can create an account on Google AdMob to add your app, and get the App ID for the banner unit.

To get the test device id, you'll have to run the app first, and find in the console the id with adb logcat.

public BasicView(String name) {
    super(name);

    Services.get(AdViewService.class).ifPresent(ads -> {
        ads.setAdUnit("ca-app-pub-17652XXXXXXXXXX/83XXXXXXXX", "0283A9A0758XXXXXXXXXXXXXXXX", true);
    });

    Label label = new Label("Hello JavaFX World!");
    ...
}

Run the sample on your Android device

You should see the ads at the bottom, and some logs at the console as well.

04-02 12:42:45.352 25520 25520 I Ads     : Starting ad request.
04-02 12:42:47.844 25520 25520 I Ads     : Scheduling ad refresh 60000 milliseconds from now.
04-02 12:42:47.889 25520 25520 I Ads     : Ad finished loading.

iOS

For iOS it is possible as well. The problem is that it requires downloading the Google Mobile Ads SDK, and adding the GoogleMobileAds.framework to the list of frameworks, so when compiling the native code it finds it.

This should be done in the jfxmobile-plugin, so it is out of scope in this question for now.


来源: stackexchange

问:
Collection view beginInteractiveMovementForItem returns false
I'm using collection view and want to move cells when user paned. This is the code.

```<code>func longPressPhotoCollectionView(sender: UILongPressGestureRecognizer) {
    guard isEditing else {
        return
    }
    let point = sender.location(in: photoCollectionView)
    switch sender.state {
    case .began:
        guard let indexPath = photoCollectionView.indexPathForItem(at: point) else {
            return
        }
        let isS = photoCollectionView.beginInteractiveMovementForItem(at: indexPath)
        print(isS)
    case .changed:
        photoCollectionView.updateInteractiveMovementTargetPosition(point)
    case .ended:
        photoCollectionView.endInteractiveMovement()
    default:
        photoCollectionView.cancelInteractiveMovement()
    }
}
</code>```

I doubt custom layout will cause this problem. And I found this from Apple's Doc.

When you call this method, the collection view consults its delegate to make sure the item can be moved. If the data source does not support the movement of the item, this method returns false.

I don't know how to handle animations, especially with custom layout. Please help me! Thanks!

答:
Implement the following in your UICollectionViewDataSource:</p>

```<code>func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

    print("MOVING!")
    // Switch the Items in the DataSource
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using collection view and want to move cells when user paned. This is the code.

func longPressPhotoCollectionView(sender: UILongPressGestureRecognizer) {
    guard isEditing else {
        return
    }
    let point = sender.location(in: photoCollectionView)
    switch sender.state {
    case .began:
        guard let indexPath = photoCollectionView.indexPathForItem(at: point) else {
            return
        }
        let isS = photoCollectionView.beginInteractiveMovementForItem(at: indexPath)
        print(isS)
    case .changed:
        photoCollectionView.updateInteractiveMovementTargetPosition(point)
    case .ended:
        photoCollectionView.endInteractiveMovement()
    default:
        photoCollectionView.cancelInteractiveMovement()
    }
}

I doubt custom layout will cause this problem. And I found this from Apple's Doc.

When you call this method, the collection view consults its delegate to make sure the item can be moved. If the data source does not support the movement of the item, this method returns false.

I don't know how to handle animations, especially with custom layout. Please help me! Thanks!

Body:
Implement the following in your UICollectionViewDataSource:

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

    print("MOVING!")
    // Switch the Items in the DataSource
}


问:
Scrollable div inside section of Fullpage.js doesn't work
I want to have a scrollable div inside a section of fullpage.js but when I include scrollOverflow: true then I get this error: Cannot read property 'scrollHeight' of undefined.

The scrollOverflow library is included:

http://jsfiddle.net/97tbk/1827/

I wonder what am I missing:

```<code>$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    scrollOverflow: true
});
$('.fp-scrollable').slimScroll({
    alwaysVisible: true,
    color: 'black',
    size: '10px',
    allowPageScroll: true,
});
</code>```

答:
Your issue comes from scrollOverflow: true . It might mean your are missing slimScroll . You've got full details here.

Calling something on unknown means the object you need haven't been defined yet at usage time. It might be wise to use:

```<code>$(document).ready(function(){ /*code*/ });
</code>```

To avoid problems. Although it doesn't fix your current issue.

-- EDIT bcs of -1
=> Still proud of my anser. #EOF

Body:
I want to have a scrollable div inside a section of fullpage.js but when I include scrollOverflow: true then I get this error: Cannot read property 'scrollHeight' of undefined.

The scrollOverflow library is included:

http://jsfiddle.net/97tbk/1827/

I wonder what am I missing:

$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    scrollOverflow: true
});
$('.fp-scrollable').slimScroll({
    alwaysVisible: true,
    color: 'black',
    size: '10px',
    allowPageScroll: true,
});

Body:
Your issue comes from scrollOverflow: true . It might mean your are missing slimScroll . You've got full details here.

Calling something on unknown means the object you need haven't been defined yet at usage time. It might be wise to use:

$(document).ready(function(){ /*code*/ });

To avoid problems. Although it doesn't fix your current issue.

-- EDIT bcs of -1
=> Still proud of my anser. #EOF


问:
How much low-level stuff to expose in an API?
When designing the public API of a generic library, how much of the low-level stuff that's used internally should be exposed?  On the one hand, users should not depend too heavily on implementation details, and too many low-level functions/classes might clutter the API.  Therefore, the knee-jerk response might be "none".  On the other hand, some of the low-level functionality might be useful to people, and exposing more of it can prevent abstraction inversion (the re-implementing of low-level constructs on top of high-level constructs).

Furthermore, exposing more low-level details could provide performance shortcuts.  For example, let's say you have a function to find the median of an array.  The principle of least surprise says that you should duplicate the array so that users of your API don't have to care that its implementation involves the side effect of reordering elements.  Should you, in this case, note that median() costs a memory allocation and provide another function that bypasses the allocation, but will arbitrarily reorder the user's input?

What are some general guidelines for how much of this kind of detail to expose?

答:
One way I've heard it expressed: Expose the what, but not the how.

The goal is to provide a useful and rich library for clients to use, without making them dependent of the library's internals. You want to be able to change the internals, without breaking the callers (as someone else already noted).

Writing a good API involves a certain amount of artful brinkmanship.

OwnerDisplayName: dsimcha

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brian Clapper


问:
datepicker not working if it is inside a master page
Can someone help me out. Really desperate to make it work. Here is my full master page code:

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>IslandGas</title>
    <link href="/css/bootstrap.css" rel="stylesheet" />
    <link href="/css/font-awesome.min.css" rel="stylesheet" />
    <script src ="/js/bootstrap.js" type = "text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server" class="form-horizontal">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="AdminUpdatePanel" runat="server">

    <ContentTemplate>
    <div class="navbar navbar-default navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <a id="home" href="~/Admin/dash.aspx" runat="server" class="navbar-brand">Island Gas Admin</a>
                <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#navbar-main">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                </button>
            </div>
            <div class="navbar-collapse collapse" id="navbar-main" style="height: 1px;">
                <ul class="nav navbar-nav">
                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" id="products" href="#"><i class="fa fa-fw fa-wrench"></i>Products <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a id="A1" href="ViewProducts.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>View Products</a></li>
                            <li><a id="A2" href="AddNewProduct.aspx" runat="server"><i class="fa fa-fw fa-edit"></i>Add a Product</a></li>

                        </ul>
                    </li>
                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" id="suppliers" href="#"><i class="fa fa-fw fa-wrench"></i>Category <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a id="A29" href="ViewCategory.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>View Product Categories</a></li>
                            <li><a id="A6" href="AddCategory.aspx" runat="server"><i class="fa fa-fw fa-edit"></i>Add Product Category</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" id="orders" href="#"><i class="fa fa-fw fa-table"></i>Customer Orders <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a id="A10" href="CustomerOrder.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>View Orders</a></li>

                        </ul>
                    </li>

                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" id="reports" href="#"><i class="fa fa-fw fa-table"></i>Income Reports <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a id="A17" href="IncomeReports.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>Report</a></li>
                            <li><a id="A3" href="ReportCustomerTrack.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>Customer Track Report</a></li>
                            <li><a id="A7" href="ReportProducts.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>Products Report</a></li>

                            <li><a id="A9" href="ReportRegisteredCustomers.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>Registered Customer</a></li>
                            <li><a id="A4" href="ReportsGR.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>Return Goods Requests</a></li>
                        </ul>
                    </li><li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" id="A5" href="#"><i class="fa fa-fw fa-table"></i>Audit Trail <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a id="A8" href="AuditTrail.aspx" runat="server"><i class="fa fa-fw fa-eye"></i>View Audit Trail</a></li>

                        </ul>
                    </li>

                </ul>
                <ul class="nav navbar-nav pull-right">
                    <li id="user" runat="server" class="dropdown" visible="true">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                            <asp:Literal ID="ltUser" runat="server" Text="Administrator" /> <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu">

                            <li class="divider"></li>
                            <asp:linkbutton ID="linkLogout" runat="server" onclick="link_Logout_Click" CausesValidation="False" >[Log Out]</asp:linkbutton>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="clearfix">
            <div class="page-header">
                <div class="row">
                    <div class="col-lg-12">
                        <h1><asp:ContentPlaceHolder ID="title" runat="server" /></h1>
                    </div>
                </div>
            </div>
            <div class="row">
                <asp:ContentPlaceHolder ID="content" runat="server" />
            </div>
        </div>
        <footer>
            <div class="row">
                <div class="col-lg-12">
                    <p>Made by <a href="#">Duhaylungsod, Paolo</a></p>
                </div>
            </div>
        </footer>
    </div>
    <script type="text/javascript" src='<%= Page.ResolveUrl("~/js/jquery-1.11.3.min.js") %>'></script>
    <script type="text/javascript" src='<%= Page.ResolveUrl("~/js/bootstrap.min.js") %>'></script>
    </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>
</code>```

i am trying to make datepicker work. i have found a good code and it works perfectly fine in pages w/o a master page, update panel, script manager etc.
head code:

```<code>    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
</code>```

content:

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

      $('[id$=txtExpiry]').datepicker({ showAnim: 'slideDown' });

  });
</code>```

textbox:

```<code><div class ="form-group">
        <label class ="control-label col-lg-4"> Expiry Date</label>
        <div class = "col-lg-8">
        <asp:TextBox ID="txtExpiry" runat="server" class="form-control"></asp:TextBox>
</div>
</code>```

really really desperate to make this work. help me out please

答:
When you are using a master page, to avoid same id in a page, asp.net itself change the textbox id, actually it adds the name of placeholder to the id of your control.

For Example:
  TextBox with "txtExpiry" id, in a placeholder with "content" id, become: "content_txtExpiry" when it rendered.

so may javascripts and jquery codes can not find the input!
and the solution is defining the datepicker not using the class or old id, using the final rendered names as "content_txtExpiry" so change your code as:

$('[id$=content_txtExpiry]').datepicker({ showAnim: 'slideDown' });

Body:
Can someone help me out. Really desperate to make it work. Here is my full master page code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>IslandGas</title>
    <link href="/css/bootstrap.css" rel="stylesheet" />
    <link href="/css/font-awesome.min.css" rel="stylesheet" />

    <form id="form1" runat="server" class="form-horizontal">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="AdminUpdatePanel" runat="server">

    <ContentTemplate>

                Island Gas Admin
                <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#navbar-main">

                </button>

                        Products

View Products

Add a Product

                        Category

View Product Categories

Add Product Category

                        Customer Orders

View Orders

                        Income Reports

Report

Customer Track Report

Products Report

Registered Customer

Return Goods Requests

                        Audit Trail

View Audit Trail

                            <asp:Literal ID="ltUser" runat="server" Text="Administrator" />

                            <asp:linkbutton ID="linkLogout" runat="server" onclick="link_Logout_Click" CausesValidation="False" >[Log Out]</asp:linkbutton>

<asp:ContentPlaceHolder ID="title" runat="server" />

                <asp:ContentPlaceHolder ID="content" runat="server" />

Made by Duhaylungsod, Paolo

    </ContentTemplate>
    </asp:UpdatePanel>
    </form>

i am trying to make datepicker work. i have found a good code and it works perfectly fine in pages w/o a master page, update panel, script manager etc.
head code:

content:

  $(document).ready(function () {

      $('[id$=txtExpiry]').datepicker({ showAnim: 'slideDown' });

  });

textbox:

         Expiry Date

        <asp:TextBox ID="txtExpiry" runat="server" class="form-control"></asp:TextBox>

really really desperate to make this work. help me out please


问:
Trouble with CSS positioning for small screen
I need to add CSS for my webpage to make it better suitable for small screens and phones. My @media modification doesn't seem to work. I have to make it look like this:

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
nav ul li {
  margin: 0.2em;
  padding: 0.75em 1em;
  background: #689;
  background-image: linear-gradient(to bottom, #689, #245);
  border-radius: 1.25em;
}
nav a {
  color: #fff;
  text-decoration: none;
  font-weight: bold;
}

h1 {
  text-align: center;
}
nav {
   float: left;
   padding-right: 30px;
   width: 15%;
}
main {
   float: left;
   width: 40em;
}

@media (max-width: 480px) {
  float: none;
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="top">Protocols</h1>

<nav>
  <ul>
  <li>Top of Page</li>
  <li>Email</li>
  <li>HTTP</li>
  </ul>
</nav>

<main>
<p><dfn>Protocols</dfn> (or <dfn>communications protocols</dfn>) are agreed ways for to computers to communicate and exchange information. The Wikipedia page on communications protocols contains much more information than we can cover here.</p>

<section id="email">
<h2>Email Protocols</h2>
<p>There are several protocols that make email work:</p>
<ul>
<li><p><abbr title="Internet Message Access Protocol">IMAP</abbr> is used to fetch mail from the server so you can read it in clients like Thunderbird or on your phone.</p></li>
<li><p><abbr title="Post Office Protocol">POP</abbr> is an older protocol that does the same job as IMAP, but is less flexible.</p></li>
<li><p>The <abbr title="Simple Mail Transfer Protocol">SMTP</abbr> protocol is used to send email, either from a client program you are using, or from one mail server to another. SMTP has existed since the 1980s, but has been extended several times to add user authentication, encryption, and other features.</p>
<p>SMTP is where most spam fighting happens: preventing fraudulent email from being sent the the ultimate goal.</p></li>
</ul>
</section>

<section id="http">
<h2>HTTP</h2>
<p>The  World Wide Web rests on the protocol <abbr title="Hypertext Transfer Protocol">HTTP</abbr>.</p>
<p>HTTP is a client-server protocol. That means that an HTTP client (like a web browser, also called a “user agent”) contacts an HTTP server and makes a request. The request is likely a request for a particular web page available on that server. The server will respond with a response: often the contents of the web page that was requested.</p>
  <section id="uses">
  <h3>Uses</h3>
  <p>HTTP is often used to transfer <abbr title="Hypertext Markup Language">HTML</abbr> documents which we generally think of as “web pages”. HTML contains markup like <code class="html"><em></code> and <code class="html">href="http://example.com/"></code>.</p>
  <p>Every piece of content available on the web is called a <dfn>resource</dfn> and is available at a URL like <code class="url">http://example.com/somepage.html</code>.</p>
  </section>
</section>

</main></code>```

答:
Try this

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
nav ul li {
  margin: 0.2em;
  padding: 0.75em 1em;
  background: #689;
  background-image: linear-gradient(to bottom, #689, #245);
  border-radius: 1.25em;
}
nav a {
  color: #fff;
  text-decoration: none;
  font-weight: bold;
}

h1 {
  text-align: center;
}
nav {
   float: left;
   padding-right: 30px;
   width: 15%;
}
main {
   float: left;
   width: 40em;
}

@media (max-width: 480px) {
 nav ul li {
  display: inline;
  float: none;
  width: 100%;
 }
 main {
  float: left;
  width: 100%;
  margin: 1em;
 }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="top">Protocols</h1>

<nav>
  <ul>
  <li>Top of Page</li>
  <li>Email</li>
  <li>HTTP</li>
  </ul>
</nav>

<main>
<p><dfn>Protocols</dfn> (or <dfn>communications protocols</dfn>) are agreed ways for to computers to communicate and exchange information. The Wikipedia page on communications protocols contains much more information than we can cover here.</p>

<section id="email">
<h2>Email Protocols</h2>
<p>There are several protocols that make email work:</p>
<ul>
<li><p><abbr title="Internet Message Access Protocol">IMAP</abbr> is used to fetch mail from the server so you can read it in clients like Thunderbird or on your phone.</p></li>
<li><p><abbr title="Post Office Protocol">POP</abbr> is an older protocol that does the same job as IMAP, but is less flexible.</p></li>
<li><p>The <abbr title="Simple Mail Transfer Protocol">SMTP</abbr> protocol is used to send email, either from a client program you are using, or from one mail server to another. SMTP has existed since the 1980s, but has been extended several times to add user authentication, encryption, and other features.</p>
<p>SMTP is where most spam fighting happens: preventing fraudulent email from being sent the the ultimate goal.</p></li>
</ul>
</section>

<section id="http">
<h2>HTTP</h2>
<p>The  World Wide Web rests on the protocol <abbr title="Hypertext Transfer Protocol">HTTP</abbr>.</p>
<p>HTTP is a client-server protocol. That means that an HTTP client (like a web browser, also called a “user agent”) contacts an HTTP server and makes a request. The request is likely a request for a particular web page available on that server. The server will respond with a response: often the contents of the web page that was requested.</p>
  <section id="uses">
  <h3>Uses</h3>
  <p>HTTP is often used to transfer <abbr title="Hypertext Markup Language">HTML</abbr> documents which we generally think of as “web pages”. HTML contains markup like <code class="html"><em></code> and <code class="html">href="http://example.com/"></code>.</p>
  <p>Every piece of content available on the web is called a <dfn>resource</dfn> and is available at a URL like <code class="url">http://example.com/somepage.html</code>.</p>
  </section>
</section>

</main></code>```

Body:
I need to add CSS for my webpage to make it better suitable for small screens and phones. My @media modification doesn't seem to work. I have to make it look like this:

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
nav ul li {
  margin: 0.2em;
  padding: 0.75em 1em;
  background: #689;
  background-image: linear-gradient(to bottom, #689, #245);
  border-radius: 1.25em;
}
nav a {
  color: #fff;
  text-decoration: none;
  font-weight: bold;
}

h1 {
  text-align: center;
}
nav {
   float: left;
   padding-right: 30px;
   width: 15%;
}
main {
   float: left;
   width: 40em;
}

@media (max-width: 480px) {
  float: none;
  display: inline;
}

Protocols

Top of Page

Email

HTTP

<dfn>Protocols</dfn> (or <dfn>communications protocols</dfn>) are agreed ways for to computers to communicate and exchange information. The Wikipedia page on communications protocols contains much more information than we can cover here.

Email Protocols

There are several protocols that make email work:

IMAP is used to fetch mail from the server so you can read it in clients like Thunderbird or on your phone.

POP is an older protocol that does the same job as IMAP, but is less flexible.

The SMTP protocol is used to send email, either from a client program you are using, or from one mail server to another. SMTP has existed since the 1980s, but has been extended several times to add user authentication, encryption, and other features.

SMTP is where most spam fighting happens: preventing fraudulent email from being sent the the ultimate goal.

HTTP

The  World Wide Web rests on the protocol HTTP.

HTTP is a client-server protocol. That means that an HTTP client (like a web browser, also called a “user agent”) contacts an HTTP server and makes a request. The request is likely a request for a particular web page available on that server. The server will respond with a response: often the contents of the web page that was requested.

Uses

HTTP is often used to transfer HTML documents which we generally think of as “web pages”. HTML contains markup like  and .

Every piece of content available on the web is called a <dfn>resource</dfn> and is available at a URL like http://example.com/somepage.html.

Body:
Try this

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
nav ul li {
  margin: 0.2em;
  padding: 0.75em 1em;
  background: #689;
  background-image: linear-gradient(to bottom, #689, #245);
  border-radius: 1.25em;
}
nav a {
  color: #fff;
  text-decoration: none;
  font-weight: bold;
}

h1 {
  text-align: center;
}
nav {
   float: left;
   padding-right: 30px;
   width: 15%;
}
main {
   float: left;
   width: 40em;
}

@media (max-width: 480px) {
 nav ul li {
  display: inline;
  float: none;
  width: 100%;
 }
 main {
  float: left;
  width: 100%;
  margin: 1em;
 }

}

<h1 id="top">Protocols</h1>

<nav>
  <ul>
  <li><a href="#top">Top of Page</a></li>
  <li><a href="#email">Email</a></li>
  <li><a href="#http">HTTP</a></li>
  </ul>
</nav>

<main>
<p><dfn>Protocols</dfn> (or <dfn>communications protocols</dfn>) are agreed ways for to computers to communicate and exchange information. The Wikipedia page on <a href="https://en.wikipedia.org/wiki/Communications_protocol">communications protocols</a> contains much more information than we can cover here.</p>

<section id="email">
<h2>Email Protocols</h2>
<p>There are several protocols that make email work:</p>
<ul>
<li><p><abbr title="Internet Message Access Protocol">IMAP</abbr> is used to fetch mail from the server so you can read it in clients like Thunderbird or on your phone.</p></li>
<li><p><abbr title="Post Office Protocol">POP</abbr> is an older protocol that does the same job as IMAP, but is less flexible.</p></li>
<li><p>The <abbr title="Simple Mail Transfer Protocol">SMTP</abbr> protocol is used to send email, either from a client program you are using, or from one mail server to another. SMTP has existed since the 1980s, but has been extended several times to add user authentication, encryption, and other features.</p>
<p>SMTP is where most spam fighting happens: preventing fraudulent email from being sent the the ultimate goal.</p></li>
</ul>
</section>

<section id="http">
<h2>HTTP</h2>
<p>The  <a href="https://en.wikipedia.org/wiki/World_Wide_Web">World Wide Web</a> rests on the protocol <abbr title="Hypertext Transfer Protocol">HTTP</abbr>.</p>
<p>HTTP is a client-server protocol. That means that an HTTP client (like a web browser, also called a &ldquo;user agent&rdquo;) contacts an HTTP server and makes a request. The request is likely a request for a particular web page available on that server. The server will respond with a response: often the contents of the web page that was requested.</p>
  <section id="uses">
  <h3>Uses</h3>
  <p>HTTP is often used to transfer <abbr title="Hypertext Markup Language">HTML</abbr> documents which we generally think of as &ldquo;web pages&rdquo;. HTML contains markup like <code class="html">&lt;em&gt;</code> and <code class="html">&lt;a href="http://example.com/"&gt;</code>.</p>
  <p>Every piece of content available on the web is called a <dfn>resource</dfn> and is available at a URL like <code class="url">http://example.com/somepage.html</code>.</p>
  </section>
</section>

</main>


问:
How to avoid in a Mac app that an item of a NStableView is highlighted when empty?
I have a app for macOS where I use a view based NSTableView as a list of clickable items that start an action. Because in Cocoa there are not groups in tableView I separated all the items of a certain type with a blank item (which has three spaces as text).

How can get to not highlight the item with three space as text?

答:
Implement delegate method

```<code>- (NSIndexSet *)tableView:(NSTableView *)tableView selectionIndexesForProposedSelection:(NSIndexSet *)proposedSelectionIndexes;
</code>```

or

```<code>- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row;
</code>```

Body:
Implement delegate method

- (NSIndexSet *)tableView:(NSTableView *)tableView selectionIndexesForProposedSelection:(NSIndexSet *)proposedSelectionIndexes;

or

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row;


问:
Delete Method Cors issue in Rest Controller
I have some Rest endpoints in my project which I call from a client application in another server. I have successfully disabled Cors using the @CrossOrigin annotation, and all the methods work fine except the Delete method which throws the following error on Chrome:

XMLHttpRequest cannot load http://localhost:8856/robotpart/1291542214/compatibilities. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8888' is therefore not allowed access. The response had HTTP status code 403.

Here is my controller:

```<code>@CrossOrigin(origins = "*")
@ExposesResourceFor(RobotPart.class)
public class RobotPartController {

      //All endpoints are working except the Delete Mapping

    @GetMapping("/robotpart")
    public ResponseEntity<List<RobotPartResource>> listAllParts() {
        //..
    }

    @GetMapping("/robotpart/{id}")
    public ResponseEntity<RobotPartResource> getById(@PathVariable Integer id) {
        //..
    }

    @GetMapping("/robotpart/{id}/compatibilities")
    public ResponseEntity<Collection<RobotPartResource>> getRobotCompatibilities(@PathVariable Integer id,
          //..
    }

    @PostMapping("/robotpart")
    public ResponseEntity<RobotPartResource> getById(@RequestBody @Valid RobotPart newRobot) {
        //..

    @PutMapping("/robotpart/{id}")
    public ResponseEntity<RobotPartResource> modify(@PathVariable Integer id, @Valid @RequestBody RobotPart newRobot) {

         //...
    }

    @DeleteMapping("/robotpart/{id}")
    public ResponseEntity<RobotPart> deleteById(@PathVariable Integer id) {

        //...
    }

    }
</code>```

Any way around it?

答:
I found a solution, after analyzing http requests, I noticed that Access-Control-Allow-Methods header was missing the DELETE method, so I have added it by delete the <code>@CrossOrigin</code> annotation, and adding this bean to the configuration: </p>

```<code>        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/robotpart/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");

                }
            };
        }
</code>```

Body:
I have some Rest endpoints in my project which I call from a client application in another server. I have successfully disabled Cors using the @CrossOrigin annotation, and all the methods work fine except the Delete method which throws the following error on Chrome:

XMLHttpRequest cannot load http://localhost:8856/robotpart/1291542214/compatibilities. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8888' is therefore not allowed access. The response had HTTP status code 403.

Here is my controller:

@CrossOrigin(origins = "*")
@ExposesResourceFor(RobotPart.class)
public class RobotPartController {

      //All endpoints are working except the Delete Mapping

    @GetMapping("/robotpart")
    public ResponseEntity<List<RobotPartResource>> listAllParts() {
        //..
    }

    @GetMapping("/robotpart/{id}")
    public ResponseEntity<RobotPartResource> getById(@PathVariable Integer id) {
        //..
    }

    @GetMapping("/robotpart/{id}/compatibilities")
    public ResponseEntity<Collection<RobotPartResource>> getRobotCompatibilities(@PathVariable Integer id,
          //..
    }

    @PostMapping("/robotpart")
    public ResponseEntity<RobotPartResource> getById(@RequestBody @Valid RobotPart newRobot) {
        //..

    @PutMapping("/robotpart/{id}")
    public ResponseEntity<RobotPartResource> modify(@PathVariable Integer id, @Valid @RequestBody RobotPart newRobot) {

         //...
    }

    @DeleteMapping("/robotpart/{id}")
    public ResponseEntity<RobotPart> deleteById(@PathVariable Integer id) {

        //...
    }

    }

Any way around it?

Body:
I found a solution, after analyzing http requests, I noticed that Access-Control-Allow-Methods header was missing the DELETE method, so I have added it by delete the @CrossOrigin annotation, and adding this bean to the configuration:

        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/robotpart/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");

                }
            };
        }


问:
What is this line is in Angular syntax?
Unfortunately I do not understand following syntax. I know what it does, it removes a listener for the listener's array.

```<code>this._listeners = this._listeners.filter(1 => 1 !== listener);
</code>```

I do not understand this syntax in Angular2 and it is used everywhere.
1 => 1 !== listener.

The whole code snippet is

```<code>subscribe(listener: ListenerCallback): UnsubscribeCallback {
    this._listeners.push(listener);

    return () => { // returns an unsubscribe function
        this._listener = this._listeners.filter(1 => 1 !== listener);
    };
}
</code>```

答:
```<code>1 => 1 !== listener
</code>```

This is ES6 arrow function, read more here.

For example, var even = [1,2,3,4].filter(v => v % 2 == 0); will give your even numbers. Try this in the console of your browser.

And in your question you just need to replace 1 => 1 !== listener, with item => item !== listener.

Title: What is this line is in Angular syntax?

Body:
Unfortunately I do not understand following syntax. I know what it does, it removes a listener for the listener's array.

this._listeners = this._listeners.filter(1 => 1 !== listener);

I do not understand this syntax in Angular2 and it is used everywhere.
1 => 1 !== listener.

The whole code snippet is

subscribe(listener: ListenerCallback): UnsubscribeCallback {
    this._listeners.push(listener);

    return () => { // returns an unsubscribe function
        this._listener = this._listeners.filter(1 => 1 !== listener);
    };
}

Body:
1 => 1 !== listener

This is ES6 arrow function, read more here.

For example, var even = [1,2,3,4].filter(v => v % 2 == 0); will give your even numbers. Try this in the console of your browser.

And in your question you just need to replace 1 => 1 !== listener, with item => item !== listener.


问:
How to write a multiple dataframes to same sheet without duplicating the column labels
I have two questions regarding writing dataframe data to a file:

My program produces summary statistics on many grouped rows of a dataframe and save those to a StringIO buffer which writes to my output.csv file at completion. I have a feeling the pd.concat would be better suited but I couldn't get that to work. I can try adding a snippet of code when I get a chance and hopefully someone can explain how to properly concat and I assume that will solve my issue.

That being said, my program works and that's more than I can ask for. What is bugging me though is how the CSV file ends up repeating the same column labels for every summary statistic dataframe that was written to the buffer and incidentally into my CSV file as well. Is there a way to only write the column labels once and avoid multiple duplicate label rows?

My second question is in regards to writing to Excel to skip an unnecessary copy and paste. Like my previous issue, this is only a minor hindrance but still bugs me as I would  like to do things the right way. The issue is that i want all the frames written to the same sheet. In order  to avoid overwriting the same data it is necessary to use a buffer to store the data until the end.  None of the docs seemed to helpful in  my particular situation. I devised a workaround: xlwt to  buffer -> output.write(buffer.getvalue()) -> pd.to_csv(output) and then reimport that same file via pd.read_csv and finally add another writer that writes the dataframe to Excel. After all that work I ended just sticking with the simplicity of CSV since the Excel writer actually magnified the ugliness of the duplicating rows. Any suggestions on how my buffer issue can be handled better as I would prefer the streamline and control of Excel writer to a CSV output.

Sorry for not having any code for context. I tired my best to explain without it. If necessary I can add the code when I get a free chance.

答:
I'd agree that concatenating the dataframes is probably a better solution. You should probably ask a question specifically for that with some sample codes/dataframes.

For your second question you can position a dataframe in an Excel worksheet using the startrow and startcol parameters. You can skip the repeated header using the header boolean parameter, and you can skip the index using the index boolean parameter.

For example:

```<code>import pandas as pd

# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})
df4 = pd.DataFrame({'Data': [41, 42, 43, 44]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')

# Add the first dataframe to the worksheet.
df1.to_excel(writer, sheet_name='Sheet1', index=False)

offset = len(df1) + 1  # Add extra row for column header.

# Add the other dataframes.
for df in (df2, df3, df4):
    # Write the datafram without a column header or index.
    df.to_excel(writer, sheet_name='Sheet1', startrow=offset,
                header=False, index=False)

    offset += len(df)

# Close the Pandas Excel writer and output the Excel file.
writer.save()
</code>```

Output:

Body:
I'd agree that concatenating the dataframes is probably a better solution. You should probably ask a question specifically for that with some sample codes/dataframes.

For your second question you can position a dataframe in an Excel worksheet using the startrow and startcol parameters. You can skip the repeated header using the header boolean parameter, and you can skip the index using the index boolean parameter.

For example:

import pandas as pd

# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})
df4 = pd.DataFrame({'Data': [41, 42, 43, 44]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')

# Add the first dataframe to the worksheet.
df1.to_excel(writer, sheet_name='Sheet1', index=False)

offset = len(df1) + 1  # Add extra row for column header.

# Add the other dataframes.
for df in (df2, df3, df4):
    # Write the datafram without a column header or index.
    df.to_excel(writer, sheet_name='Sheet1', startrow=offset,
                header=False, index=False)

    offset += len(df)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:


问:
Spring MVC - Getting NullPointerException of a Model Class
The problem im facing is , when a customer tries to add an item to a cart , a NullPointerException is raised at Controller at this line of code

```<code>CustomerCart customercart = customer.getCustomercart();
</code>```

Please check the Exception information

xps_id : XPS00008  qty : 1 CUD00001 Apr 02, 2017 12:39:10 PM
  org.apache.catalina.core.StandardWrapperValve invoke SEVERE:
  Servlet.service() for servlet [dispatcher] in context with path
  [/TechNXT] threw exception [Request processing failed; nested
  exception is java.lang.NullPointerException] with root cause
  java.lang.NullPointerException    at
  technxt.controller.TechNXTCustomerController.addItemToCart(TechNXTCustomerController.java:150)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at
  org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at
  org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at
  org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at
  org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at
  org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at
  org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at
  org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1354)
    at
  org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

So the addItemToCart is my Controller Method
here is the Method

```<code>@RequestMapping("/customerreqAddItemToCart/{xps_id}")
    public String addItemToCart(@PathVariable("xps_id")String xps_id,@RequestParam("qty")int qty,Principal principal,HttpSession hsession,Model m){

        System.out.println("xps_id : "+xps_id + "  qty : " + qty);

        String customerid=principal.getName();
        System.out.println(customerid);
        Customer customer =cuss.getCustomerByUserId(customerid);
        CustomerCart customercart = customer.getCustomercart();
        Xmap_ps xmap_ps = xpss.getXPSbyId(xps_id);
        CustomerCartItems cartitem = new CustomerCartItems();

        cartitem.setCustomercart(customercart);
        cartitem.setXmap_ps(xmap_ps);
        cartitem.setCus_cartquantity(qty);
        cartitem.setCus_cartitemwisetotal(xmap_ps.getXps_price()*qty);
        /*cartitem.setProduct_id(xmap_ps.getProduct_id());
        cartitem.setSupplier_id(xmap_ps.getSupplier_id());*/

        ccis.addCartItem(cartitem);

        Customer customer1=cuss.getCustomerByUserId(customerid);
        CustomerCart cart1=customer1.getCustomercart();

        int cartsize = ccss.getCartSize(cart1);

        List<CustomerCartItems> cartitems = cart1.getCustomercartitems();
        int sum=0;
        for(CustomerCartItems critem :cartitems){
            sum+= critem.getCus_cartitemwisetotal();
        }

        cart1.setCus_cartgrandtotal(sum);
        ccss.updateCart(cart1);

        List<VwXmapPS> xpsdata = vxpss.getBestVwPs();

        m.addAttribute("xpsdata", xpsdata);

        m.addAttribute("customername",hsession.getAttribute("customername"));
        m.addAttribute("customerid",hsession.getAttribute("customerid"));
        m.addAttribute("cartsize",hsession.getAttribute("cartsize"));

        m.addAttribute("cartmessage","Item added to cart successfully");

        hsession.setAttribute("cartsize", cartsize);

        System.out.println("cart size :" + cartsize);

        return "redirect:/reqdisplaycustomerhomepage";

    }
</code>```

Let me also share my Model class with you all

CustomerCart Model class which has One to Many Relationship with CustomerCartItems Model class

```<code>@Entity
public class CustomerCart {

    @Id
    private String cus_cartid;
    private double cus_cartgrandtotal;

    @OneToOne(mappedBy="customercart")
    private Customer customer;

    @OneToMany(mappedBy="customercart", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private List<CustomerCartItems> customercartitems;
</code>```

CustomerCartItems Model class

```<code>@Entity
public class CustomerCartItems {

    @Id
        private String cus_cartitemid;
        private int cus_cartquantity;
        private int cus_cartitemwisetotal;

        @ManyToOne
        @JoinColumn(name="cus_cartid")
        private CustomerCart customercart;

        @ManyToOne
        @JoinColumn(name="xps_id")
        private Xmap_ps xmap_ps;
</code>```

3.And also The Customer Model Class which has all the Foreign Key relationship to other tables

```<code> @Entity
public class Customer {

    @Id
    private String cus_id;
    private String cus_name;
    private String cus_emailid;
    private String cus_mobileno;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_loginid")
    private CustomerDetails customerdetails;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_billingaddressid")
    private CustomerBillingAddress customerbillingaddress;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_shippingaddressid")
    private CustomerShippingAddress customershippingaddress;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_cartid")
    private CustomerCart customercart;
</code>```

I dont think i made any kind of Error with my Model Class
And please let me know what else i can share with you all so that i can get a solution of it

Thank you for taking your time and Helping me <3

答:
Does this really do what you think it does?:

```<code>String customerid=principal.getName();
</code>```

It don't think it gives you the Id field value that you have in the database.
You could store the logged in user's Id in the session or take it as a request parameter from the jsp.

debug it and you will see that customer is null.

Body:
The problem im facing is , when a customer tries to add an item to a cart , a NullPointerException is raised at Controller at this line of code

CustomerCart customercart = customer.getCustomercart();

Please check the Exception information

xps_id : XPS00008  qty : 1 CUD00001 Apr 02, 2017 12:39:10 PM
  org.apache.catalina.core.StandardWrapperValve invoke SEVERE:
  Servlet.service() for servlet [dispatcher] in context with path
  [/TechNXT] threw exception [Request processing failed; nested
  exception is java.lang.NullPointerException] with root cause
  java.lang.NullPointerException    at
  technxt.controller.TechNXTCustomerController.addItemToCart(TechNXTCustomerController.java:150)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at
  org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at
  org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at
  org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at
  org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at
  org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at
  org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at
  org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at
  org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1354)
    at
  org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

So the addItemToCart is my Controller Method
here is the Method

@RequestMapping("/customerreqAddItemToCart/{xps_id}")
    public String addItemToCart(@PathVariable("xps_id")String xps_id,@RequestParam("qty")int qty,Principal principal,HttpSession hsession,Model m){

        System.out.println("xps_id : "+xps_id + "  qty : " + qty);

        String customerid=principal.getName();
        System.out.println(customerid);
        Customer customer =cuss.getCustomerByUserId(customerid);
        CustomerCart customercart = customer.getCustomercart();
        Xmap_ps xmap_ps = xpss.getXPSbyId(xps_id);
        CustomerCartItems cartitem = new CustomerCartItems();

        cartitem.setCustomercart(customercart);
        cartitem.setXmap_ps(xmap_ps);
        cartitem.setCus_cartquantity(qty);
        cartitem.setCus_cartitemwisetotal(xmap_ps.getXps_price()*qty);
        /*cartitem.setProduct_id(xmap_ps.getProduct_id());
        cartitem.setSupplier_id(xmap_ps.getSupplier_id());*/

        ccis.addCartItem(cartitem);

        Customer customer1=cuss.getCustomerByUserId(customerid);
        CustomerCart cart1=customer1.getCustomercart();

        int cartsize = ccss.getCartSize(cart1);

        List<CustomerCartItems> cartitems = cart1.getCustomercartitems();
        int sum=0;
        for(CustomerCartItems critem :cartitems){
            sum+= critem.getCus_cartitemwisetotal();
        }

        cart1.setCus_cartgrandtotal(sum);
        ccss.updateCart(cart1);

        List<VwXmapPS> xpsdata = vxpss.getBestVwPs();

        m.addAttribute("xpsdata", xpsdata);

        m.addAttribute("customername",hsession.getAttribute("customername"));
        m.addAttribute("customerid",hsession.getAttribute("customerid"));
        m.addAttribute("cartsize",hsession.getAttribute("cartsize"));

        m.addAttribute("cartmessage","Item added to cart successfully");

        hsession.setAttribute("cartsize", cartsize);

        System.out.println("cart size :" + cartsize);

        return "redirect:/reqdisplaycustomerhomepage";

    }

Let me also share my Model class with you all

CustomerCart Model class which has One to Many Relationship with CustomerCartItems Model class

@Entity
public class CustomerCart {

    @Id
    private String cus_cartid;
    private double cus_cartgrandtotal;

    @OneToOne(mappedBy="customercart")
    private Customer customer;

    @OneToMany(mappedBy="customercart", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private List<CustomerCartItems> customercartitems;

CustomerCartItems Model class

@Entity
public class CustomerCartItems {

    @Id
        private String cus_cartitemid;
        private int cus_cartquantity;
        private int cus_cartitemwisetotal;

        @ManyToOne
        @JoinColumn(name="cus_cartid")
        private CustomerCart customercart;

        @ManyToOne
        @JoinColumn(name="xps_id")
        private Xmap_ps xmap_ps;

3.And also The Customer Model Class which has all the Foreign Key relationship to other tables

 @Entity
public class Customer {

    @Id
    private String cus_id;
    private String cus_name;
    private String cus_emailid;
    private String cus_mobileno;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_loginid")
    private CustomerDetails customerdetails;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_billingaddressid")
    private CustomerBillingAddress customerbillingaddress;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_shippingaddressid")
    private CustomerShippingAddress customershippingaddress;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cus_cartid")
    private CustomerCart customercart;

I dont think i made any kind of Error with my Model Class
And please let me know what else i can share with you all so that i can get a solution of it

Thank you for taking your time and Helping me <3

Body:
Does this really do what you think it does?:

String customerid=principal.getName();

It don't think it gives you the Id field value that you have in the database.
You could store the logged in user's Id in the session or take it as a request parameter from the jsp.

debug it and you will see that customer is null.


问:
how to split a column in pandas
how do i split the 'datetime' column into 'date' column and 'time' column?
I would like to have the 'date' as column 1 and 'time' as column 2.
The rest of the columns will have the same header.</p>

```<code> datetime                  C     H     L     O  OI  V    WAP
0  2017-03-13 19:00:00  8.22  8.22  8.10  8.10   4  6  8.143
1  2017-03-13 19:01:00  8.22  8.22  8.22  8.22   0  0  8.220
2  2017-03-13 19:02:00  8.22  8.22  8.22  8.22   0  0  8.220
3  2017-03-13 19:03:00  8.22  8.22  8.22  8.22   0  0  8.220
4  2017-03-13 19:04:00  8.22  8.22  8.22  8.22   0  0  8.220

print(df.head())
new_date_and_time = lambda x : x.split()
df['new_date_and_time'] = df['datetime'].apply(new_date_and_time)
print(df.head())
</code>```

答:
Assuming the column is already a "datetime" datatype you could just call the dataframe method "dt" on the original column and reassign to new columns:

```<code>df['date'] = df['datetime'].dt.date
df['time'] = df['datetime'].dt.time
# optional, drop original column
df.drop('datetime', axis=1, inplace=True)
</code>```

Obviously dropping the date time column is optional.

Title: how to split a column in pandas

Body:
how do i split the 'datetime' column into 'date' column and 'time' column?
I would like to have the 'date' as column 1 and 'time' as column 2.
The rest of the columns will have the same header.

 datetime                  C     H     L     O  OI  V    WAP
0  2017-03-13 19:00:00  8.22  8.22  8.10  8.10   4  6  8.143
1  2017-03-13 19:01:00  8.22  8.22  8.22  8.22   0  0  8.220
2  2017-03-13 19:02:00  8.22  8.22  8.22  8.22   0  0  8.220
3  2017-03-13 19:03:00  8.22  8.22  8.22  8.22   0  0  8.220
4  2017-03-13 19:04:00  8.22  8.22  8.22  8.22   0  0  8.220

print(df.head())
new_date_and_time = lambda x : x.split()
df['new_date_and_time'] = df['datetime'].apply(new_date_and_time)
print(df.head())

Body:
Assuming the column is already a "datetime" datatype you could just call the dataframe method "dt" on the original column and reassign to new columns:

df['date'] = df['datetime'].dt.date
df['time'] = df['datetime'].dt.time
# optional, drop original column
df.drop('datetime', axis=1, inplace=True)

Obviously dropping the date time column is optional.


问:
Xcode: TEST vs DEBUG preprocessor macros
When creating a new project with unit tests, Xcode sets the build configuration to Debug for the Test scheme (same for the Run scheme).

Should I differentiate between Run (Command-R) & Test (Command-U) schemes?

I.e., should I create a new Build Configuration called Test, add a preprocessor macro TEST=1 to it, and use it as the build configuration for the Test scheme instead? Or, should I just keep Run & Test both as Debug?

I come from a Ruby/Rails background, where you usually have test, development, and production environments. It seems to me that Debug is like development and Release is like production, but we're missing a test, which is why I'm thinking it might make sense to add Test.

Comments? Opinions? Suggestions?

I'm specifically asking this because I want to compile something for Test with:

```<code>#ifdef TEST
// Do something when I test.
#endif
</code>```

I don't think it matters if I also compile this for Debug. So, I really could just do:

```<code>#ifdef DEBUG
// Do something when I run or test.
#endif
</code>```

But, I'm really only intending to do it for tests for now. So, that's why I'm thinking I should differentiate between debug & test but am wondering why Xcode doesn't do that for you by default? Does Apple think you shouldn't differentiate between them?

答:
Robert's answer in SWIFT 3.0:</p>

```<code>func isRunningTests() -> Bool {
    let environment = ProcessInfo().environment
    return (environment["XCInjectBundleInto"] != nil);
}
</code>```

Body:
When creating a new project with unit tests, Xcode sets the build configuration to Debug for the Test scheme (same for the Run scheme).

Should I differentiate between Run (Command-R) & Test (Command-U) schemes?

I.e., should I create a new Build Configuration called Test, add a preprocessor macro TEST=1 to it, and use it as the build configuration for the Test scheme instead? Or, should I just keep Run & Test both as Debug?

I come from a Ruby/Rails background, where you usually have test, development, and production environments. It seems to me that Debug is like development and Release is like production, but we're missing a test, which is why I'm thinking it might make sense to add Test.

Comments? Opinions? Suggestions?

I'm specifically asking this because I want to compile something for Test with:

#ifdef TEST
// Do something when I test.
#endif

I don't think it matters if I also compile this for Debug. So, I really could just do:

#ifdef DEBUG
// Do something when I run or test.
#endif

But, I'm really only intending to do it for tests for now. So, that's why I'm thinking I should differentiate between debug & test but am wondering why Xcode doesn't do that for you by default? Does Apple think you shouldn't differentiate between them?

Body:
Robert's answer in SWIFT 3.0:

func isRunningTests() -> Bool {
    let environment = ProcessInfo().environment
    return (environment["XCInjectBundleInto"] != nil);
}


问:
No module named flaskext.mysql
I'm following this Python-Flask Web App tutorial:

On Step 5, it says to install Flask-Mysql and then import it using this:

from flaskext.mysql import MySQL

However, I keep getting the error when I try to run the app that:

ImportError: no module named flaskext.mysql

I'm not sure what I'm doing wrong? I have MySQL installed already. I installed Flask and Flask-Mysql using pip.

Thank you,
Amy

答:
first you have to install flask-mysql using following command:

sudo pip install flask-mysql

and then import mysql
from flaskext.mysql import MySQL
it works fine for me :)

Title: No module named flaskext.mysql


问:
"FileName.h" not found in Xcode 8.2 , Objective-c
I am preparing a SDK in objective framework, i added a file and imported a "FileName.h" but it giving me an error of file not found.
Any suggestion will be greatful

答:
Are you able import the framework in your project. If YES, check

Framework Search Paths in Build settings.

Example: $(PROJECT_DIR)/xxxxxxxx/GoogleSignIn\

Add your framework inside

Embedded Binaries


问:
Render React ES6 to String for Express
I've coded an React Application in ES6 style, all my Components are build like the following:

```<code>import React, { Component } from 'react';

class Test extends Component {
    render() {
        return (
            <div className="testDiv">
                Hello Word
            </div>
        )
    }
}

export default Test;
</code>```

This website is running via the default configuration via "npm start" at port 3000.

Furthermore I've an nodeJS application with an API via expressJS on port 8080. Now I want to create an single route to express where I can render the React application and deliver the HTML String back to the client. What's the best way to do this ? I'm new to React development, hope somebody can help.

答:
Here's a minimalistic example how to render your Test component on an Express server:</p>

```<code>import express from 'express';
import Test from './Test';
import React from 'react';
import ReactDOM from 'react-dom/server';

const app = express();

app.get('*', (req, res) => res.send(ReactDOM.renderToString(<Test />)));

app.listen(8080);
</code>```

Title: Render React ES6 to String for Express

Body:
I've coded an React Application in ES6 style, all my Components are build like the following:

import React, { Component } from 'react';

class Test extends Component {
    render() {
        return (

                Hello Word

        )
    }
}

export default Test;

This website is running via the default configuration via "npm start" at port 3000.

Furthermore I've an nodeJS application with an API via expressJS on port 8080. Now I want to create an single route to express where I can render the React application and deliver the HTML String back to the client. What's the best way to do this ? I'm new to React development, hope somebody can help.

Body:
Here's a minimalistic example how to render your Test component on an Express server:

import express from 'express';
import Test from './Test';
import React from 'react';
import ReactDOM from 'react-dom/server';

const app = express();

app.get('*', (req, res) => res.send(ReactDOM.renderToString(<Test />)));

app.listen(8080);